This repository has been archived by the owner on Dec 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 520
/
browser.coffee
388 lines (349 loc) · 13.4 KB
/
browser.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
jsdom = require("jsdom")
require "./jsdom_patches"
require "./sizzle"
require "./forms"
# Use the browser to open up new windows and load documents.
#
# The browser maintains state for cookies and localStorage.
class Browser
constructor: ->
cookies = require("./cookies").use(this)
storage = require("./storage").use(this)
eventloop = require("./eventloop").use(this)
history = require("./history").use(this)
xhr = require("./xhr").use(this)
window = null
# ### browser.open() => Window
#
# Open new browser window.
this.open = ->
window = jsdom.createWindow(jsdom.dom.level3.html)
window.__defineGetter__ "browser", => this
cookies.extend window
storage.extend window
eventloop.extend window
history.extend window
xhr.extend window
# TODO: Fix
window.Image = ->
window.JSON = JSON
return window
# Always start with an open window.
@open()
# Events
# ------
# ### browser.wait(callback)
# ### browser.wait(terminator, callback)
#
# Process all events from the queue. This method returns immediately, events
# are processed in the background. When all events are exhausted, it calls
# the callback with `null, browser`; if any event fails, it calls the
# callback with the exception.
#
# With one argument, that argument is the callback. With two arguments, the
# first argument is a terminator and the last argument is the callback. The
# terminator is one of:
# - null -- process all events
# - number -- process that number of events
# - function -- called after each event, stop processing when function
# returns false
#
# Events include timeout, interval and XHR `onreadystatechange`. DOM events
# are handled synchronously.
this.wait = (terminate, callback)->
if !callback
callback = terminate
terminate = null
eventloop.wait window, terminate, (err) => callback err, this
return
# ### browser.fire(name, target, calback?)
#
# Fire a DOM event. You can use this to simulate a DOM event, e.g. clicking a
# link. These events will bubble up and can be cancelled. With a callback, this
# function will call `wait`.
#
# name -- Even name (e.g `click`)
# target -- Target element (e.g a link)
# callback -- Wait for events to be processed, then call me (optional)
this.fire = (name, target, callback)->
event = window.document.createEvent("HTMLEvents")
event.initEvent name, true, true
target.dispatchEvent event
@wait callback if callback
# ### browser.clock => Number
#
# The current system time according to the browser (see also
# `browser.clock`).
#
# You can change this to advance the system clock during tests. It will
# also advance when handling timeout/interval events.
@clock = new Date().getTime()
# ### browser.now => Date
#
# The current system time according to the browser (see also
# `browser.clock`).
@__defineGetter__ "now", -> new Date(clock)
# Accessors
# ---------
# ### browser.find(selector, context?) => [Elements]
#
# Returns an array of all the elements that match the selector. Without
# context, searches through the entire document.
#
# selector -- CSS selector
# context -- Context element (if missing, uses document)
# Returns an array of elements
this.find = (selector, context)-> window.document?.find(selector, context)
# ### browser.text(selector, context?) => String
#
# Returns the text contents of the selected elements (see also
# `browser.find`).
#
# selector -- CSS selector
# context -- Context element (if missing, uses document)
# Returns a string
this.text = (selector, context)->
elements = @find(selector || "body", context)
window.Sizzle?.getText(elements)
# ### browser.html(selector?, context?) => String
#
# Returns the HTML contents of the selected elements (see also
# `browser.find`).
#
# selector -- CSS selector
# context -- Context element (if missing, uses document)
# Returns a string
this.html = (selector, context)->
if selector
@find(selector, context).map((elem)-> elem.outerHTML).join("")
else
return window.document.outerHTML
# ### browser.window => Window
#
# Returns the main window.
@__defineGetter__ "window", -> window
# ### browser.document => Document
#
# Returns the main window's document. Only valid after opening a document
# (see `browser.open`).
@__defineGetter__ "document", -> window?.document
# ### browser.body => Element
#
# Returns the body Element of the current document.
@__defineGetter__ "body", -> window.document?.find("body")[0]
# Navigation
# ----------
# ### browser.visit(url, callback)
#
# Loads document from the specified URL, processes events and calls the
# callback.
#
# If it fails to download, calls the callback with the error.
this.visit = (url, callback)->
history._assign url
window.addEventListener "error", (err)-> callback err
window.document.addEventListener "DOMContentLoaded", => @wait callback
return
# ### browser.location => Location
#
# Return the location of the current document (same as `window.location.href`).
@__defineGetter__ "location", -> window.location.href
# ### browser.location = url
#
# Changes document location, loads new document if necessary (same as
# setting `window.location`).
@__defineSetter__ "location", (url)-> window.location = url
# Forms
# -----
# ### browser.clickLink(selector, callback)
#
# Clicks on a link. Clicking on a link can trigger other events, load new
# page, etc: use a callback to be notified of completion. Finds link by
# text content or selector.
#
# selector -- CSS selector or link text
# callback -- Called with two arguments: error and browser
this.clickLink = (selector, callback)->
if link = @find(selector)[0]
@fire "click", link, callback if link
return
for link in @find("body a")
if window.Sizzle.getText([link]).trim() == selector
@fire "click", link, callback
return
return
# Forms
# -----
# HTML5 field types that you can "fill in".
textTypes = "email number password range search text url".split(" ")
# Find input field from selector, name or label.
findInput = (selector, match)=>
# Try more specific selector first.
fields = @find(selector)
return fields[0] if fields[0] && match(fields[0])
# Use field name (case sensitive).
fields = @find("[name='#{selector}']")
return fields[0] if fields[0] && match(fields[0])
# Try finding field from label.
for label in @find("label")
text = ""
for c in label.children
text = text + c.nodeValue if c.nodeType == 3
if text.trim() == selector
# Label can either reference field or enclose it
if for_attr = label.getAttribute("for")
fields = @find("#" + for_attr)
else
fields = @find("input, textarea, select", label)
return fields[0] if fields[0] && match(fields[0])
# ### browser.fill(field, value) => this
#
# Fill in a field: input field or text area.
#
# field -- CSS selector, field name or text of the field label
# value -- Field value
# Returns this
this.fill = (field, value)->
match = (elem)-> elem.nodeName == "TEXTAREA" || textTypes.indexOf(elem.type?.toLowerCase()) >= 0
if input = findInput(field, match)
throw new Error("This INPUT field is disabled") if input.getAttribute("input")
throw new Error("This INPUT field is readonly") if input.getAttribute("readonly")
input.value = value
@fire "change", input
return this
throw new Error("No INPUT matching '#{field}'")
setCheckbox = (field, state)=>
match = (elem)-> elem.nodeName == "INPUT" && elem.type == "checkbox"
if input = findInput(field, match)
throw new Error("This INPUT field is disabled") if input.getAttribute("input")
throw new Error("This INPUT field is readonly") if input.getAttribute("readonly")
input.checked = state
@fire "change", input
@fire "click", input
return this
else
throw new Error("No checkbox INPUT matching '#{field}'")
# ### browser.check(field) => this
#
# Checks a checkbox.
#
# field -- CSS selector, field name or text of the field label
# Returns this
this.check = (field)-> setCheckbox field, true
# ### browser.uncheck(field) => this
#
# Unchecks a checkbox.
#
# field -- CSS selector, field name or text of the field label
# Returns this
this.uncheck = (field)-> setCheckbox field, false
# ### browser.choose(field) => this
#
# Selects a radio box option.
#
# field -- CSS selector, field value or text of the field label
# Returns this
this.choose = (field)->
match = (elem)-> elem.nodeName == "INPUT" && elem.type?.toLowerCase() == "radio"
input = findInput(field, match) || @find(":radio[value='#{field}']")[0]
if input
radios = @find(":radio[name='#{input.getAttribute("name")}']", input.form)
for radio in radios
throw new Error("This INPUT field is disabled") if radio.getAttribute("input")
throw new Error("This INPUT field is readonly") if radio.getAttribute("readonly")
radio.checked = false for radio in radios
input.checked = true
@fire "change", input
@fire "click", input
return this
else
throw new Error("No radio INPUT matching '#{field}'")
# ### browser.select(field, value) => this
#
# Selects an option.
#
# field -- CSS selector, field name or text of the field label
# value -- Value (or label) or option to select
# Returns this
this.select = (field, value)->
match = (elem)-> elem.nodeName == "SELECT"
if select = findInput(field, match)
throw new Error("This SELECT field is disabled") if select.getAttribute("disabled")
for option in select.options
if option.value == value
select.value = option.value
@fire "change", select
return this
for option in select.options
if option.label == value
select.value = option.value
@fire "change", select
return this
throw new Error("No OPTION '#{value}'")
else
throw new Error("No SELECT matching '#{field}'")
# ### browser.pressButton(name, callback)
#
# Press a button (button element or input of type `submit`). Typically
# this will submit the form. Use the callback to wait for the from
# submission, page to load and all events run their course.
#
# name -- CSS selector, button name or text of BUTTON element
# callback -- Called with two arguments: error and browser
this.pressButton = (name, callback)->
if button = @find(name).first
button.click()
return @wait(callback)
for button in @find("form button")
continue if button.getAttribute("disabled")
if window.Sizzle.getText([button]).trim() == name
@fire "click", button
return @wait(callback)
for input in @find("form :submit")
continue if input.getAttribute("disabled")
if input.name == name
input.click()
return @wait(callback)
for input in @find("form :submit")
continue if input.getAttribute("disabled")
if input.value == name
input.click()
return @wait(callback)
throw new Error("No BUTTON '#{name}'")
# Cookies and storage
# -------------------
# ### browser.cookies(domain, path) => Cookies
#
# Returns all the cookies for this domain/path. Path defaults to "/".
this.cookies = (domain, path)-> cookies.access(domain, path)
# ### brower.localStorage(host) => Storage
#
# Returns local Storage based on the document origin (hostname/port). This
# is the same storage area you can access from any document of that origin.
this.localStorage = (host)-> storage.local(host)
# ### brower.sessionStorage(host) => Storage
#
# Returns session Storage based on the document origin (hostname/port). This
# is the same storage area you can access from any document of that origin.
this.sessionStorage = (host)-> storage.session(host)
# Debugging
# ---------
trail = []
this.record = (request)->
trail.push pending = { request: request }
pending
# ### browser.last_request => Object
#
# Returns the last request sent by this browser. The object will have the
# properties url, method, headers, and if applicable, body.
@__defineGetter__ "last_request", -> trail[trail.length - 1]?.request
# ### browser.last_response => Object
#
# Returns the last response received by this browser. The object will have the
# properties status, headers and body. Long bodies may be truncated.
@__defineGetter__ "last_response", -> trail[trail.length - 1]?.response
# ### browser.last_error => Object
#
# Returns the last error received by this browser in lieu of response.
@__defineGetter__ "last_error", -> trail[trail.length - 1]?.error
exports.Browser = Browser