f698bc301806e406d244905e9599e1b6de063a2c
[librarian.git] / src / librarian / elements / poetry / strofa.py
1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from copy import copy
5 import re
6 from ..base import WLElement
7 from .wers import Wers
8
9
10 class Strofa(WLElement):
11     NUMBERING = 'i'
12
13     TXT_TOP_MARGIN = 2
14     TXT_BOTTOM_MARGIN = 2
15
16     EPUB_TAG = HTML_TAG = 'div'
17     EPUB_CLASS = HTML_CLASS = 'stanza'
18
19     def epub_build(self, builder):
20         super().epub_build(builder)
21         builder.start_element(
22             'div',
23             {
24                 'class': 'stanza-spacer'
25             }
26         )
27         builder.push_text('\u00a0');
28         builder.end_element()
29
30     def preprocess(self):
31         from librarian.parser import parser
32
33         verses = [
34             parser.makeelement('wers')
35         ]
36         if self.text:
37             # Before any tags. These are text-only verses.
38             pieces = re.split(r"/\s+", self.text)
39             for piece in pieces[:-1]:
40                 verses[-1].text = piece
41                 verses.append(parser.makeelement('wers'))
42             verses[-1].text = pieces[-1]
43
44         for child in self:
45             if child.tail:
46                 pieces = re.split(r"/\s+", child.tail)
47                 child_copy = copy(child)
48                 child_copy.tail = pieces[0]
49                 verses[-1].append(child_copy)
50
51                 for piece in pieces[1:]:
52                     verses.append(parser.makeelement('wers'))
53                     verses[-1].text = piece
54                 
55             else:
56                 verses[-1].append(child)
57
58         verses = [
59             verse[0] if len(verse) == 1 and isinstance(verse[0], Wers)
60             else verse
61             for verse in verses
62         ]
63
64         while len(self):
65             self.remove(self[0])
66         self.text = None
67
68         for verse in verses:
69             self.append(verse)