1 | import { DocParagraph, DocNodeKind, DocPlainText } from '../nodes';
|
2 |
|
3 |
|
4 |
|
5 | var TrimSpacesTransform = (function () {
|
6 | function TrimSpacesTransform() {
|
7 | }
|
8 | TrimSpacesTransform.transform = function (docParagraph) {
|
9 | var transformedNodes = [];
|
10 |
|
11 | var pendingSpace = false;
|
12 |
|
13 | var accumulatedTextChunks = [];
|
14 | var accumulatedNodes = [];
|
15 |
|
16 |
|
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 |
|
55 | if (accumulatedTextChunks.length > 0) {
|
56 |
|
57 |
|
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 |
|
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 | }());
|
86 | export { TrimSpacesTransform };
|
87 |
|
\ | No newline at end of file |