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

refactor(shared): improve start/end handling in generateCodeFrame #10883

Merged
merged 2 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 26 additions & 0 deletions packages/shared/__tests__/__snapshots__/codeframe.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,31 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`compiler: codeframe > invalid start and end 1`] = `
"1 | <div>
| ^
2 | <template key="one"></template>
3 | <ul>"
`;

exports[`compiler: codeframe > invalid start and end 2`] = `
"1 | <div>
| ^^^^^
2 | <template key="one"></template>
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3 | <ul>
| ^^^^^^
4 | <li v-for="foobar">hi</li>
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5 | </ul>
| ^^^^^^^
6 | <template key="two"></template>
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
7 | </div>
| ^^^^^^"
`;

exports[`compiler: codeframe > invalid start and end 3`] = `""`;

exports[`compiler: codeframe > line in middle 1`] = `
"2 | <template key="one"></template>
3 | <ul>
Expand Down
6 changes: 6 additions & 0 deletions packages/shared/__tests__/codeframe.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ attr
expect(generateCodeFrame(source, attrStart, attrEnd)).toMatchSnapshot()
})

test('invalid start and end', () => {
expect(generateCodeFrame(source, -Infinity, 0)).toMatchSnapshot()
expect(generateCodeFrame(source, 0, Infinity)).toMatchSnapshot()
expect(generateCodeFrame(source, Infinity, 0)).toMatchSnapshot()
})

{
const source = `
<template>
Expand Down
6 changes: 6 additions & 0 deletions packages/shared/src/codeframe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ export function generateCodeFrame(
start = 0,
end = source.length,
): string {
// Ensure start and end are within the source length
start = Math.max(0, Math.min(start, source.length))
end = Math.max(0, Math.min(end, source.length))

if (start > end) return ''

// Split the content into individual lines but capture the newline sequence
// that separated each line. This is important because the actual sequence is
// needed to properly take into account the full line length for offset
Expand Down