This repository has been archived by the owner on Dec 12, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcss.js
613 lines (535 loc) · 16.9 KB
/
css.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/**
* CSS EditTree is a module that can parse a CSS rule into a tree with
* convenient methods for adding, modifying and removing CSS properties. These
* changes can be written back to string with respect of code formatting.
*/
if (typeof module === 'object' && typeof define !== 'function') {
var define = function (factory) {
module.exports = factory(require, exports, module);
};
}
define(function(require, exports, module) {
var utils = require('../utils/common');
var editTree = require('./base');
var cssParser = require('../parser/css');
var cssSections = require('../utils/cssSections');
var range = require('../assets/range');
var stringStream = require('../assets/stringStream');
var tokenIterator = require('../assets/tokenIterator');
var defaultOptions = {
styleBefore: '\n\t',
styleSeparator: ': ',
offset: 0
};
var reSpaceStart = /^\s+/;
var reSpaceEnd = /\s+$/;
var WHITESPACE_REMOVE_FROM_START = 1;
var WHITESPACE_REMOVE_FROM_END = 2;
/**
* Modifies given range to remove whitespace from beginning
* and/or from the end
* @param {Range} rng Range to modify
* @param {String} text Text that range belongs to
* @param {Number} mask Mask indicating from which end
* whitespace should be removed
* @return {Range}
*/
function trimWhitespaceInRange(rng, text, mask) {
mask = mask || (WHITESPACE_REMOVE_FROM_START | WHITESPACE_REMOVE_FROM_END);
text = rng.substring(text);
var m;
if ((mask & WHITESPACE_REMOVE_FROM_START) && (m = text.match(reSpaceStart))) {
rng.start += m[0].length;
}
if ((mask & WHITESPACE_REMOVE_FROM_END) && (m = text.match(reSpaceEnd))) {
rng.end -= m[0].length;
}
// in case given range is just a whatespace
if (rng.end < rng.start) {
rng.end = rng.start;
}
return rng;
}
/**
* Consumes CSS property and value from current token
* iterator state. Offsets iterator pointer into token
* that can be used for next value consmption
* @param {TokenIterator} it
* @param {String} text
* @return {Object} Object with `name` and `value` properties
* ar ranges. Value range can be zero-length.
*/
function consumeSingleProperty(it, text) {
var name, value, end;
var token = it.current();
if (!token) {
return null;
}
// skip whitespace
var ws = {'white': 1, 'line': 1, 'comment': 1};
while ((token = it.current())) {
if (!(token.type in ws)) {
break;
}
it.next();
}
if (!it.hasNext()) {
return null;
}
// consume property name
token = it.current();
name = range(token.start, token.value);
var isAtProperty = token.value.charAt(0) == '@';
while (token = it.next()) {
name.end = token.end;
if (token.type == ':' || token.type == 'white') {
name.end = token.start;
it.next();
if (token.type == ':' || isAtProperty) {
// XXX I really ashame of this hardcode, but I need
// to stop parsing if this is an SCSS mixin call,
// for example: @include border-radius(10px)
break;
}
} else if (token.type == ';' || token.type == 'line') {
// there’s no value, looks like a mixin
// or a special use case:
// user is writing a new property or abbreviation
name.end = token.start;
value = range(token.start, 0);
it.next();
break;
}
}
token = it.current();
if (!value && token) {
if (token.type == 'line') {
lastNewline = token;
}
// consume value
value = range(token.start, token.value);
var lastNewline;
while ((token = it.next())) {
value.end = token.end;
if (token.type == 'line') {
lastNewline = token;
} else if (token.type == '}' || token.type == ';') {
value.end = token.start;
if (token.type == ';') {
end = range(token.start, token.value);
}
it.next();
break;
} else if (token.type == ':' && lastNewline) {
// A special case:
// user is writing a value before existing
// property, but didn’t inserted closing semi-colon.
// In this case, limit value range to previous
// newline
value.end = lastNewline.start;
it._i = it.tokens.indexOf(lastNewline);
break;
}
}
}
if (!value) {
value = range(name.end, 0);
}
return {
name: trimWhitespaceInRange(name, text),
value: trimWhitespaceInRange(value, text, WHITESPACE_REMOVE_FROM_START | (end ? WHITESPACE_REMOVE_FROM_END : 0)),
end: end || range(value.end, 0)
};
}
/**
* Finds parts of complex CSS value
* @param {String} str
* @returns {Array} Returns list of <code>Range</code>'s
*/
function findParts(str) {
/** @type StringStream */
var stream = stringStream.create(str);
var ch;
var result = [];
var sep = /[\s\u00a0,;]/;
var add = function() {
stream.next();
result.push(range(stream.start, stream.current()));
stream.start = stream.pos;
};
// skip whitespace
stream.eatSpace();
stream.start = stream.pos;
while ((ch = stream.next())) {
if (ch == '"' || ch == "'") {
stream.next();
if (!stream.skipTo(ch)) break;
add();
} else if (ch == '(') {
// function found, may have nested function
stream.backUp(1);
if (!stream.skipToPair('(', ')')) break;
stream.backUp(1);
add();
} else {
if (sep.test(ch)) {
result.push(range(stream.start, stream.current().length - 1));
stream.eatWhile(sep);
stream.start = stream.pos;
}
}
}
add();
return utils.unique(result.filter(function(item) {
return !!item.length();
}));
}
/**
* Parses CSS properties from given CSS source
* and adds them to CSSEditContainer node
* @param {CSSEditContainer} node
* @param {String} source CSS source
* @param {Number} offset Offset of properties subset from original source
*/
function consumeProperties(node, source, offset) {
var list = extractPropertiesFromSource(source, offset);
list.forEach(function(property) {
node._children.push(new CSSEditElement(node,
editTree.createToken(property.name.start, property.nameText),
editTree.createToken(property.value.start, property.valueText),
editTree.createToken(property.end.start, property.endText)
));
});
}
/**
* Parses given CSS source and returns list of ranges of located CSS properties.
* Normally, CSS source must contain properties only, it must be,
* for example, a content of CSS selector or text between nested
* CSS sections
* @param {String} source CSS source
* @param {Number} offset Offset of properties subset from original source.
* Used to provide proper ranges of locates items
*/
function extractPropertiesFromSource(source, offset) {
offset = offset || 0;
source = source.replace(reSpaceEnd, '');
var out = [];
if (!source) {
return out;
}
var tokens = cssParser.parse(source);
var it = tokenIterator.create(tokens);
var property;
while ((property = consumeSingleProperty(it, source))) {
out.push({
nameText: property.name.substring(source),
name: property.name.shift(offset),
valueText: property.value.substring(source),
value: property.value.shift(offset),
endText: property.end.substring(source),
end: property.end.shift(offset)
});
}
return out;
}
/**
* @class
* @extends EditContainer
*/
var CSSEditContainer = editTree.EditContainer.extend({
initialize: function(source, options) {
utils.extend(this.options, defaultOptions, options);
if (Array.isArray(source)) {
source = cssParser.toSource(source);
}
var allRules = cssSections.findAllRules(source);
var currentRule = allRules.shift();
// keep top-level rules only since they will
// be parsed by nested CSSEditContainer call
var topLevelRules = [];
allRules.forEach(function(r) {
var isTopLevel = !utils.find(topLevelRules, function(tr) {
return tr.contains(r);
});
if (isTopLevel) {
topLevelRules.push(r);
}
});
var selectorRange = range.create2(currentRule.start, currentRule._selectorEnd);
this._name = selectorRange.substring(source);
this._positions.name = selectorRange.start;
this._positions.contentStart = currentRule._contentStart + 1;
var sectionOffset = currentRule._contentStart + 1;
var sectionEnd = currentRule.end - 1;
// parse properties between nested rules
// and add nested rules as children
var that = this;
topLevelRules.forEach(function(r) {
consumeProperties(that, source.substring(sectionOffset, r.start), sectionOffset);
var opt = utils.extend({}, that.options, {offset: r.start + that.options.offset});
// XXX I think I don’t need nested containers here
// They should be handled separately
// that._children.push(new CSSEditContainer(r.substring(source), opt));
sectionOffset = r.end;
});
// consume the rest of data
consumeProperties(this, source.substring(sectionOffset, currentRule.end - 1), sectionOffset);
this._saveStyle();
},
/**
* Remembers all styles of properties
* @private
*/
_saveStyle: function() {
var start = this._positions.contentStart;
var source = this.source;
this.list().forEach(function(p) {
if (p.type === 'container') {
return;
}
p.styleBefore = source.substring(start, p.namePosition());
// a small hack here:
// Sometimes users add empty lines before properties to logically
// separate groups of properties. In this case, a blind copy of
// characters between rules may lead to undesired behavior,
// especially when current rule is duplicated or used as a donor
// to create new rule.
// To solve this issue, we‘ll take only last newline indentation
var lines = utils.splitByLines(p.styleBefore);
if (lines.length > 1) {
p.styleBefore = '\n' + lines[lines.length - 1];
}
p.styleSeparator = source.substring(p.nameRange().end, p.valuePosition());
// graceful and naive comments removal
var parts = p.styleBefore.split('*/');
p.styleBefore = parts[parts.length - 1];
p.styleSeparator = p.styleSeparator.replace(/\/\*.*?\*\//g, '');
start = p.range().end;
});
},
/**
* Returns position of element name token
* @param {Boolean} isAbsolute Return absolute position
* @returns {Number}
*/
namePosition: function(isAbsolute) {
return this._pos(this._positions.name, isAbsolute);
},
/**
* Returns position of element value token
* @param {Boolean} isAbsolute Return absolute position
* @returns {Number}
*/
valuePosition: function(isAbsolute) {
return this._pos(this._positions.contentStart, isAbsolute);
},
/**
* Returns element value range
* @param {Boolean} isAbsolute Return absolute range
* @returns {Range}
*/
valueRange: function(isAbsolute) {
return range.create2(this.valuePosition(isAbsolute), this._pos(this.valueOf().length, isAbsolute) - 1);
},
/**
* Adds new CSS property
* @param {String} name Property name
* @param {String} value Property value
* @param {Number} pos Position at which to insert new property. By
* default the property is inserted at the end of rule
* @returns {CSSEditProperty}
*/
add: function(name, value, pos) {
var list = this.list();
var start = this._positions.contentStart;
var styles = utils.pick(this.options, 'styleBefore', 'styleSeparator');
if (typeof pos === 'undefined') {
pos = list.length;
}
/** @type CSSEditProperty */
var donor = list[pos];
if (donor) {
start = donor.fullRange().start;
} else if ((donor = list[pos - 1])) {
// make sure that donor has terminating semicolon
donor.end(';');
start = donor.range().end;
}
if (donor) {
styles = utils.pick(donor, 'styleBefore', 'styleSeparator');
}
var nameToken = editTree.createToken(start + styles.styleBefore.length, name);
var valueToken = editTree.createToken(nameToken.end + styles.styleSeparator.length, value);
var property = new CSSEditElement(this, nameToken, valueToken,
editTree.createToken(valueToken.end, ';'));
utils.extend(property, styles);
// write new property into the source
this._updateSource(property.styleBefore + property.toString(), start);
// insert new property
this._children.splice(pos, 0, property);
return property;
}
});
/**
* @class
* @type CSSEditElement
* @constructor
*/
var CSSEditElement = editTree.EditElement.extend({
initialize: function(rule, name, value, end) {
this.styleBefore = rule.options.styleBefore;
this.styleSeparator = rule.options.styleSeparator;
this._end = end.value;
this._positions.end = end.start;
},
/**
* Returns ranges of complex value parts
* @returns {Array} Returns <code>null</code> if value is not complex
*/
valueParts: function(isAbsolute) {
var parts = findParts(this.value());
if (isAbsolute) {
var offset = this.valuePosition(true);
parts.forEach(function(p) {
p.shift(offset);
});
}
return parts;
},
/**
* Sets of gets element value.
* When setting value, this implementation will ensure that your have
* proper name-value separator
* @param {String} val New element value. If not passed, current
* value is returned
* @returns {String}
*/
value: function(val) {
var isUpdating = typeof val !== 'undefined';
var allItems = this.parent.list();
if (isUpdating && this.isIncomplete()) {
var self = this;
var donor = utils.find(allItems, function(item) {
return item !== self && !item.isIncomplete();
});
this.styleSeparator = donor
? donor.styleSeparator
: this.parent.options.styleSeparator;
this.parent._updateSource(this.styleSeparator, range(this.valueRange().start, 0));
}
var value = this.constructor.__super__.value.apply(this, arguments);
if (isUpdating) {
// make sure current property has terminating semi-colon
// if it’s not the last one
var ix = allItems.indexOf(this);
if (ix !== allItems.length - 1 && !this.end()) {
this.end(';');
}
}
return value;
},
/**
* Test if current element is incomplete, e.g. has no explicit
* name-value separator
* @return {Boolean} [description]
*/
isIncomplete: function() {
return this.nameRange().end === this.valueRange().start;
},
/**
* Sets of gets property end value (basically, it's a semicolon)
* @param {String} val New end value. If not passed, current
* value is returned
*/
end: function(val) {
if (typeof val !== 'undefined' && this._end !== val) {
this.parent._updateSource(val, this._positions.end, this._positions.end + this._end.length);
this._end = val;
}
return this._end;
},
/**
* Returns full rule range, with indentation
* @param {Boolean} isAbsolute Return absolute range (with respect of
* rule offset)
* @returns {Range}
*/
fullRange: function(isAbsolute) {
var r = this.range(isAbsolute);
r.start -= this.styleBefore.length;
return r;
},
/**
* Returns item string representation
* @returns {String}
*/
valueOf: function() {
return this.name() + this.styleSeparator + this.value() + this.end();
}
});
return {
/**
* Parses CSS rule into editable tree
* @param {String} source
* @param {Object} options
* @memberOf emmet.cssEditTree
* @returns {EditContainer}
*/
parse: function(source, options) {
return new CSSEditContainer(source, options);
},
/**
* Extract and parse CSS rule from specified position in <code>content</code>
* @param {String} content CSS source code
* @param {Number} pos Character position where to start source code extraction
* @returns {EditContainer}
*/
parseFromPosition: function(content, pos, isBackward) {
var bounds = cssSections.locateRule(content, pos, isBackward);
if (!bounds || !bounds.inside(pos)) {
// no matching CSS rule or caret outside rule bounds
return null;
}
return this.parse(bounds.substring(content), {
offset: bounds.start
});
},
/**
* Locates CSS property in given CSS code fragment under specified character position
* @param {String} css CSS code or parsed CSSEditContainer
* @param {Number} pos Character position where to search CSS property
* @return {CSSEditElement}
*/
propertyFromPosition: function(css, pos) {
var cssProp = null;
/** @type EditContainer */
var cssRule = typeof css === 'string' ? this.parseFromPosition(css, pos, true) : css;
if (cssRule) {
cssProp = cssRule.itemFromPosition(pos, true);
if (!cssProp) {
// in case user just started writing CSS property
// and didn't include semicolon–try another approach
cssProp = utils.find(cssRule.list(), function(elem) {
return elem.range(true).end == pos;
});
}
}
return cssProp;
},
/**
* Removes vendor prefix from CSS property
* @param {String} name CSS property
* @return {String}
*/
baseName: function(name) {
return name.replace(/^\s*\-\w+\-/, '');
},
/**
* Finds parts of complex CSS value
* @param {String} str
* @returns {Array}
*/
findParts: findParts,
extractPropertiesFromSource: extractPropertiesFromSource
};
});