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

     1  package html
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/MontFerret/ferret/pkg/drivers/common"
     7  
     8  	"github.com/MontFerret/ferret/pkg/drivers"
     9  	"github.com/MontFerret/ferret/pkg/runtime/core"
    10  	"github.com/MontFerret/ferret/pkg/runtime/values"
    11  	"github.com/MontFerret/ferret/pkg/runtime/values/types"
    12  )
    13  
    14  // ATTR_SET sets or updates a single or more attribute(s) of a given element.
    15  // @param {HTMLPage | HTMLDocument | HTMLElement} node - Target node.
    16  // @param {String | Object} nameOrObj - Attribute name or an object representing a key-value pair of attributes.
    17  // @param {String} value - If a second parameter is a string value, this parameter represent an attribute value.
    18  func AttributeSet(ctx context.Context, args ...core.Value) (core.Value, error) {
    19  	err := core.ValidateArgs(args, 2, core.MaxArgs)
    20  
    21  	if err != nil {
    22  		return values.None, err
    23  	}
    24  
    25  	el, err := drivers.ToElement(args[0])
    26  
    27  	if err != nil {
    28  		return values.None, err
    29  	}
    30  
    31  	switch arg1 := args[1].(type) {
    32  	case values.String:
    33  		// ATTR_SET(el, name, value)
    34  		err = core.ValidateArgs(args, 3, 3)
    35  
    36  		if err != nil {
    37  			return values.None, nil
    38  		}
    39  
    40  		switch arg2 := args[2].(type) {
    41  		case values.String:
    42  			return values.None, el.SetAttribute(ctx, arg1, arg2)
    43  		case *values.Object:
    44  			if arg1 == common.AttrNameStyle {
    45  				return values.None, el.SetAttribute(ctx, arg1, common.SerializeStyles(ctx, arg2))
    46  			}
    47  
    48  			return values.None, el.SetAttribute(ctx, arg1, values.NewString(arg2.String()))
    49  		default:
    50  			return values.None, core.TypeError(arg1.Type(), types.String, types.Object)
    51  		}
    52  	case *values.Object:
    53  		// ATTR_SET(el, values)
    54  		return values.None, el.SetAttributes(ctx, arg1)
    55  	default:
    56  		return values.None, core.TypeError(arg1.Type(), types.String, types.Object)
    57  	}
    58  }