001/*
002 * (C) Copyright 2015-2016 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.nuxeo.functionaltests;
017
018import org.openqa.selenium.JavascriptExecutor;
019import org.openqa.selenium.NoSuchElementException;
020import org.openqa.selenium.WebDriver;
021
022import com.google.common.base.Function;
023
024/**
025 * @since 7.10
026 */
027public class EventListener {
028
029    private static int COUNT = 0;
030
031    private final String id = "evt_listener_" + COUNT++;
032
033    private final String event;
034
035    private final String selector;
036
037    private final JavascriptExecutor js;
038
039    public EventListener(WebDriver driver, String event, String selector) {
040        super();
041        this.event = event;
042        this.selector = selector;
043        js = (JavascriptExecutor) driver;
044        listen();
045    }
046
047    public void listen() {
048        StringBuilder sb = new StringBuilder();
049        sb.append("window." + id + " = 0;");
050        sb.append("var els = document.querySelectorAll('" + selector + "');");
051        sb.append("for (var i=0; i<els.length; i++) {");
052        sb.append("  els[i].addEventListener('" + event + "', function(e) { window." + id + "++; });");
053        sb.append("}");
054        js.executeScript(sb.toString());
055    }
056
057    public void waitCalled() {
058        waitCalled(1);
059    }
060
061    public void waitCalled(int times) {
062        waitUntil(driver -> (Boolean) js.executeScript("return window." + id + " == " + times + ";"));
063    }
064
065    public void reset() {
066        js.executeScript("window." + id + " = 0;");
067    }
068
069    private void waitUntil(Function<WebDriver, Boolean> function) {
070        Locator.waitUntilGivenFunctionIgnoring(function, NoSuchElementException.class);
071    }
072
073}