1/*
2 * Copyright 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17import { ContentNode } from './types';
18
19export class PlainTextFormatter {
20  static plainTextFor(nodes: ContentNode[]): string {
21    const output: string[] = [];
22    for (let i = 0; i < nodes.length; i += 1) {
23      let node = nodes[i];
24      if (!node.localName || node.localName.startsWith('#comment')) {
25        // Ignore comments
26        continue;
27      }
28      if (!node.textContent) {
29        continue;
30      }
31      // Split the textContent into lines.
32      // Analyze every line and check for
33      // empty spaces (\s*) and new lines (\r?\n).
34      let lines = node.textContent.split(/\r?\n/);
35      let content: string[] = [];
36      for (let i = 0; i < lines.length; i += 1) {
37        if (!PlainTextFormatter.isEmpty(lines[i])) {
38          content.push(lines[i]);
39        }
40      }
41      let payload = content.join('\r\n');
42      if (!PlainTextFormatter.isEmpty(payload)) {
43        output.push(payload);
44      }
45    }
46    return output.join('\r\n');
47  }
48
49  private static isEmpty(content: string): boolean {
50    if (/^\s*$/.exec(content)) {
51      return true;
52    }
53    if (/^r?\n$/.exec(content)) {
54      return true;
55    }
56    return false;
57  }
58}
59