generic.js 17 KB

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