<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="377351" data-post-id="377351">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rhcarvalho" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/120/32243_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rhcarvalho
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Thank you for the PR.</p>
<aside class="quote group-Phoenix-Core-Team" data-username="steffend" data-post="11" data-topic="53870">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/steffend/48/20548_2.png" class="avatar"> steffend:</div>
<blockquote>
<p>You’ll still need to do write it like the following, but you can implement Jason.Encoder by just delegating to <code>to_string</code> and then omit the extra to_string call.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">push_event(socket, "do-something", %{data: to_string(JS.add_class("foo"))})
</code></pre>
</blockquote>
</aside>
<p>I wouldn’t mind the <code>to_string</code>, but on second thought I realized:</p>
<ol>
<li>The <code>Jason.Encoder</code> implementation would need to assume <code>to_string</code> returns safe JSON to pass it as is instead of encoding as a JSON string; or</li>
<li>JavaScript code would need to decode the payload string and then parse it as JSON to turn it into a valid JS command, once again assuming a JS command is valid JSON.</li>
</ol>
<p>In this case, <a class="mention" href="/u/lostkobrakai" rel="nofollow">@LostKobrakai</a>’s suggestion seems like a better contract. <code>JS.to_json</code> would naturally appear in HexDocs at the right context (module docs), be more discoverable through search, and imply JSON compatibility.</p>
<hr>
<p>Copying from <a href="https://forum.elixirforum.com/t/animating-list-items-with-liveview-streams/60753/6" class="inline-onebox" rel="nofollow">Animating list items with LiveView streams - #6 by rhcarvalho</a> to bring a concise use case as example, both Elixir and JavaScript side:</p>
<aside class="quote no-group quote-modified" data-username="rhcarvalho" data-post="6" data-topic="60753">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/48/32243_2.png" class="avatar"><a href="https://forum.elixirforum.com/t/animating-list-items-with-liveview-streams/60753/6" rel="nofollow">Animating list items with LiveView streams</a></div>
<blockquote>
<p>A more generic listener could even exec any set of JS commands stored in an attribute (or sent along the event payload):</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">window.addEventListener("phx:exec", event =&gt; {
  const el = document.querySelector(event.detail.selector);
  if (!el) return;
  liveSocket.execJS(el, event.detail.js || el.getAttribute(event.detail.attr));
});
</code></pre>
<p>On the server side:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">&lt;div
  id={@id}
  data-phx-show={JS.transition({"ease-out duration-200", "opacity-0 scale-95", "opacity-100 scale-100"})}
&gt;...&lt;/div&gt;
</code></pre>
<pre data-code-wrap="elixir"><code class="lang-elixir">    socket
    |&gt; push_event("exec", %{
      "selector" =&gt; "#urls-#{url.id}",
      "attr" =&gt; "data-phx-show"
    })
</code></pre>
<p>Or (see <a href="https://forum.elixirforum.com/t/make-js-t-a-public-data-structure-or-json-serializable/53870" rel="nofollow">Make <code>JS.t()</code> a public data structure, or json serializable</a>):</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">    socket
    |&gt; push_event("exec", %{
      "selector" =&gt; "#urls-#{url.id}",
      "js" =&gt;
        JS.transition({"ease-out duration-200", "opacity-0 scale-95", "opacity-100 scale-100"}).ops
        |&gt; JSON.encode!()
    })
</code></pre>
</blockquote>
</aside>
<p>So, <a class="mention" href="/u/steffend" rel="nofollow">@steffend</a>, if we write <code>JS.transition(...) |&gt; to_string()</code> we’d end up with a string in the JS event handler, not a deeply nested list which is a valid JS command. Either JS code would need to call <code>JSON.parse(payload_str)</code>, or server code needs to assume the result from <code>to_string</code> is valid JSON as-is (which would be undocumented behavior).</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="377351" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/make-js-t-a-public-data-structure-or-json-serializable/53870/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-377351" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="377351"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="377353" data-post-id="377353">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="steffend" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/steffend/120/20548_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  steffend
                  </h3>
		          </div>
						
			          <div class="user-title">
									<span>Phoenix Core Team</span>
			          </div>
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>A string is valid JSON - am I missing something?</p>
<p>Edit: it would look like this:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defimpl Jason.Encoder, for: Phoenix.LiveView.JS do
  def encode(%Phoenix.LiveView.JS{} = js, arg) do
    Jason.Encode.string(to_string(js), arg)
  end
end
</code></pre>
<p>And that will work with <code>execJS</code>.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="377353" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/make-js-t-a-public-data-structure-or-json-serializable/53870/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-377353" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="377353"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="377365" data-post-id="377365">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rhcarvalho" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/120/32243_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rhcarvalho
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>The difference is</p>
<pre data-code-wrap="json"><code class="lang-json">[["transition",{"transition":[["ease-out","duration-200"],["opacity-0"],["opacity-100"]]}]]
</code></pre>
<p>which is <code>JSON.encode!(%JS{}.ops)</code></p>
<p>vs</p>
<pre data-code-wrap="json"><code class="lang-json">"[[\\"transition\\",{\\"transition\\":[[\\"ease-out\\",\\"duration-200\\"],[\\"opacity-0\\"],[\\"opacity-100\\"]]}]]"
</code></pre>
<p>which is the string version of the above.</p>
<p>The <code>LiveSocket.execJS</code> code will parse one level of JSON encoding expecting a list:</p>
<p><a href="https://github.com/phoenixframework/phoenix_live_view/blob/f4344b4a020e55dfe33694439d269892d8af475c/assets/js/phoenix_live_view/js.js#L7-L16" class="onebox" target="_blank" rel="noopener nofollow ugc">https://github.com/phoenixframework/phoenix_live_view/blob/f4344b4a020e55dfe33694439d269892d8af475c/assets/js/phoenix_live_view/js.js#L7-L16</a></p>
<p>If the content is, however, a string, it will not work.</p>
<p>I think the protocol implementation would have to be:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defimpl Jason.Encoder, for: Phoenix.LiveView.JS do
  def encode(%Phoenix.LiveView.JS{} = js, arg) do
    # assume valid JSON
    to_string(js)
  end
end
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="377365" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/make-js-t-a-public-data-structure-or-json-serializable/53870/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-377365" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="377365"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="377393" data-post-id="377393">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rhcarvalho" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/120/32243_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rhcarvalho
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Good morning!</p>
<p>I thought about it a bit further, I think <code>to_string/1</code> as in the PR is indeed a good contract (but see Option 1 vs Option 2 below).</p>
<p>When we write a JS command inside a HEEx template, we’re intuitively serializing it as a string in an HTML attribute (with proper escaping taken care of for us).</p>
<p>The new use case we’re unlocking, <code>push_event</code> with a JS command in the payload, requires a JSON-serializable payload. A string is JSON-serializable, and so is a map with a string value.</p>
<p>On the client side, <code>LiveSocket.execJS</code> expects an “encoded JS command” as argument. “Encoded” in this context means encoded as a string (which happens to be a JSON serialization of a list, but that is not part of the public contract, and could be anything).</p>
<p>If not implementing <code>String.Chars</code> / <code>to_string</code>, the alternative would be some explicit function, like the <code>to_json</code> mentioned earlier. The downside of <code>JS.to_json</code> is that it prescribes the serialization format. <code>JS.encode/1</code> (taking a <code>%JS{}</code> as input, returning <code>binary</code>) would keep the underlying serialization format opaque, and is inline with the “encoded JS” terminology.</p>
<p>I understand implementing <code>String.Chars</code> can be convenient, examples:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">iex(1)&gt; alias Phoenix.LiveView.JS
Phoenix.LiveView.JS
iex(2)&gt; JS.transition({"ease-out duration-200", "opacity-0", "opacity-100"}) |&gt; IO.puts()
[["transition",{"transition":[["ease-out","duration-200"],["opacity-0"],["opacity-100"]]}]]
:ok
iex(3)&gt; "#{JS.transition({"ease-out duration-200", "opacity-0", "opacity-100"})}"
"[[\"transition\",{\"transition\":[[\"ease-out\",\"duration-200\"],[\"opacity-0\"],[\"opacity-100\"]]}]]"
</code></pre>
<p>A potential downside is having the protocol implementation trigger unexpected behavior, e.g. serializing the JS command in unexpected contexts instead of throwing or failing to type-check at compile time. In this case, the explicit function would be, well, explicit, though less convenient.</p>
<p>So I think it comes down to deciding whether implementing <code>String.Chars</code> has any unintended consequences, and how we’d document the <code>push_event</code> use case.</p>
<h2><a name="p-377393-option-1-stringchars-1" class="anchor" href="#p-377393-option-1-stringchars-1" aria-label="Heading link" rel="nofollow"></a>Option 1: <code>String.Chars</code></h2>
<pre data-code-wrap="elixir"><code class="lang-elixir">    socket
    |&gt; push_event("exec", %{
      "selector" =&gt; "#urls-#{url.id}",
      "js" =&gt; "#{JS.transition({"ease-out duration-200", "opacity-0 scale-95", "opacity-100 scale-100"})}"
    })
</code></pre>
<ul>
<li>Could be documented in the module docs at <a href="https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.JS.html" class="inline-onebox" rel="noopener nofollow ugc">Phoenix.LiveView.JS — Phoenix LiveView v1.2.5</a>.</li>
</ul>
<h2><a name="p-377393-option-2-jsencode1-or-similar-2" class="anchor" href="#p-377393-option-2-jsencode1-or-similar-2" aria-label="Heading link" rel="nofollow"></a>Option 2: <code>JS.encode/1</code> (or similar)</h2>
<pre data-code-wrap="elixir"><code class="lang-elixir">    socket
    |&gt; push_event("exec", %{
      "selector" =&gt; "#urls-#{url.id}",
      "js" =&gt;
        JS.transition({"ease-out duration-200", "opacity-0 scale-95", "opacity-100 scale-100"})
        |&gt; JS.encode()
    })
</code></pre>
<ul>
<li>Would be documented at the function level.</li>
<li>Accidentally dropping a <code>%JS{}</code> inside a string (i.e. not HEEx) would still produce an error as is the current behavior.</li>
</ul>
<p>In my current thinking, I prefer Option 2 because it preserves existing behavior, is more discoverable, doesn’t impede us from implementing <code>String.Chars</code> in the future and is inline with what <a class="mention" href="/u/steffend" rel="nofollow">@steffend</a> said:</p>
<aside class="quote group-Phoenix-Core-Team" data-username="steffend" data-post="8" data-topic="53870">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/steffend/48/20548_2.png" class="avatar"> steffend:</div>
<blockquote>
<p>LiveView only exposes APIs for working with the encoded JS</p>
</blockquote>
</aside>
<hr>
<p><a class="mention" href="/u/steffend" rel="nofollow">@steffend</a> I think user code shouldn’t need to implement <code>Jason.Encoder</code> for JS commands. It is easier to reason about passing an opaque string (“encoded JS”) to <code>push_event</code>.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="377393" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/make-js-t-a-public-data-structure-or-json-serializable/53870/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-377393" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="377393"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="377398" data-post-id="377398">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rhcarvalho" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/120/32243_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rhcarvalho
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I implemented “Option 2”, explicit <code>encode/1</code> function, in a PR <a href="https://github.com/phoenixframework/phoenix_live_view/pull/4046" class="inline-onebox" rel="noopener nofollow ugc">Add JS.encode/1 function by rhcarvalho · Pull Request #4046 · phoenixframework/phoenix_live_view · GitHub</a> for us to have a comparison (borrowed the test updates from you, <a class="mention" href="/u/steffend" rel="nofollow">@steffend</a>).</p>
<p>Reflecting upon the tests, I realized that both PRs do not guarantee that encoding the same <code>%JS{}</code> value multiple times returns a consistent string representation.</p>
<p>That’s because we’re encoding maps to JSON, thus no guaranteed order. The tests, however, are careful to sort map keys before JSON serialization.</p>
<p>We might opt to move that behavior from tests to the implementation, so that we guarantee a stable representation (good for tests in API consumers / LiveView users, and perhaps for reducing unnecessary diffs and churn when sending data over the wire – thinking about both server-side change tracking and morphdom patching).</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="377398" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/make-js-t-a-public-data-structure-or-json-serializable/53870/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-377398" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="377398"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #15"></div>
  </section>
</div>
    <div class="postbit" id="377399" data-post-id="377399">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="rhcarvalho" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/120/32243_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  rhcarvalho
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="rhcarvalho" data-post="16" data-topic="53870">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/rhcarvalho/48/32243_2.png" class="avatar"> rhcarvalho:</div>
<blockquote>
<p>We might opt to move that behavior from tests to the implementation, so that we guarantee a stable representation (good for tests in API consumers / LiveView users, and perhaps for reducing unnecessary diffs and churn when sending data over the wire – thinking about both server-side change tracking and morphdom patching).</p>
</blockquote>
</aside>
<p>Hmm even if it is decided that neither <code>String.Chars</code> nor <code>JS.encode</code> should be added to LiveView, making the current <code>Phoenix.HTML.Safe</code> implementation for <code>JS</code> stable seems like a worthy change.</p>
<p>Currently, recomputing some function component that contains JS commands may trigger a diff solely because of arbitrary map order.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="377399" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/make-js-t-a-public-data-structure-or-json-serializable/53870/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-377399" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="377399"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>