-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmain.js
373 lines (321 loc) · 14.4 KB
/
main.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
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
367
368
369
370
371
372
373
/*
* Copyright (c) 2013 Adobe Systems Incorporated.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, $, brackets */
/**
* The CSS Shapes Editor extension adds a GUI for editing shapes when LivePreview mode is on,
* and the cursor is focused on a CSS Shapes property value, like polygon(), circle() or ellipse();
* Other properties, such as border-box and inset() is not yet supported.
*
* The code for the shapes editor lives in ./thirdparty/CSSShapesEditor.js
* @see https://github.com/adobe-webplatform/css-shapes-editor/
*
* The shapes editor turns on over the first element matched by the selector associated to the
* CSS Declaration Block being edited. The editor will not turn on if the focused CSS Rule does
* not apply, either because of media queries not matching or selector specificity being overturned.
*
* On LiveDevelopment.STATUS_ACTIVE, the CSS Shapes Editor library from /thirdparty/, and its dependencies
* are injected into the page in LivePreview. A mirror LiveEditorRemoteDriver.js is also injected.
* This will be driven by LiveEditorLocalDriver.js
* A Model with the currently focused CSS property, value and their range is built on every cursor
* navigation or change in the document. This model will be passed onto the injected LiveEditorRemoteDriver.js
* and will be kept in sync to mirror the changes between the Brackets code editor and the CSS Shapes Editor
* from the LivePreview page.
*
* This extension can be extended to handle other CSS properties by adding other GUI editor & dependencies
* to the _remoteEditors array and mention which properties they operate on in the SUPPORTED_PROPS array.
* See ./thirdparty/CSSShapesEditorProvider.js for the minimal API other editors must provide.
*/
define(function (require, exports, module) {
"use strict";
var EditorManager = brackets.getModule("editor/EditorManager"),
CSSUtils = brackets.getModule("language/CSSUtils"),
LiveDevelopment = brackets.getModule("LiveDevelopment/LiveDevelopment"),
CSSAgent = brackets.getModule("LiveDevelopment/Agents/CSSAgent"),
ProjectManager = brackets.getModule("project/ProjectManager"),
Model = require("Model"),
LiveEditorDriver = require("LiveEditorLocalDriver");
// TODO: Keep this list up to date with newly added/supported properties
var SUPPORTED_PROPS = ["shape-inside", "-webkit-shape-inside", "shape-outside", "-webkit-shape-outside"];
// Intentional bias towards only -webkit-clip-path (prefixed),
// because clip-path (unprefixed) only applies to SVG.
// -webkit-clip-path applies to HTML & SVG. The properties will merge, eventually.
SUPPORTED_PROPS.push("-webkit-clip-path");
// String source of editor and provider
var CSSShapesEditor = require("text!thirdparty/CSSShapesEditor-min.js"),
CSSShapesEditorProvider = require("text!thirdparty/CSSShapesEditorProvider.js");
/** @type {Array} Dependencies as strings to be injected in the HTML page in LivePreview */
var _remoteEditors = [CSSShapesEditor, CSSShapesEditorProvider];
/** @type {Array} Stylesheet URLs that are used by the active HTML page in LivePreview */
var _relatedStylesheets = [];
/** @type {Editor} */
var _currentEditor = EditorManager.getActiveEditor();
/** @type {boolean} Flag set to true if the LivePreview has just been turned on */
var _isFirstLaunch = false;
/** @type {Model} Stores state to sync between code editor and in-browser editor */
var model = new Model({
property: null,
value: null,
selector: null
});
/**
* @private
* Constructs the global model with data if the cursor is on a CSS rule
* with a property from SUPPORTED_PROPS.
*
* Adds attributes to the model:
* {
* value: {string}, // the CSS value
* property: {string}, // the CSS property
* selector: {string}, // the selector associated with the CSS block
* range: {Object} // the range in the code editor for the CSS value
* }
*
* Resets the existing model if:
* - the cursor is not on a CSS value;
* - the css property is not supported; @see SUPPORTED_PROPS
* - a selector cannot be extracted for the CSS block;
*
* Model triggers 'change' event if any attribute value has changed since last stored.
* Does not trigger 'change' event if cursor is just moving within the same CSS value.
*
* @param {!Event} e 'change' or 'cursorActivity' event dispatched by editor
*/
function _constructModel(e) {
var editor = e.target,
selection = editor.getSelection(),
info,
selector,
range;
// Get the CSS rule info at the selection start position
info = CSSUtils.getInfoAtPos(editor, selection.start);
if (info.context !== CSSUtils.PROP_VALUE || (SUPPORTED_PROPS.indexOf(info.name) < 0)) {
model.reset();
return;
}
selector = CSSUtils.findSelectorAtDocumentPos(editor, selection.start);
if (!selector || typeof selector !== "string") {
model.reset();
return;
}
range = info.range;
// TODO: support multi-line values when we can handle line breaks.
if (info.range && (info.range.start.line !== info.range.end.line)) {
model.reset();
return;
}
model.set({
selector: selector,
property: info.name,
range: range,
value: editor.document.getRange(range.start, range.end)
});
}
/**
* @private
* Check if the current editor is attached to a stylesheet
* related to the page in LivePreview mode.
*
* @return {boolean}
*/
function _isEditingRelatedStylesheet() {
var fullPath = _currentEditor.document.file.fullPath,
projectPath = ProjectManager.getProjectRoot().fullPath,
relativePath = fullPath.replace(projectPath, "");
return (_relatedStylesheets.indexOf(relativePath) > -1);
}
/**
* @private
* Update the Brackets text editor property value using the given model,
* which contains the range and the new property value.
* @param {!Model} model
*/
function _updateCodeEditor(model) {
var range = model.get("range"),
value = model.get("value"),
rangeText;
if (!range) {
return;
}
rangeText = _currentEditor.document.getRange(range.start, range.end);
if (rangeText === value) {
return;
}
_currentEditor.document.replaceRange(value, range.start, range.end, "+");
}
/**
* @private
* Send a command to the LiveEditorDriver update the in-browser editor using the given model
* @param {!Model} model
*/
function _updateLiveEditor(model) {
if (!LiveDevelopment.status || LiveDevelopment.status < LiveDevelopment.STATUS_ACTIVE) {
return;
}
// Emit commands to the live editor only if:
// - the code editor is focused (hence, data comes from input in Brackets)
// OR
// - LivePreview has just started (to immediately show the editor if a shape property is focused)
//
// AND
// - the code editor is invoked on a stylesheet linked to the page in LivePreview
//
// Checking for this avoids echoing back data received from the in-browser editor.
// The echoed data might be stale if the in-browser editor is being actively used.
if ((_isFirstLaunch || EditorManager.getFocusedEditor()) && _isEditingRelatedStylesheet()) {
if (model.get("property")) {
LiveEditorDriver.update(model);
_isFirstLaunch = false;
} else {
LiveEditorDriver.remove();
}
}
}
/**
* @private
* Handle swapping of the currently active editor.
* Remove in-browser editor, event handlers from old code editor.
*/
function _onActiveEditorChange() {
if (_currentEditor) {
$(_currentEditor).off("cursorActivity change", _constructModel);
LiveEditorDriver.remove();
model.reset();
}
_currentEditor = EditorManager.getActiveEditor();
if (_currentEditor) {
$(_currentEditor).on("cursorActivity change", _constructModel);
$(_currentEditor).triggerHandler("cursorActivity");
}
}
/**
* @private
* Handle adding new stylesheet to the page in LivePreview
* Extracts relative URL of added stylesheet
* @param {!Event} styleSheetAdded event
* @param {!string} url of stylesheet
*/
function _onStyleSheetAdded(e, url) {
var baseUrl = LiveDevelopment.getServerBaseUrl();
var relUrl = url.replace(baseUrl, "");
_relatedStylesheets.push(relUrl);
}
/**
* @private
* Setup the extension after LiveDevelopment is turned on
*
* Listen to "change" events to global model of the focused CSS property, its value and its range,
* to synchronize the Brackets editor and the CSS Shapes Editor, which lives in the page in LivePreview
*
* Listen to "styleSheetAdded" events of the page currently in LivePreview to track related stylesheets,
* so we don't edit un-related stylesheets, even if the selector matches.
*
* Listen to changes of the currently active editor
*
* Inject the CSS Shapes Editor and its dependencies into the page in LivePreview
*
* Listen for changes to the model coming from the in-browser editor and synchronize them
* to the model in Brackets
*/
function _setup() {
$(model).on("change", function () {
_updateCodeEditor(model);
_updateLiveEditor(model);
});
$(CSSAgent).on("styleSheetAdded", _onStyleSheetAdded);
$(EditorManager).on("activeEditorChange", _onActiveEditorChange);
LiveEditorDriver.init(_remoteEditors).then(function () {
// Force a first-pass through the workflow after the page loads.
// This will automatically turn on the shape editor if the cursor was focused on a supported property
_isFirstLaunch = true;
$(EditorManager).triggerHandler("activeEditorChange");
});
$(LiveEditorDriver).on("update.model", function (e, data, force) {
// Ignore model updates from live editor if the user is still typing in the code editor.
//
// The code editor and live editor in live preview cannot be both focused at the same time;
// state updates from live editor are likely echoes after syncing with the code editor.
//
// Avoids weird state bugs as a result of the frequency of sync loop in LiveEditorDriver.
//
// ---
//
// If there is a request to force a model update, circumvent this.
//
// A forced update is required when leveraging the live editor to infer coordinates.
// @example circle() -> circle(50%, 50%, 50%)
if (EditorManager.getFocusedEditor() && !force) {
return;
}
model.set(data);
});
}
/**
* @private
* Remove all handlers and clean-up after LiveDevelopment is turned off.
*/
function _teardown() {
$(model).off("change");
$(EditorManager).off("activeEditorChange", _onActiveEditorChange);
$(CSSAgent).off("styleSheetAdded", _onStyleSheetAdded);
_relatedStylesheets.length = 0;
LiveEditorDriver.remove();
$(LiveEditorDriver).off("update.model");
}
/**
* @private
* Handle change in LiveDevelopment (LivePreview) state
* @param {!Event} event
* @param {!number} status
*/
function _onLiveDevelopmentStatusChange(event, status) {
switch (status) {
case LiveDevelopment.STATUS_ACTIVE:
_setup();
break;
case LiveDevelopment.STATUS_LOADING_AGENTS:
// Collects stylesheets on first page load of the LiveDevelopment mode.
//
// Navigations through other pages while LiveDevelopment is on do not cause reloading of agents,
// so LiveDevelopment.STATUS_LOADING_AGENTS is not reached again. For those cases, reusing this method in _setup().
//
// Can't use this only in _setup() because on the first run
// the 'styleSheetAdded' events will have already triggered before reaching LiveDevelopment.STATUS_ACTIVE.
$(CSSAgent).on("styleSheetAdded", _onStyleSheetAdded);
break;
case LiveDevelopment.STATUS_CONNECTING:
case LiveDevelopment.STATUS_INACTIVE:
case LiveDevelopment.STATUS_ERROR:
_teardown();
break;
}
}
$(LiveDevelopment).on("statusChange", _onLiveDevelopmentStatusChange);
// for testing only
exports.model = model;
exports._constructModel = _constructModel;
exports._setCurrentEditor = function (editor) { _currentEditor = editor; };
exports._updateCodeEditor = _updateCodeEditor;
exports._updateLiveEditor = _updateLiveEditor;
exports._setup = _setup;
exports._teardown = _teardown;
});