rel
[librarian.git] / src / librarian / elements / poetry / strofa.py
1 from copy import copy
2 import re
3 from ..base import WLElement
4 from .wers import Wers
5
6
7 class Strofa(WLElement):
8     TXT_TOP_MARGIN = 2
9     TXT_BOTTOM_MARGIN = 2
10     TXT_LEGACY_TOP_MARGIN = 1
11     TXT_LEGACY_BOTTOM_MARGIN = 0
12
13     EPUB_TAG = HTML_TAG = 'div'
14     EPUB_CLASS = HTML_CLASS = 'stanza'
15
16     def epub_build(self, builder):
17         super().epub_build(builder)
18         builder.start_element(
19             'div',
20             {
21                 'class': 'stanza-spacer'
22             }
23         )
24         builder.push_text('\u00a0');
25         builder.end_element()
26     
27     def get_verses(self):
28         from librarian.parser import parser
29
30         verses = [
31             parser.makeelement('wers')
32         ]
33         if self.text:
34             # Before any tags. These are text-only verses.
35             pieces = re.split(r"/\s+", self.text)
36             for piece in pieces[:-1]:
37                 verses[-1].text = piece
38                 verses.append(parser.makeelement('wers'))
39             verses[-1].text = pieces[-1]
40
41         for child in self:
42             if child.tail:
43                 pieces = re.split(r"/\s+", child.tail)
44                 child_copy = copy(child)
45                 child_copy.tail = pieces[0]
46                 verses[-1].append(child_copy)
47
48                 for piece in pieces[1:]:
49                     verses.append(parser.makeelement('wers'))
50                     verses[-1].text = piece
51                 
52             else:
53                 verses[-1].append(child)
54
55         for verse in verses:
56             verse.stanza = self
57             if len(verse) == 1 and isinstance(verse[0], Wers):
58                 assert not (verse.text or '').strip()
59                 assert not (verse[0].tail or '').strip()
60                 yield verse[0]
61             else:
62                 yield verse
63
64     def _build_inner(self, builder, build_method):
65         for child in self.get_verses():
66             getattr(child, build_method)(builder)