-
Notifications
You must be signed in to change notification settings - Fork 0
/
rails_hotwire_notes.txt
1797 lines (1163 loc) · 55.2 KB
/
rails_hotwire_notes.txt
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Channels (Action Cable)
========================================================================
> rails g channel room
app/channels
├── application_cable
│ ├── channel.rb *
│ └── connection.rb *
└── room_channel.rb <----------
app/javascript/channels
├── consumer.js
├── index.js
└── room_channel.js <----------
Now,
channel.rb:
module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
connection.rb:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
logger.info "========================== connected"
# logger.info env['warden'].user.id
self.current_user = find_verified_user <-- used with devise
logger.add_tags 'ActionCable', current_user.id
end
protected
def find_verified_user # this checks whether a user is authenticated with devise
if verified_user = env['warden'].user
verified_user
else
reject_unauthorized_connection
end
end
end
end
room_channel.rb:
class RoomChannel < ApplicationCable::Channel
def subscribed
stream_from "room_channel" <-----------------
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
----
room_channel.js:
import consumer from "./consumer"
consumer.subscriptions.create("RoomChannel", {
connected() {
// Called when the subscription is ready for use on the server
console.log("connected")
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
// Called when there's incoming data on the websocket for this channel
}
});
- From anywhere in rails, do
ActionCable.server.broadcast "room_channel", message: "helllo"
# This will be captured inside room_channel.js:
received(data) {
// Called when there's incoming data on the websocket for this channel
--> data['message']
}
- To send a message from client to server (channel).
consumer.send({
command: 'message', data: JSON.stringify({
message: 'This is a cool chat app.'
}),
identifier: JSON.stringify({
channel: "RoomChannel"
})
});
Stimulus
========================================================================
# # https://www.stimulus-components.com/docs/stimulus-lightbox/
# After setting up your rails with stimulus (Rails 7 by defualt)
- You need to know that Turbolinks and UJS Replaced by Turbo and Stimulus
├── application.js
├── controllers
│ ├── application.js
│ ├── hello_controller.js
│ └── index.js
└── lib.js // ignore
application.js:
// Entry point for the build script in your package.json
import "@hotwired/turbo-rails"
import "./controllers"
# add this to capture whenever turbolink is loaded
# check other events
# with jQuery
$(document).on('turbo:load', function() {})
# Or vanilla
document.addEventListener("turbo:before-cache", function() {})
document.addEventListener("turbo:load", function() {})
controllers/index.js
// This file is auto-generated by ./bin/rails stimulus:manifest:update
// Run that command whenever you add a new controller or create them with
// ./bin/rails generate stimulus controllerName
import { application } from "./application"
import HelloController from "./hello_controller"
application.register("hello", HelloController);
controllers/application.js
import { Application } from "@hotwired/stimulus"
const application = Application.start()
// Configure Stimulus development experience
application.debug = false
window.Stimulus = application
export { application }
controllers/hello_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
this.element.textContent = "Hello World!" // this will replace everything inside the controller element
}
}
- create a new controller. app/javascript/controllers/demo_controller.js:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
this.element.textContent = "Hello World!"
}
# conditional loading .. return true to load
static get shouldLoad() {
return true; // false
}
}
- this includes a list of properties to be used
this.application -> stimulus application instance
this.element -> html element and therefor you can read the id
this.element.dataset -> to read values of data-id="1" as this.element.dataset.id
this.element.value -> to read the value of element (input field)
- Register the controller in index.js
import DemoController from "./demo_controller"
application.register("demo", DemoController);
# If you use Stimulus for Rails with an import map or Webpack together with the @hotwired/stimulus-webpack-helpers package,
your application will automatically load and register controller classes following the conventions above.
# In our case (esbuild) If not, your application must manually load and register each controller class.
- View
<div id="1" data-id="1" data-controller="demo">
</div>
# You can have as many views you want in the same page, all will be activated by the same controller
# check for which element
connect() {
this.element.dataset.id --> 1
const element = this.element;
const data = element.dataset;
const id = element.id # this is possible if used id=""
if (data.id == 1) {
element.textContent = "Hello 1"
} else {
element.textContent = "Hello 2"
}
}
- Controllers
# identifiers naming
controllers/demo_controller.js -> data-controller="demo"
clipboard_controller.js clipboard
date_picker_controller.js date-picker
users/list_item_controller.js users--list-item <-----
local-time-controller.js local-time
# scope
# Everything inside this div within the scope of controller including the parent
<div data-id="1" data-controller="demo">
<h1>Hello</h1>
</div>
# nested
<ul id="parent" data-controller="list">
<li data-list-target="item">One</li>
<li>
<ul id="child" data-controller="list">
<li data-list-target="item">I am</li> <------ not part of parent scope
</ul>
</li>
</ul>
# you can have multiple controllers, also you can have multiple elements on the page reference to the same controller
<div data-controller="clipboard list-item"></div>
# cross controllers communications
# The Controller class has a convenience method called (dispatch)
# Both controllers need to be set on the same view (scope)
class ClipboardController extends Controller {
static targets = [ "source" ]
copy() {
# dispatch event called "copy"
# with payload in detail: { content: this.sourceTarget.value }
this.dispatch("copy", { target: document, detail: { content: this.sourceTarget.value } }) --> read the value in input field
--> <input data-clipboard-target="source" type="text" value="1234" readonly>
this.sourceTarget.select()
document.execCommand("copy") <-- execute the command dispatch copy
}
}
class EffectsController extends Controller {
flash({ detail: { content } }) {
// e.detail.content
// e.target -----> the sender element (clipboard) .. tyou can pass document { target: document, detail: { content: this.sourceTarget.value } }
// e.params
// e.type -----> clipboard:copy
console.log(content) // 1234
}
}
<div data-controller="clipboard effects" data-action="clipboard:copy->effects#flash"> 2 --> this will call flash method once clipboard.copy id dispatched !!
PIN: <input data-clipboard-target="source" type="text" value="1234" readonly>
<button data-action="clipboard#copy">Copy to Clipboard</button> 1 --> this will invoke method copy()
</div>
# For distant controllers / views use @document
data-action="clipboard:copy@document->effects#flash"
# Directly Invoking Other Controllers
class MyController extends Controller {
static targets = [ "other" ]
copy() {
const otherController = this.application.getControllerForElementAndIdentifier(this.otherTarget, 'other')
otherController.otherMethod()
}
}
# a batter way
export default class extends Controller {
connect () {
this.element[this.identifier] = this
}
name () {
this.element.innerHTML = `I am ${this.element.dataset.name}.`
}
}
// index.html
<div id="person" data-controller="test" data-name="Steve"></div>
// run this in your console
document.querySelector('#person').test.name()
# https://www.betterstimulus.com/interaction/controller-dom-mapper.html
#### be aware of the Turbolinks’ preview cache
*********************************************
[D]uring standard navigation (via Application Visits), Turbolinks will immediately restore the page from cache and display it as a preview while simultaneously loading a fresh copy from the network. This gives the illusion of instantaneous page loads for frequently accessed locations.
when dealing with action generated from a link with href="#" .. use in action fun:
event.preventDefault()
You can disable preview
<meta name="turbo-cache-control" content="no-preview">
Or disable caching completely
<meta name="turbo-cache-control" content="no-cache">
Set these meta data for certain pages, or all pages except --> use content_for
# Callbacks
initialize() Once, when the controller is first instantiated
[name]TargetConnected(target: Element) Anytime a target is connected to the DOM
connect() Anytime the controller is connected to the DOM
[name]TargetDisconnected(target: Element) Anytime a target is disconnected from the DOM
disconnect() Anytime the controller is disconnected from the DOM
- So if you have
static targets = [ "name", "output" ] --> <input data-hello-target="name" type="text">
<h2 data-hello-target="output"></h2>
This will be called:
nameTargetConnected(e) {
console.log("name ......... connected");
e.value = "45" // initial value
}
# Params (within controller)
<div data-controller="demo" data-id="1" data-demo-page="1" data-demo-some-param="3" data-id="1">
# can be captured
this.element.dataset.id
this.element.dataset.demoPage
this.element.dataset.demoSomeParam
# state
<div data-controller="slideshow" data-index="1">
initialize() {
this.index = Number(this.element.dataset.index) // whatever variable
}
# you can use values
- Actions
# view
<div data-controller="gallery">
<button data-action="click->gallery#next">…</button>
</div>
# gallery_controller.js
next(event) {
// …
// event.type The name of the event (e.g. "click")
// event.target The target that dispatched the event (i.e. the innermost element that was clicked)
// event.currentTarget The target on which the event listener is installed (either the element with the data-action attribute, or document or window)
// event.params The action params passed by the action submitter element
// event.preventDefault() Cancels the event’s default behavior (e.g. following a link or submitting a form)
// event.stopPropagation() Stops the event before it bubbles up to other listeners on parent elements
// event.stopImmediatePropagation() This will ignore any further actions (multiple actions)
}
# click here can be removed for certain element to use the default
click->gallery#next
# defaults
a click
button click
details toggle // what is this ?
form submit
input input
input type=submit click
select change
textarea input
# Global Events
# You can append @window or @document to the event name in an action descriptor to install the event listener on window or document
data-action="resize@window->gallery#layout"
# options
# check https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#parameters
data-action="scroll->gallery#layout:!passive"
:capture { capture: true }
:once { once: true }
:passive { passive: true }
:!passive { passive: false }
# you can have multiple actions
<input type="text" data-action="focus->field#highlight input->search#update">
# Params - How to read params from events
<div data-controller="demo" data-demo-some-param="3" data-id="1"> --> e.params.some
data-[controller]-id-param="12345" 123 Number
data-[controller]-url-param="/votes" "/votes" String
data-[controller]-payload-param='{"value":"1234567"}' { value: 1234567 } Object
data-[controller]-active-param="true" true Boolean
# from controller
func(e) {
e.params.url --> "/votes"
}
# shortcut to read only params from event
upvote({ params }) {
// { id: 12345, url: "/votes", active: true, payload: { value: 1234567 } }
console.log(params)
}
upvote({ params: { id, url } }) {
console.log(id) // 12345
console.log(url) // "/votes"
}
- Targets
# Targets let you reference important elements by name.
# https://www.npmjs.com/package/stimulus-data-bindings
<input type="text" data-search-target="query">
# to read it from controller
const tragets = ['search']
...
this.searchTarget
# As
Kind Name Value
---------------------------------------------------------------------
Singular this.[name]Target The first matching target in scope
Plural this.[name]Targets An array of all matching targets in scope
Existential this.has[Name]Target A boolean indicating whether there is a matching target in scope
# if (this.hasResultsTarget) { this.resultsTarget.innerHTML = "…"}
# properites
this.searchTarget.textContent
this.searchTarget.value
# Yes since the target here is an HTML element ..
# Shared Targets
<form data-controller="search checkbox">
<input type="checkbox" data-search-target="projects" data-checkbox-target="input">
<input type="checkbox" data-search-target="messages" data-checkbox-target="input">
…
</form>
# Inside the checkbox controller, this.inputTargets returns an array with both checkboxes.
# Optional
if (this.hasResultsTarget) {
this.resultsTarget.innerHTML = "…"
}
﹟Connected and Disconnected Callbacks
# Target element callbacks let you respond whenever a target element is added or removed within the controller’s element.
export default class extends Controller {
static targets = [ "item" ]
itemTargetConnected(element) {
this.sortElements(this.itemTargets)
}
itemTargetDisconnected(element) {
this.sortElements(this.itemTargets)
}
// Private
sortElements(itemTargets) { /* ... */ }
}
- Values
# You can read and write HTML data attributes on controller elements as typed values using special controller properties.
# Example
<div id="1" data-id="1" data-demo-url-value="/messages" data-controller="demo">
</div>
# You can have as many views you want in the same page, all will be activated by the same controller
# check for which element
static values = {
url: String --> this will read data-demo-url-value
# contentType --> data-demo-content-type-value
}
connect() {
// this.element.dataset.id --> 1
fetch(this.urlValue).then(/* … */)
}
# definition
static values = {
url: String, // OR url: { type: String, default: '/bill' },
interval: Number,
params: Object
}
# types
Array JSON.stringify(array) JSON.parse(value []
Boolean boolean.toString() !(value == "0" || value == "false") false
Number number.toString() Number(value) 0
Object JSON.stringify(object) JSON.parse(value) {}
String Itself Itself ""
﹟Properties and Attributes
Getter this.[name]Value Reads data-[identifier]-[name]-value
Setter this.[name]Value= Writes data-[identifier]-[name]-value
Existential this.has[Name]Value Tests for data-[identifier]-[name]-value
# Callbacks
export default class extends Controller {
static values = { url: String }
urlValueChanged(value, previousValue) {
/* … */
}
}
- Working With External Resources
# fetch
<div data-controller="content-loader"
data-content-loader-url-value="/messages.html"></div>
fetch(this.urlValue)
.then(response => response.text())
.then(html => this.element.innerHTML = html)
# to read json
<div data-controller="content-loader"
data-content-loader-url-value="/messages.json"></div>
fetch(this.urlValue)
.then(response => response.json())
.then(data => {
console.log(data);
})
# releasing resources
# you might run some interval to reload certain data every certain time
connect() {
this.refreshTimer = startRefreshing() {
setInterval(() => {
this.load()
}, this.refreshIntervalValue)
}
}
disconnect() {
if (this.refreshTimer) {
clearInterval(this.refreshTimer)
}
}
Good references
# https://www.betterstimulus.com/
Confirm Message Example
------------------------------------------------------------------------
- Link
<%= link_to "Delete", message, method: :delete, data: { :turbo_method => :delete, :turbo_confirm => "Are you sure"} %>
- With controller
<%= link_to "Delete", message, method: :delete, data: { :turbo_method => :delete, :turbo_confirm => "Are you sure"} %>
<%= link_to "Delete", message, method: :delete, data: { :turbo_method => :delete, action: "click->messages#delete" } do %>
# Make sure to register it
messages_controller.js:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
delete(event) {
let confirmed = confirm("Are you sure ?");
if(!confirmed) {
event.preventDefault();
}
}
}
Turbo
========================================================================
# Turbo bundles several techniques for creating fast, modern, progressively enhanced web applications without using much JavaScript.
# all the logic in front-end
# With Turbo, you let the server deliver HTML directly, which means all the logic for checking permissions, interacting directly with your domain model, and everything else that goes into programming an application can happen more or less exclusively within your favorite programming language.
- Turbo Drive accelerates links and form submissions by negating the need for full page reloads.
- Turbo Frames decompose pages into independent contexts, which scope navigation and can be lazily loaded.
- Turbo Streams deliver page changes over WebSocket, SSE or in response to form submissions using just HTML and a set of CRUD-like actions.
- Turbo Native lets your majestic monolith form the center of your native iOS and Android apps, with seamless transitions between web and native sections.
** It's all done by sending HTML over the wire. And for those instances when that's not enough, you can reach for the other side of Hotwire, and finish the job with Stimulus.
# https://github.com/jasonfb/hot-glue (commercial)
# https://www.colby.so/posts/turbo-frames-on-rails
- Turbo is composed of Turbo Drive, Turbo Frames, Turbo Streams, and Turbo Native.
- Each is a valuable piece of the puzzle but today we’re going to focus on Turbo Frames.
- Turbo Drive
-------------------------------------------------------------------------
- Turbo Drive gives you that same speed by using the same persistent-process model, but without requiring you to craft your entire application around the paradigm.
- There’s no client-side router to maintain, there’s no state to carefully manage.
- The persistent process is managed by Turbo, and you write your server-side code as though you were living back in the early aughts – blissfully isolated from the complexities of today’s SPA monstrosities!
- There are two types of visit:
- an application visit, which has an action of advance or replace,
- and a restoration visit, which has an action of restore.
- Application visit
- network request
- When the response arrives, Turbo Drive renders its HTML and completes the visit.
Turbo.visit(location)
# Preview
# If possible, Turbo Drive will render a preview of the page from cache immediately after the visit starts.
# This improves the perceived speed of frequent navigation between the same pages.
- If the visit’s location includes an anchor, Turbo Drive will attempt to scroll to the anchored element. Otherwise, it will scroll to the top of the page.
- Uses: history.pushState.
-You may wish to visit a location without pushing a new history entry onto the stack.
Turbo.visit("/edit", { action: "replace" }) --> <a href="/edit" data-turbo-action="replace">Edit</a>
Turbo.clearCache() # Removes all entries from the Turbo Drive page cache. Call this when state has changed on the server that may affect cached pages.
Turbo.setProgressBarDelay(ms) # Sets the delay after which the progress bar will appear during navigation, in milliseconds.
Turbo.session.drive = false # Turns Turbo Drive off by default. You must now opt-in to Turbo Drive on a per-link and per-form basis using data-turbo="true"
- Restoring
Restoration visits have an action of restore and Turbo Drive reserves them for internal use.
You should not attempt to annotate links or invoke Turbo.visit with an action of restore.
Turbo.visit("/edit", { action: "restore" })
- Canceling Visits Before They Start
- Listen for the turbo:before-visit event to be notified when a visit is about to start, and use event.detail.url
turbo:before-visit --> event.preventDefault()
- Pausing render
turbo:before-render --> event.preventDefault() --> event.detail.resume()
document.addEventListener('turbo:before-render', async (event) => {
event.preventDefault()
await animateOut()
event.detail.resume()
})
- Pausing Requests
turbo:before-fetch-request --> event.preventDefault() --> event.detail.resume()
document.addEventListener('turbo:before-fetch-request', async (event) => {
event.preventDefault()
const token = await getSessionToken(window.app)
event.detail.fetchOptions.headers['Authorization'] = `Bearer ${token}`
event.detail.resume()
})
- Performing Visits With a Different Method
<a href="/articles/54" data-turbo-method="delete">Delete the article</a>
- Disabling Turbo Drive on Specific Links or Forms
<a href="/" data-turbo="false">Disabled</a>
<form action="/messages" method="post" data-turbo="false">
...
</form>
<div data-turbo="false">
<a href="/">Disabled</a>
<a href="/" data-turbo="true">Enabled</a>
<form action="/messages" method="post">
...
</form>
</div>
- If you want Drive to be opt-in rather than opt-out, then you can set Turbo.session.drive = false; then, data-turbo="true" is used to enable Drive on a per-element basis.
- If you’re importing Turbo in a JavaScript pack, you can do this globally:
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false
- Displaying Progress
During Turbo Drive navigation, the browser will not display its native progress indicator.
Turbo Drive installs a CSS-based progress bar to provide feedback while issuing a request.
It appears automatically for any page that takes longer than 500ms to load. (You can change this delay with the Turbo.setProgressBarDelay method.)
The progress bar is a <div> element with the class name turbo-progress-bar. Its default styles appear first in the document and can be overridden by rules that come later.
<div class="turbo-progress-bar"></div>
- Reloading When Assets Change
Turbo Drive can track the URLs of asset elements in <head> from one page to the next and automatically issue a full reload if they change.
<head>
...
<link rel="stylesheet" href="/application-258e88d.css" data-turbo-track="reload">
<script src="/application-cbd3cd4.js" data-turbo-track="reload"></script>
</head>
Ensuring Specific Pages Trigger a Full Reload
<meta name="turbo-visit-control" content="reload">
- Setting a Root Location
<head>
...
<meta name="turbo-root" content="/app">
</head>
- Form Submissions
Form submissions can issue stateful requests using the HTTP POST method
Link clicks only ever issue stateless HTTP GET requests.
Events:
turbo:submit-start
turbo:before-fetch-request
turbo:before-fetch-response
turbo:submit-end
During a submission, Turbo Drive will set the “submitter” element’s disabled attribute when the submission begins, then remove the attribute after the submission ends
Submitter -> HTMLFormElement.requestSubmit()
addEventListener("turbo:submit-start", ({ target }) => {
for (const field of target.elements) {
field.disabled = true
}
})
- Turbo Frames: Decompose complex pages
-------------------------------------------------------------------------
- turbo-rails
# https://github.com/hotwired/turbo-rails
import { Turbo } from "@hotwired/turbo-rails"
Turbo.session.drive = false
Then you can use data-turbo="true" to enable Drive on a per-element basis.
<%# app/views/todos/show.html.erb %>
<%= turbo_frame_tag @todo do %>
<p><%= @todo.description %></p>
<%= link_to 'Edit this todo', edit_todo_path(@todo) %>
<% end %>
<%# app/views/todos/edit.html.erb %>
<%= turbo_frame_tag @todo do %>
<%= render "form" %>
<%= link_to 'Cancel', todo_path(@todo) %>
<% end %>
- Turbo Frames allow predefined parts of a page to be updated on request.
- Any links and forms inside a frame are captured, and the frame contents automatically updated after receiving a response.
- Regardless of whether the server provides a full document, or just a fragment containing an updated version of the requested frame, only that particular frame will be extracted from the response to replace the existing content.
- Frames are created by wrapping a segment of the page in a <turbo-frame> element.
- At a high level, Turbo Frames are pieces of a webpage that can be updated independently, without impacting the rest of the content on the page.
- Links and forms within a frame will, by default, attempt to update only the content of the containing frame, whether the server sends a completely new HTML document or only a page fragment.
- Overview
<%= turbo_frame_tag @message, :data => {:controller => "message"} do %>
<%= render @message %>
<%= link_to "Edit this message", edit_message_path(@message) %> |
<%= link_to "Back to messages", messages_path, "data-turbo-frame": "_top" %> |
<%= button_to "Delete", @message, method: :delete, data: { :action => "click->message#delete", :turbo => false } %>
<% end %>
- Notice the click->message#delete is a stimulus controller call
==
<turbo-frame id="message_1" data-controller="message">
<!-- render messages/message -->
</turbo-frame>
- When src is supplied, the frame will be populated after the initial page load via a separate HTTP request to the frame’s
<%= turbo_frame_tag "messages", src: messages_path do %>
<% end %>
=
<turbo-frame id="messages">
<!-- A list of messages, perhaps -->
</turbo-frame>
*- Navigating within frames
- By default, links and forms within a Turbo Frame will perform the navigation within the frame, rather than performing a full page turn.
<% @messages do |message| %>
<%= turbo_frame_tag message do %>
<div>
<%= link_to message.body, edit_message_path(message) %> --> this will load the edit form of this comment and replace it with original content
</div>
<% end %>
<% end %>
=
<turbo-frame id="message_1">
<div>
<a href="/messages/1/edit">Message 1</a>
</div>
</turbo-frame>
- The Turbo Frame request is a normal HTML request with an additional Turbo-Frame header included in the request, with a value that matches the id of the target Turbo Frame.
- You can identify if the request coming from a frame
if turbo_frame_request?
render partial: "some_turbo_frame_partial"
else
render partial: "some_other_partial"
end
- But it''s better to use the turbo_stream . variant to detect if request coming from a frame (dealing with turbo_streams) - see conditional template rendering using variants
# When receving response
# Here Turbo Drive will do it's job and replaces the content of the target frame, leaving the rest of the page untouched.
- The edit view could contain something like this.
<%= turbo_frame_tag @message do %>
<%= form_with(model: @message) do |form| %>
............
<% end %>
<% end %>
- This will replace the frame tag of the related comment id
- Notice the request was a normal get to edit page request
# GET /messages/1/edit
def edit
end
- From the server, you might redirect the user to the show page of the comment in the example (Create / POST)
- When the request occurs within a Turbo Frame, a “redirect” still occurs, but rather than redirecting the page in the browser, the redirect is followed, the new HTML content is sent from the server, and that HTML is used to update the frame.
# POST /messages or /messages.json
def create
@message = Message.new(message_params)
respond_to do |format|
if @message.save
format.html { redirect_to message_url(@message), notice: "Message was successfully created." }
format.json { render :show, status: :created, location: @message }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @message.errors, status: :unprocessable_entity }
end
end
end
- Therefor the view page will look like this
<%= turbo_frame_tag @comment do %>
<div>
<%= link_to @comment.body, edit_comment_path(@comment) %>
</div>
<% end %>
- Breaking out of a frame
<%= link_to comment.body, edit_comment_path(comment), data: { turbo_frame: "_top" } %>
<%= turbo_frame_tag 'new_search', target: '_top' do %>
<!-- any link inside will break the frame -->
<% end %>
- Targeting a frame from the outside
<a href="user/1/favorites" data-turbo-frame="main">
Favorites
</a>