MCPcopy Index your code
hub / github.com/callstack/linaria / getDeindentedStyleTextAndOffsets

Function getDeindentedStyleTextAndOffsets

packages/postcss-linaria/src/parse.ts:51–96  ·  view source on GitHub ↗
(
  styleText: string,
  node: TaggedTemplateExpression
)

Source from the content-addressed store, hash-verified

49};
50
51const getDeindentedStyleTextAndOffsets = (
52 styleText: string,
53 node: TaggedTemplateExpression
54) => {
55 const baseIndentation = (node.quasi.loc?.end.column ?? 1) - 1;
56 const sourceLines = styleText.split('\n');
57 const baseIndentations = new Map<number, number>();
58 const indentationPattern = new RegExp(`^[ \\t]{${baseIndentation}}`);
59 const emptyLinePattern = /^[ \\t\r]*$/;
60 const deindentedLines: string[] = [];
61 const prefixOffsets = { lines: 0, offset: 0 };
62
63 // remove the first line if it's an empty string and update the prefix
64 // offset to be the lines 1 instead of lines 0
65 if (
66 sourceLines.length > 1 &&
67 sourceLines[0] !== undefined &&
68 emptyLinePattern.test(sourceLines[0])
69 ) {
70 prefixOffsets.lines = 1;
71 prefixOffsets.offset = sourceLines[0].length + 1;
72 sourceLines.shift();
73 }
74
75 // go through each source line and deindent lines
76 for (let i = 0; i < sourceLines.length; i++) {
77 const sourceLine = sourceLines[i];
78 if (sourceLine !== undefined) {
79 // if the sourceline has the indentation pattern
80 if (indentationPattern.test(sourceLine)) {
81 deindentedLines.push(sourceLine.replace(indentationPattern, ''));
82 baseIndentations.set(i + 1, baseIndentation);
83 // Roots don't have an end line, so we can't look this up so easily
84 // later on. Having a special '-1' key helps here.
85 if (i === sourceLines.length - 1) {
86 baseIndentations.set(-1, baseIndentation);
87 }
88 } else {
89 deindentedLines.push(sourceLine);
90 }
91 }
92 }
93
94 const deindentedStyleText = deindentedLines.join('\n');
95 return { deindentedStyleText, prefixOffsets, baseIndentations };
96};
97
98/**
99 * Parses CSS from within tagged template literals in a JavaScript document

Callers 1

parseFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected