summaryrefslogtreecommitdiff
path: root/vendor/github.com/playwright-community/playwright-go/selectors.go
blob: 1151647818a937d6c4fddcd5e6ca0ac9a5a7db74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package playwright

import (
	"errors"
	"os"
	"sync"
)

type selectorsOwnerImpl struct {
	channelOwner
}

func (s *selectorsOwnerImpl) setTestIdAttributeName(name string) {
	s.channel.SendNoReply("setTestIdAttributeName", map[string]interface{}{
		"testIdAttributeName": name,
	})
}

func newSelectorsOwner(parent *channelOwner, objectType string, guid string, initializer map[string]interface{}) *selectorsOwnerImpl {
	obj := &selectorsOwnerImpl{}
	obj.createChannelOwner(obj, parent, objectType, guid, initializer)
	return obj
}

type selectorsImpl struct {
	channels      sync.Map
	registrations []map[string]interface{}
}

func (s *selectorsImpl) Register(name string, script Script, options ...SelectorsRegisterOptions) error {
	if script.Path == nil && script.Content == nil {
		return errors.New("Either source or path should be specified")
	}
	source := ""
	if script.Path != nil {
		content, err := os.ReadFile(*script.Path)
		if err != nil {
			return err
		}
		source = string(content)
	} else {
		source = *script.Content
	}
	params := map[string]interface{}{
		"name":   name,
		"source": source,
	}
	if len(options) == 1 && options[0].ContentScript != nil {
		params["contentScript"] = *options[0].ContentScript
	}
	var err error
	s.channels.Range(func(key, value any) bool {
		_, err = value.(*selectorsOwnerImpl).channel.Send("register", params)
		return err == nil
	})
	if err != nil {
		return err
	}
	s.registrations = append(s.registrations, params)
	return nil
}

func (s *selectorsImpl) SetTestIdAttribute(name string) {
	setTestIdAttributeName(name)
	s.channels.Range(func(key, value any) bool {
		value.(*selectorsOwnerImpl).setTestIdAttributeName(name)
		return true
	})
}

func (s *selectorsImpl) addChannel(channel *selectorsOwnerImpl) {
	s.channels.Store(channel.guid, channel)
	for _, params := range s.registrations {
		channel.channel.SendNoReply("register", params)
		channel.setTestIdAttributeName(getTestIdAttributeName())
	}
}

func (s *selectorsImpl) removeChannel(channel *selectorsOwnerImpl) {
	s.channels.Delete(channel.guid)
}

func newSelectorsImpl() *selectorsImpl {
	return &selectorsImpl{
		channels:      sync.Map{},
		registrations: make([]map[string]interface{}, 0),
	}
}