actions.js 18.9 KB
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 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

'use strict';

const command = require('./command');
const error = require('./error');
const input = require('./input');


/**
 * @param {!IArrayLike} args .
 * @return {!Array} .
 */
function flatten(args) {
  let result = [];
  for (let i = 0; i < args.length; i++) {
    let element = args[i];
    if (Array.isArray(element)) {
      result.push.apply(result, flatten(element));
    } else {
      result.push(element);
    }
  }
  return result;
}


const MODIFIER_KEYS = new Set([
  input.Key.ALT,
  input.Key.CONTROL,
  input.Key.SHIFT,
  input.Key.COMMAND
]);


/**
 * Checks that a key is a modifier key.
 * @param {!input.Key} key The key to check.
 * @throws {error.InvalidArgumentError} If the key is not a modifier key.
 * @private
 */
function checkModifierKey(key) {
  if (!MODIFIER_KEYS.has(key)) {
    throw new error.InvalidArgumentError('Not a modifier key');
  }
}


/**
 * Class for defining sequences of complex user interactions. Each sequence
 * will not be executed until {@link #perform} is called.
 *
 * Example:
 *
 *     new ActionSequence(driver).
 *         keyDown(Key.SHIFT).
 *         click(element1).
 *         click(element2).
 *         dragAndDrop(element3, element4).
 *         keyUp(Key.SHIFT).
 *         perform();
 *
 */
class ActionSequence {
  /**
   * @param {!./webdriver.WebDriver} driver The driver that should be used to
   *     perform this action sequence.
   */
  constructor(driver) {
    /** @private {!./webdriver.WebDriver} */
    this.driver_ = driver;

    /** @private {!Array<{description: string, command: !command.Command}>} */
    this.actions_ = [];
  }

  /**
   * Schedules an action to be executed each time {@link #perform} is called on
   * this instance.
   *
   * @param {string} description A description of the command.
   * @param {!command.Command} command The command.
   * @private
   */
  schedule_(description, command) {
    this.actions_.push({
      description: description,
      command: command
    });
  }

  /**
   * Executes this action sequence.
   *
   * @return {!./promise.Promise} A promise that will be resolved once
   *     this sequence has completed.
   */
  perform() {
    // Make a protected copy of the scheduled actions. This will protect against
    // users defining additional commands before this sequence is actually
    // executed.
    let actions = this.actions_.concat();
    let driver = this.driver_;
    return driver.controlFlow().execute(function() {
      actions.forEach(function(action) {
        driver.schedule(action.command, action.description);
      });
    }, 'ActionSequence.perform');
  }

  /**
   * Moves the mouse.  The location to move to may be specified in terms of the
   * mouse's current location, an offset relative to the top-left corner of an
   * element, or an element (in which case the middle of the element is used).
   *
   * @param {(!./webdriver.WebElement|{x: number, y: number})} location The
   *     location to drag to, as either another WebElement or an offset in
   *     pixels.
   * @param {{x: number, y: number}=} opt_offset If the target {@code location}
   *     is defined as a {@link ./webdriver.WebElement}, this parameter defines
   *     an offset within that element. The offset should be specified in pixels
   *     relative to the top-left corner of the element's bounding box. If
   *     omitted, the element's center will be used as the target offset.
   * @return {!ActionSequence} A self reference.
   */
  mouseMove(location, opt_offset) {
    let cmd = new command.Command(command.Name.MOVE_TO);

    if (typeof location.x === 'number') {
      setOffset(/** @type {{x: number, y: number}} */(location));
    } else {
      cmd.setParameter('element', location.getRawId());
      if (opt_offset) {
        setOffset(opt_offset);
      }
    }

    this.schedule_('mouseMove', cmd);
    return this;

    /** @param {{x: number, y: number}} offset The offset to use. */
    function setOffset(offset) {
      cmd.setParameter('xoffset', offset.x || 0);
      cmd.setParameter('yoffset', offset.y || 0);
    }
  }

  /**
   * Schedules a mouse action.
   * @param {string} description A simple descriptive label for the scheduled
   *     action.
   * @param {!command.Name} commandName The name of the command.
   * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either
   *     the element to interact with or the button to click with.
   *     Defaults to {@link input.Button.LEFT} if neither an element nor
   *     button is specified.
   * @param {input.Button=} opt_button The button to use. Defaults to
   *     {@link input.Button.LEFT}. Ignored if the previous argument is
   *     provided as a button.
   * @return {!ActionSequence} A self reference.
   * @private
   */
  scheduleMouseAction_(
      description, commandName, opt_elementOrButton, opt_button) {
    let button;
    if (typeof opt_elementOrButton === 'number') {
      button = opt_elementOrButton;
    } else {
      if (opt_elementOrButton) {
        this.mouseMove(
            /** @type {!./webdriver.WebElement} */ (opt_elementOrButton));
      }
      button = opt_button !== void(0) ? opt_button : input.Button.LEFT;
    }

    let cmd = new command.Command(commandName).
        setParameter('button', button);
    this.schedule_(description, cmd);
    return this;
  }

  /**
   * Presses a mouse button. The mouse button will not be released until
   * {@link #mouseUp} is called, regardless of whether that call is made in this
   * sequence or another. The behavior for out-of-order events (e.g. mouseDown,
   * click) is undefined.
   *
   * If an element is provided, the mouse will first be moved to the center
   * of that element. This is equivalent to:
   *
   *     sequence.mouseMove(element).mouseDown()
   *
   * Warning: this method currently only supports the left mouse button. See
   * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047).
   *
   * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either
   *     the element to interact with or the button to click with.
   *     Defaults to {@link input.Button.LEFT} if neither an element nor
   *     button is specified.
   * @param {input.Button=} opt_button The button to use. Defaults to
   *     {@link input.Button.LEFT}. Ignored if a button is provided as the
   *     first argument.
   * @return {!ActionSequence} A self reference.
   */
  mouseDown(opt_elementOrButton, opt_button) {
    return this.scheduleMouseAction_('mouseDown',
        command.Name.MOUSE_DOWN, opt_elementOrButton, opt_button);
  }

  /**
   * Releases a mouse button. Behavior is undefined for calling this function
   * without a previous call to {@link #mouseDown}.
   *
   * If an element is provided, the mouse will first be moved to the center
   * of that element. This is equivalent to:
   *
   *     sequence.mouseMove(element).mouseUp()
   *
   * Warning: this method currently only supports the left mouse button. See
   * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047).
   *
   * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either
   *     the element to interact with or the button to click with.
   *     Defaults to {@link input.Button.LEFT} if neither an element nor
   *     button is specified.
   * @param {input.Button=} opt_button The button to use. Defaults to
   *     {@link input.Button.LEFT}. Ignored if a button is provided as the
   *     first argument.
   * @return {!ActionSequence} A self reference.
   */
  mouseUp(opt_elementOrButton, opt_button) {
    return this.scheduleMouseAction_('mouseUp',
        command.Name.MOUSE_UP, opt_elementOrButton, opt_button);
  }

  /**
   * Convenience function for performing a "drag and drop" manuever. The target
   * element may be moved to the location of another element, or by an offset (in
   * pixels).
   *
   * @param {!./webdriver.WebElement} element The element to drag.
   * @param {(!./webdriver.WebElement|{x: number, y: number})} location The
   *     location to drag to, either as another WebElement or an offset in
   *     pixels.
   * @return {!ActionSequence} A self reference.
   */
  dragAndDrop(element, location) {
    return this.mouseDown(element).mouseMove(location).mouseUp();
  }

  /**
   * Clicks a mouse button.
   *
   * If an element is provided, the mouse will first be moved to the center
   * of that element. This is equivalent to:
   *
   *     sequence.mouseMove(element).click()
   *
   * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either
   *     the element to interact with or the button to click with.
   *     Defaults to {@link input.Button.LEFT} if neither an element nor
   *     button is specified.
   * @param {input.Button=} opt_button The button to use. Defaults to
   *     {@link input.Button.LEFT}. Ignored if a button is provided as the
   *     first argument.
   * @return {!ActionSequence} A self reference.
   */
  click(opt_elementOrButton, opt_button) {
    return this.scheduleMouseAction_('click',
        command.Name.CLICK, opt_elementOrButton, opt_button);
  }

  /**
   * Double-clicks a mouse button.
   *
   * If an element is provided, the mouse will first be moved to the center of
   * that element. This is equivalent to:
   *
   *     sequence.mouseMove(element).doubleClick()
   *
   * Warning: this method currently only supports the left mouse button. See
   * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047).
   *
   * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either
   *     the element to interact with or the button to click with.
   *     Defaults to {@link input.Button.LEFT} if neither an element nor
   *     button is specified.
   * @param {input.Button=} opt_button The button to use. Defaults to
   *     {@link input.Button.LEFT}. Ignored if a button is provided as the
   *     first argument.
   * @return {!ActionSequence} A self reference.
   */
  doubleClick(opt_elementOrButton, opt_button) {
    return this.scheduleMouseAction_('doubleClick',
        command.Name.DOUBLE_CLICK, opt_elementOrButton, opt_button);
  }

  /**
   * Schedules a keyboard action.
   *
   * @param {string} description A simple descriptive label for the scheduled
   *     action.
   * @param {!Array<(string|!input.Key)>} keys The keys to send.
   * @return {!ActionSequence} A self reference.
   * @private
   */
  scheduleKeyboardAction_(description, keys) {
    let cmd = new command.Command(command.Name.SEND_KEYS_TO_ACTIVE_ELEMENT)
        .setParameter('value', keys);
    this.schedule_(description, cmd);
    return this;
  }

  /**
   * Performs a modifier key press. The modifier key is <em>not released</em>
   * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be
   * targetted at the currently focused element.
   *
   * @param {!input.Key} key The modifier key to push. Must be one of
   *     {ALT, CONTROL, SHIFT, COMMAND, META}.
   * @return {!ActionSequence} A self reference.
   * @throws {error.InvalidArgumentError} If the key is not a valid modifier
   *     key.
   */
  keyDown(key) {
    checkModifierKey(key);
    return this.scheduleKeyboardAction_('keyDown', [key]);
  }

  /**
   * Performs a modifier key release. The release is targetted at the currently
   * focused element.
   * @param {!input.Key} key The modifier key to release. Must be one of
   *     {ALT, CONTROL, SHIFT, COMMAND, META}.
   * @return {!ActionSequence} A self reference.
   * @throws {error.InvalidArgumentError} If the key is not a valid modifier
   *     key.
   */
  keyUp(key) {
    checkModifierKey(key);
    return this.scheduleKeyboardAction_('keyUp', [key]);
  }

  /**
   * Simulates typing multiple keys. Each modifier key encountered in the
   * sequence will not be released until it is encountered again. All key events
   * will be targetted at the currently focused element.
   *
   * @param {...(string|!input.Key|!Array<(string|!input.Key)>)} var_args
   *     The keys to type.
   * @return {!ActionSequence} A self reference.
   * @throws {Error} If the key is not a valid modifier key.
   */
  sendKeys(var_args) {
    let keys = flatten(arguments);
    return this.scheduleKeyboardAction_('sendKeys', keys);
  }
}


/**
 * Class for defining sequences of user touch interactions. Each sequence
 * will not be executed until {@link #perform} is called.
 *
 * Example:
 *
 *     new TouchSequence(driver).
 *         tapAndHold({x: 0, y: 0}).
 *         move({x: 3, y: 4}).
 *         release({x: 10, y: 10}).
 *         perform();
 *
 */
class TouchSequence {
  /**
   * @param {!./webdriver.WebDriver} driver The driver that should be used to
   *     perform this action sequence.
   */
  constructor(driver) {
    /** @private {!./webdriver.WebDriver} */
    this.driver_ = driver;

    /** @private {!Array<{description: string, command: !command.Command}>} */
    this.actions_ = [];
  }

  /**
   * Schedules an action to be executed each time {@link #perform} is called on
   * this instance.
   * @param {string} description A description of the command.
   * @param {!command.Command} command The command.
   * @private
   */
  schedule_(description, command) {
    this.actions_.push({
      description: description,
      command: command
    });
  }

  /**
   * Executes this action sequence.
   * @return {!./promise.Promise} A promise that will be resolved once
   *     this sequence has completed.
   */
  perform() {
    // Make a protected copy of the scheduled actions. This will protect against
    // users defining additional commands before this sequence is actually
    // executed.
    let actions = this.actions_.concat();
    let driver = this.driver_;
    return driver.controlFlow().execute(function() {
      actions.forEach(function(action) {
        driver.schedule(action.command, action.description);
      });
    }, 'TouchSequence.perform');
  }

  /**
   * Taps an element.
   *
   * @param {!./webdriver.WebElement} elem The element to tap.
   * @return {!TouchSequence} A self reference.
   */
  tap(elem) {
    let cmd = new command.Command(command.Name.TOUCH_SINGLE_TAP).
        setParameter('element', elem.getId());

    this.schedule_('tap', cmd);
    return this;
  }

  /**
   * Double taps an element.
   *
   * @param {!./webdriver.WebElement} elem The element to double tap.
   * @return {!TouchSequence} A self reference.
   */
  doubleTap(elem) {
    let cmd = new command.Command(command.Name.TOUCH_DOUBLE_TAP).
        setParameter('element', elem.getId());

    this.schedule_('doubleTap', cmd);
    return this;
  }

  /**
   * Long press on an element.
   *
   * @param {!./webdriver.WebElement} elem The element to long press.
   * @return {!TouchSequence} A self reference.
   */
  longPress(elem) {
    let cmd = new command.Command(command.Name.TOUCH_LONG_PRESS).
        setParameter('element', elem.getId());

    this.schedule_('longPress', cmd);
    return this;
  }

  /**
   * Touch down at the given location.
   *
   * @param {{x: number, y: number}} location The location to touch down at.
   * @return {!TouchSequence} A self reference.
   */
  tapAndHold(location) {
    let cmd = new command.Command(command.Name.TOUCH_DOWN).
        setParameter('x', location.x).
        setParameter('y', location.y);

    this.schedule_('tapAndHold', cmd);
    return this;
  }

  /**
   * Move a held {@linkplain #tapAndHold touch} to the specified location.
   *
   * @param {{x: number, y: number}} location The location to move to.
   * @return {!TouchSequence} A self reference.
   */
  move(location) {
    let cmd = new command.Command(command.Name.TOUCH_MOVE).
        setParameter('x', location.x).
        setParameter('y', location.y);

    this.schedule_('move', cmd);
    return this;
  }

  /**
   * Release a held {@linkplain #tapAndHold touch} at the specified location.
   *
   * @param {{x: number, y: number}} location The location to release at.
   * @return {!TouchSequence} A self reference.
   */
  release(location) {
    let cmd = new command.Command(command.Name.TOUCH_UP).
        setParameter('x', location.x).
        setParameter('y', location.y);

    this.schedule_('release', cmd);
    return this;
  }

  /**
   * Scrolls the touch screen by the given offset.
   *
   * @param {{x: number, y: number}} offset The offset to scroll to.
   * @return {!TouchSequence} A self reference.
   */
  scroll(offset) {
    let cmd = new command.Command(command.Name.TOUCH_SCROLL).
        setParameter('xoffset', offset.x).
        setParameter('yoffset', offset.y);

    this.schedule_('scroll', cmd);
    return this;
  }

  /**
   * Scrolls the touch screen, starting on `elem` and moving by the specified
   * offset.
   *
   * @param {!./webdriver.WebElement} elem The element where scroll starts.
   * @param {{x: number, y: number}} offset The offset to scroll to.
   * @return {!TouchSequence} A self reference.
   */
  scrollFromElement(elem, offset) {
    let cmd = new command.Command(command.Name.TOUCH_SCROLL).
        setParameter('element', elem.getId()).
        setParameter('xoffset', offset.x).
        setParameter('yoffset', offset.y);

    this.schedule_('scrollFromElement', cmd);
    return this;
  }

  /**
   * Flick, starting anywhere on the screen, at speed xspeed and yspeed.
   *
   * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each
         direction, in pixels per second.
   * @return {!TouchSequence} A self reference.
   */
  flick(speed) {
    let cmd = new command.Command(command.Name.TOUCH_FLICK).
        setParameter('xspeed', speed.xspeed).
        setParameter('yspeed', speed.yspeed);

    this.schedule_('flick', cmd);
    return this;
  }

  /**
   * Flick starting at elem and moving by x and y at specified speed.
   *
   * @param {!./webdriver.WebElement} elem The element where flick starts.
   * @param {{x: number, y: number}} offset The offset to flick to.
   * @param {number} speed The speed to flick at in pixels per second.
   * @return {!TouchSequence} A self reference.
   */
  flickElement(elem, offset, speed) {
    let cmd = new command.Command(command.Name.TOUCH_FLICK).
        setParameter('element', elem.getId()).
        setParameter('xoffset', offset.x).
        setParameter('yoffset', offset.y).
        setParameter('speed', speed);

    this.schedule_('flickElement', cmd);
    return this;
  }
}


// PUBLIC API

module.exports = {
  ActionSequence: ActionSequence,
  TouchSequence: TouchSequence,
};