github.com/MontFerret/ferret@v0.18.0/pkg/stdlib/html/wait_element.go (about)

     1  package html
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/drivers"
     7  	"github.com/MontFerret/ferret/pkg/runtime/core"
     8  	"github.com/MontFerret/ferret/pkg/runtime/values"
     9  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    10  )
    11  
    12  // WAIT_ELEMENT waits for element to appear in the DOM.
    13  // Stops the execution until it finds an element or operation times out.
    14  // @param {HTMLPage | HTMLDocument | HTMLElement} node - Target html node.
    15  // @param {String} selector - Target element's selector.
    16  // @param {Int} [timeout=5000] - Wait timeout.
    17  func WaitElement(ctx context.Context, args ...core.Value) (core.Value, error) {
    18  	return waitElementWhen(ctx, args, drivers.WaitEventPresence)
    19  }
    20  
    21  // WAIT_NO_ELEMENT waits for element to disappear in the DOM.
    22  // Stops the execution until it does not find an element or operation times out.
    23  // @param {HTMLPage | HTMLDocument | HTMLElement} node - Target html node.
    24  // @param {String} selector - Target element's selector.
    25  // @param {Int} [timeout=5000] - Wait timeout.
    26  func WaitNoElement(ctx context.Context, args ...core.Value) (core.Value, error) {
    27  	return waitElementWhen(ctx, args, drivers.WaitEventAbsence)
    28  }
    29  
    30  func waitElementWhen(ctx context.Context, args []core.Value, when drivers.WaitEvent) (core.Value, error) {
    31  	err := core.ValidateArgs(args, 2, 3)
    32  
    33  	if err != nil {
    34  		return values.None, err
    35  	}
    36  
    37  	el, err := drivers.ToElement(args[0])
    38  
    39  	if err != nil {
    40  		return values.None, err
    41  	}
    42  
    43  	selector, err := drivers.ToQuerySelector(args[1])
    44  
    45  	if err != nil {
    46  		return values.None, err
    47  	}
    48  
    49  	timeout := values.NewInt(drivers.DefaultWaitTimeout)
    50  
    51  	if len(args) > 2 {
    52  		err = core.ValidateType(args[2], types.Int)
    53  
    54  		if err != nil {
    55  			return values.None, err
    56  		}
    57  
    58  		timeout = args[2].(values.Int)
    59  	}
    60  
    61  	ctx, fn := waitTimeout(ctx, timeout)
    62  	defer fn()
    63  
    64  	return values.True, el.WaitForElement(ctx, selector, when)
    65  }