generic.cjs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. 'use strict';
  2. const genericConst = require('./generic-const.cjs');
  3. const genericAnPlusB = require('./generic-an-plus-b.cjs');
  4. const genericUrange = require('./generic-urange.cjs');
  5. const charCodeDefinitions = require('../tokenizer/char-code-definitions.cjs');
  6. const types = require('../tokenizer/types.cjs');
  7. const utils = require('../tokenizer/utils.cjs');
  8. const calcFunctionNames = ['calc(', '-moz-calc(', '-webkit-calc('];
  9. const balancePair = new Map([
  10. [types.Function, types.RightParenthesis],
  11. [types.LeftParenthesis, types.RightParenthesis],
  12. [types.LeftSquareBracket, types.RightSquareBracket],
  13. [types.LeftCurlyBracket, types.RightCurlyBracket]
  14. ]);
  15. // safe char code getter
  16. function charCodeAt(str, index) {
  17. return index < str.length ? str.charCodeAt(index) : 0;
  18. }
  19. function eqStr(actual, expected) {
  20. return utils.cmpStr(actual, 0, actual.length, expected);
  21. }
  22. function eqStrAny(actual, expected) {
  23. for (let i = 0; i < expected.length; i++) {
  24. if (eqStr(actual, expected[i])) {
  25. return true;
  26. }
  27. }
  28. return false;
  29. }
  30. // IE postfix hack, i.e. 123\0 or 123px\9
  31. function isPostfixIeHack(str, offset) {
  32. if (offset !== str.length - 2) {
  33. return false;
  34. }
  35. return (
  36. charCodeAt(str, offset) === 0x005C && // U+005C REVERSE SOLIDUS (\)
  37. charCodeDefinitions.isDigit(charCodeAt(str, offset + 1))
  38. );
  39. }
  40. function outOfRange(opts, value, numEnd) {
  41. if (opts && opts.type === 'Range') {
  42. const num = Number(
  43. numEnd !== undefined && numEnd !== value.length
  44. ? value.substr(0, numEnd)
  45. : value
  46. );
  47. if (isNaN(num)) {
  48. return true;
  49. }
  50. // FIXME: when opts.min is a string it's a dimension, skip a range validation
  51. // for now since it requires a type covertation which is not implmented yet
  52. if (opts.min !== null && num < opts.min && typeof opts.min !== 'string') {
  53. return true;
  54. }
  55. // FIXME: when opts.max is a string it's a dimension, skip a range validation
  56. // for now since it requires a type covertation which is not implmented yet
  57. if (opts.max !== null && num > opts.max && typeof opts.max !== 'string') {
  58. return true;
  59. }
  60. }
  61. return false;
  62. }
  63. function consumeFunction(token, getNextToken) {
  64. let balanceCloseType = 0;
  65. let balanceStash = [];
  66. let length = 0;
  67. // balanced token consuming
  68. scan:
  69. do {
  70. switch (token.type) {
  71. case types.RightCurlyBracket:
  72. case types.RightParenthesis:
  73. case types.RightSquareBracket:
  74. if (token.type !== balanceCloseType) {
  75. break scan;
  76. }
  77. balanceCloseType = balanceStash.pop();
  78. if (balanceStash.length === 0) {
  79. length++;
  80. break scan;
  81. }
  82. break;
  83. case types.Function:
  84. case types.LeftParenthesis:
  85. case types.LeftSquareBracket:
  86. case types.LeftCurlyBracket:
  87. balanceStash.push(balanceCloseType);
  88. balanceCloseType = balancePair.get(token.type);
  89. break;
  90. }
  91. length++;
  92. } while (token = getNextToken(length));
  93. return length;
  94. }
  95. // TODO: implement
  96. // can be used wherever <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> values are allowed
  97. // https://drafts.csswg.org/css-values/#calc-notation
  98. function calc(next) {
  99. return function(token, getNextToken, opts) {
  100. if (token === null) {
  101. return 0;
  102. }
  103. if (token.type === types.Function && eqStrAny(token.value, calcFunctionNames)) {
  104. return consumeFunction(token, getNextToken);
  105. }
  106. return next(token, getNextToken, opts);
  107. };
  108. }
  109. function tokenType(expectedTokenType) {
  110. return function(token) {
  111. if (token === null || token.type !== expectedTokenType) {
  112. return 0;
  113. }
  114. return 1;
  115. };
  116. }
  117. // =========================
  118. // Complex types
  119. //
  120. // https://drafts.csswg.org/css-values-4/#custom-idents
  121. // 4.2. Author-defined Identifiers: the <custom-ident> type
  122. // Some properties accept arbitrary author-defined identifiers as a component value.
  123. // This generic data type is denoted by <custom-ident>, and represents any valid CSS identifier
  124. // that would not be misinterpreted as a pre-defined keyword in that property’s value definition.
  125. //
  126. // See also: https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident
  127. function customIdent(token) {
  128. if (token === null || token.type !== types.Ident) {
  129. return 0;
  130. }
  131. const name = token.value.toLowerCase();
  132. // The CSS-wide keywords are not valid <custom-ident>s
  133. if (eqStrAny(name, genericConst.cssWideKeywords)) {
  134. return 0;
  135. }
  136. // The default keyword is reserved and is also not a valid <custom-ident>
  137. if (eqStr(name, 'default')) {
  138. return 0;
  139. }
  140. // TODO: ignore property specific keywords (as described https://developer.mozilla.org/en-US/docs/Web/CSS/custom-ident)
  141. // Specifications using <custom-ident> must specify clearly what other keywords
  142. // are excluded from <custom-ident>, if any—for example by saying that any pre-defined keywords
  143. // in that property’s value definition are excluded. Excluded keywords are excluded
  144. // in all ASCII case permutations.
  145. return 1;
  146. }
  147. // https://drafts.csswg.org/css-values-4/#dashed-idents
  148. // The <dashed-ident> production is a <custom-ident>, with all the case-sensitivity that implies,
  149. // with the additional restriction that it must start with two dashes (U+002D HYPHEN-MINUS).
  150. function dashedIdent(token) {
  151. if (token === null || token.type !== types.Ident) {
  152. return 0;
  153. }
  154. // ... must start with two dashes (U+002D HYPHEN-MINUS)
  155. if (charCodeAt(token.value, 0) !== 0x002D || charCodeAt(token.value, 1) !== 0x002D) {
  156. return 0;
  157. }
  158. return 1;
  159. }
  160. // https://drafts.csswg.org/css-variables/#typedef-custom-property-name
  161. // A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo.
  162. // The <custom-property-name> production corresponds to this: it’s defined as any <dashed-ident>
  163. // (a valid identifier that starts with two dashes), except -- itself, which is reserved for future use by CSS.
  164. function customPropertyName(token) {
  165. // ... it’s defined as any <dashed-ident>
  166. if (!dashedIdent(token)) {
  167. return 0;
  168. }
  169. // ... except -- itself, which is reserved for future use by CSS
  170. if (token.value === '--') {
  171. return 0;
  172. }
  173. return 1;
  174. }
  175. // https://drafts.csswg.org/css-color-4/#hex-notation
  176. // The syntax of a <hex-color> is a <hash-token> token whose value consists of 3, 4, 6, or 8 hexadecimal digits.
  177. // In other words, a hex color is written as a hash character, "#", followed by some number of digits 0-9 or
  178. // letters a-f (the case of the letters doesn’t matter - #00ff00 is identical to #00FF00).
  179. function hexColor(token) {
  180. if (token === null || token.type !== types.Hash) {
  181. return 0;
  182. }
  183. const length = token.value.length;
  184. // valid values (length): #rgb (4), #rgba (5), #rrggbb (7), #rrggbbaa (9)
  185. if (length !== 4 && length !== 5 && length !== 7 && length !== 9) {
  186. return 0;
  187. }
  188. for (let i = 1; i < length; i++) {
  189. if (!charCodeDefinitions.isHexDigit(charCodeAt(token.value, i))) {
  190. return 0;
  191. }
  192. }
  193. return 1;
  194. }
  195. function idSelector(token) {
  196. if (token === null || token.type !== types.Hash) {
  197. return 0;
  198. }
  199. if (!charCodeDefinitions.isIdentifierStart(charCodeAt(token.value, 1), charCodeAt(token.value, 2), charCodeAt(token.value, 3))) {
  200. return 0;
  201. }
  202. return 1;
  203. }
  204. // https://drafts.csswg.org/css-syntax/#any-value
  205. // It represents the entirety of what a valid declaration can have as its value.
  206. function declarationValue(token, getNextToken) {
  207. if (!token) {
  208. return 0;
  209. }
  210. let balanceCloseType = 0;
  211. let balanceStash = [];
  212. let length = 0;
  213. // The <declaration-value> production matches any sequence of one or more tokens,
  214. // so long as the sequence does not contain ...
  215. scan:
  216. do {
  217. switch (token.type) {
  218. // ... <bad-string-token>, <bad-url-token>,
  219. case types.BadString:
  220. case types.BadUrl:
  221. break scan;
  222. // ... unmatched <)-token>, <]-token>, or <}-token>,
  223. case types.RightCurlyBracket:
  224. case types.RightParenthesis:
  225. case types.RightSquareBracket:
  226. if (token.type !== balanceCloseType) {
  227. break scan;
  228. }
  229. balanceCloseType = balanceStash.pop();
  230. break;
  231. // ... or top-level <semicolon-token> tokens
  232. case types.Semicolon:
  233. if (balanceCloseType === 0) {
  234. break scan;
  235. }
  236. break;
  237. // ... or <delim-token> tokens with a value of "!"
  238. case types.Delim:
  239. if (balanceCloseType === 0 && token.value === '!') {
  240. break scan;
  241. }
  242. break;
  243. case types.Function:
  244. case types.LeftParenthesis:
  245. case types.LeftSquareBracket:
  246. case types.LeftCurlyBracket:
  247. balanceStash.push(balanceCloseType);
  248. balanceCloseType = balancePair.get(token.type);
  249. break;
  250. }
  251. length++;
  252. } while (token = getNextToken(length));
  253. return length;
  254. }
  255. // https://drafts.csswg.org/css-syntax/#any-value
  256. // The <any-value> production is identical to <declaration-value>, but also
  257. // allows top-level <semicolon-token> tokens and <delim-token> tokens
  258. // with a value of "!". It represents the entirety of what valid CSS can be in any context.
  259. function anyValue(token, getNextToken) {
  260. if (!token) {
  261. return 0;
  262. }
  263. let balanceCloseType = 0;
  264. let balanceStash = [];
  265. let length = 0;
  266. // The <any-value> production matches any sequence of one or more tokens,
  267. // so long as the sequence ...
  268. scan:
  269. do {
  270. switch (token.type) {
  271. // ... does not contain <bad-string-token>, <bad-url-token>,
  272. case types.BadString:
  273. case types.BadUrl:
  274. break scan;
  275. // ... unmatched <)-token>, <]-token>, or <}-token>,
  276. case types.RightCurlyBracket:
  277. case types.RightParenthesis:
  278. case types.RightSquareBracket:
  279. if (token.type !== balanceCloseType) {
  280. break scan;
  281. }
  282. balanceCloseType = balanceStash.pop();
  283. break;
  284. case types.Function:
  285. case types.LeftParenthesis:
  286. case types.LeftSquareBracket:
  287. case types.LeftCurlyBracket:
  288. balanceStash.push(balanceCloseType);
  289. balanceCloseType = balancePair.get(token.type);
  290. break;
  291. }
  292. length++;
  293. } while (token = getNextToken(length));
  294. return length;
  295. }
  296. // =========================
  297. // Dimensions
  298. //
  299. function dimension(type) {
  300. if (type) {
  301. type = new Set(type);
  302. }
  303. return function(token, getNextToken, opts) {
  304. if (token === null || token.type !== types.Dimension) {
  305. return 0;
  306. }
  307. const numberEnd = utils.consumeNumber(token.value, 0);
  308. // check unit
  309. if (type !== null) {
  310. // check for IE postfix hack, i.e. 123px\0 or 123px\9
  311. const reverseSolidusOffset = token.value.indexOf('\\', numberEnd);
  312. const unit = reverseSolidusOffset === -1 || !isPostfixIeHack(token.value, reverseSolidusOffset)
  313. ? token.value.substr(numberEnd)
  314. : token.value.substring(numberEnd, reverseSolidusOffset);
  315. if (type.has(unit.toLowerCase()) === false) {
  316. return 0;
  317. }
  318. }
  319. // check range if specified
  320. if (outOfRange(opts, token.value, numberEnd)) {
  321. return 0;
  322. }
  323. return 1;
  324. };
  325. }
  326. // =========================
  327. // Percentage
  328. //
  329. // §5.5. Percentages: the <percentage> type
  330. // https://drafts.csswg.org/css-values-4/#percentages
  331. function percentage(token, getNextToken, opts) {
  332. // ... corresponds to the <percentage-token> production
  333. if (token === null || token.type !== types.Percentage) {
  334. return 0;
  335. }
  336. // check range if specified
  337. if (outOfRange(opts, token.value, token.value.length - 1)) {
  338. return 0;
  339. }
  340. return 1;
  341. }
  342. // =========================
  343. // Numeric
  344. //
  345. // https://drafts.csswg.org/css-values-4/#numbers
  346. // The value <zero> represents a literal number with the value 0. Expressions that merely
  347. // evaluate to a <number> with the value 0 (for example, calc(0)) do not match <zero>;
  348. // only literal <number-token>s do.
  349. function zero(next) {
  350. if (typeof next !== 'function') {
  351. next = function() {
  352. return 0;
  353. };
  354. }
  355. return function(token, getNextToken, opts) {
  356. if (token !== null && token.type === types.Number) {
  357. if (Number(token.value) === 0) {
  358. return 1;
  359. }
  360. }
  361. return next(token, getNextToken, opts);
  362. };
  363. }
  364. // § 5.3. Real Numbers: the <number> type
  365. // https://drafts.csswg.org/css-values-4/#numbers
  366. // Number values are denoted by <number>, and represent real numbers, possibly with a fractional component.
  367. // ... It corresponds to the <number-token> production
  368. function number(token, getNextToken, opts) {
  369. if (token === null) {
  370. return 0;
  371. }
  372. const numberEnd = utils.consumeNumber(token.value, 0);
  373. const isNumber = numberEnd === token.value.length;
  374. if (!isNumber && !isPostfixIeHack(token.value, numberEnd)) {
  375. return 0;
  376. }
  377. // check range if specified
  378. if (outOfRange(opts, token.value, numberEnd)) {
  379. return 0;
  380. }
  381. return 1;
  382. }
  383. // §5.2. Integers: the <integer> type
  384. // https://drafts.csswg.org/css-values-4/#integers
  385. function integer(token, getNextToken, opts) {
  386. // ... corresponds to a subset of the <number-token> production
  387. if (token === null || token.type !== types.Number) {
  388. return 0;
  389. }
  390. // The first digit of an integer may be immediately preceded by `-` or `+` to indicate the integer’s sign.
  391. let i = charCodeAt(token.value, 0) === 0x002B || // U+002B PLUS SIGN (+)
  392. charCodeAt(token.value, 0) === 0x002D ? 1 : 0; // U+002D HYPHEN-MINUS (-)
  393. // When written literally, an integer is one or more decimal digits 0 through 9 ...
  394. for (; i < token.value.length; i++) {
  395. if (!charCodeDefinitions.isDigit(charCodeAt(token.value, i))) {
  396. return 0;
  397. }
  398. }
  399. // check range if specified
  400. if (outOfRange(opts, token.value, i)) {
  401. return 0;
  402. }
  403. return 1;
  404. }
  405. // token types
  406. const tokenTypes = {
  407. 'ident-token': tokenType(types.Ident),
  408. 'function-token': tokenType(types.Function),
  409. 'at-keyword-token': tokenType(types.AtKeyword),
  410. 'hash-token': tokenType(types.Hash),
  411. 'string-token': tokenType(types.String),
  412. 'bad-string-token': tokenType(types.BadString),
  413. 'url-token': tokenType(types.Url),
  414. 'bad-url-token': tokenType(types.BadUrl),
  415. 'delim-token': tokenType(types.Delim),
  416. 'number-token': tokenType(types.Number),
  417. 'percentage-token': tokenType(types.Percentage),
  418. 'dimension-token': tokenType(types.Dimension),
  419. 'whitespace-token': tokenType(types.WhiteSpace),
  420. 'CDO-token': tokenType(types.CDO),
  421. 'CDC-token': tokenType(types.CDC),
  422. 'colon-token': tokenType(types.Colon),
  423. 'semicolon-token': tokenType(types.Semicolon),
  424. 'comma-token': tokenType(types.Comma),
  425. '[-token': tokenType(types.LeftSquareBracket),
  426. ']-token': tokenType(types.RightSquareBracket),
  427. '(-token': tokenType(types.LeftParenthesis),
  428. ')-token': tokenType(types.RightParenthesis),
  429. '{-token': tokenType(types.LeftCurlyBracket),
  430. '}-token': tokenType(types.RightCurlyBracket)
  431. };
  432. // token production types
  433. const productionTypes = {
  434. // token type aliases
  435. 'string': tokenType(types.String),
  436. 'ident': tokenType(types.Ident),
  437. // percentage
  438. 'percentage': calc(percentage),
  439. // numeric
  440. 'zero': zero(),
  441. 'number': calc(number),
  442. 'integer': calc(integer),
  443. // complex types
  444. 'custom-ident': customIdent,
  445. 'dashed-ident': dashedIdent,
  446. 'custom-property-name': customPropertyName,
  447. 'hex-color': hexColor,
  448. 'id-selector': idSelector, // element( <id-selector> )
  449. 'an-plus-b': genericAnPlusB,
  450. 'urange': genericUrange,
  451. 'declaration-value': declarationValue,
  452. 'any-value': anyValue
  453. };
  454. // dimensions types depend on units set
  455. function createDemensionTypes(units) {
  456. const {
  457. angle,
  458. decibel,
  459. frequency,
  460. flex,
  461. length,
  462. resolution,
  463. semitones,
  464. time
  465. } = units || {};
  466. return {
  467. 'dimension': calc(dimension(null)),
  468. 'angle': calc(dimension(angle)),
  469. 'decibel': calc(dimension(decibel)),
  470. 'frequency': calc(dimension(frequency)),
  471. 'flex': calc(dimension(flex)),
  472. 'length': calc(zero(dimension(length))),
  473. 'resolution': calc(dimension(resolution)),
  474. 'semitones': calc(dimension(semitones)),
  475. 'time': calc(dimension(time))
  476. };
  477. }
  478. function createGenericTypes(units) {
  479. return {
  480. ...tokenTypes,
  481. ...productionTypes,
  482. ...createDemensionTypes(units)
  483. };
  484. }
  485. exports.createDemensionTypes = createDemensionTypes;
  486. exports.createGenericTypes = createGenericTypes;
  487. exports.productionTypes = productionTypes;
  488. exports.tokenTypes = tokenTypes;