• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"use strict";
2
3exports.__esModule = true;
4exports["default"] = void 0;
5exports.unescapeValue = unescapeValue;
6var _cssesc = _interopRequireDefault(require("cssesc"));
7var _unesc = _interopRequireDefault(require("../util/unesc"));
8var _namespace = _interopRequireDefault(require("./namespace"));
9var _types = require("./types");
10var _CSSESC_QUOTE_OPTIONS;
11function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
12function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
13function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
14function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
15function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
16var deprecate = require("util-deprecate");
17var WRAPPED_IN_QUOTES = /^('|")([^]*)\1$/;
18var warnOfDeprecatedValueAssignment = deprecate(function () {}, "Assigning an attribute a value containing characters that might need to be escaped is deprecated. " + "Call attribute.setValue() instead.");
19var warnOfDeprecatedQuotedAssignment = deprecate(function () {}, "Assigning attr.quoted is deprecated and has no effect. Assign to attr.quoteMark instead.");
20var warnOfDeprecatedConstructor = deprecate(function () {}, "Constructing an Attribute selector with a value without specifying quoteMark is deprecated. Note: The value should be unescaped now.");
21function unescapeValue(value) {
22  var deprecatedUsage = false;
23  var quoteMark = null;
24  var unescaped = value;
25  var m = unescaped.match(WRAPPED_IN_QUOTES);
26  if (m) {
27    quoteMark = m[1];
28    unescaped = m[2];
29  }
30  unescaped = (0, _unesc["default"])(unescaped);
31  if (unescaped !== value) {
32    deprecatedUsage = true;
33  }
34  return {
35    deprecatedUsage: deprecatedUsage,
36    unescaped: unescaped,
37    quoteMark: quoteMark
38  };
39}
40function handleDeprecatedContructorOpts(opts) {
41  if (opts.quoteMark !== undefined) {
42    return opts;
43  }
44  if (opts.value === undefined) {
45    return opts;
46  }
47  warnOfDeprecatedConstructor();
48  var _unescapeValue = unescapeValue(opts.value),
49    quoteMark = _unescapeValue.quoteMark,
50    unescaped = _unescapeValue.unescaped;
51  if (!opts.raws) {
52    opts.raws = {};
53  }
54  if (opts.raws.value === undefined) {
55    opts.raws.value = opts.value;
56  }
57  opts.value = unescaped;
58  opts.quoteMark = quoteMark;
59  return opts;
60}
61var Attribute = /*#__PURE__*/function (_Namespace) {
62  _inheritsLoose(Attribute, _Namespace);
63  function Attribute(opts) {
64    var _this;
65    if (opts === void 0) {
66      opts = {};
67    }
68    _this = _Namespace.call(this, handleDeprecatedContructorOpts(opts)) || this;
69    _this.type = _types.ATTRIBUTE;
70    _this.raws = _this.raws || {};
71    Object.defineProperty(_this.raws, 'unquoted', {
72      get: deprecate(function () {
73        return _this.value;
74      }, "attr.raws.unquoted is deprecated. Call attr.value instead."),
75      set: deprecate(function () {
76        return _this.value;
77      }, "Setting attr.raws.unquoted is deprecated and has no effect. attr.value is unescaped by default now.")
78    });
79    _this._constructed = true;
80    return _this;
81  }
82
83  /**
84   * Returns the Attribute's value quoted such that it would be legal to use
85   * in the value of a css file. The original value's quotation setting
86   * used for stringification is left unchanged. See `setValue(value, options)`
87   * if you want to control the quote settings of a new value for the attribute.
88   *
89   * You can also change the quotation used for the current value by setting quoteMark.
90   *
91   * Options:
92   *   * quoteMark {'"' | "'" | null} - Use this value to quote the value. If this
93   *     option is not set, the original value for quoteMark will be used. If
94   *     indeterminate, a double quote is used. The legal values are:
95   *     * `null` - the value will be unquoted and characters will be escaped as necessary.
96   *     * `'` - the value will be quoted with a single quote and single quotes are escaped.
97   *     * `"` - the value will be quoted with a double quote and double quotes are escaped.
98   *   * preferCurrentQuoteMark {boolean} - if true, prefer the source quote mark
99   *     over the quoteMark option value.
100   *   * smart {boolean} - if true, will select a quote mark based on the value
101   *     and the other options specified here. See the `smartQuoteMark()`
102   *     method.
103   **/
104  var _proto = Attribute.prototype;
105  _proto.getQuotedValue = function getQuotedValue(options) {
106    if (options === void 0) {
107      options = {};
108    }
109    var quoteMark = this._determineQuoteMark(options);
110    var cssescopts = CSSESC_QUOTE_OPTIONS[quoteMark];
111    var escaped = (0, _cssesc["default"])(this._value, cssescopts);
112    return escaped;
113  };
114  _proto._determineQuoteMark = function _determineQuoteMark(options) {
115    return options.smart ? this.smartQuoteMark(options) : this.preferredQuoteMark(options);
116  }
117
118  /**
119   * Set the unescaped value with the specified quotation options. The value
120   * provided must not include any wrapping quote marks -- those quotes will
121   * be interpreted as part of the value and escaped accordingly.
122   */;
123  _proto.setValue = function setValue(value, options) {
124    if (options === void 0) {
125      options = {};
126    }
127    this._value = value;
128    this._quoteMark = this._determineQuoteMark(options);
129    this._syncRawValue();
130  }
131
132  /**
133   * Intelligently select a quoteMark value based on the value's contents. If
134   * the value is a legal CSS ident, it will not be quoted. Otherwise a quote
135   * mark will be picked that minimizes the number of escapes.
136   *
137   * If there's no clear winner, the quote mark from these options is used,
138   * then the source quote mark (this is inverted if `preferCurrentQuoteMark` is
139   * true). If the quoteMark is unspecified, a double quote is used.
140   *
141   * @param options This takes the quoteMark and preferCurrentQuoteMark options
142   * from the quoteValue method.
143   */;
144  _proto.smartQuoteMark = function smartQuoteMark(options) {
145    var v = this.value;
146    var numSingleQuotes = v.replace(/[^']/g, '').length;
147    var numDoubleQuotes = v.replace(/[^"]/g, '').length;
148    if (numSingleQuotes + numDoubleQuotes === 0) {
149      var escaped = (0, _cssesc["default"])(v, {
150        isIdentifier: true
151      });
152      if (escaped === v) {
153        return Attribute.NO_QUOTE;
154      } else {
155        var pref = this.preferredQuoteMark(options);
156        if (pref === Attribute.NO_QUOTE) {
157          // pick a quote mark that isn't none and see if it's smaller
158          var quote = this.quoteMark || options.quoteMark || Attribute.DOUBLE_QUOTE;
159          var opts = CSSESC_QUOTE_OPTIONS[quote];
160          var quoteValue = (0, _cssesc["default"])(v, opts);
161          if (quoteValue.length < escaped.length) {
162            return quote;
163          }
164        }
165        return pref;
166      }
167    } else if (numDoubleQuotes === numSingleQuotes) {
168      return this.preferredQuoteMark(options);
169    } else if (numDoubleQuotes < numSingleQuotes) {
170      return Attribute.DOUBLE_QUOTE;
171    } else {
172      return Attribute.SINGLE_QUOTE;
173    }
174  }
175
176  /**
177   * Selects the preferred quote mark based on the options and the current quote mark value.
178   * If you want the quote mark to depend on the attribute value, call `smartQuoteMark(opts)`
179   * instead.
180   */;
181  _proto.preferredQuoteMark = function preferredQuoteMark(options) {
182    var quoteMark = options.preferCurrentQuoteMark ? this.quoteMark : options.quoteMark;
183    if (quoteMark === undefined) {
184      quoteMark = options.preferCurrentQuoteMark ? options.quoteMark : this.quoteMark;
185    }
186    if (quoteMark === undefined) {
187      quoteMark = Attribute.DOUBLE_QUOTE;
188    }
189    return quoteMark;
190  };
191  _proto._syncRawValue = function _syncRawValue() {
192    var rawValue = (0, _cssesc["default"])(this._value, CSSESC_QUOTE_OPTIONS[this.quoteMark]);
193    if (rawValue === this._value) {
194      if (this.raws) {
195        delete this.raws.value;
196      }
197    } else {
198      this.raws.value = rawValue;
199    }
200  };
201  _proto._handleEscapes = function _handleEscapes(prop, value) {
202    if (this._constructed) {
203      var escaped = (0, _cssesc["default"])(value, {
204        isIdentifier: true
205      });
206      if (escaped !== value) {
207        this.raws[prop] = escaped;
208      } else {
209        delete this.raws[prop];
210      }
211    }
212  };
213  _proto._spacesFor = function _spacesFor(name) {
214    var attrSpaces = {
215      before: '',
216      after: ''
217    };
218    var spaces = this.spaces[name] || {};
219    var rawSpaces = this.raws.spaces && this.raws.spaces[name] || {};
220    return Object.assign(attrSpaces, spaces, rawSpaces);
221  };
222  _proto._stringFor = function _stringFor(name, spaceName, concat) {
223    if (spaceName === void 0) {
224      spaceName = name;
225    }
226    if (concat === void 0) {
227      concat = defaultAttrConcat;
228    }
229    var attrSpaces = this._spacesFor(spaceName);
230    return concat(this.stringifyProperty(name), attrSpaces);
231  }
232
233  /**
234   * returns the offset of the attribute part specified relative to the
235   * start of the node of the output string.
236   *
237   * * "ns" - alias for "namespace"
238   * * "namespace" - the namespace if it exists.
239   * * "attribute" - the attribute name
240   * * "attributeNS" - the start of the attribute or its namespace
241   * * "operator" - the match operator of the attribute
242   * * "value" - The value (string or identifier)
243   * * "insensitive" - the case insensitivity flag;
244   * @param part One of the possible values inside an attribute.
245   * @returns -1 if the name is invalid or the value doesn't exist in this attribute.
246   */;
247  _proto.offsetOf = function offsetOf(name) {
248    var count = 1;
249    var attributeSpaces = this._spacesFor("attribute");
250    count += attributeSpaces.before.length;
251    if (name === "namespace" || name === "ns") {
252      return this.namespace ? count : -1;
253    }
254    if (name === "attributeNS") {
255      return count;
256    }
257    count += this.namespaceString.length;
258    if (this.namespace) {
259      count += 1;
260    }
261    if (name === "attribute") {
262      return count;
263    }
264    count += this.stringifyProperty("attribute").length;
265    count += attributeSpaces.after.length;
266    var operatorSpaces = this._spacesFor("operator");
267    count += operatorSpaces.before.length;
268    var operator = this.stringifyProperty("operator");
269    if (name === "operator") {
270      return operator ? count : -1;
271    }
272    count += operator.length;
273    count += operatorSpaces.after.length;
274    var valueSpaces = this._spacesFor("value");
275    count += valueSpaces.before.length;
276    var value = this.stringifyProperty("value");
277    if (name === "value") {
278      return value ? count : -1;
279    }
280    count += value.length;
281    count += valueSpaces.after.length;
282    var insensitiveSpaces = this._spacesFor("insensitive");
283    count += insensitiveSpaces.before.length;
284    if (name === "insensitive") {
285      return this.insensitive ? count : -1;
286    }
287    return -1;
288  };
289  _proto.toString = function toString() {
290    var _this2 = this;
291    var selector = [this.rawSpaceBefore, '['];
292    selector.push(this._stringFor('qualifiedAttribute', 'attribute'));
293    if (this.operator && (this.value || this.value === '')) {
294      selector.push(this._stringFor('operator'));
295      selector.push(this._stringFor('value'));
296      selector.push(this._stringFor('insensitiveFlag', 'insensitive', function (attrValue, attrSpaces) {
297        if (attrValue.length > 0 && !_this2.quoted && attrSpaces.before.length === 0 && !(_this2.spaces.value && _this2.spaces.value.after)) {
298          attrSpaces.before = " ";
299        }
300        return defaultAttrConcat(attrValue, attrSpaces);
301      }));
302    }
303    selector.push(']');
304    selector.push(this.rawSpaceAfter);
305    return selector.join('');
306  };
307  _createClass(Attribute, [{
308    key: "quoted",
309    get: function get() {
310      var qm = this.quoteMark;
311      return qm === "'" || qm === '"';
312    },
313    set: function set(value) {
314      warnOfDeprecatedQuotedAssignment();
315    }
316
317    /**
318     * returns a single (`'`) or double (`"`) quote character if the value is quoted.
319     * returns `null` if the value is not quoted.
320     * returns `undefined` if the quotation state is unknown (this can happen when
321     * the attribute is constructed without specifying a quote mark.)
322     */
323  }, {
324    key: "quoteMark",
325    get: function get() {
326      return this._quoteMark;
327    }
328
329    /**
330     * Set the quote mark to be used by this attribute's value.
331     * If the quote mark changes, the raw (escaped) value at `attr.raws.value` of the attribute
332     * value is updated accordingly.
333     *
334     * @param {"'" | '"' | null} quoteMark The quote mark or `null` if the value should be unquoted.
335     */,
336    set: function set(quoteMark) {
337      if (!this._constructed) {
338        this._quoteMark = quoteMark;
339        return;
340      }
341      if (this._quoteMark !== quoteMark) {
342        this._quoteMark = quoteMark;
343        this._syncRawValue();
344      }
345    }
346  }, {
347    key: "qualifiedAttribute",
348    get: function get() {
349      return this.qualifiedName(this.raws.attribute || this.attribute);
350    }
351  }, {
352    key: "insensitiveFlag",
353    get: function get() {
354      return this.insensitive ? 'i' : '';
355    }
356  }, {
357    key: "value",
358    get: function get() {
359      return this._value;
360    },
361    set:
362    /**
363     * Before 3.0, the value had to be set to an escaped value including any wrapped
364     * quote marks. In 3.0, the semantics of `Attribute.value` changed so that the value
365     * is unescaped during parsing and any quote marks are removed.
366     *
367     * Because the ambiguity of this semantic change, if you set `attr.value = newValue`,
368     * a deprecation warning is raised when the new value contains any characters that would
369     * require escaping (including if it contains wrapped quotes).
370     *
371     * Instead, you should call `attr.setValue(newValue, opts)` and pass options that describe
372     * how the new value is quoted.
373     */
374    function set(v) {
375      if (this._constructed) {
376        var _unescapeValue2 = unescapeValue(v),
377          deprecatedUsage = _unescapeValue2.deprecatedUsage,
378          unescaped = _unescapeValue2.unescaped,
379          quoteMark = _unescapeValue2.quoteMark;
380        if (deprecatedUsage) {
381          warnOfDeprecatedValueAssignment();
382        }
383        if (unescaped === this._value && quoteMark === this._quoteMark) {
384          return;
385        }
386        this._value = unescaped;
387        this._quoteMark = quoteMark;
388        this._syncRawValue();
389      } else {
390        this._value = v;
391      }
392    }
393  }, {
394    key: "insensitive",
395    get: function get() {
396      return this._insensitive;
397    }
398
399    /**
400     * Set the case insensitive flag.
401     * If the case insensitive flag changes, the raw (escaped) value at `attr.raws.insensitiveFlag`
402     * of the attribute is updated accordingly.
403     *
404     * @param {true | false} insensitive true if the attribute should match case-insensitively.
405     */,
406    set: function set(insensitive) {
407      if (!insensitive) {
408        this._insensitive = false;
409
410        // "i" and "I" can be used in "this.raws.insensitiveFlag" to store the original notation.
411        // When setting `attr.insensitive = false` both should be erased to ensure correct serialization.
412        if (this.raws && (this.raws.insensitiveFlag === 'I' || this.raws.insensitiveFlag === 'i')) {
413          this.raws.insensitiveFlag = undefined;
414        }
415      }
416      this._insensitive = insensitive;
417    }
418  }, {
419    key: "attribute",
420    get: function get() {
421      return this._attribute;
422    },
423    set: function set(name) {
424      this._handleEscapes("attribute", name);
425      this._attribute = name;
426    }
427  }]);
428  return Attribute;
429}(_namespace["default"]);
430exports["default"] = Attribute;
431Attribute.NO_QUOTE = null;
432Attribute.SINGLE_QUOTE = "'";
433Attribute.DOUBLE_QUOTE = '"';
434var CSSESC_QUOTE_OPTIONS = (_CSSESC_QUOTE_OPTIONS = {
435  "'": {
436    quotes: 'single',
437    wrap: true
438  },
439  '"': {
440    quotes: 'double',
441    wrap: true
442  }
443}, _CSSESC_QUOTE_OPTIONS[null] = {
444  isIdentifier: true
445}, _CSSESC_QUOTE_OPTIONS);
446function defaultAttrConcat(attrValue, attrSpaces) {
447  return "" + attrSpaces.before + attrValue + attrSpaces.after;
448}