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