Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[feature] Add autofocus support to TextField. #156

Merged
merged 1 commit into from
Aug 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 />"#)
}
}