summaryrefslogtreecommitdiff
path: root/@linaria/packages/babel/src/utils/stripLines.ts
blob: d0495ae30d0bc661f979b8a9073b01833fe4b382 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import type { Location } from '../types';

// Stripping away the new lines ensures that we preserve line numbers
// This is useful in case of tools such as the stylelint pre-processor
// This should be safe because strings cannot contain newline: https://www.w3.org/TR/CSS2/syndata.html#strings
export default function stripLines(
  loc: { start: Location; end: Location },
  text: string | number
) {
  let result = String(text)
    .replace(/[\r\n]+/g, ' ')
    .trim();

  // If the start and end line numbers aren't same, add new lines to span the text across multiple lines
  if (loc.start.line !== loc.end.line) {
    result += '\n'.repeat(loc.end.line - loc.start.line);

    // Add extra spaces to offset the column
    result += ' '.repeat(loc.end.column);
  }

  return result;
}