Skip to content

Commit 3253bf1

Browse files
committed
Refactor screenshot options
1 parent be8459e commit 3253bf1

File tree

1 file changed

+31
-23
lines changed

1 file changed

+31
-23
lines changed

lib/ferrum/page/screenshot.rb

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -124,45 +124,53 @@ def pdf_options(**opts)
124124
options.transform_keys { |k| to_camel_case(k) }
125125
end
126126

127-
def screenshot_options(path = nil, format: nil, scale: 1.0, **opts)
128-
options = {}
127+
def screenshot_options(path = nil, format: nil, scale: 1.0, **options)
128+
screenshot_options = {}
129129

130+
format, quality = format_options(format, path, options[:quality])
131+
screenshot_options.merge!(quality: quality) if quality
132+
screenshot_options.merge!(format: format)
133+
134+
clip = area_options(options[:full], options[:selector], scale)
135+
screenshot_options.merge!(clip: clip) if clip
136+
137+
screenshot_options
138+
end
139+
140+
def format_options(format, path, quality)
130141
format ||= path ? File.extname(path).delete(".") : "png"
131142
format = "jpeg" if format == "jpg"
132143
raise "Not supported options `:format` #{format}. jpeg | png" if format !~ /jpeg|png/i
133144

134-
options.merge!(format: format)
135-
options.merge!(quality: opts[:quality] || 75) if format == "jpeg"
145+
quality ||= 75 if format == "jpeg"
136146

137-
if opts[:full] && opts[:selector]
138-
warn "Ignoring :selector in #screenshot since full: true was given at #{caller(1..1).first}"
139-
end
147+
[format, quality]
148+
end
140149

141-
if opts[:full]
142-
width, height = document_size
143-
if width.positive? && height.positive?
144-
options.merge!(clip: { x: 0, y: 0,
145-
width: width,
146-
height: height,
147-
scale: scale })
148-
end
149-
elsif opts[:selector]
150-
options.merge!(clip: get_bounding_rect(opts[:selector]).merge(scale: scale))
151-
end
150+
def area_options(full, selector, scale)
151+
message = "Ignoring :selector in #screenshot since full: true was given at #{caller(1..1).first}"
152+
warn(message) if full && selector
153+
154+
clip = if full
155+
width, height = document_size
156+
{ x: 0, y: 0, width: width, height: height, scale: scale } if width.positive? && height.positive?
157+
elsif selector
158+
bounding_rect(selector).merge(scale: scale)
159+
end
152160

153161
if scale != 1
154-
unless options[:clip]
162+
unless clip
155163
width, height = viewport_size
156-
options[:clip] = { x: 0, y: 0, width: width, height: height }
164+
clip = { x: 0, y: 0, width: width, height: height }
157165
end
158166

159-
options[:clip].merge!(scale: scale)
167+
clip.merge!(scale: scale)
160168
end
161169

162-
options
170+
clip
163171
end
164172

165-
def get_bounding_rect(selector)
173+
def bounding_rect(selector)
166174
rect = evaluate_async(%(
167175
const rect = document
168176
.querySelector('#{selector}')

0 commit comments

Comments
 (0)