-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Move normalizeWhitespace to separate file
- Loading branch information
1 parent
f25ef65
commit 73772b1
Showing
2 changed files
with
54 additions
and
52 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import type { RawGlimmerTemplate } from '../types/glimmer'; | ||
|
||
function replaceRange( | ||
original: string, | ||
range: { start: number; end: number }, | ||
substitute: string, | ||
): string { | ||
return ( | ||
original.slice(0, range.start) + substitute + original.slice(range.end) | ||
); | ||
} | ||
|
||
const STATIC_OPEN = 'static{`'; | ||
const STATIC_CLOSE = '`}'; | ||
const NEWLINE = '\n'; | ||
|
||
export function normalizeWhitespace( | ||
templateNode: RawGlimmerTemplate, | ||
originalCode: string, | ||
currentCode: string, | ||
): string { | ||
let prefix: string; | ||
let suffix: string; | ||
|
||
if (templateNode.type === 'class-member') { | ||
prefix = STATIC_OPEN; | ||
suffix = STATIC_CLOSE; | ||
} else { | ||
const nextWord = originalCode.slice(templateNode.range.end).match(/\S+/); | ||
prefix = '{'; | ||
suffix = '}'; | ||
if (nextWord && nextWord[0] === 'as') { | ||
prefix = '(' + prefix; | ||
suffix = suffix + ')'; | ||
} else if (!nextWord || ![',', ')'].includes(nextWord[0][0] || '')) { | ||
suffix += ';'; | ||
} | ||
} | ||
|
||
const lineBreakCount = [...templateNode.contents].reduce( | ||
(sum, currentContents) => sum + (currentContents === NEWLINE ? 1 : 0), | ||
0, | ||
); | ||
const totalLength = templateNode.range.end - templateNode.range.start; | ||
const spaces = totalLength - prefix.length - suffix.length - lineBreakCount; | ||
const content = ' '.repeat(spaces) + NEWLINE.repeat(lineBreakCount); | ||
|
||
return replaceRange( | ||
currentCode, | ||
templateNode.range, | ||
`${prefix}${content}${suffix}`, | ||
); | ||
} |