Module: PlaywrightRunner

Defined in:
lib/playwrightrunner.rb,
lib/playwrightrunner/version.rb

Constant Summary collapse

VERSION =
'1.2.0'

Class Method Summary collapse

Class Method Details

.default_config(config) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/playwrightrunner.rb', line 12

def default_config(config)
  config[:playwright_path] ||= './node_modules/.bin/playwright'

  # for Mermaid
  config[:selfcrop] = true if config[:selfcrop].nil?
  config[:pdfcrop_path] ||= 'pdfcrop'
  config[:pdftocairo_path] ||= 'pdftocairo'

  config
end

.mermaids_to_images(passed_config, src: '.', dest: '.', type: 'pdf') ⇒ Object



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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/playwrightrunner.rb', line 23

def mermaids_to_images(passed_config, src: '.', dest: '.', type: 'pdf')
  config = default_config(passed_config)
  Playwright.create(playwright_cli_executable_path: config[:playwright_path]) do |playwright|
    playwright.chromium.launch(headless: true) do |browser|
      page = browser.new_page
      Dir.glob(File.join(src, '*.html')).each do |entry|
        id = File.basename(entry).sub('.html', '')
        page.goto("file:///#{File.absolute_path(entry)}")
        page.locator('svg').wait_for(state: 'visible')
        sleep(1)
        1.upto(4) do
          bounds = page.locator('svg').bounding_box

          unless bounds
            sleep(1)
            next
          end

          if config[:selfcrop]
            x = bounds['x'].floor
            y = bounds['y'].floor
            width = bounds['width'].ceil
            height = bounds['height'].ceil
            page.set_viewport_size({ width: x + width, height: y + height })

            if type == 'png'
              page.screenshot(path: File.join(dest, "#{id}.png"), clip: { x: x, y: y, width: width, height: height })
              break
            end

            page.pdf(path: File.join(dest, "#{id}.pdf"),
                     width: "#{width + (x * 2)}px",
                     height: "#{height + (y * 2)}px")
          else
            page.pdf(path: File.join(dest, '__PLAYWRIGHT_TMP__.pdf'))
            Open3.capture2e(config[:pdfcrop_path],
                            File.join(dest, '__PLAYWRIGHT_TMP__.pdf'),
                            File.join(dest, "#{id}.pdf"))
          end

          break
        end

        next unless type == 'svg'

        Open3.capture2e(config[:pdftocairo_path],
                        '-svg',
                        '-f',
                        '1',
                        '-l',
                        '1',
                        File.join(dest, "#{id}.pdf"),
                        File.join(dest, "#{id}.svg"))
        FileUtils.rm_f(File.join(dest, "#{id}.pdf"))
      end

      FileUtils.rm_f(File.join(dest, '__PLAYWRIGHT_TMP__.pdf'))
    end
  end
end