parsers.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. /*********************************************************************
  2. * These are commonly used parsers for CSS Values they take a string *
  3. * to parse and return a string after it's been converted, if needed *
  4. ********************************************************************/
  5. 'use strict';
  6. exports.TYPES = {
  7. INTEGER: 1,
  8. NUMBER: 2,
  9. LENGTH: 3,
  10. PERCENT: 4,
  11. URL: 5,
  12. COLOR: 6,
  13. STRING: 7,
  14. ANGLE: 8,
  15. KEYWORD: 9,
  16. NULL_OR_EMPTY_STR: 10
  17. };
  18. /*jslint regexp: true*/
  19. // rough regular expressions
  20. var integerRegEx = /^[\-+]?[0-9]+$/;
  21. var numberRegEx = /^[\-+]?[0-9]*\.[0-9]+$/;
  22. var lengthRegEx = /^(0|[\-+]?[0-9]*\.?[0-9]+(in|cm|em|mm|pt|pc|px|ex|rem|vh|vw))$/;
  23. var percentRegEx = /^[\-+]?[0-9]*\.?[0-9]+%$/;
  24. var urlRegEx = /^url\(\s*([^\)]*)\s*\)$/;
  25. var stringRegEx = /^(\"[^\"]*\"|\'[^\']*\')$/;
  26. var colorRegEx1 = /^#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])?$/;
  27. var colorRegEx2 = /^rgb\(([^\)]*)\)$/;
  28. var colorRegEx3 = /^rgba\(([^\)]*)\)$/;
  29. var angleRegEx = /^([\-+]?[0-9]*\.?[0-9]+)(deg|grad|rad)$/;
  30. /*jslint regexp: false*/
  31. // This will return one of the above types based on the passed in string
  32. exports.valueType = function valueType(val) {
  33. if (val === '' || val === null) {
  34. return exports.TYPES.NULL_OR_EMPTY_STR;
  35. }
  36. if (typeof val === 'number') {
  37. val = val.toString();
  38. }
  39. if (typeof val !== 'string') {
  40. return undefined;
  41. }
  42. if (integerRegEx.test(val)) {
  43. return exports.TYPES.INTEGER;
  44. }
  45. if (numberRegEx.test(val)) {
  46. return exports.TYPES.NUMBER;
  47. }
  48. if (lengthRegEx.test(val)) {
  49. return exports.TYPES.LENGTH;
  50. }
  51. if (percentRegEx.test(val)) {
  52. return exports.TYPES.PERCENT;
  53. }
  54. if (urlRegEx.test(val)) {
  55. return exports.TYPES.URL;
  56. }
  57. if (stringRegEx.test(val)) {
  58. return exports.TYPES.STRING;
  59. }
  60. if (angleRegEx.test(val)) {
  61. return exports.TYPES.ANGLE;
  62. }
  63. if (colorRegEx1.test(val)) {
  64. return exports.TYPES.COLOR;
  65. }
  66. var res = colorRegEx2.exec(val);
  67. var parts;
  68. if (res !== null) {
  69. parts = res[1].split(/\s*,\s*/);
  70. if (parts.length !== 3) {
  71. return undefined;
  72. }
  73. if (parts.every(percentRegEx.test.bind(percentRegEx)) || parts.every(integerRegEx.test.bind(integerRegEx))) {
  74. return exports.TYPES.COLOR;
  75. }
  76. return undefined;
  77. }
  78. res = colorRegEx3.exec(val);
  79. if (res !== null) {
  80. parts = res[1].split(/\s*,\s*/);
  81. if (parts.length !== 4) {
  82. return undefined;
  83. }
  84. if (parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx)) || parts.every(integerRegEx.test.bind(integerRegEx))) {
  85. if (numberRegEx.test(parts[3])) {
  86. return exports.TYPES.COLOR;
  87. }
  88. }
  89. return undefined;
  90. }
  91. // could still be a color, one of the standard keyword colors
  92. val = val.toLowerCase();
  93. switch (val) {
  94. case 'maroon':
  95. case 'red':
  96. case 'orange':
  97. case 'yellow':
  98. case 'olive':
  99. case 'purple':
  100. case 'fuchsia':
  101. case 'white':
  102. case 'lime':
  103. case 'green':
  104. case 'navy':
  105. case 'blue':
  106. case 'aqua':
  107. case 'teal':
  108. case 'black':
  109. case 'silver':
  110. case 'gray':
  111. // the following are deprecated in CSS3
  112. case 'activeborder':
  113. case 'activecaption':
  114. case 'appworkspace':
  115. case 'background':
  116. case 'buttonface':
  117. case 'buttonhighlight':
  118. case 'buttonshadow':
  119. case 'buttontext':
  120. case 'captiontext':
  121. case 'graytext':
  122. case 'highlight':
  123. case 'highlighttext':
  124. case 'inactiveborder':
  125. case 'inactivecaption':
  126. case 'inactivecaptiontext':
  127. case 'infobackground':
  128. case 'infotext':
  129. case 'menu':
  130. case 'menutext':
  131. case 'scrollbar':
  132. case 'threeddarkshadow':
  133. case 'threedface':
  134. case 'threedhighlight':
  135. case 'threedlightshadow':
  136. case 'threedshadow':
  137. case 'window':
  138. case 'windowframe':
  139. case 'windowtext':
  140. return exports.TYPES.COLOR;
  141. default:
  142. return exports.TYPES.KEYWORD;
  143. }
  144. };
  145. exports.parseInteger = function parseInteger(val) {
  146. var type = exports.valueType(val);
  147. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  148. return val;
  149. }
  150. if (type !== exports.TYPES.INTEGER) {
  151. return undefined;
  152. }
  153. return String(parseInt(val, 10));
  154. };
  155. exports.parseNumber = function parseNumber(val) {
  156. var type = exports.valueType(val);
  157. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  158. return val;
  159. }
  160. if (type !== exports.TYPES.NUMBER && type !== exports.TYPES.INTEGER) {
  161. return undefined;
  162. }
  163. return String(parseFloat(val));
  164. };
  165. exports.parseLength = function parseLength(val) {
  166. if (val === 0 || val === '0') {
  167. return '0px';
  168. }
  169. var type = exports.valueType(val);
  170. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  171. return val;
  172. }
  173. if (type !== exports.TYPES.LENGTH) {
  174. return undefined;
  175. }
  176. return val;
  177. };
  178. exports.parsePercent = function parsePercent(val) {
  179. if (val === 0 || val === '0') {
  180. return '0%';
  181. }
  182. var type = exports.valueType(val);
  183. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  184. return val;
  185. }
  186. if (type !== exports.TYPES.PERCENT) {
  187. return undefined;
  188. }
  189. return val;
  190. };
  191. // either a length or a percent
  192. exports.parseMeasurement = function parseMeasurement(val) {
  193. var length = exports.parseLength(val);
  194. if (length !== undefined) {
  195. return length;
  196. }
  197. return exports.parsePercent(val);
  198. };
  199. exports.parseUrl = function parseUrl(val) {
  200. var type = exports.valueType(val);
  201. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  202. return val;
  203. }
  204. var res = urlRegEx.exec(val);
  205. // does it match the regex?
  206. if (!res) {
  207. return undefined;
  208. }
  209. var str = res[1];
  210. // if it starts with single or double quotes, does it end with the same?
  211. if ((str[0] === '"' || str[0] === "'") && str[0] !== str[str.length - 1]) {
  212. return undefined;
  213. }
  214. if (str[0] === '"' || str[0] === "'") {
  215. str = str.substr(1, str.length - 2);
  216. }
  217. var i;
  218. for (i = 0; i < str.length; i++) {
  219. switch (str[i]) {
  220. case '(':
  221. case ')':
  222. case ' ':
  223. case '\t':
  224. case '\n':
  225. case "'":
  226. case '"':
  227. return undefined;
  228. case '\\':
  229. i++;
  230. break;
  231. }
  232. }
  233. return 'url(' + str + ')';
  234. };
  235. exports.parseString = function parseString(val) {
  236. var type = exports.valueType(val);
  237. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  238. return val;
  239. }
  240. if (type !== exports.TYPES.STRING) {
  241. return undefined;
  242. }
  243. var i;
  244. for (i = 1; i < val.length - 1; i++) {
  245. switch (val[i]) {
  246. case val[0]:
  247. return undefined;
  248. case '\\':
  249. i++;
  250. while (i < val.length - 1 && /[0-9A-Fa-f]/.test(val[i])) {
  251. i++;
  252. }
  253. break;
  254. }
  255. }
  256. if (i >= val.length) {
  257. return undefined;
  258. }
  259. return val;
  260. };
  261. exports.parseColor = function parseColor(val) {
  262. var type = exports.valueType(val);
  263. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  264. return val;
  265. }
  266. var red, green, blue, alpha = 1;
  267. var parts;
  268. var res = colorRegEx1.exec(val);
  269. // is it #aaa or #ababab
  270. if (res) {
  271. var hex = val.substr(1);
  272. if (hex.length === 3) {
  273. hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  274. }
  275. red = parseInt(hex.substr(0, 2), 16);
  276. green = parseInt(hex.substr(2, 2), 16);
  277. blue = parseInt(hex.substr(4, 2), 16);
  278. return 'rgb(' + red + ', ' + green + ', ' + blue + ')';
  279. }
  280. res = colorRegEx2.exec(val);
  281. if (res) {
  282. parts = res[1].split(/\s*,\s*/);
  283. if (parts.length !== 3) {
  284. return undefined;
  285. }
  286. if (parts.every(percentRegEx.test.bind(percentRegEx))) {
  287. red = Math.floor(parseFloat(parts[0].slice(0, -1)) * 255 / 100);
  288. green = Math.floor(parseFloat(parts[1].slice(0, -1)) * 255 / 100);
  289. blue = Math.floor(parseFloat(parts[2].slice(0, -1)) * 255 / 100);
  290. } else if (parts.every(integerRegEx.test.bind(integerRegEx))) {
  291. red = parseInt(parts[0], 10);
  292. green = parseInt(parts[1], 10);
  293. blue = parseInt(parts[2], 10);
  294. } else {
  295. return undefined;
  296. }
  297. red = Math.min(255, Math.max(0, red));
  298. green = Math.min(255, Math.max(0, green));
  299. blue = Math.min(255, Math.max(0, blue));
  300. return 'rgb(' + red + ', ' + green + ', ' + blue + ')';
  301. }
  302. res = colorRegEx3.exec(val);
  303. if (res) {
  304. parts = res[1].split(/\s*,\s*/);
  305. if (parts.length !== 4) {
  306. return undefined;
  307. }
  308. if (parts.slice(0, 3).every(percentRegEx.test.bind(percentRegEx))) {
  309. red = Math.floor(parseFloat(parts[0].slice(0, -1)) * 255 / 100);
  310. green = Math.floor(parseFloat(parts[1].slice(0, -1)) * 255 / 100);
  311. blue = Math.floor(parseFloat(parts[2].slice(0, -1)) * 255 / 100);
  312. alpha = parseFloat(parts[3]);
  313. } else if (parts.slice(0, 3).every(integerRegEx.test.bind(integerRegEx))) {
  314. red = parseInt(parts[0], 10);
  315. green = parseInt(parts[1], 10);
  316. blue = parseInt(parts[2], 10);
  317. alpha = parseFloat(parts[3]);
  318. } else {
  319. return undefined;
  320. }
  321. if (isNaN(alpha)) {
  322. alpha = 1;
  323. }
  324. red = Math.min(255, Math.max(0, red));
  325. green = Math.min(255, Math.max(0, green));
  326. blue = Math.min(255, Math.max(0, blue));
  327. alpha = Math.min(1, Math.max(0, alpha));
  328. if (alpha === 1) {
  329. return 'rgb(' + red + ', ' + green + ', ' + blue + ')';
  330. }
  331. return 'rgba(' + red + ', ' + green + ', ' + blue + ', ' + alpha + ')';
  332. }
  333. if (type === exports.TYPES.COLOR) {
  334. return val;
  335. }
  336. return undefined;
  337. };
  338. exports.parseAngle = function parseAngle(val) {
  339. var type = exports.valueType(val);
  340. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  341. return val;
  342. }
  343. if (type !== exports.TYPES.ANGLE) {
  344. return undefined;
  345. }
  346. var res = angleRegEx.exec(val);
  347. var flt = parseFloat(res[1]);
  348. if (res[2] === 'rad') {
  349. flt *= 180 / Math.PI;
  350. } else if (res[2] === 'grad') {
  351. flt *= 360 / 400;
  352. }
  353. while (flt < 0) {
  354. flt += 360;
  355. }
  356. while (flt > 360) {
  357. flt -= 360;
  358. }
  359. return flt + 'deg';
  360. };
  361. exports.parseKeyword = function parseKeyword(val, valid_keywords) {
  362. var type = exports.valueType(val);
  363. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  364. return val;
  365. }
  366. if (type !== exports.TYPES.KEYWORD) {
  367. return undefined;
  368. }
  369. val = val.toString().toLowerCase();
  370. var i;
  371. for (i = 0; i < valid_keywords.length; i++) {
  372. if (valid_keywords[i].toLowerCase() === val) {
  373. return valid_keywords[i];
  374. }
  375. }
  376. return undefined;
  377. };
  378. // utility to translate from border-width to borderWidth
  379. var dashedToCamelCase = function (dashed) {
  380. var i;
  381. var camel = '';
  382. var nextCap = false;
  383. for (i = 0; i < dashed.length; i++) {
  384. if (dashed[i] !== '-') {
  385. camel += nextCap ? dashed[i].toUpperCase() : dashed[i];
  386. nextCap = false;
  387. } else {
  388. nextCap = true;
  389. }
  390. }
  391. return camel;
  392. };
  393. exports.dashedToCamelCase = dashedToCamelCase;
  394. var is_space = /\s/;
  395. var opening_deliminators = ['"', '\'', '('];
  396. var closing_deliminators = ['"', '\'', ')'];
  397. // this splits on whitespace, but keeps quoted and parened parts together
  398. var getParts = function (str) {
  399. var deliminator_stack = [];
  400. var length = str.length;
  401. var i;
  402. var parts = [];
  403. var current_part = '';
  404. var opening_index;
  405. var closing_index;
  406. for (i = 0; i < length; i++) {
  407. opening_index = opening_deliminators.indexOf(str[i]);
  408. closing_index = closing_deliminators.indexOf(str[i]);
  409. if (is_space.test(str[i])) {
  410. if (deliminator_stack.length === 0) {
  411. if (current_part !== '') {
  412. parts.push(current_part);
  413. }
  414. current_part = '';
  415. } else {
  416. current_part += str[i];
  417. }
  418. } else {
  419. if (str[i] === '\\') {
  420. i++;
  421. current_part += str[i];
  422. } else {
  423. current_part += str[i];
  424. if (closing_index !== -1 && closing_index === deliminator_stack[deliminator_stack.length - 1]) {
  425. deliminator_stack.pop();
  426. } else if (opening_index !== -1) {
  427. deliminator_stack.push(opening_index);
  428. }
  429. }
  430. }
  431. }
  432. if (current_part !== '') {
  433. parts.push(current_part);
  434. }
  435. return parts;
  436. };
  437. /*
  438. * this either returns undefined meaning that it isn't valid
  439. * or returns an object where the keys are dashed short
  440. * hand properties and the values are the values to set
  441. * on them
  442. */
  443. exports.shorthandParser = function parse(v, shorthand_for) {
  444. var obj = {};
  445. var type = exports.valueType(v);
  446. if (type === exports.TYPES.NULL_OR_EMPTY_STR) {
  447. Object.keys(shorthand_for).forEach(function (property) {
  448. obj[property] = '';
  449. });
  450. return obj;
  451. }
  452. if (typeof v === 'number') {
  453. v = v.toString();
  454. }
  455. if (typeof v !== 'string') {
  456. return undefined;
  457. }
  458. if (v.toLowerCase() === 'inherit') {
  459. return {};
  460. }
  461. var parts = getParts(v);
  462. var valid = true;
  463. parts.forEach(function (part) {
  464. var part_valid = false;
  465. Object.keys(shorthand_for).forEach(function (property) {
  466. if (shorthand_for[property].isValid(part)) {
  467. part_valid = true;
  468. obj[property] = part;
  469. }
  470. });
  471. valid = valid && part_valid;
  472. });
  473. if (!valid) {
  474. return undefined;
  475. }
  476. return obj;
  477. };
  478. exports.shorthandSetter = function (property, shorthand_for) {
  479. return function (v) {
  480. var obj = exports.shorthandParser(v, shorthand_for);
  481. if (obj === undefined) {
  482. return;
  483. }
  484. //console.log('shorthandSetter for:', property, 'obj:', obj);
  485. Object.keys(obj).forEach(function (subprop) {
  486. // in case subprop is an implicit property, this will clear
  487. // *its* subpropertiesX
  488. var camel = dashedToCamelCase(subprop);
  489. this[camel] = obj[subprop];
  490. // in case it gets translated into something else (0 -> 0px)
  491. obj[subprop] = this[camel];
  492. this.removeProperty(subprop);
  493. // don't add in empty properties
  494. if (obj[subprop] !== '') {
  495. this._values[subprop] = obj[subprop];
  496. }
  497. }, this);
  498. Object.keys(shorthand_for).forEach(function (subprop) {
  499. if (!obj.hasOwnProperty(subprop)) {
  500. this.removeProperty(subprop);
  501. delete this._values[subprop];
  502. }
  503. }, this);
  504. // in case the value is something like 'none' that removes all values,
  505. // check that the generated one is not empty, first remove the property
  506. // if it already exists, then call the shorthandGetter, if it's an empty
  507. // string, don't set the property
  508. this.removeProperty(property);
  509. var calculated = exports.shorthandGetter(property, shorthand_for).call(this);
  510. if (calculated !== '') {
  511. this._setProperty(property, calculated);
  512. }
  513. };
  514. };
  515. exports.shorthandGetter = function (property, shorthand_for) {
  516. return function () {
  517. if (this._values[property] !== undefined) {
  518. return this.getPropertyValue(property);
  519. }
  520. return Object.keys(shorthand_for).map(function (subprop) {
  521. return this.getPropertyValue(subprop);
  522. }, this).filter(function (value) {
  523. return value !== '';
  524. }).join(' ');
  525. };
  526. };
  527. // isValid(){1,4} | inherit
  528. // if one, it applies to all
  529. // if two, the first applies to the top and bottom, and the second to left and right
  530. // if three, the first applies to the top, the second to left and right, the third bottom
  531. // if four, top, right, bottom, left
  532. exports.implicitSetter = function (property_before, property_after, isValid, parser) {
  533. property_after = property_after || '';
  534. if (property_after !== '') {
  535. property_after = '-' + property_after;
  536. }
  537. var part_names = ["top","right","bottom","left"];
  538. return function (v) {
  539. if (typeof v === 'number') {
  540. v = v.toString();
  541. }
  542. if (typeof v !== 'string') {
  543. return undefined;
  544. }
  545. var parts;
  546. if (v.toLowerCase() === 'inherit' || v === '') {
  547. parts = [v];
  548. } else {
  549. parts = getParts(v);
  550. }
  551. if (parts.length < 1 || parts.length > 4) {
  552. return undefined;
  553. }
  554. if (!parts.every(isValid)) {
  555. return undefined;
  556. }
  557. parts = parts.map(function (part) {
  558. return parser(part);
  559. });
  560. this._setProperty(property_before + property_after, parts.join(' '));
  561. if (parts.length === 1) {
  562. parts[1] = parts[0];
  563. }
  564. if (parts.length === 2) {
  565. parts[2] = parts[0];
  566. }
  567. if (parts.length === 3) {
  568. parts[3] = parts[1];
  569. }
  570. for (var i = 0; i < 4; i++) {
  571. var property = property_before + "-" + part_names[i] + property_after;
  572. this.removeProperty(property);
  573. if (parts[i] !== '') {
  574. this._values[property] = parts[i];
  575. }
  576. }
  577. return v;
  578. };
  579. };
  580. //
  581. // Companion to implicitSetter, but for the individual parts.
  582. // This sets the individual value, and checks to see if all four
  583. // sub-parts are set. If so, it sets the shorthand version and removes
  584. // the individual parts from the cssText.
  585. //
  586. exports.subImplicitSetter = function (prefix, part, isValid, parser) {
  587. var property = prefix + '-' + part;
  588. var subparts = [prefix+"-top", prefix+"-right", prefix+"-bottom", prefix+"-left"];
  589. return function (v) {
  590. if (typeof v === 'number') {
  591. v = v.toString();
  592. }
  593. if (typeof v !== 'string') {
  594. return undefined;
  595. }
  596. if (!isValid(v)) {
  597. return undefined;
  598. }
  599. v = parser(v);
  600. this._setProperty(property,v);
  601. var parts = [];
  602. for (var i = 0; i < 4; i++) {
  603. if (this._values[subparts[i]] == null || this._values[subparts[i]] === '') {
  604. break;
  605. }
  606. parts.push(this._values[subparts[i]]);
  607. }
  608. if (parts.length === 4) {
  609. for (i = 0; i < 4; i++) {
  610. this.removeProperty(subparts[i]);
  611. this._values[subparts[i]] = parts[i];
  612. }
  613. this._setProperty(prefix,parts.join(" "));
  614. }
  615. return v;
  616. };
  617. };
  618. var camel_to_dashed = /[A-Z]/g;
  619. /*jslint regexp: true*/
  620. var first_segment = /^\([^\-]\)-/;
  621. /*jslint regexp: false*/
  622. var vendor_prefixes = ['o', 'moz', 'ms', 'webkit'];
  623. exports.camelToDashed = function (camel_case) {
  624. var match;
  625. var dashed = camel_case.replace(camel_to_dashed, '-$&').toLowerCase();
  626. match = dashed.match(first_segment);
  627. if (match && vendor_prefixes.indexOf(match[1]) !== -1) {
  628. dashed = '-' + dashed;
  629. }
  630. return dashed;
  631. };