|
1 | 1 | export const snippedTagContentAttribute = '✂prettier:content✂';
|
2 | 2 |
|
3 |
| -export function snipTagContent(tagName: string, source: string, placeholder = ''): string { |
4 |
| - const regex = new RegExp(`<!--[^]*?-->|<${tagName}([^]*?)>([^]*?)<\/${tagName}>`, 'g'); |
5 |
| - return source.replace(regex, (match, attributes, content) => { |
6 |
| - if (match.startsWith('<!--')) { |
7 |
| - return match; |
| 3 | +export function snipScriptAndStyleTagContent(source: string): string { |
| 4 | + const scriptMatchSpans = getMatchIndexes('script'); |
| 5 | + const styleMatchSpans = getMatchIndexes('style'); |
| 6 | + |
| 7 | + return snipTagContent( |
| 8 | + snipTagContent(source, 'script', '{}', scriptMatchSpans, styleMatchSpans), |
| 9 | + 'style', |
| 10 | + '', |
| 11 | + styleMatchSpans, |
| 12 | + scriptMatchSpans, |
| 13 | + ); |
| 14 | + |
| 15 | + function getMatchIndexes(tagName: string) { |
| 16 | + const regex = getRegexp(tagName); |
| 17 | + const indexes: [number, number][] = []; |
| 18 | + let match = null; |
| 19 | + while ((match = regex.exec(source)) != null) { |
| 20 | + indexes.push([match.index, regex.lastIndex]); |
8 | 21 | }
|
9 |
| - const encodedContent = Buffer.from(content).toString('base64'); |
10 |
| - return `<${tagName}${attributes} ${snippedTagContentAttribute}="${encodedContent}">${placeholder}</${tagName}>`; |
11 |
| - }); |
| 22 | + return indexes; |
| 23 | + } |
| 24 | + |
| 25 | + function snipTagContent( |
| 26 | + _source: string, |
| 27 | + tagName: string, |
| 28 | + placeholder: string, |
| 29 | + ownSpans: [number, number][], |
| 30 | + otherSpans: [number, number][], |
| 31 | + ) { |
| 32 | + const regex = getRegexp(tagName); |
| 33 | + let idx = 0; |
| 34 | + return _source.replace(regex, (match, attributes, content) => { |
| 35 | + if (match.startsWith('<!--') || withinOtherSpan(idx)) { |
| 36 | + return match; |
| 37 | + } |
| 38 | + const encodedContent = Buffer.from(content).toString('base64'); |
| 39 | + return `<${tagName}${attributes} ${snippedTagContentAttribute}="${encodedContent}">${placeholder}</${tagName}>`; |
| 40 | + }); |
| 41 | + |
| 42 | + function withinOtherSpan(idx: number) { |
| 43 | + return otherSpans.some( |
| 44 | + (otherSpan) => ownSpans[idx][0] > otherSpan[0] && ownSpans[idx][1] < otherSpan[1], |
| 45 | + ); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + function getRegexp(tagName: string) { |
| 50 | + return new RegExp(`<!--[^]*?-->|<${tagName}([^]*?)>([^]*?)<\/${tagName}>`, 'g'); |
| 51 | + } |
12 | 52 | }
|
13 | 53 |
|
14 | 54 | export function hasSnippedContent(text: string) {
|
|
0 commit comments