From 9e531758182749befe851f15afb8b6725f8b8157 Mon Sep 17 00:00:00 2001 From: Will Sackfield Date: Thu, 7 May 2020 17:43:40 +0100 Subject: [PATCH] Add onclick attribute to HTML nodes (#43) Makes onclick a first class attribute on HTML body nodes. --- Sources/Plot/API/HTMLAttributes.swift | 11 +++++++++++ Tests/PlotTests/HTMLTests.swift | 16 +++++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/Sources/Plot/API/HTMLAttributes.swift b/Sources/Plot/API/HTMLAttributes.swift index 17b058a..0641f97 100644 --- a/Sources/Plot/API/HTMLAttributes.swift +++ b/Sources/Plot/API/HTMLAttributes.swift @@ -464,6 +464,17 @@ public extension Node where Context == HTML.ScriptContext { } } +// MARK: - Javascript + +public extension Node where Context: HTML.BodyContext { + /// Add a script to execute when the user clicks the current element. + /// - parameter script: The script to execute when the user clicks on the node. + /// Usually prefixed with `javascript:`. + static func onclick(_ script: String) -> Node { + .attribute(named: "onclick", value: script) + } +} + // MARK: - Other, element-specific attributes public extension Node where Context == HTML.AbbreviationContext { diff --git a/Tests/PlotTests/HTMLTests.swift b/Tests/PlotTests/HTMLTests.swift index 660401a..c909e72 100644 --- a/Tests/PlotTests/HTMLTests.swift +++ b/Tests/PlotTests/HTMLTests.swift @@ -671,6 +671,19 @@ final class HTMLTests: XCTestCase { """) } + + func testOnClick() { + let html = HTML( + .body( + .div( + .onclick("javascript:alert('Hello World')") + ) + ) + ) + assertEqualHTMLContent(html, """ +
+ """) + } } extension HTMLTests { @@ -738,7 +751,8 @@ extension HTMLTests { ("testDataAttributes", testDataAttributes), ("testSubresourceIntegrity", testSubresourceIntegrity), ("testComments", testComments), - ("testPicture", testPicture) + ("testPicture", testPicture), + ("testOnClick", testOnClick) ] } }