This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathCSSUtils.js
More file actions
1391 lines (1224 loc) · 55.6 KB
/
CSSUtils.js
File metadata and controls
1391 lines (1224 loc) · 55.6 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
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* 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, indent: 4, maxerr: 50, regexp: true */
/*global define, $, _parseRuleList: true */
// JSLint Note: _parseRuleList() is cyclical dependency, not a global function.
// It was added to this list to prevent JSLint warning about being used before being defined.
/**
* Set of utilities for simple parsing of CSS text.
*/
define(function (require, exports, module) {
"use strict";
var CodeMirror = require("thirdparty/CodeMirror2/lib/codemirror"),
Async = require("utils/Async"),
DocumentManager = require("document/DocumentManager"),
EditorManager = require("editor/EditorManager"),
HTMLUtils = require("language/HTMLUtils"),
ProjectManager = require("project/ProjectManager"),
TokenUtils = require("utils/TokenUtils");
// Constants
var SELECTOR = "selector",
PROP_NAME = "prop.name",
PROP_VALUE = "prop.value",
IMPORT_URL = "import.url";
var RESERVED_FLOW_NAMES = ["content", "element"],
INVALID_FLOW_NAMES = ["none", "inherit", "default", "auto", "initial"],
IGNORED_FLOW_NAMES = RESERVED_FLOW_NAMES.concat(INVALID_FLOW_NAMES);
/**
* @private
* Checks if the current cursor position is inside the property name context
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {boolean} true if the context is in property name
*/
function _isInPropName(ctx) {
var state,
lastToken;
if (!ctx || !ctx.token || !ctx.token.state || ctx.token.type === "comment") {
return false;
}
state = ctx.token.state.localState || ctx.token.state;
if (!state.context) {
return false;
}
lastToken = state.context.type;
return (lastToken === "{" || lastToken === "rule" || lastToken === "block");
}
/**
* @private
* Checks if the current cursor position is inside the property value context
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {boolean} true if the context is in property value
*/
function _isInPropValue(ctx) {
var state;
if (!ctx || !ctx.token || !ctx.token.state || ctx.token.type === "comment") {
return false;
}
state = ctx.token.state.localState || ctx.token.state;
if (!state.context || !state.context.prev) {
return false;
}
return ((state.context.type === "prop" &&
(state.context.prev.type === "rule" || state.context.prev.type === "block")) ||
(state.context.type === "parens" && state.context.prev.type === "prop"));
}
/**
* @private
* Checks if the current cursor position is inside an at-rule
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {boolean} true if the context is in property value
*/
function _isInAtRule(ctx) {
var state;
if (!ctx || !ctx.token || !ctx.token.state) {
return false;
}
state = ctx.token.state.localState || ctx.token.state;
if (!state.context) {
return false;
}
return (state.context.type === "at");
}
/**
* @private
* Creates a context info object
* @param {string=} context A constant string
* @param {number=} offset The offset of the token for a given cursor position
* @param {string=} name Property name of the context
* @param {number=} index The index of the property value for a given cursor position
* @param {Array.<string>=} values An array of property values
* @param {boolean=} isNewItem If this is true, then the value in index refers to the index at which a new item
* is going to be inserted and should not be used for accessing an existing value in values array.
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean}} A CSS context info object.
*/
function createInfo(context, offset, name, index, values, isNewItem) {
var ruleInfo = { context: context || "",
offset: offset || 0,
name: name || "",
index: -1,
values: [],
isNewItem: (isNewItem) ? true : false };
if (context === PROP_VALUE || context === SELECTOR || context === IMPORT_URL) {
ruleInfo.index = index;
ruleInfo.values = values;
}
return ruleInfo;
}
/**
* @private
* Scan backwards to check for any prefix if the current context is property name.
* If the current context is in a prefix (either 'meta' or '-'), then scan forwards
* to collect the entire property name. Return the name of the property in the CSS
* context info object if there is one that seems to be valid. Return an empty context
* info when we find an invalid one.
*
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} ctx context
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean}} A CSS context info object.
*/
function _getPropNameInfo(ctx) {
var propName = "",
offset = TokenUtils.offsetInToken(ctx),
tokenString = ctx.token.string,
excludedCharacters = [";", "{", "}"];
if (ctx.token.type === "property" || ctx.token.type === "property error" ||
ctx.token.type === "tag") {
propName = tokenString;
if (TokenUtils.movePrevToken(ctx) && ctx.token.string.trim() !== "" &&
excludedCharacters.indexOf(ctx.token.string) === -1) {
propName = ctx.token.string + tokenString;
offset += ctx.token.string.length;
}
} else if (ctx.token.type === "meta" || tokenString === "-") {
propName = tokenString;
if (TokenUtils.moveNextToken(ctx) &&
(ctx.token.type === "property" || ctx.token.type === "property error" ||
ctx.token.type === "tag")) {
propName += ctx.token.string;
}
} else if (tokenString.trim() !== "" && excludedCharacters.indexOf(tokenString) === -1) {
// We're not inside the property name context.
return createInfo();
} else {
var testPos = {ch: ctx.pos.ch + 1, line: ctx.pos.line},
testToken = ctx.editor.getTokenAt(testPos, true);
if (testToken.type === "property" || testToken.type === "property error" ||
testToken.type === "tag") {
propName = testToken.string;
offset = 0;
}
}
// If we're in the property name context but not in an existing property name,
// then reset offset to zero.
if (propName === "") {
offset = 0;
}
return createInfo(PROP_NAME, offset, propName);
}
/**
* @private
* Scans backwards from the current context and returns the name of the property if there is
* a valid one.
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {string} the property name of the current rule.
*/
function _getPropNameStartingFromPropValue(ctx) {
var ctxClone = $.extend({}, ctx),
propName = "";
do {
// If we're no longer in the property value before seeing a colon, then we don't
// have a valid property name. Just return an empty string.
if (ctxClone.token.string !== ":" && !_isInPropValue(ctxClone)) {
return "";
}
} while (ctxClone.token.string !== ":" && TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctxClone));
if (ctxClone.token.string === ":" && TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctxClone) &&
(ctxClone.token.type === "property" || ctxClone.token.type === "property error")) {
propName = ctxClone.token.string;
if (TokenUtils.movePrevToken(ctxClone) && ctxClone.token.type === "meta") {
propName = ctxClone.token.string + propName;
}
}
return propName;
}
/**
* @private
* Gets all of the space/comma seperated tokens before the the current cursor position.
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @return {?Array.<string>} An array of all the space/comma seperated tokens before the
* current cursor position
*/
function _getPrecedingPropValues(ctx) {
var lastValue = "",
curValue,
propValues = [];
while (ctx.token.string !== ":" && TokenUtils.movePrevToken(ctx)) {
if (ctx.token.string === ":" || !_isInPropValue(ctx)) {
break;
}
curValue = ctx.token.string;
if (lastValue !== "") {
curValue += lastValue;
}
if ((ctx.token.string.length > 0 && !ctx.token.string.match(/\S/)) ||
ctx.token.string === ",") {
lastValue = curValue;
} else {
lastValue = "";
if (propValues.length === 0 || curValue.match(/,\s*$/)) {
// stack is empty, or current value ends with a comma
// (and optional whitespace), so push it on the stack
propValues.push(curValue);
} else {
// current value does not end with a comma (and optional ws) so prepend
// to last stack item (e.g. "rgba(50" get broken into 2 tokens)
propValues[propValues.length - 1] = curValue + propValues[propValues.length - 1];
}
}
}
if (propValues.length > 0) {
propValues.reverse();
}
return propValues;
}
/**
* @private
* Gets all of the space/comma seperated tokens after the the current cursor position.
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @param {string} currentValue The token string at the current cursor position
* @return {?Array.<string>} An array of all the space/comma seperated tokens after the
* current cursor position
*/
function _getSucceedingPropValues(ctx, currentValue) {
var lastValue = currentValue,
curValue,
propValues = [];
while (ctx.token.string !== ";" && ctx.token.string !== "}" && TokenUtils.moveNextToken(ctx)) {
if (ctx.token.string === ";" || ctx.token.string === "}") {
break;
}
if (!_isInPropValue(ctx)) {
lastValue = "";
break;
}
if (lastValue === "") {
lastValue = ctx.token.string.trim();
} else if (lastValue.length > 0) {
if (ctx.token.string.length > 0 && !ctx.token.string.match(/\S/)) {
lastValue += ctx.token.string;
propValues.push(lastValue);
lastValue = "";
} else if (ctx.token.string === ",") {
lastValue += ctx.token.string;
} else if (lastValue && lastValue.match(/,$/)) {
propValues.push(lastValue);
if (ctx.token.string.length > 0) {
lastValue = ctx.token.string;
} else {
lastValue = "";
}
} else {
// e.g. "rgba(50" gets broken into 2 tokens
lastValue += ctx.token.string;
}
}
}
if (lastValue.length > 0) {
propValues.push(lastValue);
}
return propValues;
}
/**
* @private
* Returns a context info object for the current CSS style rule
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @param {!Editor} editor
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean}} A CSS context info object.
*/
function _getRuleInfoStartingFromPropValue(ctx, editor) {
var propNamePos = $.extend({}, ctx.pos),
backwardPos = $.extend({}, ctx.pos),
forwardPos = $.extend({}, ctx.pos),
propNameCtx = TokenUtils.getInitialContext(editor._codeMirror, propNamePos),
backwardCtx,
forwardCtx,
lastValue = "",
propValues = [],
index = -1,
offset = TokenUtils.offsetInToken(ctx),
canAddNewOne = false,
testPos = {ch: ctx.pos.ch + 1, line: ctx.pos.line},
testToken = editor._codeMirror.getTokenAt(testPos, true),
propName;
// Get property name first. If we don't have a valid property name, then
// return a default rule info.
propName = _getPropNameStartingFromPropValue(propNameCtx);
if (!propName) {
return createInfo();
}
// Scan backward to collect all preceding property values
backwardCtx = TokenUtils.getInitialContext(editor._codeMirror, backwardPos);
propValues = _getPrecedingPropValues(backwardCtx);
lastValue = "";
if (ctx.token.string === ":") {
index = 0;
canAddNewOne = true;
} else {
index = propValues.length - 1;
if (ctx.token.string === ",") {
propValues[index] += ctx.token.string;
index++;
canAddNewOne = true;
} else {
index = (index < 0) ? 0 : index + 1;
if (ctx.token.string.match(/\S/)) {
lastValue = ctx.token.string;
} else {
// Last token is all whitespace
canAddNewOne = true;
if (index > 0) {
// Append all spaces before the cursor to the previous value in values array
propValues[index - 1] += ctx.token.string.substr(0, offset);
}
}
}
}
if (canAddNewOne) {
offset = 0;
// If pos is at EOL, then there's implied whitespace (newline).
if (editor.document.getLine(ctx.pos.line).length > ctx.pos.ch &&
(testToken.string.length === 0 || testToken.string.match(/\S/))) {
canAddNewOne = false;
}
}
// Scan forward to collect all succeeding property values and append to all propValues.
forwardCtx = TokenUtils.getInitialContext(editor._codeMirror, forwardPos);
propValues = propValues.concat(_getSucceedingPropValues(forwardCtx, lastValue));
// If current index is more than the propValues size, then the cursor is
// at the end of the existing property values and is ready for adding another one.
if (index === propValues.length) {
canAddNewOne = true;
}
return createInfo(PROP_VALUE, offset, propName, index, propValues, canAddNewOne);
}
/**
* @private
* Returns a context info object for the current CSS import rule
* @param {editor:{CodeMirror}, pos:{ch:{string}, line:{number}}, token:{object}} context
* @param {!Editor} editor
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean}} A CSS context info object.
*/
function _getImportUrlInfo(ctx, editor) {
var propNamePos = $.extend({}, ctx.pos),
backwardPos = $.extend({}, ctx.pos),
forwardPos = $.extend({}, ctx.pos),
backwardCtx,
forwardCtx,
index = 0,
propValues = [],
offset = TokenUtils.offsetInToken(ctx),
testPos = {ch: ctx.pos.ch + 1, line: ctx.pos.line},
testToken = editor._codeMirror.getTokenAt(testPos, true);
// Currently only support url. May be null if starting to type
if (ctx.token.type && ctx.token.type !== "string") {
return createInfo();
}
// Move backward to @import and collect data as we go. We return propValues
// array, but we can only have 1 value, so put all data in first item
backwardCtx = TokenUtils.getInitialContext(editor._codeMirror, backwardPos);
propValues[0] = backwardCtx.token.string;
while (TokenUtils.movePrevToken(backwardCtx)) {
if (backwardCtx.token.type === "def" && backwardCtx.token.string === "@import") {
break;
}
if (backwardCtx.token.type && backwardCtx.token.type !== "tag" && backwardCtx.token.string !== "url") {
// Previous token may be white-space
// Otherwise, previous token may only be "url("
break;
}
propValues[0] = backwardCtx.token.string + propValues[0];
offset += backwardCtx.token.string.length;
}
if (backwardCtx.token.type !== "def" || backwardCtx.token.string !== "@import") {
// Not in url
return createInfo();
}
// Get value after cursor up until closing paren or newline
forwardCtx = TokenUtils.getInitialContext(editor._codeMirror, forwardPos);
do {
if (!TokenUtils.moveNextToken(forwardCtx)) {
if (forwardCtx.token.string === "(") {
break;
} else {
return createInfo();
}
}
propValues[0] += forwardCtx.token.string;
} while (forwardCtx.token.string !== ")" && forwardCtx.token.string !== "");
return createInfo(IMPORT_URL, offset, "", index, propValues, false);
}
/**
* Returns a context info object for the given cursor position
* @param {!Editor} editor
* @param {{ch: number, line: number}} constPos A CM pos (likely from editor.getCursorPos())
* @return {{context: string,
* offset: number,
* name: string,
* index: number,
* values: Array.<string>,
* isNewItem: boolean}} A CSS context info object.
*/
function getInfoAtPos(editor, constPos) {
// We're going to be changing pos a lot, but we don't want to mess up
// the pos the caller passed in so we use extend to make a safe copy of it.
var pos = $.extend({}, constPos),
ctx = TokenUtils.getInitialContext(editor._codeMirror, pos),
offset = TokenUtils.offsetInToken(ctx),
propName = "",
mode = editor.getModeForSelection();
// Check if this is inside a style block or in a css/less document.
if (mode !== "css" && mode !== "text/x-scss" && mode !== "text/x-less") {
return createInfo();
}
if (_isInPropName(ctx)) {
return _getPropNameInfo(ctx, editor);
}
if (_isInPropValue(ctx)) {
return _getRuleInfoStartingFromPropValue(ctx, editor);
}
if (_isInAtRule(ctx)) {
return _getImportUrlInfo(ctx, editor);
}
return createInfo();
}
/**
* Extracts all CSS selectors from the given text
* Returns an array of selectors. Each selector is an object with the following properties:
selector: the text of the selector (note: comma separated selector groups like
"h1, h2" are broken into separate selectors)
ruleStartLine: line in the text where the rule (including preceding comment) appears
ruleStartChar: column in the line where the rule (including preceding comment) starts
selectorStartLine: line in the text where the selector appears
selectorStartChar: column in the line where the selector starts
selectorEndLine: line where the selector ends
selectorEndChar: column where the selector ends
selectorGroupStartLine: line where the comma-separated selector group (e.g. .foo, .bar, .baz)
starts that this selector (e.g. .baz) is part of. Particularly relevant for
groups that are on multiple lines.
selectorGroupStartChar: column in line where the selector group starts.
selectorGroup: the entire selector group containing this selector, or undefined if there
is only one selector in the rule.
declListStartLine: line where the declaration list for the rule starts
declListStartChar: column in line where the declaration list for the rule starts
declListEndLine: line where the declaration list for the rule ends
declListEndChar: column in the line where the declaration list for the rule ends
* @param text {!string} CSS text to extract from
* @return {Array.<Object>} Array with objects specifying selectors.
*/
function extractAllSelectors(text) {
var selectors = [];
var mode = CodeMirror.getMode({indentUnit: 2}, "css");
var state, lines, lineCount;
var token, style, stream, line;
var currentSelector = "";
var ruleStartChar = -1, ruleStartLine = -1;
var selectorStartChar = -1, selectorStartLine = -1;
var selectorGroupStartLine = -1, selectorGroupStartChar = -1;
var declListStartLine = -1, declListStartChar = -1;
var escapePattern = new RegExp("\\\\[^\\\\]+", "g");
var validationPattern = new RegExp("\\\\([a-f0-9]{6}|[a-f0-9]{4}(\\s|\\\\|$)|[a-f0-9]{2}(\\s|\\\\|$)|.)", "i");
// implement _firstToken()/_nextToken() methods to
// provide a single stream of tokens
function _hasStream() {
while (stream.eol()) {
line++;
if (line >= lineCount) {
return false;
}
if (currentSelector.match(/\S/)) {
// If we are in a current selector and starting a newline,
// make sure there is whitespace in the selector
currentSelector += " ";
}
stream = new CodeMirror.StringStream(lines[line]);
}
return true;
}
function _firstToken() {
state = CodeMirror.startState(mode);
lines = CodeMirror.splitLines(text);
lineCount = lines.length;
if (lineCount === 0) {
return false;
}
line = 0;
stream = new CodeMirror.StringStream(lines[line]);
if (!_hasStream()) {
return false;
}
style = mode.token(stream, state);
token = stream.current();
return true;
}
function _nextToken() {
// advance the stream past this token
stream.start = stream.pos;
if (!_hasStream()) {
return false;
}
style = mode.token(stream, state);
token = stream.current();
return true;
}
function _firstTokenSkippingWhitespace() {
if (!_firstToken()) {
return false;
}
while (!token.match(/\S/)) {
if (!_nextToken()) {
return false;
}
}
return true;
}
function _nextTokenSkippingWhitespace() {
if (!_nextToken()) {
return false;
}
while (!token.match(/\S/)) {
if (!_nextToken()) {
return false;
}
}
return true;
}
function _isStartComment() {
return (token.match(/^\/\*/));
}
function _parseComment() {
while (!token.match(/\*\/$/)) {
if (!_nextToken()) {
break;
}
}
}
function _nextTokenSkippingComments() {
if (!_nextToken()) {
return false;
}
while (_isStartComment()) {
_parseComment();
if (!_nextToken()) {
return false;
}
}
return true;
}
function _parseSelector(start) {
currentSelector = "";
selectorStartChar = start;
selectorStartLine = line;
// Everything until the next ',' or '{' is part of the current selector
while (token !== "," && token !== "{") {
currentSelector += token;
if (!_nextTokenSkippingComments()) {
return false; // eof
}
}
// Unicode character replacement as defined in http://www.w3.org/TR/CSS21/syndata.html#characters
if (/\\/.test(currentSelector)) {
// Double replace in case of pattern overlapping (regex improvement?)
currentSelector = currentSelector.replace(escapePattern, function (escapedToken) {
return escapedToken.replace(validationPattern, function (unicodeChar) {
unicodeChar = unicodeChar.substr(1);
if (unicodeChar.length === 1) {
return unicodeChar;
} else {
if (parseInt(unicodeChar, 16) < 0x10FFFF) {
return String.fromCharCode(parseInt(unicodeChar, 16));
} else { return String.fromCharCode(0xFFFD); }
}
});
});
}
currentSelector = currentSelector.trim();
var startChar = (selectorGroupStartLine === -1) ? selectorStartChar : selectorStartChar + 1;
var selectorStart = (stream.string.indexOf(currentSelector, selectorStartChar) !== -1) ? stream.string.indexOf(currentSelector, selectorStartChar - currentSelector.length) : startChar;
if (currentSelector !== "") {
selectors.push({selector: currentSelector,
ruleStartLine: ruleStartLine,
ruleStartChar: ruleStartChar,
selectorStartLine: selectorStartLine,
selectorStartChar: selectorStart,
declListEndLine: -1,
selectorEndLine: line,
selectorEndChar: selectorStart + currentSelector.length,
selectorGroupStartLine: selectorGroupStartLine,
selectorGroupStartChar: selectorGroupStartChar
});
currentSelector = "";
}
selectorStartChar = -1;
return true;
}
function _parseSelectorList() {
selectorGroupStartLine = (stream.string.indexOf(",") !== -1) ? line : -1;
selectorGroupStartChar = stream.start;
if (!_parseSelector(stream.start)) {
return false;
}
while (token === ",") {
if (!_nextTokenSkippingComments()) {
return false; // eof
}
if (!_parseSelector(stream.start)) {
return false;
}
}
return true;
}
function _parseDeclarationList() {
var j;
declListStartLine = Math.min(line, lineCount - 1);
declListStartChar = stream.start;
// Extract the entire selector group we just saw.
var selectorGroup, sgLine;
if (selectorGroupStartLine !== -1) {
selectorGroup = "";
for (sgLine = selectorGroupStartLine; sgLine <= declListStartLine; sgLine++) {
var startChar = 0, endChar = lines[sgLine].length;
if (sgLine === selectorGroupStartLine) {
startChar = selectorGroupStartChar;
} else {
selectorGroup += " "; // replace the newline with a single space
}
if (sgLine === declListStartLine) {
endChar = declListStartChar;
}
selectorGroup += lines[sgLine].substring(startChar, endChar);
}
selectorGroup = selectorGroup.trim();
}
// Since we're now in a declaration list, that means we also finished
// parsing the whole selector group. Therefore, reset selectorGroupStartLine
// so that next time we parse a selector we know it's a new group
selectorGroupStartLine = -1;
selectorGroupStartChar = -1;
ruleStartLine = -1;
ruleStartChar = -1;
// Skip everything until the next '}'
while (token !== "}") {
if (!_nextTokenSkippingComments()) {
break;
}
}
// assign this declaration list position and selector group to every selector on the stack
// that doesn't have a declaration list start and end line
for (j = selectors.length - 1; j >= 0; j--) {
if (selectors[j].declListEndLine !== -1) {
break;
} else {
selectors[j].declListStartLine = declListStartLine;
selectors[j].declListStartChar = declListStartChar;
selectors[j].declListEndLine = line;
selectors[j].declListEndChar = stream.pos - 1; // stream.pos actually points to the char after the }
if (selectorGroup) {
selectors[j].selectorGroup = selectorGroup;
}
}
}
}
function includeCommentInNextRule() {
if (ruleStartChar !== -1) {
return false; // already included
}
if (stream.start > 0 && lines[line].substr(0, stream.start).indexOf("}") !== -1) {
return false; // on same line as '}', so it's for previous rule
}
return true;
}
function _isStartAtRule() {
return (token.match(/^@/));
}
function _parseAtRule() {
// reset these fields to ignore comments preceding @rules
ruleStartLine = -1;
ruleStartChar = -1;
selectorStartLine = -1;
selectorStartChar = -1;
selectorGroupStartLine = -1;
selectorGroupStartChar = -1;
if (token.match(/@media/i)) {
// @media rule holds a rule list
// Skip everything until the opening '{'
while (token !== "{") {
if (!_nextTokenSkippingComments()) {
return; // eof
}
}
// skip past '{', to next non-ws token
if (!_nextTokenSkippingWhitespace()) {
return; // eof
}
// Parse rules until we see '}'
_parseRuleList("}");
} else if (token.match(/@(charset|import|namespace)/i)) {
// This code handles @rules in this format:
// @rule ... ;
// Skip everything until the next ';'
while (token !== ";") {
if (!_nextTokenSkippingComments()) {
return; // eof
}
}
} else {
// This code handle @rules that use this format:
// @rule ... { ... }
// such as @page, @keyframes (also -webkit-keyframes, etc.), and @font-face.
// Skip everything until the next '}'
while (token !== "}") {
if (!_nextTokenSkippingComments()) {
return; // eof
}
}
}
}
// parse a style rule
function _parseRule() {
if (!_parseSelectorList()) {
return false;
}
_parseDeclarationList();
}
function _parseRuleList(escapeToken) {
while ((!escapeToken) || token !== escapeToken) {
if (_isStartAtRule()) {
// @rule
_parseAtRule();
} else if (_isStartComment()) {
// comment - make this part of style rule
if (includeCommentInNextRule()) {
ruleStartChar = stream.start;
ruleStartLine = line;
}
_parseComment();
} else {
// Otherwise, it's style rule
if (ruleStartChar === -1) {
ruleStartChar = stream.start;
ruleStartLine = line;
}
_parseRule();
}
if (!_nextTokenSkippingWhitespace()) {
break;
}
}
}
// Do parsing
if (_firstTokenSkippingWhitespace()) {
// Style sheet is a rule list
_parseRuleList();
}
return selectors;
}
/*
* This code can be used to create an "independent" HTML document that can be passed to jQuery
* calls. Allows using jQuery's CSS selector engine without actually putting anything in the browser's DOM
*
var _htmlDoctype = document.implementation.createDocumentType('html',
'-//W3C//DTD XHTML 1.0 Strict//EN',
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
);
var _htmlDocument = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', _htmlDoctype);
function checkIfSelectorSelectsHTML(selector, theHTML) {
$('html', _htmlDocument).html(theHTML);
return ($(selector, _htmlDocument).length > 0);
}
*/
/**
* Finds all instances of the specified selector in "text".
* Returns an Array of Objects with start and end properties.
*
* For Sprint 4, we only support simple selectors. This function will need to change
* dramatically to support full selectors.
*
* FUTURE: (JRB) It would be nice to eventually use the browser/jquery to do the selector evaluation.
* One way to do this would be to take the user's HTML, add a special attribute to every tag with a UID,
* and then construct a DOM (using the commented out code above). Then, give this DOM and the selector to
* jquery and ask what matches. If the node that the user's cursor is in comes back from jquery, then
* we know the selector applies.
*
* @param text {!string} CSS text to search
* @param selector {!string} selector to search for
* @return {Array.<{selectorGroupStartLine:number, declListEndLine:number, selector:string}>}
* Array of objects containing the start and end line numbers (0-based, inclusive range) for each
* matched selector.
*/
function _findAllMatchingSelectorsInText(text, selector) {
var allSelectors = extractAllSelectors(text);
var result = [];
var i;
// For sprint 4 we only match the rightmost simple selector, and ignore
// attribute selectors and pseudo selectors
var classOrIdSelector = selector[0] === "." || selector[0] === "#";
var prefix = "";
// Escape initial "." in selector, if present.
if (selector[0] === ".") {
selector = "\\" + selector;
}
if (!classOrIdSelector) {
// Tag selectors must have nothing, whitespace, or a combinator before it.
selector = "(^|[\\s>+~])" + selector;
}
var re = new RegExp(selector + "(\\[[^\\]]*\\]|:{1,2}[\\w-()]+|\\.[\\w-]+|#[\\w-]+)*\\s*$", classOrIdSelector ? "" : "i");
allSelectors.forEach(function (entry) {
if (entry.selector.search(re) !== -1) {
result.push(entry);
} else if (!classOrIdSelector) {
// Special case for tag selectors - match "*" as the rightmost character
if (entry.selector.trim().search(/\*$/) !== -1) {
result.push(entry);
}
}
});
return result;
}
/**
* Converts the results of _findAllMatchingSelectorsInText() into a simpler bag of data and
* appends those new objects to the given 'resultSelectors' Array.
* @param {Array.<{document:Document, lineStart:number, lineEnd:number}>} resultSelectors
* @param {Array.<{selectorGroupStartLine:number, declListEndLine:number, selector:string}>} selectorsToAdd
* @param {!Document} sourceDoc
* @param {!number} lineOffset Amount to offset all line number info by. Used if the first line
* of the parsed CSS text is not the first line of the sourceDoc.
*/
function _addSelectorsToResults(resultSelectors, selectorsToAdd, sourceDoc, lineOffset) {
selectorsToAdd.forEach(function (selectorInfo) {
resultSelectors.push({
name: selectorInfo.selector,
document: sourceDoc,
lineStart: selectorInfo.ruleStartLine + lineOffset,