/
markdown_editor.go
105 lines (85 loc) · 2.4 KB
/
markdown_editor.go
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
package markdowneditor
import (
"github.com/gopherjs/gopherjs/js"
"honnef.co/go/js/dom"
"myitcv.io/react"
"myitcv.io/remarkable"
)
//go:generate gobin -m -run myitcv.io/react/cmd/reactGen
// MarkdownEditorDef is the definition of the MarkdownEditor component
type MarkdownEditorDef struct {
react.ComponentDef
}
// MarkdownEditorState is the state type for the MarkdownEditor component
type MarkdownEditorState struct {
value string
remark *remarkable.Remarkable
// We don't actually use the DOM element for the containing div in the
// logic of the MarkdownEditor example, rather it's just a demonstration
// of React Refs at work.
div *divRef
}
// MarkdownEditor creates instances of the MarkdownEditor component
func MarkdownEditor() *MarkdownEditorElem {
return buildMarkdownEditorElem()
}
// GetInitialState returns the initial state for a MarkdownEditor component
func (m MarkdownEditorDef) GetInitialState() MarkdownEditorState {
remark := remarkable.NewRemarkable()
return MarkdownEditorState{
value: "Type some *markdown* here!",
remark: remark,
div: &divRef{m: m},
}
}
// Render renders the MarkdownEditor component
func (m MarkdownEditorDef) Render() react.Element {
val := m.State().value
return react.Div(&react.DivProps{Ref: m.State().div},
react.H3(nil, react.S("Input")),
react.TextArea(
&react.TextAreaProps{
ClassName: "form-control",
Value: val,
OnChange: inputChange{m},
},
),
react.H3(nil, react.S("Output")),
react.Div(
&react.DivProps{
ClassName: "well",
DangerouslySetInnerHTML: m.getRawMarkup(),
},
),
)
}
func (m MarkdownEditorDef) getRawMarkup() *react.DangerousInnerHTML {
st := m.State()
md := st.remark.Render(st.value)
return react.NewDangerousInnerHTML(md)
}
type inputChange struct{ m MarkdownEditorDef }
func (i inputChange) OnChange(se *react.SyntheticEvent) {
st := i.m.State()
target := se.Target().(*dom.HTMLTextAreaElement)
st.value = target.Value
i.m.SetState(st)
}
type divRef struct {
m MarkdownEditorDef
div *dom.HTMLDivElement
}
func (d *divRef) Ref(h *js.Object) {
if h == nil {
// unmounting
return
}
var div *dom.HTMLDivElement
if e := dom.WrapHTMLElement(h); e != nil {
div = e.(*dom.HTMLDivElement)
}
d.div = div
print("Here is the containing div for the rendered MarkdownEditor", div.Object)
// in case we need to re-render at this point we could call
d.m.ForceUpdate()
}