-
Notifications
You must be signed in to change notification settings - Fork 90
/
phoenix_live_reload.js
185 lines (160 loc) · 5.17 KB
/
phoenix_live_reload.js
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
let buildFreshUrl = (link) => {
let date = Math.round(Date.now() / 1000).toString()
let url = link.href.replace(/(\&|\\?)vsn=\d*/, "")
let newLink = document.createElement('link')
let onComplete = () => {
if(link.parentNode !== null){
link.parentNode.removeChild(link)
}
}
newLink.onerror = onComplete
newLink.onload = onComplete
link.setAttribute("data-pending-removal", "")
newLink.setAttribute("rel", "stylesheet");
newLink.setAttribute("type", "text/css");
newLink.setAttribute("href", url + (url.indexOf("?") >= 0 ? "&" : "?") + "vsn=" + date)
link.parentNode.insertBefore(newLink, link.nextSibling)
return newLink
}
let repaint = () => {
let browser = navigator.userAgent.toLowerCase()
if(browser.indexOf("chrome") > -1){
setTimeout(() => document.body.offsetHeight, 25)
}
}
let cssStrategy = () => {
let reloadableLinkElements = window.parent.document.querySelectorAll(
"link[rel=stylesheet]:not([data-no-reload]):not([data-pending-removal])"
)
Array.from(reloadableLinkElements)
.filter(link => link.href)
.forEach(link => buildFreshUrl(link))
repaint()
};
let pageStrategy = channel => {
channel.off("assets_change")
window[targetWindow].location.reload()
}
let reloadStrategies = {
css: reloadPageOnCssChanges ? pageStrategy : cssStrategy,
page: pageStrategy
};
class LiveReloader {
constructor(socket){
this.socket = socket
this.logsEnabled = false
this.enabledOnce = false
this.editorURL = null
}
enable(){
this.socket.onOpen(() => {
if(this.enabledOnce){ return }
this.enabledOnce = true
if(["complete", "loaded", "interactive"].indexOf(parent.document.readyState) >= 0){
this.dispatchConnected()
} else {
parent.addEventListener("load", () => this.dispatchConnected())
}
})
this.channel = socket.channel("phoenix:live_reload", {})
this.channel.on("assets_change", msg => {
let reloadStrategy = reloadStrategies[msg.asset_type] || reloadStrategies.page
setTimeout(() => reloadStrategy(this.channel), interval)
})
this.channel.on("log", ({msg, level}) => this.logsEnabled && this.log(level, msg))
this.channel.join().receive("ok", ({editor_url}) => {
this.editorURL = editor_url
})
this.socket.connect()
}
disable(){
this.channel.leave()
socket.disconnect()
}
enableServerLogs(){ this.logsEnabled = true }
disableServerLogs(){ this.logsEnabled = false }
openEditorAtCaller(targetNode){
if(!this.editorURL){
return console.error("phoenix_live_reload cannot openEditorAtCaller without configured PLUG_EDITOR")
}
let fileLineApp = this.closestCallerFileLine(targetNode)
if(fileLineApp){
this.openFullPath(...fileLineApp)
}
}
openEditorAtDef(targetNode){
if(!this.editorURL){
return console.error("phoenix_live_reload cannot openEditorAtDef without configured PLUG_EDITOR")
}
let fileLineApp = this.closestDefFileLine(targetNode)
if(fileLineApp){
this.openFullPath(...fileLineApp)
}
}
// private
openFullPath(file, line, app){
console.log("opening full path", file, line, app)
this.channel.push("full_path", {rel_path: file, app: app})
.receive("ok", ({full_path}) => {
console.log("full path", full_path)
let url = this.editorURL
.replace("__RELATIVEFILE__", file)
.replace("__FILE__", full_path)
.replace("__LINE__", line)
window.open(url, "_self")
})
.receive("error", reason => console.error("failed to resolve full path", reason))
}
dispatchConnected(){
parent.dispatchEvent(new CustomEvent("phx:live_reload:attached", {detail: this}))
}
log(level, str){
let levelColor = level === "debug" ? "darkcyan" : "inherit"
let consoleFunc = this.logFunc(level)
this.logMsg(consoleFunc, str, levelColor)
}
logMsg(fun, str, color) {
fun(`%c📡 ${str}`, `color: ${color};`)
}
logFunc(level){
switch(level) {
case "debug":
return console.debug;
case "info":
return console.info;
case "warning":
return console.warn;
default:
return console.error;
}
}
closestCallerFileLine(node){
while(node.previousSibling){
node = node.previousSibling
if(node.nodeType === Node.COMMENT_NODE){
let callerComment = node.previousSibling
let callerMatch = callerComment &&
callerComment.nodeType === Node.COMMENT_NODE &&
callerComment.nodeValue.match(/\s@caller\s+(.+):(\d+)\s\((.*)\)\s/i)
if(callerMatch){
return [callerMatch[1], callerMatch[2], callerMatch[3]]
}
}
}
if(node.parentNode){ return this.closestCallerFileLine(node.parentNode) }
}
closestDefFileLine(node){
while(node.previousSibling){
node = node.previousSibling
if(node.nodeType === Node.COMMENT_NODE){
let fcMatch = node.nodeValue.match(/.*>\s([\w\/]+.*ex):(\d+)\s\((.*)\)\s/i)
if(fcMatch){
return [fcMatch[1], fcMatch[2], fcMatch[3]]
}
}
}
if(node.parentNode){ return this.closestDefFileLine(node.parentNode) }
}
}
reloader = new LiveReloader(socket)
reloader.enable()