2018-09-18 22:42:38 +02:00
|
|
|
package html
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2018-10-14 19:06:27 +02:00
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/drivers"
|
2018-09-18 22:42:38 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
2019-02-13 19:31:18 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values/types"
|
2018-09-18 22:42:38 +02:00
|
|
|
)
|
|
|
|
|
2019-06-19 23:58:56 +02:00
|
|
|
// GetElement finds an element by a given CSS selector.
|
2018-10-14 19:06:27 +02:00
|
|
|
// Returns NONE if element not found.
|
|
|
|
// @param docOrEl (HTMLDocument|HTMLElement) - Parent document or element.
|
|
|
|
// @param selector (String) - CSS selector.
|
|
|
|
// @returns (HTMLElement | None) - Returns an HTMLElement if found, otherwise NONE.
|
2019-02-21 04:24:05 +02:00
|
|
|
func Element(ctx context.Context, args ...core.Value) (core.Value, error) {
|
2018-10-07 04:33:39 +02:00
|
|
|
el, selector, err := queryArgs(args)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return values.None, err
|
|
|
|
}
|
|
|
|
|
2019-09-07 03:02:41 +02:00
|
|
|
return el.QuerySelector(ctx, selector)
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2019-06-19 23:58:56 +02:00
|
|
|
func queryArgs(args []core.Value) (drivers.HTMLElement, values.String, error) {
|
2018-10-07 04:33:39 +02:00
|
|
|
err := core.ValidateArgs(args, 2, 2)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
|
|
|
if err != nil {
|
2018-10-07 04:33:39 +02:00
|
|
|
return nil, values.EmptyString, err
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2019-06-19 23:58:56 +02:00
|
|
|
el, err := drivers.ToElement(args[0])
|
2018-09-18 22:42:38 +02:00
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, values.EmptyString, err
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2019-02-13 19:31:18 +02:00
|
|
|
err = core.ValidateType(args[1], types.String)
|
2018-09-18 22:42:38 +02:00
|
|
|
|
2018-10-07 04:33:39 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, values.EmptyString, err
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|
|
|
|
|
2019-06-19 23:58:56 +02:00
|
|
|
return el, args[1].(values.String), nil
|
2018-09-18 22:42:38 +02:00
|
|
|
}
|