Skip to content

Commit

Permalink
Commit of changes necessary to modify head element textContent proper…
Browse files Browse the repository at this point in the history
…ty, in addition to attributes.
  • Loading branch information
magic-pills-movie committed Nov 30, 2024
1 parent d3837d7 commit 333c8ec
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
14 changes: 13 additions & 1 deletion assets/js/phoenix_live_head/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,19 @@ module PhxLiveHead {

changes.forEach(function (change: change) {
const [action, attr_input, value] = change;
const attr = ATTR[attr_input] || attr_input;
const attr = ATTR[attr_input] || attr_input

// If the passed attribute is 'textContent', we're targeting the element's
// property
// if the action is "s", set the property, if "a", append to it
if (attr === "t") {
switch (action) {
case "s": el["textContent"] = value; break;
case "a": el["textContent"] += value; break;
default: null
}
return;
};

// we collect all replacements so we can set them all at once
// as there might be multiple in a single attribute
Expand Down
22 changes: 22 additions & 0 deletions lib/live_head.ex
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,29 @@ defmodule Phx.Live.Head do
push_or_merge_head_event(socket, query, [action, attr, value])
end

@doc """
Pushes `action` to apply on `textContent` property of elements matching `query`.
## Comments
Why `textContent` and not `innerHTML`? As per MDN web docs,
[Node: textContent property](https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent),
"...there is still a security risk whenever you use innerHTML to set strings
over which you have no control. ... For that reason, it is recommended that
instead of innerHTML you use ... `Node.textContent` when inserting plain
text, as this inserts it as raw text rather than parsing it as HTML."
"""
@spec push_content(socket :: Socket.t(), query, action, value) :: Socket.t()
def push_content(socket, query, action, value)
when action == :add or action == :set do
push(socket, query, action, "textContent", value)
end

def push_content(socket, _query, _action, _value), do: socket

@spec maybe_min_attr(attr) :: String.t()
defp maybe_min_attr("textContent"), do: "t"
defp maybe_min_attr("class"), do: "c"
defp maybe_min_attr("class-name"), do: "c"
defp maybe_min_attr("href"), do: "h"
Expand Down

0 comments on commit 333c8ec

Please sign in to comment.