wip change fb2 api
[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     FB2_TAG = 'stanza'
20     
21
22     def epub_build(self, builder):
23         super().epub_build(builder)
24         builder.start_element(
25             'div',
26             {
27                 'class': 'stanza-spacer'
28             }
29         )
30         builder.push_text('\u00a0');
31         builder.end_element()
32
33     def preprocess(self):
34         from librarian.parser import parser
35
36         verses = [
37             parser.makeelement('wers')
38         ]
39         if self.text:
40             # Before any tags. These are text-only verses.
41             pieces = re.split(r"/\s+", self.text)
42             for piece in pieces[:-1]:
43                 verses[-1].text = piece
44                 verses.append(parser.makeelement('wers'))
45             verses[-1].text = pieces[-1]
46
47         for child in self:
48             if child.tail:
49                 pieces = re.split(r"/\s+", child.tail)
50                 child_copy = copy(child)
51                 child_copy.tail = pieces[0]
52                 verses[-1].append(child_copy)
53
54                 for piece in pieces[1:]:
55                     verses.append(parser.makeelement('wers'))
56                     verses[-1].text = piece
57                 
58             else:
59                 verses[-1].append(child)
60
61         verses = [
62             verse[0] if len(verse) == 1 and isinstance(verse[0], Wers)
63             else verse
64             for verse in verses
65         ]
66
67         while len(self):
68             self.remove(self[0])
69         self.text = None
70
71         for verse in verses:
72             self.append(verse)