aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/zwobble/mammoth/internal/conversion/DocumentToHtml.java
blob: 6186cdb08cb27811c1ccb6bc954c64708181d9e5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package org.zwobble.mammoth.internal.conversion;

import org.zwobble.mammoth.internal.documents.*;
import org.zwobble.mammoth.internal.html.Html;
import org.zwobble.mammoth.internal.html.HtmlNode;
import org.zwobble.mammoth.internal.results.InternalResult;
import org.zwobble.mammoth.internal.styles.HtmlPath;
import org.zwobble.mammoth.internal.styles.StyleMap;
import org.zwobble.mammoth.internal.util.Lists;
import org.zwobble.mammoth.internal.util.Maps;

import java.io.IOException;
import java.util.*;
import java.util.function.Supplier;

import static org.zwobble.mammoth.internal.util.Casts.tryCast;
import static org.zwobble.mammoth.internal.util.Iterables.findIndex;
import static org.zwobble.mammoth.internal.util.Lists.*;
import static org.zwobble.mammoth.internal.util.Maps.*;

public class DocumentToHtml {
    public static InternalResult<List<HtmlNode>> convertToHtml(Document document, DocumentToHtmlOptions options) {
        DocumentToHtml documentConverter = new DocumentToHtml(options, document.getComments());
        return new InternalResult<>(
            documentConverter.convertToHtml(document, INITIAL_CONTEXT),
            documentConverter.warnings);
    }

    private static List<Note> findNotes(Document document, Iterable<NoteReference> noteReferences) {
        return eagerMap(
            noteReferences,
            // TODO: handle missing notes
            reference -> document.getNotes().findNote(reference.getNoteType(), reference.getNoteId()).get());
    }

    public static InternalResult<List<HtmlNode>> convertToHtml(DocumentElement element, DocumentToHtmlOptions options) {
        DocumentToHtml documentConverter = new DocumentToHtml(options, list());
        return new InternalResult<>(
            documentConverter.convertToHtml(element, INITIAL_CONTEXT),
            documentConverter.warnings);
    }

    private static class ReferencedComment {
        private final String label;
        private final Comment comment;

        private ReferencedComment(String label, Comment comment) {
            this.label = label;
            this.comment = comment;
        }
    }

    private final String idPrefix;
    private final boolean preserveEmptyParagraphs;
    private final StyleMap styleMap;
    private final InternalImageConverter imageConverter;
    private final Map<String, Comment> comments;
    private final List<NoteReference> noteReferences = new ArrayList<>();
    private final List<ReferencedComment> referencedComments = new ArrayList<>();
    private final Set<String> warnings = new HashSet<>();

    private static final Context INITIAL_CONTEXT = new Context(false);

    private static class Context {
        private final boolean isHeader;

        Context(boolean isHeader) {
            this.isHeader = isHeader;
        }

        Context isHeader(boolean isHeader) {
            return new Context(isHeader);
        }
    }

    private DocumentToHtml(DocumentToHtmlOptions options, List<Comment> comments) {
        this.idPrefix = options.idPrefix();
        this.preserveEmptyParagraphs = options.shouldPreserveEmptyParagraphs();
        this.styleMap = options.styleMap();
        this.imageConverter = options.imageConverter();
        this.comments = Maps.toMapWithKey(comments, Comment::getCommentId);
    }

    private List<HtmlNode> convertToHtml(Document document, Context context) {
        List<HtmlNode> mainBody = convertChildrenToHtml(document, context);
        // TODO: can you have note references inside a note?
        List<Note> notes = findNotes(document, noteReferences);

        List<HtmlNode> noteNodes = notes.isEmpty()
            ? list()
            : list(Html.element("ol", eagerMap(notes, note -> convertToHtml(note, context))));

        List<HtmlNode> commentNodes = referencedComments.isEmpty()
            ? list()
            : list(Html.element("dl", eagerFlatMap(referencedComments, comment -> convertToHtml(comment, context))));

        return eagerConcat(mainBody, noteNodes, commentNodes);
    }

    private HtmlNode convertToHtml(Note note, Context context) {
        String id = generateNoteHtmlId(note.getNoteType(), note.getId());
        String referenceId = generateNoteRefHtmlId(note.getNoteType(), note.getId());
        List<HtmlNode> noteBody = convertToHtml(note.getBody(), context);
        // TODO: we probably want this to collapse more eagerly than other collapsible elements
        // -- for instance, any paragraph will probably do, regardless of attributes. (Possible other elements will do too.)
        HtmlNode backLink = Html.collapsibleElement("p", list(
            Html.text(" "),
            Html.element("a", map("href", "#" + referenceId), list(Html.text("↑")))));
        return Html.element("li", map("id", id), eagerConcat(noteBody, list(backLink)));
    }

    private List<HtmlNode> convertToHtml(ReferencedComment referencedComment, Context context) {
        // TODO: remove duplication with notes
        String commentId = referencedComment.comment.getCommentId();
        List<HtmlNode> body = convertToHtml(referencedComment.comment.getBody(), context);
        // TODO: we probably want this to collapse more eagerly than other collapsible elements
        // -- for instance, any paragraph will probably do, regardless of attributes. (Possible other elements will do too.)
        HtmlNode backLink = Html.collapsibleElement("p", list(
            Html.text(" "),
            Html.element("a", map("href", "#" + generateReferenceHtmlId("comment", commentId)), list(Html.text("↑")))));

        return list(
            Html.element(
                "dt",
                map("id", generateReferentHtmlId("comment", commentId)),
                list(Html.text("Comment " + referencedComment.label))),
            Html.element("dd",
                eagerConcat(body, list(backLink))));
    }

    private List<HtmlNode> convertToHtml(List<DocumentElement> elements, Context context) {
        return eagerFlatMap(
            elements,
            element -> convertToHtml(element, context)
        );
    }

    private <T> List<HtmlNode> convertChildrenToHtml(HasChildren<T> element, Context context) {
        return convertToHtml(element.getChildren(), context);
    }

    private class ElementConverterVisitor implements DocumentElementVisitor<List<HtmlNode>, Context> {
        @Override
        public List<HtmlNode> visit(Paragraph paragraph, Context context) {
            Supplier<List<HtmlNode>> children = () -> {
                List<HtmlNode> content = convertChildrenToHtml(paragraph, context);
                return preserveEmptyParagraphs ? cons(Html.FORCE_WRITE, content) : content;
            };
            HtmlPath mapping = styleMap.getParagraphHtmlPath(paragraph)
                .orElseGet(() -> {
                    if (paragraph.getStyle().isPresent()) {
                        warnings.add("Unrecognised paragraph style: " + paragraph.getStyle().get().describe());
                    }
                    return HtmlPath.element("p");
                });
            return mapping.wrap(children).get();
        }

        @Override
        public List<HtmlNode> visit(Run run, Context context) {
            Supplier<List<HtmlNode>> nodes = () -> convertChildrenToHtml(run, context);
            if (run.getHighlight().isPresent()) {
                nodes = styleMap.getHighlightHtmlPath(run.getHighlight().get())
                    .orElse(HtmlPath.EMPTY)
                    .wrap(nodes);
            }
            if (run.isSmallCaps()) {
                nodes = styleMap.getSmallCaps().orElse(HtmlPath.EMPTY).wrap(nodes);
            }
            if (run.isAllCaps()) {
                nodes = styleMap.getAllCaps().orElse(HtmlPath.EMPTY).wrap(nodes);
            }
            if (run.isStrikethrough()) {
                nodes = styleMap.getStrikethrough().orElse(HtmlPath.collapsibleElement("s")).wrap(nodes);
            }
            if (run.isUnderline()) {
                nodes = styleMap.getUnderline().orElse(HtmlPath.EMPTY).wrap(nodes);
            }
            if (run.getVerticalAlignment() == VerticalAlignment.SUBSCRIPT) {
                nodes = HtmlPath.collapsibleElement("sub").wrap(nodes);
            }
            if (run.getVerticalAlignment() == VerticalAlignment.SUPERSCRIPT) {
                nodes = HtmlPath.collapsibleElement("sup").wrap(nodes);
            }
            if (run.isItalic()) {
                nodes = styleMap.getItalic().orElse(HtmlPath.collapsibleElement("em")).wrap(nodes);
            }
            if (run.isBold()) {
                nodes = styleMap.getBold().orElse(HtmlPath.collapsibleElement("strong")).wrap(nodes);
            }
            HtmlPath mapping = styleMap.getRunHtmlPath(run)
                .orElseGet(() -> {
                    if (run.getStyle().isPresent()) {
                        warnings.add("Unrecognised run style: " + run.getStyle().get().describe());
                    }
                    return HtmlPath.EMPTY;
                });
            return mapping.wrap(nodes).get();
        }

        @Override
        public List<HtmlNode> visit(Text text, Context context) {
            if (text.getValue().isEmpty()) {
                return list();
            } else {
                return list(Html.text(text.getValue()));
            }
        }

        @Override
        public List<HtmlNode> visit(Tab tab, Context context) {
            return list(Html.text("\t"));
        }

        @Override
        public List<HtmlNode> visit(Break breakElement, Context context) {
            HtmlPath mapping = styleMap.getBreakHtmlPath(breakElement)
                .orElseGet(() -> {
                    if (breakElement.getType() == Break.Type.LINE) {
                        return HtmlPath.element("br");
                    } else {
                        return HtmlPath.EMPTY;
                    }
                });
            return mapping.wrap(() -> list()).get();
        }

        @Override
        public List<HtmlNode> visit(Table table, Context context) {
            HtmlPath mapping = styleMap.getTableHtmlPath(table)
                .orElse(HtmlPath.element("table"));
            return mapping.wrap(() -> generateTableChildren(table, context)).get();
        }

        private List<HtmlNode> generateTableChildren(Table table, Context context) {
            int bodyIndex = findIndex(table.getChildren(), child -> !isHeader(child))
                .orElse(table.getChildren().size());
            if (bodyIndex == 0) {
                return convertToHtml(table.getChildren(), context.isHeader(false));
            } else {
                List<HtmlNode> headRows = convertToHtml(
                    table.getChildren().subList(0, bodyIndex),
                    context.isHeader(true)
                );
                List<HtmlNode> bodyRows = convertToHtml(
                    table.getChildren().subList(bodyIndex, table.getChildren().size()),
                    context.isHeader(false)
                );
                return list(
                    Html.element("thead", headRows),
                    Html.element("tbody", bodyRows)
                );
            }
        }

        private boolean isHeader(DocumentElement child) {
            return tryCast(TableRow.class, child)
                .map(TableRow::isHeader)
                .orElse(false);
        }

        @Override
        public List<HtmlNode> visit(TableRow tableRow, Context context) {
            return list(Html.element("tr", Lists.cons(Html.FORCE_WRITE, convertChildrenToHtml(tableRow, context))));
        }

        @Override
        public List<HtmlNode> visit(TableCell tableCell, Context context) {
            String tagName = context.isHeader ? "th" : "td";
            Map<String, String> attributes = new HashMap<>();
            if (tableCell.getColspan() != 1) {
                attributes.put("colspan", Integer.toString(tableCell.getColspan()));
            }
            if (tableCell.getRowspan() != 1) {
                attributes.put("rowspan", Integer.toString(tableCell.getRowspan()));
            }
            return list(Html.element(tagName, attributes,
                Lists.cons(Html.FORCE_WRITE, convertChildrenToHtml(tableCell, context))));
        }

        @Override
        public List<HtmlNode> visit(Hyperlink hyperlink, Context context) {
            Map<String, String> attributes = mutableMap("href", generateHref(hyperlink));
            hyperlink.getTargetFrame().ifPresent(targetFrame ->
                attributes.put("target", targetFrame)
            );

            return list(Html.collapsibleElement("a", attributes, convertChildrenToHtml(hyperlink, context)));
        }

        private String generateHref(Hyperlink hyperlink) {
            if (hyperlink.getHref().isPresent()) {
                return hyperlink.getHref().get();
            } else if (hyperlink.getAnchor().isPresent()) {
                return "#" + generateId(hyperlink.getAnchor().get());
            } else {
                return "";
            }
        }

        @Override
        public List<HtmlNode> visit(Checkbox checkbox, Context context) {
            Map<String, String> attributes = new HashMap<>();
            attributes.put("type", "checkbox");

            if (checkbox.checked()) {
                attributes.put("checked", "checked");
            }

            return list(Html.element("input", attributes));
        }

        @Override
        public List<HtmlNode> visit(Bookmark bookmark, Context context) {
            return list(Html.element("a", map("id", generateId(bookmark.getName())), list(Html.FORCE_WRITE)));
        }

        @Override
        public List<HtmlNode> visit(NoteReference noteReference, Context context) {
            noteReferences.add(noteReference);
            String noteAnchor = generateNoteHtmlId(noteReference.getNoteType(), noteReference.getNoteId());
            String noteReferenceAnchor = generateNoteRefHtmlId(noteReference.getNoteType(), noteReference.getNoteId());
            return list(Html.element("sup", list(
                Html.element("a", map("href", "#" + noteAnchor, "id", noteReferenceAnchor), list(
                    Html.text("[" + noteReferences.size() + "]"))))));
        }

        @Override
        public List<HtmlNode> visit(CommentReference commentReference, Context context) {
            return styleMap.getCommentReference().orElse(HtmlPath.IGNORE).wrap(() -> {
                String commentId = commentReference.getCommentId();
                Comment comment = lookup(comments, commentId)
                    .orElseThrow(() -> new RuntimeException("Referenced comment could not be found, id: " + commentId));
                String label = "[" + comment.getAuthorInitials().orElse("") + (referencedComments.size() + 1) + "]";
                referencedComments.add(new ReferencedComment(label, comment));

                // TODO: Remove duplication with note references
                return list(Html.element(
                    "a",
                    map(
                        "href", "#" + generateReferentHtmlId("comment", commentId),
                        "id", generateReferenceHtmlId("comment", commentId)),
                    list(Html.text(label))));
            }).get();
        }

        @Override
        public List<HtmlNode> visit(Image image, Context context) {
            // TODO: custom image handlers
            try {
                return imageConverter.convert(image);
            } catch (IOException exception) {
                warnings.add(exception.getMessage());
                return Lists.<HtmlNode>list();
            }
        }
    }

    private List<HtmlNode> convertToHtml(DocumentElement element, Context context) {
        return element.accept(new ElementConverterVisitor(), context);
    }

    private String generateNoteHtmlId(NoteType noteType, String noteId) {
        return generateReferentHtmlId(noteTypeToIdFragment(noteType), noteId);
    }

    private String generateNoteRefHtmlId(NoteType noteType, String noteId) {
        return generateReferenceHtmlId(noteTypeToIdFragment(noteType), noteId);
    }

    private String generateReferentHtmlId(String referenceType, String referenceId) {
        return generateId(referenceType + "-" + referenceId);
    }

    private String generateReferenceHtmlId(String referenceType, String referenceId) {
        return generateId(referenceType + "-ref-" + referenceId);
    }

    private String noteTypeToIdFragment(NoteType noteType) {
        switch (noteType) {
            case FOOTNOTE:
                return "footnote";
            case ENDNOTE:
                return "endnote";
            default:
                throw new UnsupportedOperationException();
        }
    }

    private String generateId(String bookmarkName) {
        return idPrefix + bookmarkName;
    }
}