forked from phoenixframework/phoenix_html
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphoenix_html.ex
More file actions
527 lines (385 loc) · 16.3 KB
/
phoenix_html.ex
File metadata and controls
527 lines (385 loc) · 16.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
defmodule Phoenix.HTML do
@moduledoc """
The default building blocks for working with HTML safely
in Phoenix.
This library provides three main functionalities:
* HTML safety
* Form handling (with CSRF protection)
* A tiny JavaScript library to enhance applications
## HTML safety
One of the main responsibilities of this package is to
provide convenience functions for escaping and marking
HTML code as safe.
By default, data output in templates is not considered
safe:
<%= "<hello>" %>
will be shown as:
<hello>
User data or data coming from the database is almost never
considered safe. However, in some cases, you may want to tag
it as safe and show its "raw" contents:
<%= raw "<hello>" %>
Keep in mind most helpers will automatically escape your data
and return safe content:
<%= content_tag :p, "<hello>" %>
will properly output:
<p><hello></p>
## Form handling
See `Phoenix.HTML.Form`.
## JavaScript library
This project ships with a tiny bit of JavaScript that listens
to all click events to:
* Support `data-confirm="message"` attributes, which shows
a confirmation modal with the given message
* Support `data-method="patch|post|put|delete"` attributes,
which sends the current click as a PATCH/POST/PUT/DELETE
HTTP request. You will need to add `data-to` with the URL
and `data-csrf` with the CSRF token value. See
`link_attributes/2` for a function that wraps it all up
for you
* Dispatch a "phoenix.link.click" event. You can listen to this
event to customize the behaviour above. Returning false from
this event will disable `data-method`. Stopping propagation
will disable `data-confirm`
To use the functionality above, you must load `priv/static/phoenix_html.js`
into your build tool.
### Overriding the default confirm behaviour
You can override the default confirmation behaviour by hooking
into `phoenix.link.click`. Here is an example:
```javascript
// listen on document.body, so it's executed before the default of
// phoenix_html, which is listening on the window object
document.body.addEventListener('phoenix.link.click', function (e) {
// Prevent default implementation
e.stopPropagation();
// Introduce alternative implementation
var message = e.target.getAttribute("data-confirm");
if(!message){ return true; }
vex.dialog.confirm({
message: message,
callback: function (value) {
if (value == false) { e.preventDefault(); }
}
})
}, false);
```
"""
@doc false
defmacro __using__(_) do
quote do
import Phoenix.HTML
import Phoenix.HTML.Form
import Phoenix.HTML.Link
import Phoenix.HTML.Tag,
except: [attributes_escape: 1, csrf_token_value: 0, csrf_token_value: 1]
import Phoenix.HTML.Format
end
end
@typedoc "Guaranteed to be safe"
@type safe :: {:safe, iodata}
@typedoc "May be safe or unsafe (i.e. it needs to be converted)"
@type unsafe :: Phoenix.HTML.Safe.t()
@doc false
@deprecated "use the ~H sigil instead"
defmacro sigil_e(expr, opts) do
handle_sigil(expr, opts, __CALLER__)
end
@doc false
@deprecated "use the ~H sigil instead"
defmacro sigil_E(expr, opts) do
handle_sigil(expr, opts, __CALLER__)
end
defp handle_sigil({:<<>>, meta, [expr]}, [], caller) do
options = [
engine: Phoenix.HTML.Engine,
file: caller.file,
line: caller.line + 1,
indentation: meta[:indentation] || 0
]
EEx.compile_string(expr, options)
end
defp handle_sigil(_, _, _) do
raise ArgumentError,
"interpolation not allowed in ~e sigil. " <>
"Remove the interpolation, use <%= %> to insert values, " <>
"or use ~E to show the interpolation literally"
end
@doc """
Marks the given content as raw.
This means any HTML code inside the given
string won't be escaped.
iex> raw("<hello>")
{:safe, "<hello>"}
iex> raw({:safe, "<hello>"})
{:safe, "<hello>"}
iex> raw(nil)
{:safe, ""}
"""
@spec raw(iodata | safe | nil) :: safe
def raw({:safe, value}), do: {:safe, value}
def raw(nil), do: {:safe, ""}
def raw(value) when is_binary(value) or is_list(value), do: {:safe, value}
@doc """
Escapes the HTML entities in the given term, returning safe iodata.
iex> html_escape("<hello>")
{:safe, [[[] | "<"], "hello" | ">"]}
iex> html_escape('<hello>')
{:safe, ["<", 104, 101, 108, 108, 111, ">"]}
iex> html_escape(1)
{:safe, "1"}
iex> html_escape({:safe, "<hello>"})
{:safe, "<hello>"}
"""
@spec html_escape(unsafe) :: safe
def html_escape({:safe, _} = safe), do: safe
def html_escape(other), do: {:safe, Phoenix.HTML.Engine.encode_to_iodata!(other)}
@doc """
Converts a safe result into a string.
Fails if the result is not safe. In such cases, you can
invoke `html_escape/1` or `raw/1` accordingly before.
You can combine `html_escape/1` and `safe_to_string/1`
to convert a data structure to a escaped string:
data |> html_escape() |> safe_to_string()
"""
@spec safe_to_string(safe) :: String.t()
def safe_to_string({:safe, iodata}) do
IO.iodata_to_binary(iodata)
end
@doc ~S"""
Escapes an enumerable of attributes, returning iodata.
The attributes are rendered in the given order. Note if
a map is given, the key ordering is not guaranteed.
The keys and values can be of any shape, as long as they
implement the `Phoenix.HTML.Safe` protocol. In addition,
if the key is an atom, it will be "dasherized". In other
words, `:phx_value_id` will be converted to `phx-value-id`.
Furthermore, the following attributes provide behaviour:
* `:aria`, `:data`, and `:phx` - they accept a keyword list as
value. `data: [confirm: "are you sure?"]` is converted to
`data-confirm="are you sure?"`.
* `:class` - it accepts a list of classes as argument. Each
element in the list is separated by space. `nil` and `false`
elements are discarded. `class: ["foo", nil, "bar"]` then
becomes `class="foo bar"`.
* `:id` - it is validated raise if a number is given as ID,
which is not allowed by the HTML spec and leads to unpredictable
behaviour.
## Examples
iex> safe_to_string attributes_escape(title: "the title", id: "the id", selected: true)
" title=\"the title\" id=\"the id\" selected"
iex> safe_to_string attributes_escape(%{data: [confirm: "Are you sure?"], class: "foo"})
" class=\"foo\" data-confirm=\"Are you sure?\""
iex> safe_to_string attributes_escape(%{phx: [value: [foo: "bar"]], class: "foo"})
" class=\"foo\" phx-value-foo=\"bar\""
"""
def attributes_escape(attrs) when is_list(attrs) do
{:safe, build_attrs(attrs)}
end
def attributes_escape(attrs) do
{:safe, attrs |> Enum.to_list() |> build_attrs()}
end
defp build_attrs([{k, true} | t]),
do: [?\s, key_escape(k) | build_attrs(t)]
defp build_attrs([{_, false} | t]),
do: build_attrs(t)
defp build_attrs([{_, nil} | t]),
do: build_attrs(t)
defp build_attrs([{:id, v} | t]),
do: [" id=\"", id_value(v), ?" | build_attrs(t)]
defp build_attrs([{:class, v} | t]),
do: [" class=\"", class_value(v), ?" | build_attrs(t)]
defp build_attrs([{:aria, v} | t]) when is_list(v),
do: nested_attrs(v, " aria", t)
defp build_attrs([{:data, v} | t]) when is_list(v),
do: nested_attrs(v, " data", t)
defp build_attrs([{:phx, v} | t]) when is_list(v),
do: nested_attrs(v, " phx", t)
defp build_attrs([{"id", v} | t]),
do: [" id=\"", id_value(v), ?" | build_attrs(t)]
defp build_attrs([{"class", v} | t]),
do: [" class=\"", class_value(v), ?" | build_attrs(t)]
defp build_attrs([{"aria", v} | t]) when is_list(v),
do: nested_attrs(v, " aria", t)
defp build_attrs([{"data", v} | t]) when is_list(v),
do: nested_attrs(v, " data", t)
defp build_attrs([{"phx", v} | t]) when is_list(v),
do: nested_attrs(v, " phx", t)
defp build_attrs([{k, v} | t]),
do: [?\s, key_escape(k), ?=, ?", attr_escape(v), ?" | build_attrs(t)]
defp build_attrs([]), do: []
defp nested_attrs([{k, v} | kv], attr, t) when is_list(v),
do: [nested_attrs(v, "#{attr}-#{key_escape(k)}", []) | nested_attrs(kv, attr, t)]
defp nested_attrs([{k, v} | kv], attr, t),
do: [attr, ?-, key_escape(k), ?=, ?", attr_escape(v), ?" | nested_attrs(kv, attr, t)]
defp nested_attrs([], _attr, t),
do: build_attrs(t)
defp id_value(value) when is_number(value) do
raise ArgumentError,
"attempting to set id attribute to #{value}, " <>
"but setting the DOM ID to a number can lead to unpredictable behaviour. " <>
"Instead consider prefixing the id with a string, such as \"user-#{value}\" or similar"
end
defp id_value(value) do
attr_escape(value)
end
defp class_value(value) when is_list(value) do
value
|> Enum.filter(& &1)
|> Enum.join(" ")
|> attr_escape()
end
defp class_value(value) do
attr_escape(value)
end
defp key_escape(value) when is_atom(value), do: String.replace(Atom.to_string(value), "_", "-")
defp key_escape(value), do: attr_escape(value)
defp attr_escape({:safe, data}), do: data
defp attr_escape(nil), do: []
defp attr_escape(other) when is_binary(other), do: Phoenix.HTML.Engine.encode_to_iodata!(other)
defp attr_escape(other), do: Phoenix.HTML.Safe.to_iodata(other)
@doc """
Escapes HTML content to be inserted a JavaScript string.
This function is useful in JavaScript responses when there is a need
to escape HTML rendered from other templates, like in the following:
$("#container").append("<%= javascript_escape(render("post.html", post: @post)) %>");
It escapes quotes (double and single), double backslashes and others.
"""
@spec javascript_escape(binary) :: binary
@spec javascript_escape(safe) :: safe
def javascript_escape({:safe, data}),
do: {:safe, data |> IO.iodata_to_binary() |> javascript_escape("")}
def javascript_escape(data) when is_binary(data),
do: javascript_escape(data, "")
defp javascript_escape(<<0x2028::utf8, t::binary>>, acc),
do: javascript_escape(t, <<acc::binary, "\\u2028">>)
defp javascript_escape(<<0x2029::utf8, t::binary>>, acc),
do: javascript_escape(t, <<acc::binary, "\\u2029">>)
defp javascript_escape(<<0::utf8, t::binary>>, acc),
do: javascript_escape(t, <<acc::binary, "\\u0000">>)
defp javascript_escape(<<"</", t::binary>>, acc),
do: javascript_escape(t, <<acc::binary, ?<, ?\\, ?/>>)
defp javascript_escape(<<"\r\n", t::binary>>, acc),
do: javascript_escape(t, <<acc::binary, ?\\, ?n>>)
defp javascript_escape(<<h, t::binary>>, acc) when h in [?", ?', ?\\, ?`],
do: javascript_escape(t, <<acc::binary, ?\\, h>>)
defp javascript_escape(<<h, t::binary>>, acc) when h in [?\r, ?\n],
do: javascript_escape(t, <<acc::binary, ?\\, ?n>>)
defp javascript_escape(<<h, t::binary>>, acc),
do: javascript_escape(t, <<acc::binary, h>>)
defp javascript_escape(<<>>, acc), do: acc
@doc """
Returns a list of attributes that make an element behave like a link.
For example, to make a button work like a link:
<button {link_attributes("/home")}>
Go back to home
</button>
However, this function is more often used to create buttons that
must invoke an action on the server, such as deleting an entity,
using the relevant HTTP protocol:
<button data-confirm="Are you sure?" {link_attributes("/product/1", method: :delete}>
Delete product
</button>
The `to` argument may be a string, a URI, or a tuple `{scheme, value}`.
See the examples below.
Note: using this function requires loading the JavaScript library
at `priv/static/phoenix_html.js`. See the `Phoenix.HTML` module
documentation for more information.
## Options
* `:method` - the HTTP method for the link. Defaults to `:get`.
* `:csrf_token` - a custom token to use when method is not `:get`.
This is used to ensure the request was sent by the user who
rendered the page. By default, CSRF tokens are generated through
`Plug.CSRFProtection`. You can set this option to `false`, to
disable token generation, or set it to your own token.
When the `:method` is set to `:get` and the `:to` URL contains query
parameters the generated form element will strip the parameters in
accordance with the [W3C](https://www.w3.org/TR/html401/interact/forms.html#h-17.13.3.4)
form specification.
## Data attributes
The following data attributes can also be manually set in the element:
* `data-confirm` - shows a confirmation prompt before generating and
submitting the form.
## Examples
iex> link_attributes("/world")
[data: [method: :get, to: "/world"]]
iex> link_attributes(URI.parse("https://elixir-lang.org"))
[data: [method: :get, to: "https://elixir-lang.org"]]
iex> link_attributes("/product/1", method: :delete)
[data: [csrf: Plug.CSRFProtection.get_csrf_token(), method: :delete, to: "/product/1"]]
If the URL is absolute, only certain schemas are allowed to
avoid JavaScript injection. For example, the following will fail:
iex> link_attributes("javascript:alert('hacked!')")
** (ArgumentError) unsupported scheme given as link. In case you want to link to an
unknown or unsafe scheme, such as javascript, use a tuple: {:javascript, rest}
You can however explicitly render those unsafe schemes by using a tuple:
iex> link_attributes({:javascript, "alert('my alert!')"})
[data: [method: :get, to: ["javascript", 58, "alert('my alert!')"]]]
"""
def link_attributes(to, opts \\ []) do
to = valid_destination!(to)
method = Keyword.get(opts, :method, :get)
data = [method: method, to: to]
data =
if method == :get do
data
else
case Keyword.get(opts, :csrf_token, true) do
true -> [csrf: csrf_token_value(to)] ++ data
false -> data
csrf when is_binary(csrf) -> [csrf: csrf] ++ data
end
end
[data: data]
end
defp valid_destination!(%URI{} = uri) do
valid_destination!(URI.to_string(uri))
end
defp valid_destination!({:safe, to}) do
{:safe, valid_string_destination!(IO.iodata_to_binary(to))}
end
defp valid_destination!({other, to}) when is_atom(other) do
[Atom.to_string(other), ?:, to]
end
defp valid_destination!(to) do
valid_string_destination!(IO.iodata_to_binary(to))
end
@valid_uri_schemes ~w(http: https: ftp: ftps: mailto: news: irc: gopher:) ++
~w(nntp: feed: telnet: mms: rtsp: svn: tel: fax: xmpp:)
for scheme <- @valid_uri_schemes do
defp valid_string_destination!(unquote(scheme) <> _ = string), do: string
end
defp valid_string_destination!(to) do
if not match?("/" <> _, to) and String.contains?(to, ":") do
raise ArgumentError, """
unsupported scheme given as link. In case you want to link to an
unknown or unsafe scheme, such as javascript, use a tuple: {:javascript, rest}\
"""
else
to
end
end
@doc """
Returns the `csrf_token` value to be used by forms, meta tags, etc.
By default, CSRF tokens are generated through `Plug.CSRFProtection`
which is capable of generating a separate token per host. Therefore
it is recommended to pass the `URI` of the destination as argument.
If none is given `%URI{host: nil}` is used, which implies a local
request is being done.
This function is more often used to generate CSRF tokens to be used
on the "csrf-token" meta tag or to be used on hidden inputs to
protect forms.
For example, to generate a token for a meta tag:
<meta name="csrf-token" content={csrf_token_value()}>
If you're writing a form without the use of tag helpers like
`Phoenix.HTML.Tag.form_tag/3` or `Phoenix.HTML.Form.form_for/4`,
you can add a hidden input with the generated token to maintain CSRF protection:
<form action="/login" method="POST">
<input type="hidden" name="_csrf_token" value={csrf_token_value("/login")}>
</form>
Note that the `to` argument should be the same as the form action.
"""
def csrf_token_value(to \\ %URI{host: nil}) do
{mod, fun, args} = Application.fetch_env!(:phoenix_html, :csrf_token_reader)
apply(mod, fun, [to | args])
end
end