Class: Epub::Translator::Prompt::Interlace

Inherits:
Object
  • Object
show all
Defined in:
lib/epub/translator/prompt/interlace.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#epub_pathsObject (readonly)

Returns the value of attribute epub_paths.



13
14
15
# File 'lib/epub/translator/prompt/interlace.rb', line 13

def epub_paths
  @epub_paths
end

#interlace_levelObject (readonly)

Returns the value of attribute interlace_level.



13
14
15
# File 'lib/epub/translator/prompt/interlace.rb', line 13

def interlace_level
  @interlace_level
end

#promptObject (readonly)

Returns the value of attribute prompt.



13
14
15
# File 'lib/epub/translator/prompt/interlace.rb', line 13

def prompt
  @prompt
end

Instance Method Details

#execute(epub_paths:, prompt: ::TTY::Prompt.new) ⇒ Object



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
# File 'lib/epub/translator/prompt/interlace.rb', line 15

def execute(
  epub_paths:,
  prompt: ::TTY::Prompt.new
)
  @epub_paths = epub_paths
  @prompt = prompt

  epub_paths.each do |path|
    return unless valid_epub?(path) # rubocop:disable Lint/NonLocalExitFromIterator
  end

  new_epub_path = prompt.ask(
    'Where do you want to save the result?',
    value: epub_paths.last.pathmap("%X.interlaced%x")
  )

  @interlace_level = prompt.ask(
    "Please input CSS path of DOM level to interlace:",
    value: 'body p,h1,h2,h3,h4,h5,h6'
  )

  FileUtils.copy(epub_paths[0], new_epub_path)

  epub = EPUB::Parser.parse(new_epub_path)
  epub_other = EPUB::Parser.parse(epub_paths[1])

  epub.each_page_on_spine.select(&:xhtml?).each do |item|
    next if item.content_document.oga.css(interlace_level).empty?

    item_other = epub_other.manifest[item.id]
    lang_other = item_other.content_document.oga.lang

    new_dom = item.content_document.oga
    new_dom.interlace(
      item_other.content_document.oga,
      level: interlace_level
    )

    # Style
    new_dom.lang = nil
    style = Oga::XML::Element.new(name: 'style')
    style.inner_text = "*:lang(#{lang_other}) { color: #999 !IMPORTANT; }"
    new_dom.at_css('head').node_set.push(style)

    item.content = new_dom.to_xml
  end
  epub.save

  puts 'Interlacing complete.'
end