-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathmacro_component.ex
More file actions
398 lines (348 loc) · 13.3 KB
/
macro_component.ex
File metadata and controls
398 lines (348 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
defmodule Phoenix.Component.MacroComponent do
@moduledoc false
# A macro component is a special type of component that can modify its content
# at compile time.
#
# Instead of introducing a special tag syntax like `<#macro-component>`, LiveView
# implements them using a special `:type` attribute as the most useful macro
# components take their content and extract it to somewhere else, for example
# to a file in the local file system. A good example for this is `Phoenix.LiveView.ColocatedHook`
# and `Phoenix.LiveView.ColocatedJS`.
#
# ## AST
#
# Macro components work by defining a callback module that implements the
# `Phoenix.LiveView.MacroComponent` behaviour. The module's `c:transform/2` callback
# is called for each macro component used while LiveView compiles a HEEx component:
#
# ```heex
# <div id="hey" phx-hook=".foo">
# <!-- content -->
# </div>
#
# <script :type={ColocatedHook} name=".foo">
# export default {
# mounted() {
# this.el.firstElementChild.textContent = "Hello from JS!"
# }
# }
# </script>
# ```
#
# In this example, the `ColocatedHook`'s `c:transform/2` callback will be invoked
# with the AST of the `<script>` tag:
#
# ```elixir
# {"script",
# [{"name", ".foo"}],
# [
# "\\n export default {\\n mounted() {\\n this.el.firstElementChild.textContent = \\"Hello from JS!\\"\\n }\\n }\\n"
# ]}
# ```
#
# This module provides some utilities to work with the AST, which uses
# standard Elixir data structures:
#
# 1. A HTML tag is represented as `{tag, attributes, children, meta}`
# 2. Text is represented as a plain binary
# 3. Attributes are represented as a list of `{key, value}` tuples where
# the value is an Elixir AST (which can be a plain binary for simple attributes)
#
# > #### Limitations {: .warning}
# > The AST is not whitespace preserving. When using macro components,
# > the original whitespace between attributes is lost.
# >
# > Also, macro components can currently only contain simple HTML. Any interpolation
# > like `<%= @foo %>` or components inside are not supported.
#
# ## Example: a compile-time markdown renderer
#
# Let's say we want to create a macro component that renders markdown as HTML at
# compile time. First, we need some library that actually converts the markdown to
# HTML. For this example, we use [`mdex`](https://hex.pm/packages/mdex).
#
# We start by defining the module for the macro component:
#
# ```elixir
# defmodule MyAppWeb.MarkdownComponent do
# @behaviour Phoenix.Component.MacroComponent
#
# @impl true
# def transform({"pre", attrs, children, _tag_meta}, _meta) do
# markdown = Phoenix.Component.MacroComponent.ast_to_string(children)
# html_doc = MDEx.to_html!(markdown)
#
# {:ok, {"div", attrs, [html_doc], %{}}}
# end
# end
# ```
#
# That's it. Since the div could contain nested elements, for example when using
# an HTML code block, we need to convert the children to a string first, using the
# `Phoenix.Component.MacroComponent.ast_to_string/1` function.
#
# Then, we can simply replace the element's contents with the returned HTML string from
# MDEx.
#
# We can now use the macro component inside our HEEx templates:
#
# defmodule MyAppWeb.ExampleLiveView do
# use MyAppWeb, :live_view
#
# def render(assigns) do
# ~H\"\"\"
# <pre :type={MyAppWeb.MarkdownComponent} class="prose mt-8">
# ## Hello World
#
# This is some markdown!
#
# ```elixir
# defmodule Hello do
# def world do
# IO.puts "Hello, world!"
# end
# end
# ```
# </pre>
# \"\"\"
# end
# end
#
# Note: this example uses the `prose` class from TailwindCSS for styling.
#
# One trick to prevent issues with extra whitespace is that we use a `<pre>` tag in the LiveView
# template, which prevents the `Phoenix.LiveView.HTMLFormatter` from indenting the contents, which
# would mess with the markdown parsing. When rendering, we replace it with a `<div>` tag in the
# macro component.
#
# Another example for a macro component that transforms its content is available in
# LiveView's end to end tests: a macro component that performs
# [syntax highlighting at compile time](https://github.com/phoenixframework/phoenix_live_view/blob/38851d943f3280c5982d75679291dccb8c442534/test/e2e/support/colocated_live.ex#L4-L35)
# using the [Makeup](https://hexdocs.pm/makeup/Makeup.html) library.
#
# ## Directives
#
# Macro components may return directives from `transform/2` which can be used to influence
# other elements in the template outside of the macro component at compile-time. For example:
#
# ```elixir
# defmodule MyAppWeb.TagRootSampleComponent do
# @behaviour Phoenix.Component.MacroComponent
#
# @impl true
# def transform(_ast, _meta) do
# {:ok, "", %{}, [root_tag_attribute: {"phx-sample-one", "test"}, root_tag_attribute: {"phx-sample-two", true}]}
# end
# end
# ```
#
# The following directives are currently supported:
#
# * `:root_tag_attribute` - A `{name, value}` tuple to apply as an attribute to all root tags during template compilation.
# Requires that a global `:root_tag_attribute` is configured for the application. The attribute name must be a string and the attribute value must be a string or `true`.
# May be provided multiple times to apply multiple attributes.
#
@type tag :: binary()
@type attribute :: {binary(), Macro.t()}
@type attributes :: [attribute()]
@type children :: [heex_ast()]
@type tag_meta :: %{closing: :self | :void}
@type heex_ast :: {tag(), attributes(), children(), tag_meta()} | binary()
@type transform_meta :: %{env: Macro.Env.t()}
@type directive :: {:root_tag_attribute, {name :: String.t(), value :: String.t() | true}}
@type directives :: [directive]
@callback transform(heex_ast :: heex_ast(), meta :: transform_meta()) ::
{:ok, heex_ast()}
| {:ok, heex_ast(), data :: term()}
| {:ok, heex_ast(), data :: term(), directives :: directives()}
@doc """
Returns the stored data from macro components that returned `{:ok, ast, data}`.
As one macro component can be used multiple times in one module, the result is a map of format
%{module => list(data)}
If the component module does not have any macro components defined, an empty map is returned.
"""
@spec get_data(module()) :: map()
def get_data(component_module) do
if Code.ensure_loaded?(component_module) and
function_exported?(component_module, :__phoenix_macro_components__, 0) do
component_module.__phoenix_macro_components__()
else
%{}
end
end
@doc false
def build_ast(node, env) when is_tuple(node) do
case node do
{:self_close, :tag, name, attrs, meta} ->
closing_meta = Map.take(meta, [:closing])
{:ok, {name, attrs_to_ast(attrs, env), [], closing_meta}}
{:block, :tag, name, attrs, children, _meta, _close_meta} ->
children_ast = build_ast(children, env)
{:ok, {name, attrs_to_ast(attrs, env), children_ast, %{}}}
end
catch
{:ast_error, message, error_meta} ->
{:error, message, error_meta}
end
def build_ast(children, env) when is_list(children) do
Enum.map(children, fn
{:text, text, _meta} ->
text
{:self_close, :tag, name, attrs, meta} ->
closing_meta = Map.take(meta, [:closing])
{name, attrs_to_ast(attrs, env), [], closing_meta}
{:block, :tag, name, attrs, nested_children, _meta, _close_meta} ->
{name, attrs_to_ast(attrs, env), build_ast(nested_children, env), %{}}
{:self_close, type, _name, _attrs, meta}
when type in [:local_component, :remote_component] ->
throw({:ast_error, "function components cannot be nested inside a macro component", meta})
{:block, type, _name, _attrs, _children, meta, _close_meta}
when type in [:local_component, :remote_component] ->
throw({:ast_error, "function components cannot be nested inside a macro component", meta})
{:self_close, :slot, _name, _attrs, meta} ->
throw({:ast_error, "slots cannot be nested inside a macro component", meta})
{:block, :slot, _name, _attrs, _children, meta, _close_meta} ->
throw({:ast_error, "slots cannot be nested inside a macro component", meta})
{:body_expr, _expr, meta} ->
throw({:ast_error, "interpolation is not currently supported in macro components", meta})
{:eex, _expr, meta} ->
throw({:ast_error, "EEx is not currently supported in macro components", meta})
{:eex_block, _expr, _blocks, meta} ->
throw({:ast_error, "EEx is not currently supported in macro components", meta})
end)
end
defp attrs_to_ast(attrs, env) do
Enum.map(attrs, fn
# for now, we don't support root expressions (<div {@foo}>)
{:root, value, attr_meta} ->
format_attr = fn
{:string, binary, _meta} -> binary
{:expr, code, _meta} -> code
nil -> "nil"
end
throw(
{:ast_error,
"dynamic attributes are not supported in macro components, got: #{format_attr.(value)}",
attr_meta}
)
{name, {:string, binary, _meta}, _attr_meta} ->
{name, binary}
{name, {:expr, code, expr_meta}, _attr_meta} ->
ast =
Code.string_to_quoted!(code,
line: expr_meta.line,
column: expr_meta.column,
file: env.file
)
{name, ast}
{name, nil, _attr_meta} ->
{name, nil}
end)
end
@doc false
# Convert macro AST back to tree nodes (parser format)
# We keep reuse the original line + column metadata from the original tag
def ast_to_tree({tag, attrs, [], %{closing: _closing} = meta}, original_meta) do
tree_attrs = attrs_to_tree(attrs, original_meta)
{:self_close, :tag, tag, tree_attrs, Map.merge(original_meta, meta)}
end
def ast_to_tree({tag, attrs, children, _meta}, original_meta) do
tree_attrs = attrs_to_tree(attrs, original_meta)
tree_children = Enum.map(children, &ast_to_tree(&1, original_meta))
{:block, :tag, tag, tree_attrs, tree_children, original_meta, %{}}
end
def ast_to_tree(text, _original_meta) when is_binary(text) do
{:text, text, %{}}
end
defp attrs_to_tree(attrs, meta) do
Enum.map(attrs, fn
{name, nil} ->
{name, nil, meta}
{name, value} when is_binary(value) ->
delimiter = attr_quotes(name, value)
{name, {:string, value, Map.put(meta, :delimiter, delimiter)}, meta}
{name, ast} ->
# Convert quoted AST back to string for the tree node format
code = Macro.to_string(ast)
{name, {:expr, code, meta}, meta}
end)
end
@doc """
Turns an AST into a string.
## Options
* `attributes_encoder` - a custom function to encode attributes to iodata.
Defaults to an HTML-safe encoder.
"""
@spec ast_to_string(heex_ast(), keyword()) :: binary()
def ast_to_string(ast, opts \\ []) do
opts = Keyword.put_new(opts, :attributes_encoder, &ast_attributes_to_iodata/1)
ast
|> ast_to_iodata(opts)
|> IO.iodata_to_binary()
end
defp ast_to_iodata(list, opts) when is_list(list) do
Enum.map(list, &ast_to_iodata(&1, opts))
end
# self closing / void tags cannot have children
defp ast_to_iodata({name, attrs, [], %{closing: closing}}, opts) do
suffix =
case closing do
:void -> ">"
:self -> "/>"
end
[
"<",
name,
opts[:attributes_encoder].(attrs),
suffix
]
end
defp ast_to_iodata({name, attrs, children, _meta}, opts) do
[
"<",
name,
opts[:attributes_encoder].(attrs),
">",
Enum.map(children, &ast_to_iodata(&1, opts)),
"</",
name,
">"
]
end
defp ast_to_iodata(binary, _opts) when is_binary(binary) do
binary
end
defp ast_attributes_to_iodata(attrs) do
Enum.map(attrs, fn
{key, value} when is_binary(value) ->
encode_binary_attribute(key, value)
{key, nil} ->
~s( #{key})
{key, value} ->
raise ArgumentError,
"cannot convert AST with non-string attribute \"#{key}\" to string. Got: #{Macro.to_string(value)}"
end)
end
defp encode_binary_attribute(key, value) when is_binary(key) and is_binary(value) do
case attr_quotes(key, value) do
?" ->
~s( #{key}="#{value}")
?' ->
~s( #{key}='#{value}')
end
end
defp attr_quotes(key, value) do
case {:binary.match(value, ~s["]), :binary.match(value, "'")} do
{:nomatch, _} ->
?"
{_, :nomatch} ->
?'
_ ->
raise ArgumentError, """
invalid attribute value for \"#{key}\".
Attribute values must not contain single and double quotes at the same time.
You need to escape your attribute before using it in the MacroComponent AST. You can use `Phoenix.HTML.attributes_escape/1` to do so.
"""
end
end
end