-
-
Notifications
You must be signed in to change notification settings - Fork 195
Expand file tree
/
Copy pathLiveHTMLDocument.js
More file actions
366 lines (321 loc) · 13.7 KB
/
LiveHTMLDocument.js
File metadata and controls
366 lines (321 loc) · 13.7 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
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
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2012 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/**
* LiveHTMLDocument manages a single HTML source document. Edits to the HTML are applied live in
* the browser, and the DOM node corresponding to the selection is highlighted.
*
* LiveHTMLDocument relies on HTMLInstrumentation in order to map tags in the HTML source text
* to DOM nodes in the browser, so edits can be incrementally applied.
*/
define(function (require, exports, module) {
var EventDispatcher = require("utils/EventDispatcher"),
PerfUtils = require("utils/PerfUtils"),
_ = require("thirdparty/lodash"),
LiveDocument = require("LiveDevelopment/MultiBrowserImpl/documents/LiveDocument"),
HTMLInstrumentation = require("LiveDevelopment/MultiBrowserImpl/language/HTMLInstrumentation"),
HTMLUtils = require("language/HTMLUtils"),
CSSUtils = require("language/CSSUtils");
/**
* @constructor
* @see LiveDocument
* @param {LiveDevProtocol} protocol The protocol to use for communicating with the browser.
* @param {function(string): string} urlResolver A function that, given a path on disk, should return
* the URL that Live Development serves that path at.
* @param {Document} doc The Brackets document that this live document is connected to.
* @param {?Editor} editor If specified, a particular editor that this live document is managing.
* If not specified initially, the LiveDocument will connect to the editor for the given document
* when it next becomes the active editor.
*/
function LiveHTMLDocument(protocol, urlResolver, doc, editor) {
LiveDocument.apply(this, arguments);
this.doc.addRef();
this._instrumentationEnabled = false;
this._relatedDocuments = {
stylesheets: {},
scripts: {}
};
this._onChange = this._onChange.bind(this);
this.doc.on("change", this._onChange);
this._onRelated = this._onRelated.bind(this);
this.protocol.on("DocumentRelated", this._onRelated);
this._onStylesheetAdded = this._onStylesheetAdded.bind(this);
this.protocol.on("StylesheetAdded", this._onStylesheetAdded);
this._onStylesheetRemoved = this._onStylesheetRemoved.bind(this);
this.protocol.on("StylesheetRemoved", this._onStylesheetRemoved);
this._onScriptAdded = this._onScriptAdded.bind(this);
this.protocol.on("ScriptAdded", this._onScriptAdded);
this._onScriptRemoved = this._onScriptRemoved.bind(this);
this.protocol.on("ScriptRemoved", this._onScriptRemoved);
}
LiveHTMLDocument.prototype = Object.create(LiveDocument.prototype);
LiveHTMLDocument.prototype.constructor = LiveHTMLDocument;
LiveHTMLDocument.prototype.parentClass = LiveDocument.prototype;
EventDispatcher.makeEventDispatcher(LiveHTMLDocument.prototype);
/**
* @override
* Returns true if document edits appear live in the connected browser.
* @return {boolean}
*/
LiveHTMLDocument.prototype.isLiveEditingEnabled = function () {
return this._instrumentationEnabled;
};
/**
* @override
* Called to turn instrumentation on or off for this file. Triggered by being
* requested from the browser.
* TODO: this doesn't seem necessary...if we're a live document, we should
* always have instrumentation on anyway.
* @param {boolean} enabled
* @param {boolean} [force]
*/
LiveHTMLDocument.prototype.setInstrumentationEnabled = function (enabled, force) {
if (!this.editor) {
// TODO: error
return;
}
if (enabled && (force || !this._instrumentationEnabled)) {
// TODO: not clear why we do this here instead of waiting for the next time we want to
// generate the instrumented HTML. This won't work if the dom offsets are out of date.
HTMLInstrumentation.scanDocument(this.doc);
HTMLInstrumentation._markText(this.editor);
}
this._instrumentationEnabled = enabled;
};
/**
* Returns the instrumented version of the file.
* @return {{body: string}} instrumented doc
*/
LiveHTMLDocument.prototype.getResponseData = function (enabled) {
var body;
if (this._instrumentationEnabled) {
body = HTMLInstrumentation.generateInstrumentedHTML(this.editor, this.protocol.getRemoteScript());
}
if (!body) {
// generateInstrumentedHTML() returns null when the document is empty or its
// HTML cannot be parsed into a DOM (no instrumentable content). In that case it
// also never injected the remote <script>, so without help the served page would
// have no live-preview runtime at all — a blank page with no way to connect back
// or start editing. Fall back to the raw text but still inject the remote script
// so the runtime always loads, even for a completely empty page.
body = this.doc.getText();
if (this._instrumentationEnabled) {
body += this.protocol.getRemoteScript();
}
}
return {
body: body
};
};
/**
* @override
* Closes the live document, terminating its connection to the browser.
*/
LiveHTMLDocument.prototype.close = function () {
this.doc.releaseRef();
this.doc.off("change", this._onChange);
this.protocol.off("DocumentRelated", this._onRelated);
this.protocol.off("StylesheetAdded", this._onStylesheetAdded);
this.protocol.off("StylesheetRemoved", this._onStylesheetRemoved);
this.protocol.off("ScriptAdded", this._onScriptAdded);
this.protocol.off("ScriptRemoved", this._onScriptRemoved);
this.parentClass.close.call(this);
};
/**
* @override
* Update the highlights in the browser based on the cursor position.
*/
LiveHTMLDocument.prototype.updateHighlight = function () {
if (!this.editor || !this.isHighlightEnabled()) {
return;
}
var editor = this.editor,
mode = editor.getModeForSelection(),
ids = [],
selectors = [];
// check if the cursor is in a stylesheet context (internal styles)
// but skip CSS selector lookup for inline style attributes (style="...")
// since they have no selector — the element itself should be highlighted instead
if (mode === "css" || mode === "text/x-scss" || mode === "text/x-less") {
var primarySel = editor.getSelection();
var tagInfo = HTMLUtils.getTagInfo(editor, primarySel.start, true);
var isInlineStyle = tagInfo.position.tokenType === HTMLUtils.ATTR_VALUE &&
tagInfo.attr.name.toLowerCase() === "style";
if (!isInlineStyle) {
// find the css selector
_.each(this.editor.getSelections(), function (sel) {
let selector = CSSUtils.findSelectorAtDocumentPos(editor, (sel.reversed ? sel.end : sel.start));
if (selector) {
selectors.push(selector);
}
});
if (selectors.length) {
// to highlight the elements that match the css selectors
this.highlightRule(selectors.join(","));
return;
}
}
}
// its not found in css context, then it must be a inline style or a normal html element
_.each(this.editor.getSelections(), function (sel) {
var tagID = HTMLInstrumentation._getTagIDAtDocumentPos(
editor,
sel.reversed ? sel.end : sel.start
);
if (tagID !== -1) {
ids.push(tagID);
}
});
if (!ids.length) {
this.hideHighlight();
} else {
this.highlightDomElement(ids);
}
};
/**
* @private
* For the given editor change, compare the resulting browser DOM with the
* in-editor DOM. If there are any diffs, a warning is logged to the
* console along with each diff.
* @param {Object} change CodeMirror editor change data
*/
LiveHTMLDocument.prototype._compareWithBrowser = function (change) {
// TODO: Not implemented.
};
function _isSamePos(position, line, char) {
return position.line === line && position.ch === char;
}
/**
* @private
* Handles edits to the document. Determines what's changed in the source and sends DOM diffs to the browser.
* @param {$.Event} event
* @param {Document} doc
* @param {Object} change
*/
LiveHTMLDocument.prototype._onChange = function (event, doc, change) {
// Make sure LiveHTML is turned on
if (!this._instrumentationEnabled) {
return;
}
// Apply DOM edits is async, so previous PerfUtils timer may still be
// running. PerfUtils does not support running multiple timers with same
// name, so do not start another timer in this case.
var perfTimerName = "LiveHTMLDocument applyDOMEdits",
isNestedTimer = PerfUtils.isActive(perfTimerName);
if (!isNestedTimer) {
PerfUtils.markStart(perfTimerName);
}
var self = this,
result = HTMLInstrumentation.getUnappliedEditList(this.editor, change),
applyEditsPromise;
if (result.edits) {
let changedLineCount = change.length === 1 ? (change[0].to.line - change[0].from.line + 1) : null;
if(changedLineCount && changedLineCount > 1 && changedLineCount === change[0].removed.length
&& _isSamePos( change[0].from, 0, 0)){
// whole file change.
this.protocol.reload();
PerfUtils.addMeasurement(perfTimerName);
} else {
applyEditsPromise = this.protocol.evaluate("_LD.applyDOMEdits(" + JSON.stringify(result.edits) + ")");
applyEditsPromise.always(function () {
if (!isNestedTimer) {
PerfUtils.addMeasurement(perfTimerName);
}
});
}
}
this.errors = result.errors || [];
this._updateErrorDisplay();
// Debug-only: compare in-memory vs. in-browser DOM
// edit this file or set a conditional breakpoint at the top of this function:
// "this._debug = true, false"
if (this._debug) {
console.log("Edits applied to browser were:");
console.log(JSON.stringify(result.edits, null, 2));
applyEditsPromise.done(function () {
self._compareWithBrowser(change);
});
}
};
/**
* @private
* Handles message DocumentRelated from the browser.
* @param {$.Event} event
* @param {Object} msg
*/
LiveHTMLDocument.prototype._onRelated = function (event, msg) {
this._relatedDocuments = msg.related;
return;
};
/**
* @private
* Handles message Stylesheet.Added from the browser.
* @param {$.Event} event
* @param {Object} msg
*/
LiveHTMLDocument.prototype._onStylesheetAdded = function (event, msg) {
this._relatedDocuments.stylesheets[msg.href] = true;
return;
};
/**
* @private
* Handles message Stylesheet.Removed from the browser.
* @param {$.Event} event
* @param {Object} msg
*/
LiveHTMLDocument.prototype._onStylesheetRemoved = function (event, msg) {
delete (this._relatedDocuments.stylesheets[msg.href]);
return;
};
/**
* @private
* Handles message Script.Added from the browser.
* @param {$.Event} event
* @param {Object} msg
*/
LiveHTMLDocument.prototype._onScriptAdded = function (event, msg) {
this._relatedDocuments.scripts[msg.src] = true;
return;
};
/**
* @private
* Handles message Script.Removed from the browser.
* @param {$.Event} event
* @param {Object} msg
*/
LiveHTMLDocument.prototype._onScriptRemoved = function (event, msg) {
delete (this._relatedDocuments.scripts[msg.src]);
return;
};
/**
* For the given path, check if the document is related to the live HTML document.
* Related means that is an external Javascript or CSS file that is included as part of the DOM.
* @param {String} fullPath.
* @return {boolean} - is related or not.
*/
LiveHTMLDocument.prototype.isRelated = function (fullPath) {
return (this._relatedDocuments.scripts[this.urlResolver(fullPath)] || this._relatedDocuments.stylesheets[this.urlResolver(fullPath)]);
};
LiveHTMLDocument.prototype.getRelated = function () {
return this._relatedDocuments;
};
// Export the class
module.exports = LiveHTMLDocument;
});