|
| 1 | +require 'bundler/setup' |
| 2 | + |
| 3 | +require 'datastar' |
| 4 | + |
| 5 | +# This is a test Rack endpoint |
| 6 | +# to demo streaming Datastar updates from multiple threads. |
| 7 | +# To run: |
| 8 | +# |
| 9 | +# # install dependencies |
| 10 | +# bundle install |
| 11 | +# # run this endpoint with Puma server |
| 12 | +# bundle exec puma threads.ru |
| 13 | +# |
| 14 | +# visit http://localhost:9292 |
| 15 | +# |
| 16 | +INDEX = <<~HTML |
| 17 | + <!DOCTYPE html> |
| 18 | + <html> |
| 19 | + <head> |
| 20 | + <meta charset="UTF-8"> |
| 21 | + <title>Datastar counter</title> |
| 22 | + <style> |
| 23 | + body { padding: 10em; } |
| 24 | + .counter {#{' '} |
| 25 | + font-size: 2em;#{' '} |
| 26 | + span { font-weight: bold; } |
| 27 | + } |
| 28 | + </style> |
| 29 | + <script type="module" src="https://cdn.jsdelivr.net/gh/starfederation/datastar@release-candidate/bundles/datastar.js"></script> |
| 30 | + </head> |
| 31 | + <body> |
| 32 | + <button#{' '} |
| 33 | + data-on-click="@get('/')"#{' '} |
| 34 | + data-indicator-heartbeat#{' '} |
| 35 | + >Start</button> |
| 36 | + <p class="counter">Slow thread: <span id="slow">waiting</span></p> |
| 37 | + <p class="counter">Fast thread: <span id="fast">waiting</span></p> |
| 38 | + <p id="connection">Disconnected...</p> |
| 39 | + </body> |
| 40 | + <html> |
| 41 | +HTML |
| 42 | + |
| 43 | +trap('INT') { exit } |
| 44 | + |
| 45 | +run do |env| |
| 46 | + # Initialize Datastar with callbacks |
| 47 | + datastar = Datastar |
| 48 | + .from_rack_env(env) |
| 49 | + .on_connect do |sse| |
| 50 | + sse.patch_elements(%(<p id="connection">Connected...</p>)) |
| 51 | + p ['connect', sse] |
| 52 | + end.on_server_disconnect do |sse| |
| 53 | + sse.patch_elements(%(<p id="connection">Done...</p>)) |
| 54 | + p ['server disconnect', sse] |
| 55 | + end.on_client_disconnect do |socket| |
| 56 | + p ['client disconnect', socket] |
| 57 | + end.on_error do |error| |
| 58 | + p ['exception', error] |
| 59 | + puts error.backtrace.join("\n") |
| 60 | + end |
| 61 | + |
| 62 | + if datastar.sse? |
| 63 | + # This will run in its own thread / fiber |
| 64 | + datastar.stream do |sse| |
| 65 | + 11.times do |i| |
| 66 | + sleep 1 |
| 67 | + # Raising an error to demonstrate error handling |
| 68 | + # raise ArgumentError, 'This is an error' if i > 5 |
| 69 | + |
| 70 | + sse.patch_elements(%(<span id="slow">#{i}</span>)) |
| 71 | + end |
| 72 | + end |
| 73 | + |
| 74 | + # Another thread / fiber |
| 75 | + datastar.stream do |sse| |
| 76 | + 1000.times do |i| |
| 77 | + sleep 0.01 |
| 78 | + sse.patch_elements(%(<span id="fast">#{i}</span>)) |
| 79 | + end |
| 80 | + end |
| 81 | + else |
| 82 | + [200, { 'content-type' => 'text/html' }, [INDEX]] |
| 83 | + end |
| 84 | +end |
0 commit comments