Skip to content

Commit

Permalink
ref: Convert runtime error to InvalidScreenshotFormatError
Browse files Browse the repository at this point in the history
  • Loading branch information
route committed Nov 19, 2024
1 parent cbf33fd commit c6f4801
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
6 changes: 6 additions & 0 deletions lib/ferrum/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,12 @@ def initialize(message = "Could not compute content quads")
end
end

class InvalidScreenshotFormatError < Error
def initialize(format)
super("Invalid value #{format} for option `:format` (#{Page::Screenshot::SUPPORTED_SCREENSHOT_FORMAT.join(' | ')})")
end
end

class BrowserError < Error
attr_reader :response

Expand Down
26 changes: 13 additions & 13 deletions lib/ferrum/page/screenshot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,10 @@ module Screenshot
# page.screenshot(path: "google.jpg") # => 30902
#
# @example Save to Base64 in WebP with reduce quality:
# page.screenshot(format: 'webp', quality: 60) # "iVBORw0KGgoAAAANS...
# page.screenshot(format: "webp", quality: 60) # "iVBORw0KGgoAAAANS...
#
# @example Save to Base64 the whole page not only viewport and reduce quality:
# page.screenshot(full: true, format: 'jpeg', quality: 60) # "iVBORw0KGgoAAAANS...
# page.screenshot(full: true, format: "jpeg", quality: 60) # "iVBORw0KGgoAAAANS...
#
# @example Save with specific background color:
# page.screenshot(background_color: Ferrum::RGBA.new(0, 0, 0, 0.0))
Expand Down Expand Up @@ -216,24 +216,24 @@ def screenshot_options(path = nil, format: nil, scale: 1.0, **options)
screenshot_options
end

def format_options(screenshot_format, path, quality)
if !screenshot_format && path # try to infer from path
extension = File.extname(path).delete(".")&.downcase
screenshot_format = extension if extension && !extension.empty?
def format_options(format, path, quality)
if !format && path # try to infer from path
extension = File.extname(path).delete(".").downcase
format = extension unless extension.empty?
end

screenshot_format ||= DEFAULT_SCREENSHOT_FORMAT
screenshot_format = screenshot_format.to_s
unless SUPPORTED_SCREENSHOT_FORMAT.include?(screenshot_format)
raise "Not supported options `:format` #{screenshot_format}. #{SUPPORTED_SCREENSHOT_FORMAT.join(' | ')}"
format ||= DEFAULT_SCREENSHOT_FORMAT
format = format.to_s
unless SUPPORTED_SCREENSHOT_FORMAT.include?(format)
raise Ferrum::InvalidScreenshotFormatError, format
end

screenshot_format = "jpeg" if screenshot_format == "jpg"
format = "jpeg" if format == "jpg"

# Chrome supports screenshot qualities for JPEG and WebP
quality ||= 75 if screenshot_format != "png"
quality ||= 75 if format != "png"

[screenshot_format, quality]
[format, quality]
end

def area_options(full, selector, scale, area = nil)
Expand Down

0 comments on commit c6f4801

Please sign in to comment.