UNPKG

3.99 kBJavaScriptView Raw
1import { DocParagraph, DocNodeKind, DocPlainText } from '../nodes';
2/**
3 * Implementation of DocNodeTransforms.trimSpacesInParagraphNodes()
4 */
5var TrimSpacesTransform = /** @class */ (function () {
6 function TrimSpacesTransform() {
7 }
8 TrimSpacesTransform.transform = function (docParagraph) {
9 var transformedNodes = [];
10 // Whether the next nonempty node to be added needs a space before it
11 var pendingSpace = false;
12 // The DocPlainText node that we're currently accumulating
13 var accumulatedTextChunks = [];
14 var accumulatedNodes = [];
15 // We always trim leading whitespace for a paragraph. This flag gets set to true
16 // as soon as nonempty content is encountered.
17 var finishedSkippingLeadingSpaces = false;
18 for (var _i = 0, _a = docParagraph.nodes; _i < _a.length; _i++) {
19 var node = _a[_i];
20 switch (node.kind) {
21 case DocNodeKind.PlainText:
22 var docPlainText = node;
23 var text = docPlainText.text;
24 var startedWithSpace = /^\s/.test(text);
25 var endedWithSpace = /\s$/.test(text);
26 var collapsedText = text.replace(/\s+/g, ' ').trim();
27 if (startedWithSpace && finishedSkippingLeadingSpaces) {
28 pendingSpace = true;
29 }
30 if (collapsedText.length > 0) {
31 if (pendingSpace) {
32 accumulatedTextChunks.push(' ');
33 pendingSpace = false;
34 }
35 accumulatedTextChunks.push(collapsedText);
36 accumulatedNodes.push(node);
37 finishedSkippingLeadingSpaces = true;
38 }
39 if (endedWithSpace && finishedSkippingLeadingSpaces) {
40 pendingSpace = true;
41 }
42 break;
43 case DocNodeKind.SoftBreak:
44 if (finishedSkippingLeadingSpaces) {
45 pendingSpace = true;
46 }
47 accumulatedNodes.push(node);
48 break;
49 default:
50 if (pendingSpace) {
51 accumulatedTextChunks.push(' ');
52 pendingSpace = false;
53 }
54 // Push the accumulated text
55 if (accumulatedTextChunks.length > 0) {
56 // TODO: We should probably track the accumulatedNodes somehow, e.g. so we can map them back to the
57 // original excerpts. But we need a developer scenario before we can design this API.
58 transformedNodes.push(new DocPlainText({
59 configuration: docParagraph.configuration,
60 text: accumulatedTextChunks.join('')
61 }));
62 accumulatedTextChunks.length = 0;
63 accumulatedNodes.length = 0;
64 }
65 transformedNodes.push(node);
66 finishedSkippingLeadingSpaces = true;
67 }
68 }
69 // Push the accumulated text
70 if (accumulatedTextChunks.length > 0) {
71 transformedNodes.push(new DocPlainText({
72 configuration: docParagraph.configuration,
73 text: accumulatedTextChunks.join('')
74 }));
75 accumulatedTextChunks.length = 0;
76 accumulatedNodes.length = 0;
77 }
78 var transformedParagraph = new DocParagraph({
79 configuration: docParagraph.configuration
80 });
81 transformedParagraph.appendNodes(transformedNodes);
82 return transformedParagraph;
83 };
84 return TrimSpacesTransform;
85}());
86export { TrimSpacesTransform };
87//# sourceMappingURL=TrimSpacesTransform.js.map
\No newline at end of file