-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexample.rb
More file actions
104 lines (88 loc) · 2.58 KB
/
example.rb
File metadata and controls
104 lines (88 loc) · 2.58 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
require 'opal'
require 'opal-jquery'
require "json"
require 'react'
class Window
def self.set_interval(delay, &block)
`window.setInterval(function(){#{block.call}}, #{delay.to_i})`
end
end
class Comment
include React::Component
def render
converter = Native(`new Showdown.converter()`)
raw_markup = converter.makeHtml(params[:children].to_s)
div class_name: "comment" do
h2(class_name: "commentAuthor") { params[:author] }
span(dangerously_set_inner_HTML: {__html: raw_markup}.to_n)
end
end
end
class CommentList
include React::Component
def render
div class_name: "commentList" do
params[:data].each_with_index.map do |comment, idx|
present(Comment, author: comment["author"], key: idx) { comment["text"] }
end
end
end
end
class CommentForm
include React::Component
def render
f = form(class_name: "commentForm") do
input type: "text", placeholder: "Your name", ref: "author"
input type: "text", placeholder: "Say something...", ref: "text"
input type: "submit", value: "Post"
end
f.on(:submit) do |event|
event.prevent_default
author = self.refs[:author].dom_node.value.strip
text = self.refs[:text].dom_node.value.strip
return if !text || !author
self.emit(:comment_submit, {author: author, text: text})
self.refs[:author].dom_node.value = ""
self.refs[:text].dom_node.value = ""
end
end
end
class CommentBox
include React::Component
after_mount :load_comments_from_server, :start_polling
define_state(:data) { [] }
def load_comments_from_server
HTTP.get(params[:url]) do |response|
if response.ok?
self.data = JSON.parse(response.body)
else
puts "failed with status #{response.status_code}"
end
end
end
def start_polling
Window.set_interval(params[:poll_interval]) { load_comments_from_server }
end
def handle_comment_submit(comment)
comments = self.data
comments.push(comment)
self.data = comments
HTTP.post(params[:url], payload: comment) do |response|
if response.ok?
self.data = JSON.parse(response.body)
else
puts "failed with status #{response.status_code}"
end
end
end
def render
div class_name: "commentBox" do
h1 { "Comments" }
present CommentList, data: self.data
present(CommentForm).on(:comment_submit) {|c| handle_comment_submit(c) }
end
end
end
Document.ready? do
React.render React.create_element(CommentBox, url: "comments.json", poll_interval: 2000), `document.getElementById('content')`
end