@@ -4,25 +4,46 @@ import SwiftSoup
4
4
///
5
5
/// - SeeAlso: W3C [button](https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element) specification.
6
6
@available ( iOS 17 . 0 , macOS 14 . 0 , * )
7
- public struct Button < Content> : View where Content: View {
7
+ public struct Button < Label> : View where Label: View {
8
+ /// Creates a button that displays a custom label and executes a custom action
9
+ /// when clicked.
10
+ public init ( action: String , @ViewBuilder label: @escaping ( ) -> Label ) {
11
+ self . label = label
12
+ self . action = action
13
+ }
14
+
8
15
/// Creates a button that displays a custom label.
9
- public init ( @ViewBuilder content: @escaping ( ) -> Content ) {
10
- self . content = content
16
+ public init ( @ViewBuilder label: @escaping ( ) -> Label ) {
17
+ self . label = label
18
+ self . action = nil
11
19
}
12
20
13
21
/// Creates a button that generates its label from a string.
14
- public init ( _ text: String ) where Content == DOMString {
15
- self . content = {
22
+ public init ( _ text: String ) where Label == DOMString {
23
+ self . label = {
16
24
DOMString ( text)
17
25
}
26
+ self . action = nil
18
27
}
19
28
20
- @_documentation ( visibility: private)
21
- @ViewBuilder public let content : ( ) -> Content
29
+ /// Creates a button that generates its label from a string and executes a custom
30
+ /// action when clicked.
31
+ public init ( _ text: String , action: String ) where Label == DOMString {
32
+ self . label = {
33
+ DOMString ( text)
34
+ }
35
+ self . action = action
36
+ }
37
+
38
+ @ViewBuilder private let label : ( ) -> Label
39
+ private let action : String ?
22
40
23
41
@_documentation ( visibility: private)
24
42
public func render( _ container: Element , environment: EnvironmentValues ) throws {
25
43
let element = try container. appendElement ( " button " )
26
- try self . content ( ) . render ( element, environment: environment)
44
+ if let action {
45
+ try element. attr ( " onclick " , action)
46
+ }
47
+ try self . label ( ) . render ( element, environment: environment)
27
48
}
28
49
}
0 commit comments