Skip to content

Commit

Permalink
[feature] Add autofocus support to TextField. (#156)
Browse files Browse the repository at this point in the history
  • Loading branch information
jverkoey authored Aug 10, 2024
1 parent abf40c1 commit 4fbe98a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
13 changes: 12 additions & 1 deletion Sources/Slipstream/W3C/Elements/Forms/TextField.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,27 @@ import SwiftSoup
@available(iOS 17.0, macOS 14.0, *)
public struct TextField: View {
/// Creates a text field with a text label.
public init(_ text: String) {
///
/// - Parameters:
/// - text: The placeholder text to display in the text field when it is empty.
/// - autoFocus: If true, indicates that the view should be focused as soon as
/// the page is loaded, allowing the user to start typing without having to
/// manually focus the main view.
public init(_ text: String, autoFocus: Bool = false) {
self.text = text
self.autoFocus = autoFocus
}

@_documentation(visibility: private)
public func render(_ container: Element, environment: EnvironmentValues) throws {
let element = try container.appendElement("input")
try element.attr("type", "text")
try element.attr("placeholder", text)
if autoFocus {
try element.attr("autofocus", "")
}
}

private let text: String
private let autoFocus: Bool
}
4 changes: 4 additions & 0 deletions Tests/SlipstreamTests/W3C/Forms/TextFieldTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,8 @@ struct TextFieldTests {
@Test func placeholder() throws {
try #expect(renderHTML(TextField("Placeholder")) == #"<input type="text" placeholder="Placeholder" />"#)
}

@Test func autoFocus() throws {
try #expect(renderHTML(TextField("Placeholder", autoFocus: true)) == #"<input type="text" placeholder="Placeholder" autofocus />"#)
}
}

0 comments on commit 4fbe98a

Please sign in to comment.