/
link.coffee.erb
622 lines (486 loc) · 22 KB
/
link.coffee.erb
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
###**
Linking to fragments
====================
The `up.link` module lets you build links that update fragments instead of entire pages.
\#\#\# Motivation
In a traditional web application, the entire page is destroyed and re-created when the
user follows a link:
![Traditional page flow](/images/tutorial/fragment_flow_vanilla.svg){:width="620" class="picture has_border is_sepia has_padding"}
This makes for an unfriendly experience:
- State changes caused by AJAX updates get lost during the page transition.
- Unsaved form changes get lost during the page transition.
- The JavaScript VM is reset during the page transition.
- If the page layout is composed from multiple scrollable containers
(e.g. a pane view), the scroll positions get lost during the page transition.
- The user sees a "flash" as the browser loads and renders the new page,
even if large portions of the old and new page are the same (navigation, layout, etc.).
Unpoly fixes this by letting you annotate links with an [`up-target`](/a-up-target)
attribute. The value of this attribute is a CSS selector that indicates which page
fragment to update. The server **still renders full HTML pages**, but we only use
the targeted fragments and discard the rest:
![Unpoly page flow](/images/tutorial/fragment_flow_unpoly.svg){:width="620" class="picture has_border is_sepia has_padding"}
With this model, following links feels smooth. All transient DOM changes outside the updated fragment are preserved.
Pages also load much faster since the DOM, CSS and Javascript environments do not need to be
destroyed and recreated for every request.
\#\#\# Example
Let's say we are rendering three pages with a tabbed navigation to switch between screens:
Your HTML could look like this:
```
<nav>
<a href="/pages/a">A</a>
<a href="/pages/b">B</a>
<a href="/pages/b">C</a>
</nav>
<article>
Page A
</article>
```
Since we only want to update the `<article>` tag, we annotate the links
with an `up-target` attribute:
```
<nav>
<a href="/pages/a" up-target="article">A</a>
<a href="/pages/b" up-target="article">B</a>
<a href="/pages/b" up-target="article">C</a>
</nav>
```
Note that instead of `article` you can use any other CSS selector like `#main .article`.
With these [`up-target`](/a-up-target) annotations Unpoly only updates the targeted part of the screen.
The JavaScript environment will persist and the user will not see a white flash while the
new page is loading.
@module up.link
###
up.link = do ->
u = up.util
e = up.element
###**
Fetches this given URL with JavaScript and [replaces](/up.replace) the
current `<body>` element with the response's `<body>` element.
\#\#\# Example
This would replace the current page with the response for `/users`:
up.visit('/users')
@function up.visit
@param {string} url
The URL to visit.
@param {string} [options.target='body']
The selector to replace.
@param {Object} [options]
See options for [`up.replace()`](/up.replace)
@stable
###
visit = (url, options = {}) ->
selector = options.target ? 'body'
up.replace(selector, url, options)
###**
Fetches the given link's `[href]` with JavaScript and [replaces](/up.replace) the current page with HTML from the response.
By default the page's `<body>` element will be replaced.
If the link has an attribute like `a[up-target]`
or `a[up-modal]`, the respective Unpoly behavior will be used.
Emits the event `up:link:follow`.
\#\#\# Examples
Assume we have a link with an `a[up-target]` attribute:
<a href="/users" up-target=".main">Users</a>
Calling `up.follow()` with this link will replace the page's `.main` fragment
as if the user had clicked on the link:
var link = document.querySelector('a')
up.follow(link)
@function up.follow
@param {Element|jQuery|string} linkOrSelector
An element or selector which is either an `<a>` tag or any element with an `[up-href]` attribute.
@param {string} [options.target]
The selector to replace.
Defaults to the link's `[up-target]`, `[up-modal]` or `[up-popup]` attribute.
If no target is given, the `<body>` element will be replaced.
@param {String} [options.url]
The URL to navigate to.
Defaults to the link's `[up-href]` or `[href]` attribute.
@param {boolean|string} [options.reveal=true]
Whether to [reveal](/up.reveal) the target fragment after it was replaced.
You can also pass a CSS selector for the element to reveal.
@param {boolean|string} [options.failReveal=true]
Whether to [reveal](/up.reveal) the target fragment when the server responds with an error.
You can also pass a CSS selector for the element to reveal.
@return {Promise}
A promise that will be fulfilled when the link destination
has been loaded and rendered.
@stable
###
follow = (linkOrSelector, options) ->
link = e.get(linkOrSelector)
variant = followVariantForLink(link)
variant.followLink(link, options)
###**
This event is [emitted](/up.emit) when a link is [followed](/up.follow) through Unpoly.
The event is emitted on the `<a>` element that is being followed.
@event up:link:follow
@param {Element} event.target
The link element that will be followed.
@param event.preventDefault()
Event listeners may call this method to prevent the link from being followed.
@stable
###
###**
@function defaultFollow
@internal
###
defaultFollow = (link, options) ->
options = u.options(options)
url = options.url ? link.getAttribute('up-href') ? link.getAttribute('href')
target = options.target ? link.getAttribute('up-target')
options.failTarget ?= link.getAttribute('up-fail-target')
options.fallback ?= link.getAttribute('up-fallback')
options.transition ?= e.booleanOrStringAttr(link, 'up-transition')
options.failTransition ?= e.booleanOrStringAttr(link, 'up-fail-transition')
options.history ?= e.booleanOrStringAttr(link, 'up-history')
options.reveal ?= e.booleanOrStringAttr(link, 'up-reveal') ? true
options.failReveal ?= e.booleanOrStringAttr(link, 'up-fail-reveal') ? true
options.cache ?= e.booleanAttr(link, 'up-cache')
options.restoreScroll ?= e.booleanAttr(link, 'up-restore-scroll') # the option may contain an Object, but not the attr
options.method = followMethod(link, options)
options.origin ?= link
options.layer ?= link.getAttribute('up-layer')
options.failLayer ?= link.getAttribute('up-fail-layer')
options.confirm ?= link.getAttribute('up-confirm')
options.scrollBehavior ?= link.getAttribute('up-scroll-behavior')
options.scrollSpeed ?= link.getAttribute('up-scroll-speed')
options = u.merge(options, up.motion.animateOptions(options, link))
up.browser.whenConfirmed(options).then ->
up.replace(target, url, options)
defaultPreload = (link, options) ->
options = u.options(options)
options.preload = true
defaultFollow(link, options)
###**
Returns the HTTP method that should be used when following the given link.
Looks at the link's `up-method` or `data-method` attribute.
Defaults to `"get"`.
@function up.link.followMethod
@param link
@param options.method {string}
@internal
###
followMethod = (link, options = {}) ->
rawMethod = options.method ? link.getAttribute('up-method') ? link.getAttribute('data-method') ? 'GET'
rawMethod.toUpperCase()
###**
No-op that is called when we allow a browser's default action to go through,
so we can spy on it in unit tests. See `link_spec.js`.
@function allowDefault
@internal
###
allowDefault = (event) ->
followVariants = []
###**
Registers the given handler for links with the given selector.
This does more than a simple `click` handler:
- It also handles `[up-instant]`
- It also handles `[up-href]`
@function up.link.addFollowVariant
@param {string} simplifiedSelector
A selector without `a` or `[up-href]`, e.g. `[up-target]`
@param {Function(element, options)} options.follow
@param {Function(element, options)} options.preload
@internal
###
addFollowVariant = (simplifiedSelector, options) ->
variant = new up.FollowVariant(simplifiedSelector, options)
followVariants.push(variant)
variant.registerEvents()
variant
###**
Returns whether the given link will be [followed](/up.follow) by Unpoly
instead of making a full page load.
A link will be followed by Unpoly if it has an attribute
like `a[up-target]` or `a[up-modal]`.
@function up.link.isFollowable
@param {Element|jQuery|string} linkOrSelector
The link to check.
@experimental
###
isFollowable = (linkOrSelector) ->
linkOrSelector = e.get(linkOrSelector)
!!followVariantForLink(linkOrSelector, default: false)
###**
Returns the handler function that can be used to follow the given link.
E.g. it wil return a handler calling `up.modal.follow` if the link is a `[up-modal]`,
but a handler calling `up.link.follow` if the links is `[up-target]`.
@param {Element} link
@return {Object}
@internal
###
followVariantForLink = (link, options = {}) ->
variant = u.find followVariants, (variant) -> variant.matchesLink(link)
variant ||= DEFAULT_FOLLOW_VARIANT unless options.default is false
variant
###**
Makes sure that the given link will be [followed](/up.follow)
by Unpoly instead of making a full page load.
This is done by giving the link an `a[up-follow]` attribute
unless it already have it an attribute like `a[up-target]` or `a[up-modal]`.
@function up.link.makeFollowable
@param {Element|jQuery|string} linkOrSelector
The link to process.
@experimental
###
makeFollowable = (link) ->
unless isFollowable(link)
link.setAttribute('up-follow', '')
shouldProcessEvent = (event, link) ->
target = event.target
# We never handle events for the right mouse button, or when Shift/CTRL/Meta is pressed
return false unless u.isUnmodifiedMouseEvent(event)
# If we actually targeted `link`, save ourselves the expensive DOM traversal below
return true if target == link
# If user clicked on a child link of $link, or in an <input> within an [up-expand][up-href]
# we want those other elements handle the click.
betterTargetSelector = "a, [up-href], #{up.form.fieldSelector()}"
betterTarget = e.closest(target, betterTargetSelector)
return !betterTarget || betterTarget == link
###**
Returns whether the given link has a [safe](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1)
HTTP method like `GET`.
@function up.link.isSafe
@experimental
###
isSafe = (selectorOrLink, options) ->
method = followMethod(selectorOrLink, options)
up.proxy.isSafeMethod(method)
###**
[Follows](/up.follow) this link with JavaScript and replaces a CSS selector
on the current page with a corresponding element from the response.
\#\#\# Example
This will update the fragment `<div class="main">` with the same element
fetched from `/posts/5`:
<a href="/posts/5" up-target=".main">Read post</a>
\#\#\# Updating multiple fragments
You can update multiple fragments from a single request by separating
separators with a comma (like in CSS).
For instance, if opening a post should
also update a bubble showing the number of unread posts, you might
do this:
<a href="/posts/5" up-target=".main, .unread-count">Read post</a>
\#\#\# Appending or prepending content
By default Unpoly will replace the given selector with the same
selector from the server response. Instead of replacing you
can *append* the loaded content to the existing content by using the
`:after` pseudo selector. In the same fashion, you can use `:before`
to indicate that you would like the *prepend* the loaded content.
A practical example would be a paginated list of items. Below the list is
a button to load the next page. You can append to the existing list
by using `:after` in the `up-target` selector like this:
<ul class="tasks">
<li>Wash car</li>
<li>Purchase supplies</li>
<li>Fix tent</li>
</ul>
<a href="/page/2" class="next-page" up-target=".tasks:after, .next-page">
Load more tasks
</a>
\#\#\# Following elements that are no links
You can also use `[up-target]` to turn an arbitrary element into a link.
In this case, put the link's destination into the `[up-href]` attribute:
<button up-target=".main" up-href="/foo/bar">Go</button>
Note that using any element other than `<a>` will prevent users from
opening the destination in a new tab.
@selector a[up-target]
@param {string} up-target
The CSS selector to replace
Inside the CSS selector you may refer to this link as `&` ([like in Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector)).
@param {string} [up-method='get']
The HTTP method to use for the request.
@param {string} [up-transition='none']
The [transition](/up.motion) to use for morphing between the old and new elements.
@param [up-fail-target='body']
The CSS selector to replace if the server responds with an error.
Inside the CSS selector you may refer to this link as `&` ([like in Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector)).
@param {string} [up-fail-transition='none']
The [transition](/up.motion) to use for morphing between the old and new elements
when the server responds with an error.
@param {string} [up-fallback]
The selector to update when the original target was not found in the page.
@param {string} [up-href]
The destination URL to follow.
If omitted, the the link's `href` attribute will be used.
@param {string} [up-confirm]
A message that will be displayed in a cancelable confirmation dialog
before the link is followed.
@param {string} [up-reveal='true']
Whether to reveal the target element after it was replaced.
You can also pass a CSS selector for the element to reveal.
Inside the CSS selector you may refer to this link as `&` ([like in Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector)).
@param {string} [up-fail-reveal='true']
Whether to reveal the target element when the server responds with an error.
You can also pass a CSS selector for the element to reveal.
Inside the CSS selector you may refer to this link as `&` ([like in Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector)).
@param {string} [up-restore-scroll='false']
Whether to restore previously known scroll position of all viewports
within the target selector.
@param {string} [up-cache]
Whether to force the use of a cached response (`true`)
or never use the cache (`false`)
or make an educated guess (default).
@param {string} [up-layer='auto']
The name of the layer that ought to be updated. Valid values are
`'auto'`, `'page'`, `'modal'` and `'popup'`.
If set to `'auto'` (default), Unpoly will try to find a match in the link's layer.
If no match was found in that layer,
Unpoly will search in other layers, starting from the topmost layer.
@param {string} [up-fail-layer='auto']
The name of the layer that ought to be updated if the server sends a
non-200 status code.
@param [up-history]
Whether to push an entry to the browser history when following the link.
Set this to `'false'` to prevent the URL bar from being updated.
Set this to a URL string to update the history with the given URL.
@stable
###
DEFAULT_FOLLOW_VARIANT = addFollowVariant '[up-target], [up-follow]',
# Don't just pass the `defaultFollow` function reference so we can stub it in tests
follow: (link, options) -> defaultFollow(link, options)
preload: (link, options) -> defaultPreload(link, options)
###**
Fetches this link's `[href]` with JavaScript and [replaces](/up.replace) the
current `<body>` element with the response's `<body>` element.
To only update a fragment instead of the entire `<body>`, see `a[up-target]`.
\#\#\# Example
<a href="/users" up-follow>User list</a>
\#\#\# Turn any element into a link
You can also use `[up-follow]` to turn an arbitrary element into a link.
In this case, put the link's destination into the `up-href` attribute:
<span up-follow up-href="/foo/bar">Go</span>
Note that using any element other than `<a>` will prevent users from
opening the destination in a new tab.
@selector a[up-follow]
@param {string} [up-method='get']
The HTTP method to use for the request.
@param [up-fail-target='body']
The selector to replace if the server responds with an error.
@param {string} [up-fallback]
The selector to update when the original target was not found in the page.
@param {string} [up-transition='none']
The [transition](/up.motion) to use for morphing between the old and new elements.
@param {string} [up-fail-transition='none']
The [transition](/up.motion) to use for morphing between the old and new elements
when the server responds with an error.
@param [up-href]
The destination URL to follow.
If omitted, the the link's `href` attribute will be used.
@param {string} [up-confirm]
A message that will be displayed in a cancelable confirmation dialog
before the link is followed.
@param {string} [up-history]
Whether to push an entry to the browser history when following the link.
Set this to `'false'` to prevent the URL bar from being updated.
Set this to a URL string to update the history with the given URL.
@param [up-restore-scroll='false']
Whether to restore the scroll position of all viewports
within the response.
@stable
###
###**
By adding an `up-instant` attribute to a link, the destination will be
fetched on `mousedown` instead of `click` (`mouseup`).
<a href="/users" up-target=".main" up-instant>User list</a>
This will save precious milliseconds that otherwise spent
on waiting for the user to release the mouse button. Since an
AJAX request will be triggered right way, the interaction will
appear faster.
Note that using `[up-instant]` will prevent a user from canceling a
click by moving the mouse away from the link. However, for
navigation actions this isn't needed. E.g. popular operation
systems switch tabs on `mousedown` instead of `click`.
`[up-instant]` will also work for links that open [modals](/up.modal) or [popups](/up.popup).
@selector a[up-instant]
@stable
###
###**
[Follows](/up.follow) this link *as fast as possible*.
This is done by:
- [Following the link through AJAX](/a-up-target) instead of a full page load
- [Preloading the link's destination URL](/a-up-preload)
- [Triggering the link on `mousedown`](/a-up-instant) instead of on `click`
\#\#\# Example
Use `up-dash` like this:
<a href="/users" up-dash=".main">User list</a>
This is shorthand for:
<a href="/users" up-target=".main" up-instant up-preload>User list</a>
@selector a[up-dash]
@param {string} [up-dash='body']
The CSS selector to replace
Inside the CSS selector you may refer to this link as `&` ([like in Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector)).
@stable
###
up.macro '[up-dash]', (element) ->
target = e.booleanOrStringAttr(element, 'up-dash')
element.removeAttribute('up-dash')
newAttrs = {
'up-preload': '',
'up-instant': ''
}
if target is true
# If it's literally `true` then we don't have a target selector.
# Just follow the link by replacing `<body>`.
makeFollowable(element)
else
newAttrs['up-target'] = target
e.setMissingAttrs(element, newAttrs)
###**
Add an `[up-expand]` attribute to any element to enlarge the click area of a
descendant link.
`[up-expand]` honors all the Unppoly attributes in expanded links, like
`a[up-target]`, `a[up-instant]` or `a[up-preload]`.
It also expands links that open [modals](/up.modal) or [popups](/up.popup).
\#\#\# Example
<div class="notification" up-expand>
Record was saved!
<a href="/records">Close</a>
</div>
In the example above, clicking anywhere within `.notification` element
would [follow](/up.follow) the *Close* link.
\#\#\# Elements with multiple contained links
If a container contains more than one link, you can set the value of the
`up-expand` attribute to a CSS selector to define which link should be expanded:
<div class="notification" up-expand=".close">
Record was saved!
<a class="details" href="/records/5">Details</a>
<a class="close" href="/records">Close</a>
</div>
\#\#\# Limitations
`[up-expand]` has some limitations for advanced browser users:
- Users won't be able to right-click the expanded area to open a context menu
- Users won't be able to `CTRL`+click the expanded area to open a new tab
To overcome these limitations, consider nesting the entire clickable area in an actual `<a>` tag.
[It's OK to put block elements inside an anchor tag](https://makandracards.com/makandra/43549-it-s-ok-to-put-block-elements-inside-an-a-tag).
@selector [up-expand]
@param {string} [up-expand]
A CSS selector that defines which containing link should be expanded.
If omitted, the first link in this element will be expanded.
@stable
###
up.macro '[up-expand]', (area) ->
selector = area.getAttribute('up-expand') || 'a, [up-href]'
childLinks = e.all(area, selector)
if childLink = childLinks[0]
upAttributePattern = /^up-/
newAttrs = {}
newAttrs['up-href'] = childLink.getAttribute('href')
for attribute in childLink.attributes
name = attribute.name
if name.match(upAttributePattern)
newAttrs[name] = attribute.value
e.setMissingAttrs(area, newAttrs)
area.removeAttribute('up-expand')
makeFollowable(area)
<% if ENV['JS_KNIFE'] %>knife: eval(Knife.point)<% end %>
visit: visit
follow: follow
makeFollowable: makeFollowable
isSafe: isSafe
isFollowable: isFollowable
shouldProcessEvent: shouldProcessEvent
followMethod: followMethod
addFollowVariant: addFollowVariant
followVariantForLink: followVariantForLink
allowDefault: allowDefault
up.visit = up.link.visit
up.follow = up.link.follow