github.com/MontFerret/ferret@v0.18.0/pkg/drivers/cdp/templates/select.go (about)

     1  package templates
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/mafredri/cdp/protocol/runtime"
     7  
     8  	"github.com/MontFerret/ferret/pkg/drivers"
     9  	"github.com/MontFerret/ferret/pkg/drivers/cdp/eval"
    10  	"github.com/MontFerret/ferret/pkg/runtime/values"
    11  )
    12  
    13  const selectFragment = `
    14  	if (found.nodeName.toLowerCase() !== 'select') {
    15  		throw new Error('element is not a <select> element.');
    16  	}
    17  
    18  	const options = Array.from(found.options);
    19  
    20  	found.value = undefined;
    21  
    22  	for (var option of options) {
    23  		option.selected = values.includes(option.value);
    24  	
    25  		if (option.selected && !found.multiple) {
    26  			break;
    27  		}
    28  	}
    29  
    30  	found.dispatchEvent(new Event('input', { 'bubbles': true }));
    31  	found.dispatchEvent(new Event('change', { 'bubbles': true }));
    32  	
    33  	return options.filter(option => option.selected).map(option => option.value);
    34  `
    35  
    36  var selekt = fmt.Sprintf(`(el, values) => {
    37  const found = el;
    38  
    39  %s
    40  }`, selectFragment)
    41  
    42  func Select(id runtime.RemoteObjectID, inputs *values.Array) *eval.Function {
    43  	return eval.F(selekt).WithArgRef(id).WithArgValue(inputs)
    44  }
    45  
    46  var (
    47  	selectByCSSSelector = fmt.Sprintf(`(el, selector, values) => {
    48  	%s
    49  	
    50  	%s
    51  
    52  	%s
    53  }`, queryCSSSelectorFragment, notFoundErrorFragment, selectFragment)
    54  
    55  	selectByXPathSelector = fmt.Sprintf(`(el, selector, values) => {
    56  	%s
    57  	
    58  	%s
    59  
    60  	%s
    61  }`, xpathAsElementFragment, notFoundErrorFragment, selectFragment)
    62  )
    63  
    64  func SelectBySelector(id runtime.RemoteObjectID, selector drivers.QuerySelector, inputs *values.Array) *eval.Function {
    65  	return toFunction(selector, selectByCSSSelector, selectByXPathSelector).
    66  		WithArgRef(id).
    67  		WithArgSelector(selector).
    68  		WithArgValue(inputs)
    69  }