Skip to content
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

fix(vue): SFC toString #200

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
139 changes: 17 additions & 122 deletions packages/gogocode-core/src/vue-core/generate.js
Original file line number Diff line number Diff line change
@@ -1,123 +1,18 @@
const indentString = require('indent-string');
const jsGenerate = require('../js-core/generate')
const htmlGenerate = require('../html-core/serialize-node')
/**
* The following function is adapted from https://github.com/psalaets/vue-sfc-descriptor-to-string/blob/master/index.js
*/

/**
* The MIT License (MIT)
* Copyright (c) 2018 Paul Salaets
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

module.exports = function toString(sfcDescriptor, options = {}) {
let { template, script, scriptSetup, styles = [], customBlocks = [], templateAst, scriptAst, scriptSetupAst } = sfcDescriptor;
if (templateAst && templateAst.node) {
template.content = htmlGenerate(templateAst.node);
}
if (scriptAst && scriptAst.node) {
script.content = jsGenerate(scriptAst.node);
}

if (scriptSetupAst && scriptSetupAst.node) {
scriptSetup.content = jsGenerate(scriptSetupAst.node);
}

const indents = Object.assign(
{
template: 2,
script: 0,
style: 0
},
options.indents
);

return (
[template, script, scriptSetup, ...styles, ...customBlocks]
// discard blocks that don't exist
.filter((block) => block != null)
// sort blocks by source position
.sort((a, b) => a.start - b.start)
// figure out exact source positions of blocks
.map((block) => {
const openTag = makeOpenTag(block);
const closeTag = makeCloseTag(block);

return Object.assign({}, block, {
openTag,
closeTag,

startOfOpenTag: block.start - openTag.length,
endOfOpenTag: block.start,

startOfCloseTag: block.end,
endOfCloseTag: block.end + closeTag.length
});
})
// generate sfc source
.reduce((sfcCode, block, index, array) => {
const first = index === 0;

let newlinesBefore = 0;

if (first) {
newlinesBefore = block.startOfOpenTag;
} else {
const prevBlock = array[index - 1];
newlinesBefore =
block.startOfOpenTag - prevBlock.endOfCloseTag;
}

newlinesBefore = newlinesBefore || 1

return (
sfcCode +
'\n'.repeat(newlinesBefore) +
block.openTag +
indentString(block.content, indents[block.type] || 0) +
block.closeTag
);
}, '')
);
}

function makeOpenTag(block) {
let source = '<' + block.type;

source += Object.keys(block.attrs)
.sort()
.map((name) => {
const value = block.attrs[name];

if (value === true) {
return name;
} else {
return `${name}="${value}"`;
}
})
.map((attr) => ' ' + attr)
.join('');

return source + '>';
}

function makeCloseTag(block) {
return `</${block.type}>\n`;
const jsGenerate = require('../js-core/generate');
const htmlGenerate = require('../html-core/serialize-node');

module.exports = function toString(sfcDescriptor) {
const { source } = sfcDescriptor
return ['template', 'script', 'scriptSetup'].reduce((acc, blockType) => {
const block = sfcDescriptor[blockType]
const ast = sfcDescriptor[blockType + 'Ast']
if (!block || !ast?.node) {
return acc
}
const offset = source.length - acc.length
const transform = blockType === 'template' ? htmlGenerate : jsGenerate
const before = acc.slice(0, block.loc.start.offset - offset)
const after = acc.slice(block.loc.end.offset - offset, acc.length)
return before + transform(ast.node) + after
}, source)
}
153 changes: 148 additions & 5 deletions packages/gogocode-core/test/G.vue.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const code = `
</template>
<script>
var a = 1;

function c( sd) {
s
}
Expand Down Expand Up @@ -59,7 +59,7 @@ const keyCodeDemo = `
<div>
<p>迁移:按键修饰符</p>
<p>迁移策略:
1.Vue3不再支持使用数字 (即键码) 作为 v-on 修饰符
1.Vue3不再支持使用数字 (即键码) 作为 v-on 修饰符
2.不再支持 config.keyCodes</p>
<div te s="" class="mt20 text-left">
// te todo
Expand Down Expand Up @@ -478,12 +478,12 @@ test('test no template', () => {
const res = $(`
<script>
export default {
name: 'components',
name: 'components',
data() {
return {
name: '组件'
name: '组件'
};
}
}
};
</script>
`, { parseOptions: { language: 'vue' }})
Expand Down Expand Up @@ -635,3 +635,146 @@ test('test vue parseoptions', () => {
const res = ast.generate()
expect(res.match('&&')).toBeTruthy()
})

test('block sort order', () => {
const ast = $(`
<template>
<div>Test</div>
</template>

<custom>
//
</custom>

<script>
export default {};
</script>
`,
{ parseOptions: { language: 'vue' } }
);
const res = ast.generate();
const expected = `
<template>
<div>Test</div>
</template>

<custom>
//
</custom>

<script>
export default {};
</script>
`;
expect(res).toEqual(expected);
});

test('multiple block transformations', () => {
const ast = $(`
<template>
<div>Test</div>
</template>

<i18n>
{
"en": {
"test" "Test"
}
}
</i18n>

<script>
export default {};
</script>
<script setup>
import X from 'Y'
</script>
`,
{ parseOptions: { language: 'vue' } }
);
ast.find('<template></template>').replace('<div>$$$0</div>', '<span>$$$0</span>')
ast.find('<script></script>').replace('export default {$$$0}', 'export default {\n name: "Component"\n};')
ast.find('<script setup></script>').replace('import X from "Y"', 'import Y from "X"')
const res = ast.generate();
const expected = `
<template>
<span>Test</span>
</template>

<i18n>
{
"en": {
"test" "Test"
}
}
</i18n>

<script>
export default {
name: "Component"
};
</script>
<script setup>
import Y from "X"
</script>
`;
expect(res).toEqual(expected);
});



test('retains all newlines and comments', () => {
const ast = $(`
<template>
<div>Test</div>
</template>
<custom>
//
</custom>

<script setup>
//
</script>
<script>
export default {};
</script>

<style lang="css">
.class{}
</style>
/**
* A comment
*/
<style lang="css" src="test.css"></style>
<style lang="css" src="another.css"></style>
`,
{ parseOptions: { language: 'vue' } }
);
const res = ast.generate();
const expected = `
<template>
<div>Test</div>
</template>
<custom>
//
</custom>

<script setup>
//
</script>
<script>
export default {};
</script>

<style lang="css">
.class{}
</style>
/**
* A comment
*/
<style lang="css" src="test.css"></style>
<style lang="css" src="another.css"></style>
`;
expect(res).toEqual(expected);
})
;