Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

grid-utils.js 32KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. "use strict";
  2. function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }
  3. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  4. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
  5. var parser = require('postcss-value-parser');
  6. var list = require('postcss').list;
  7. var uniq = require('../utils').uniq;
  8. var escapeRegexp = require('../utils').escapeRegexp;
  9. var splitSelector = require('../utils').splitSelector;
  10. function convert(value) {
  11. if (value && value.length === 2 && value[0] === 'span' && parseInt(value[1], 10) > 0) {
  12. return [false, parseInt(value[1], 10)];
  13. }
  14. if (value && value.length === 1 && parseInt(value[0], 10) > 0) {
  15. return [parseInt(value[0], 10), false];
  16. }
  17. return [false, false];
  18. }
  19. function translate(values, startIndex, endIndex) {
  20. var startValue = values[startIndex];
  21. var endValue = values[endIndex];
  22. if (!startValue) {
  23. return [false, false];
  24. }
  25. var _convert = convert(startValue),
  26. start = _convert[0],
  27. spanStart = _convert[1];
  28. var _convert2 = convert(endValue),
  29. end = _convert2[0],
  30. spanEnd = _convert2[1];
  31. if (start && !endValue) {
  32. return [start, false];
  33. }
  34. if (spanStart && end) {
  35. return [end - spanStart, spanStart];
  36. }
  37. if (start && spanEnd) {
  38. return [start, spanEnd];
  39. }
  40. if (start && end) {
  41. return [start, end - start];
  42. }
  43. return [false, false];
  44. }
  45. function parse(decl) {
  46. var node = parser(decl.value);
  47. var values = [];
  48. var current = 0;
  49. values[current] = [];
  50. for (var _iterator = _createForOfIteratorHelperLoose(node.nodes), _step; !(_step = _iterator()).done;) {
  51. var i = _step.value;
  52. if (i.type === 'div') {
  53. current += 1;
  54. values[current] = [];
  55. } else if (i.type === 'word') {
  56. values[current].push(i.value);
  57. }
  58. }
  59. return values;
  60. }
  61. function insertDecl(decl, prop, value) {
  62. if (value && !decl.parent.some(function (i) {
  63. return i.prop === "-ms-" + prop;
  64. })) {
  65. decl.cloneBefore({
  66. prop: "-ms-" + prop,
  67. value: value.toString()
  68. });
  69. }
  70. } // Track transforms
  71. function prefixTrackProp(_ref) {
  72. var prop = _ref.prop,
  73. prefix = _ref.prefix;
  74. return prefix + prop.replace('template-', '');
  75. }
  76. function transformRepeat(_ref2, _ref3) {
  77. var nodes = _ref2.nodes;
  78. var gap = _ref3.gap;
  79. var _nodes$reduce = nodes.reduce(function (result, node) {
  80. if (node.type === 'div' && node.value === ',') {
  81. result.key = 'size';
  82. } else {
  83. result[result.key].push(parser.stringify(node));
  84. }
  85. return result;
  86. }, {
  87. key: 'count',
  88. size: [],
  89. count: []
  90. }),
  91. count = _nodes$reduce.count,
  92. size = _nodes$reduce.size; // insert gap values
  93. if (gap) {
  94. var _ret = function () {
  95. size = size.filter(function (i) {
  96. return i.trim();
  97. });
  98. var val = [];
  99. var _loop = function _loop(i) {
  100. size.forEach(function (item, index) {
  101. if (index > 0 || i > 1) {
  102. val.push(gap);
  103. }
  104. val.push(item);
  105. });
  106. };
  107. for (var i = 1; i <= count; i++) {
  108. _loop(i);
  109. }
  110. return {
  111. v: val.join(' ')
  112. };
  113. }();
  114. if (typeof _ret === "object") return _ret.v;
  115. }
  116. return "(" + size.join('') + ")[" + count.join('') + "]";
  117. }
  118. function prefixTrackValue(_ref4) {
  119. var value = _ref4.value,
  120. gap = _ref4.gap;
  121. var result = parser(value).nodes.reduce(function (nodes, node) {
  122. if (node.type === 'function' && node.value === 'repeat') {
  123. return nodes.concat({
  124. type: 'word',
  125. value: transformRepeat(node, {
  126. gap: gap
  127. })
  128. });
  129. }
  130. if (gap && node.type === 'space') {
  131. return nodes.concat({
  132. type: 'space',
  133. value: ' '
  134. }, {
  135. type: 'word',
  136. value: gap
  137. }, node);
  138. }
  139. return nodes.concat(node);
  140. }, []);
  141. return parser.stringify(result);
  142. } // Parse grid-template-areas
  143. var DOTS = /^\.+$/;
  144. function track(start, end) {
  145. return {
  146. start: start,
  147. end: end,
  148. span: end - start
  149. };
  150. }
  151. function getColumns(line) {
  152. return line.trim().split(/\s+/g);
  153. }
  154. function parseGridAreas(_ref5) {
  155. var rows = _ref5.rows,
  156. gap = _ref5.gap;
  157. return rows.reduce(function (areas, line, rowIndex) {
  158. if (gap.row) rowIndex *= 2;
  159. if (line.trim() === '') return areas;
  160. getColumns(line).forEach(function (area, columnIndex) {
  161. if (DOTS.test(area)) return;
  162. if (gap.column) columnIndex *= 2;
  163. if (typeof areas[area] === 'undefined') {
  164. areas[area] = {
  165. column: track(columnIndex + 1, columnIndex + 2),
  166. row: track(rowIndex + 1, rowIndex + 2)
  167. };
  168. } else {
  169. var _areas$area = areas[area],
  170. column = _areas$area.column,
  171. row = _areas$area.row;
  172. column.start = Math.min(column.start, columnIndex + 1);
  173. column.end = Math.max(column.end, columnIndex + 2);
  174. column.span = column.end - column.start;
  175. row.start = Math.min(row.start, rowIndex + 1);
  176. row.end = Math.max(row.end, rowIndex + 2);
  177. row.span = row.end - row.start;
  178. }
  179. });
  180. return areas;
  181. }, {});
  182. } // Parse grid-template
  183. function testTrack(node) {
  184. return node.type === 'word' && /^\[.+]$/.test(node.value);
  185. }
  186. function verifyRowSize(result) {
  187. if (result.areas.length > result.rows.length) {
  188. result.rows.push('auto');
  189. }
  190. return result;
  191. }
  192. function parseTemplate(_ref6) {
  193. var decl = _ref6.decl,
  194. gap = _ref6.gap;
  195. var gridTemplate = parser(decl.value).nodes.reduce(function (result, node) {
  196. var type = node.type,
  197. value = node.value;
  198. if (testTrack(node) || type === 'space') return result; // area
  199. if (type === 'string') {
  200. result = verifyRowSize(result);
  201. result.areas.push(value);
  202. } // values and function
  203. if (type === 'word' || type === 'function') {
  204. result[result.key].push(parser.stringify(node));
  205. } // divider(/)
  206. if (type === 'div' && value === '/') {
  207. result.key = 'columns';
  208. result = verifyRowSize(result);
  209. }
  210. return result;
  211. }, {
  212. key: 'rows',
  213. columns: [],
  214. rows: [],
  215. areas: []
  216. });
  217. return {
  218. areas: parseGridAreas({
  219. rows: gridTemplate.areas,
  220. gap: gap
  221. }),
  222. columns: prefixTrackValue({
  223. value: gridTemplate.columns.join(' '),
  224. gap: gap.column
  225. }),
  226. rows: prefixTrackValue({
  227. value: gridTemplate.rows.join(' '),
  228. gap: gap.row
  229. })
  230. };
  231. } // Insert parsed grid areas
  232. /**
  233. * Get an array of -ms- prefixed props and values
  234. * @param {Object} [area] area object with column and row data
  235. * @param {Boolean} [addRowSpan] should we add grid-column-row value?
  236. * @param {Boolean} [addColumnSpan] should we add grid-column-span value?
  237. * @return {Array<Object>}
  238. */
  239. function getMSDecls(area, addRowSpan, addColumnSpan) {
  240. if (addRowSpan === void 0) {
  241. addRowSpan = false;
  242. }
  243. if (addColumnSpan === void 0) {
  244. addColumnSpan = false;
  245. }
  246. return [].concat({
  247. prop: '-ms-grid-row',
  248. value: String(area.row.start)
  249. }, area.row.span > 1 || addRowSpan ? {
  250. prop: '-ms-grid-row-span',
  251. value: String(area.row.span)
  252. } : [], {
  253. prop: '-ms-grid-column',
  254. value: String(area.column.start)
  255. }, area.column.span > 1 || addColumnSpan ? {
  256. prop: '-ms-grid-column-span',
  257. value: String(area.column.span)
  258. } : []);
  259. }
  260. function getParentMedia(parent) {
  261. if (parent.type === 'atrule' && parent.name === 'media') {
  262. return parent;
  263. }
  264. if (!parent.parent) {
  265. return false;
  266. }
  267. return getParentMedia(parent.parent);
  268. }
  269. /**
  270. * change selectors for rules with duplicate grid-areas.
  271. * @param {Array<Rule>} rules
  272. * @param {Array<String>} templateSelectors
  273. * @return {Array<Rule>} rules with changed selectors
  274. */
  275. function changeDuplicateAreaSelectors(ruleSelectors, templateSelectors) {
  276. ruleSelectors = ruleSelectors.map(function (selector) {
  277. var selectorBySpace = list.space(selector);
  278. var selectorByComma = list.comma(selector);
  279. if (selectorBySpace.length > selectorByComma.length) {
  280. selector = selectorBySpace.slice(-1).join('');
  281. }
  282. return selector;
  283. });
  284. return ruleSelectors.map(function (ruleSelector) {
  285. var newSelector = templateSelectors.map(function (tplSelector, index) {
  286. var space = index === 0 ? '' : ' ';
  287. return "" + space + tplSelector + " > " + ruleSelector;
  288. });
  289. return newSelector;
  290. });
  291. }
  292. /**
  293. * check if selector of rules are equal
  294. * @param {Rule} ruleA
  295. * @param {Rule} ruleB
  296. * @return {Boolean}
  297. */
  298. function selectorsEqual(ruleA, ruleB) {
  299. return ruleA.selectors.some(function (sel) {
  300. return ruleB.selectors.some(function (s) {
  301. return s === sel;
  302. });
  303. });
  304. }
  305. /**
  306. * Parse data from all grid-template(-areas) declarations
  307. * @param {Root} css css root
  308. * @return {Object} parsed data
  309. */
  310. function parseGridTemplatesData(css) {
  311. var parsed = []; // we walk through every grid-template(-areas) declaration and store
  312. // data with the same area names inside the item
  313. css.walkDecls(/grid-template(-areas)?$/, function (d) {
  314. var rule = d.parent;
  315. var media = getParentMedia(rule);
  316. var gap = getGridGap(d);
  317. var inheritedGap = inheritGridGap(d, gap);
  318. var _parseTemplate = parseTemplate({
  319. decl: d,
  320. gap: inheritedGap || gap
  321. }),
  322. areas = _parseTemplate.areas;
  323. var areaNames = Object.keys(areas); // skip node if it doesn't have areas
  324. if (areaNames.length === 0) {
  325. return true;
  326. } // check parsed array for item that include the same area names
  327. // return index of that item
  328. var index = parsed.reduce(function (acc, _ref7, idx) {
  329. var allAreas = _ref7.allAreas;
  330. var hasAreas = allAreas && areaNames.some(function (area) {
  331. return allAreas.includes(area);
  332. });
  333. return hasAreas ? idx : acc;
  334. }, null);
  335. if (index !== null) {
  336. // index is found, add the grid-template data to that item
  337. var _parsed$index = parsed[index],
  338. allAreas = _parsed$index.allAreas,
  339. rules = _parsed$index.rules; // check if rule has no duplicate area names
  340. var hasNoDuplicates = rules.some(function (r) {
  341. return r.hasDuplicates === false && selectorsEqual(r, rule);
  342. });
  343. var duplicatesFound = false; // check need to gather all duplicate area names
  344. var duplicateAreaNames = rules.reduce(function (acc, r) {
  345. if (!r.params && selectorsEqual(r, rule)) {
  346. duplicatesFound = true;
  347. return r.duplicateAreaNames;
  348. }
  349. if (!duplicatesFound) {
  350. areaNames.forEach(function (name) {
  351. if (r.areas[name]) {
  352. acc.push(name);
  353. }
  354. });
  355. }
  356. return uniq(acc);
  357. }, []); // update grid-row/column-span values for areas with duplicate
  358. // area names. @see #1084 and #1146
  359. rules.forEach(function (r) {
  360. areaNames.forEach(function (name) {
  361. var area = r.areas[name];
  362. if (area && area.row.span !== areas[name].row.span) {
  363. areas[name].row.updateSpan = true;
  364. }
  365. if (area && area.column.span !== areas[name].column.span) {
  366. areas[name].column.updateSpan = true;
  367. }
  368. });
  369. });
  370. parsed[index].allAreas = uniq([].concat(allAreas, areaNames));
  371. parsed[index].rules.push({
  372. hasDuplicates: !hasNoDuplicates,
  373. params: media.params,
  374. selectors: rule.selectors,
  375. node: rule,
  376. duplicateAreaNames: duplicateAreaNames,
  377. areas: areas
  378. });
  379. } else {
  380. // index is NOT found, push the new item to the parsed array
  381. parsed.push({
  382. allAreas: areaNames,
  383. areasCount: 0,
  384. rules: [{
  385. hasDuplicates: false,
  386. duplicateRules: [],
  387. params: media.params,
  388. selectors: rule.selectors,
  389. node: rule,
  390. duplicateAreaNames: [],
  391. areas: areas
  392. }]
  393. });
  394. }
  395. return undefined;
  396. });
  397. return parsed;
  398. }
  399. /**
  400. * insert prefixed grid-area declarations
  401. * @param {Root} css css root
  402. * @param {Function} isDisabled check if the rule is disabled
  403. * @return {void}
  404. */
  405. function insertAreas(css, isDisabled) {
  406. // parse grid-template declarations
  407. var gridTemplatesData = parseGridTemplatesData(css); // return undefined if no declarations found
  408. if (gridTemplatesData.length === 0) {
  409. return undefined;
  410. } // we need to store the rules that we will insert later
  411. var rulesToInsert = {};
  412. css.walkDecls('grid-area', function (gridArea) {
  413. var gridAreaRule = gridArea.parent;
  414. var hasPrefixedRow = gridAreaRule.first.prop === '-ms-grid-row';
  415. var gridAreaMedia = getParentMedia(gridAreaRule);
  416. if (isDisabled(gridArea)) {
  417. return undefined;
  418. }
  419. var gridAreaRuleIndex = gridAreaMedia ? css.index(gridAreaMedia) : css.index(gridAreaRule);
  420. var value = gridArea.value; // found the data that matches grid-area identifier
  421. var data = gridTemplatesData.filter(function (d) {
  422. return d.allAreas.includes(value);
  423. })[0];
  424. if (!data) {
  425. return true;
  426. }
  427. var lastArea = data.allAreas[data.allAreas.length - 1];
  428. var selectorBySpace = list.space(gridAreaRule.selector);
  429. var selectorByComma = list.comma(gridAreaRule.selector);
  430. var selectorIsComplex = selectorBySpace.length > 1 && selectorBySpace.length > selectorByComma.length; // prevent doubling of prefixes
  431. if (hasPrefixedRow) {
  432. return false;
  433. } // create the empty object with the key as the last area name
  434. // e.g if we have templates with "a b c" values, "c" will be the last area
  435. if (!rulesToInsert[lastArea]) {
  436. rulesToInsert[lastArea] = {};
  437. }
  438. var lastRuleIsSet = false; // walk through every grid-template rule data
  439. for (var _iterator2 = _createForOfIteratorHelperLoose(data.rules), _step2; !(_step2 = _iterator2()).done;) {
  440. var rule = _step2.value;
  441. var area = rule.areas[value];
  442. var hasDuplicateName = rule.duplicateAreaNames.includes(value); // if we can't find the area name, update lastRule and continue
  443. if (!area) {
  444. var lastRuleIndex = css.index(rulesToInsert[lastArea].lastRule);
  445. if (gridAreaRuleIndex > lastRuleIndex) {
  446. rulesToInsert[lastArea].lastRule = gridAreaMedia || gridAreaRule;
  447. }
  448. continue;
  449. } // for grid-templates inside media rule we need to create empty
  450. // array to push prefixed grid-area rules later
  451. if (rule.params && !rulesToInsert[lastArea][rule.params]) {
  452. rulesToInsert[lastArea][rule.params] = [];
  453. }
  454. if ((!rule.hasDuplicates || !hasDuplicateName) && !rule.params) {
  455. // grid-template has no duplicates and not inside media rule
  456. getMSDecls(area, false, false).reverse().forEach(function (i) {
  457. return gridAreaRule.prepend(Object.assign(i, {
  458. raws: {
  459. between: gridArea.raws.between
  460. }
  461. }));
  462. });
  463. rulesToInsert[lastArea].lastRule = gridAreaRule;
  464. lastRuleIsSet = true;
  465. } else if (rule.hasDuplicates && !rule.params && !selectorIsComplex) {
  466. (function () {
  467. // grid-template has duplicates and not inside media rule
  468. var cloned = gridAreaRule.clone();
  469. cloned.removeAll();
  470. getMSDecls(area, area.row.updateSpan, area.column.updateSpan).reverse().forEach(function (i) {
  471. return cloned.prepend(Object.assign(i, {
  472. raws: {
  473. between: gridArea.raws.between
  474. }
  475. }));
  476. });
  477. cloned.selectors = changeDuplicateAreaSelectors(cloned.selectors, rule.selectors);
  478. if (rulesToInsert[lastArea].lastRule) {
  479. rulesToInsert[lastArea].lastRule.after(cloned);
  480. }
  481. rulesToInsert[lastArea].lastRule = cloned;
  482. lastRuleIsSet = true;
  483. })();
  484. } else if (rule.hasDuplicates && !rule.params && selectorIsComplex && gridAreaRule.selector.includes(rule.selectors[0])) {
  485. // grid-template has duplicates and not inside media rule
  486. // and the selector is complex
  487. gridAreaRule.walkDecls(/-ms-grid-(row|column)/, function (d) {
  488. return d.remove();
  489. });
  490. getMSDecls(area, area.row.updateSpan, area.column.updateSpan).reverse().forEach(function (i) {
  491. return gridAreaRule.prepend(Object.assign(i, {
  492. raws: {
  493. between: gridArea.raws.between
  494. }
  495. }));
  496. });
  497. } else if (rule.params) {
  498. (function () {
  499. // grid-template is inside media rule
  500. // if we're inside media rule, we need to store prefixed rules
  501. // inside rulesToInsert object to be able to preserve the order of media
  502. // rules and merge them easily
  503. var cloned = gridAreaRule.clone();
  504. cloned.removeAll();
  505. getMSDecls(area, area.row.updateSpan, area.column.updateSpan).reverse().forEach(function (i) {
  506. return cloned.prepend(Object.assign(i, {
  507. raws: {
  508. between: gridArea.raws.between
  509. }
  510. }));
  511. });
  512. if (rule.hasDuplicates && hasDuplicateName) {
  513. cloned.selectors = changeDuplicateAreaSelectors(cloned.selectors, rule.selectors);
  514. }
  515. cloned.raws = rule.node.raws;
  516. if (css.index(rule.node.parent) > gridAreaRuleIndex) {
  517. // append the prefixed rules right inside media rule
  518. // with grid-template
  519. rule.node.parent.append(cloned);
  520. } else {
  521. // store the rule to insert later
  522. rulesToInsert[lastArea][rule.params].push(cloned);
  523. } // set new rule as last rule ONLY if we didn't set lastRule for
  524. // this grid-area before
  525. if (!lastRuleIsSet) {
  526. rulesToInsert[lastArea].lastRule = gridAreaMedia || gridAreaRule;
  527. }
  528. })();
  529. }
  530. }
  531. return undefined;
  532. }); // append stored rules inside the media rules
  533. Object.keys(rulesToInsert).forEach(function (area) {
  534. var data = rulesToInsert[area];
  535. var lastRule = data.lastRule;
  536. Object.keys(data).reverse().filter(function (p) {
  537. return p !== 'lastRule';
  538. }).forEach(function (params) {
  539. if (data[params].length > 0 && lastRule) {
  540. lastRule.after({
  541. name: 'media',
  542. params: params
  543. });
  544. lastRule.next().append(data[params]);
  545. }
  546. });
  547. });
  548. return undefined;
  549. }
  550. /**
  551. * Warn user if grid area identifiers are not found
  552. * @param {Object} areas
  553. * @param {Declaration} decl
  554. * @param {Result} result
  555. * @return {void}
  556. */
  557. function warnMissedAreas(areas, decl, result) {
  558. var missed = Object.keys(areas);
  559. decl.root().walkDecls('grid-area', function (gridArea) {
  560. missed = missed.filter(function (e) {
  561. return e !== gridArea.value;
  562. });
  563. });
  564. if (missed.length > 0) {
  565. decl.warn(result, 'Can not find grid areas: ' + missed.join(', '));
  566. }
  567. return undefined;
  568. }
  569. /**
  570. * compare selectors with grid-area rule and grid-template rule
  571. * show warning if grid-template selector is not found
  572. * (this function used for grid-area rule)
  573. * @param {Declaration} decl
  574. * @param {Result} result
  575. * @return {void}
  576. */
  577. function warnTemplateSelectorNotFound(decl, result) {
  578. var rule = decl.parent;
  579. var root = decl.root();
  580. var duplicatesFound = false; // slice selector array. Remove the last part (for comparison)
  581. var slicedSelectorArr = list.space(rule.selector).filter(function (str) {
  582. return str !== '>';
  583. }).slice(0, -1); // we need to compare only if selector is complex.
  584. // e.g '.grid-cell' is simple, but '.parent > .grid-cell' is complex
  585. if (slicedSelectorArr.length > 0) {
  586. var gridTemplateFound = false;
  587. var foundAreaSelector = null;
  588. root.walkDecls(/grid-template(-areas)?$/, function (d) {
  589. var parent = d.parent;
  590. var templateSelectors = parent.selectors;
  591. var _parseTemplate2 = parseTemplate({
  592. decl: d,
  593. gap: getGridGap(d)
  594. }),
  595. areas = _parseTemplate2.areas;
  596. var hasArea = areas[decl.value]; // find the the matching selectors
  597. for (var _iterator3 = _createForOfIteratorHelperLoose(templateSelectors), _step3; !(_step3 = _iterator3()).done;) {
  598. var tplSelector = _step3.value;
  599. if (gridTemplateFound) {
  600. break;
  601. }
  602. var tplSelectorArr = list.space(tplSelector).filter(function (str) {
  603. return str !== '>';
  604. });
  605. gridTemplateFound = tplSelectorArr.every(function (item, idx) {
  606. return item === slicedSelectorArr[idx];
  607. });
  608. }
  609. if (gridTemplateFound || !hasArea) {
  610. return true;
  611. }
  612. if (!foundAreaSelector) {
  613. foundAreaSelector = parent.selector;
  614. } // if we found the duplicate area with different selector
  615. if (foundAreaSelector && foundAreaSelector !== parent.selector) {
  616. duplicatesFound = true;
  617. }
  618. return undefined;
  619. }); // warn user if we didn't find template
  620. if (!gridTemplateFound && duplicatesFound) {
  621. decl.warn(result, 'Autoprefixer cannot find a grid-template ' + ("containing the duplicate grid-area \"" + decl.value + "\" ") + ("with full selector matching: " + slicedSelectorArr.join(' ')));
  622. }
  623. }
  624. }
  625. /**
  626. * warn user if both grid-area and grid-(row|column)
  627. * declarations are present in the same rule
  628. * @param {Declaration} decl
  629. * @param {Result} result
  630. * @return {void}
  631. */
  632. function warnIfGridRowColumnExists(decl, result) {
  633. var rule = decl.parent;
  634. var decls = [];
  635. rule.walkDecls(/^grid-(row|column)/, function (d) {
  636. if (!d.prop.endsWith('-end') && !d.value.startsWith('span')) {
  637. decls.push(d);
  638. }
  639. });
  640. if (decls.length > 0) {
  641. decls.forEach(function (d) {
  642. d.warn(result, 'You already have a grid-area declaration present in the rule. ' + ("You should use either grid-area or " + d.prop + ", not both"));
  643. });
  644. }
  645. return undefined;
  646. } // Gap utils
  647. function getGridGap(decl) {
  648. var gap = {}; // try to find gap
  649. var testGap = /^(grid-)?((row|column)-)?gap$/;
  650. decl.parent.walkDecls(testGap, function (_ref8) {
  651. var prop = _ref8.prop,
  652. value = _ref8.value;
  653. if (/^(grid-)?gap$/.test(prop)) {
  654. var _parser$nodes = parser(value).nodes,
  655. row = _parser$nodes[0],
  656. column = _parser$nodes[2];
  657. gap.row = row && parser.stringify(row);
  658. gap.column = column ? parser.stringify(column) : gap.row;
  659. }
  660. if (/^(grid-)?row-gap$/.test(prop)) gap.row = value;
  661. if (/^(grid-)?column-gap$/.test(prop)) gap.column = value;
  662. });
  663. return gap;
  664. }
  665. /**
  666. * parse media parameters (for example 'min-width: 500px')
  667. * @param {String} params parameter to parse
  668. * @return {}
  669. */
  670. function parseMediaParams(params) {
  671. if (!params) {
  672. return false;
  673. }
  674. var parsed = parser(params);
  675. var prop;
  676. var value;
  677. parsed.walk(function (node) {
  678. if (node.type === 'word' && /min|max/g.test(node.value)) {
  679. prop = node.value;
  680. } else if (node.value.includes('px')) {
  681. value = parseInt(node.value.replace(/\D/g, ''));
  682. }
  683. });
  684. return [prop, value];
  685. }
  686. /**
  687. * Compare the selectors and decide if we
  688. * need to inherit gap from compared selector or not.
  689. * @type {String} selA
  690. * @type {String} selB
  691. * @return {Boolean}
  692. */
  693. function shouldInheritGap(selA, selB) {
  694. var result; // get arrays of selector split in 3-deep array
  695. var splitSelectorArrA = splitSelector(selA);
  696. var splitSelectorArrB = splitSelector(selB);
  697. if (splitSelectorArrA[0].length < splitSelectorArrB[0].length) {
  698. // abort if selectorA has lower descendant specificity then selectorB
  699. // (e.g '.grid' and '.hello .world .grid')
  700. return false;
  701. } else if (splitSelectorArrA[0].length > splitSelectorArrB[0].length) {
  702. // if selectorA has higher descendant specificity then selectorB
  703. // (e.g '.foo .bar .grid' and '.grid')
  704. var idx = splitSelectorArrA[0].reduce(function (res, _ref9, index) {
  705. var item = _ref9[0];
  706. var firstSelectorPart = splitSelectorArrB[0][0][0];
  707. if (item === firstSelectorPart) {
  708. return index;
  709. }
  710. return false;
  711. }, false);
  712. if (idx) {
  713. result = splitSelectorArrB[0].every(function (arr, index) {
  714. return arr.every(function (part, innerIndex) {
  715. return (// because selectorA has more space elements, we need to slice
  716. // selectorA array by 'idx' number to compare them
  717. splitSelectorArrA[0].slice(idx)[index][innerIndex] === part
  718. );
  719. });
  720. });
  721. }
  722. } else {
  723. // if selectorA has the same descendant specificity as selectorB
  724. // this condition covers cases such as: '.grid.foo.bar' and '.grid'
  725. result = splitSelectorArrB.some(function (byCommaArr) {
  726. return byCommaArr.every(function (bySpaceArr, index) {
  727. return bySpaceArr.every(function (part, innerIndex) {
  728. return splitSelectorArrA[0][index][innerIndex] === part;
  729. });
  730. });
  731. });
  732. }
  733. return result;
  734. }
  735. /**
  736. * inherit grid gap values from the closest rule above
  737. * with the same selector
  738. * @param {Declaration} decl
  739. * @param {Object} gap gap values
  740. * @return {Object | Boolean} return gap values or false (if not found)
  741. */
  742. function inheritGridGap(decl, gap) {
  743. var rule = decl.parent;
  744. var mediaRule = getParentMedia(rule);
  745. var root = rule.root(); // get an array of selector split in 3-deep array
  746. var splitSelectorArr = splitSelector(rule.selector); // abort if the rule already has gaps
  747. if (Object.keys(gap).length > 0) {
  748. return false;
  749. } // e.g ['min-width']
  750. var _parseMediaParams = parseMediaParams(mediaRule.params),
  751. prop = _parseMediaParams[0];
  752. var lastBySpace = splitSelectorArr[0]; // get escaped value from the selector
  753. // if we have '.grid-2.foo.bar' selector, will be '\.grid\-2'
  754. var escaped = escapeRegexp(lastBySpace[lastBySpace.length - 1][0]);
  755. var regexp = new RegExp("(" + escaped + "$)|(" + escaped + "[,.])"); // find the closest rule with the same selector
  756. var closestRuleGap;
  757. root.walkRules(regexp, function (r) {
  758. var gridGap; // abort if are checking the same rule
  759. if (rule.toString() === r.toString()) {
  760. return false;
  761. } // find grid-gap values
  762. r.walkDecls('grid-gap', function (d) {
  763. return gridGap = getGridGap(d);
  764. }); // skip rule without gaps
  765. if (!gridGap || Object.keys(gridGap).length === 0) {
  766. return true;
  767. } // skip rules that should not be inherited from
  768. if (!shouldInheritGap(rule.selector, r.selector)) {
  769. return true;
  770. }
  771. var media = getParentMedia(r);
  772. if (media) {
  773. // if we are inside media, we need to check that media props match
  774. // e.g ('min-width' === 'min-width')
  775. var propToCompare = parseMediaParams(media.params)[0];
  776. if (propToCompare === prop) {
  777. closestRuleGap = gridGap;
  778. return true;
  779. }
  780. } else {
  781. closestRuleGap = gridGap;
  782. return true;
  783. }
  784. return undefined;
  785. }); // if we find the closest gap object
  786. if (closestRuleGap && Object.keys(closestRuleGap).length > 0) {
  787. return closestRuleGap;
  788. }
  789. return false;
  790. }
  791. function warnGridGap(_ref10) {
  792. var gap = _ref10.gap,
  793. hasColumns = _ref10.hasColumns,
  794. decl = _ref10.decl,
  795. result = _ref10.result;
  796. var hasBothGaps = gap.row && gap.column;
  797. if (!hasColumns && (hasBothGaps || gap.column && !gap.row)) {
  798. delete gap.column;
  799. decl.warn(result, 'Can not implement grid-gap without grid-template-columns');
  800. }
  801. }
  802. /**
  803. * normalize the grid-template-rows/columns values
  804. * @param {String} str grid-template-rows/columns value
  805. * @return {Array} normalized array with values
  806. * @example
  807. * let normalized = normalizeRowColumn('1fr repeat(2, 20px 50px) 1fr')
  808. * normalized // <= ['1fr', '20px', '50px', '20px', '50px', '1fr']
  809. */
  810. function normalizeRowColumn(str) {
  811. var normalized = parser(str).nodes.reduce(function (result, node) {
  812. if (node.type === 'function' && node.value === 'repeat') {
  813. var key = 'count';
  814. var _node$nodes$reduce = node.nodes.reduce(function (acc, n) {
  815. if (n.type === 'word' && key === 'count') {
  816. acc[0] = Math.abs(parseInt(n.value));
  817. return acc;
  818. }
  819. if (n.type === 'div' && n.value === ',') {
  820. key = 'value';
  821. return acc;
  822. }
  823. if (key === 'value') {
  824. acc[1] += parser.stringify(n);
  825. }
  826. return acc;
  827. }, [0, '']),
  828. count = _node$nodes$reduce[0],
  829. value = _node$nodes$reduce[1];
  830. if (count) {
  831. for (var i = 0; i < count; i++) {
  832. result.push(value);
  833. }
  834. }
  835. return result;
  836. }
  837. if (node.type === 'space') {
  838. return result;
  839. }
  840. return result.concat(parser.stringify(node));
  841. }, []);
  842. return normalized;
  843. }
  844. /**
  845. * Autoplace grid items
  846. * @param {Declaration} decl
  847. * @param {Result} result
  848. * @param {Object} gap gap values
  849. * @param {String} autoflowValue grid-auto-flow value
  850. * @return {void}
  851. * @see https://github.com/postcss/autoprefixer/issues/1148
  852. */
  853. function autoplaceGridItems(decl, result, gap, autoflowValue) {
  854. if (autoflowValue === void 0) {
  855. autoflowValue = 'row';
  856. }
  857. var parent = decl.parent;
  858. var rowDecl = parent.nodes.find(function (i) {
  859. return i.prop === 'grid-template-rows';
  860. });
  861. var rows = normalizeRowColumn(rowDecl.value);
  862. var columns = normalizeRowColumn(decl.value); // Build array of area names with dummy values. If we have 3 columns and
  863. // 2 rows, filledRows will be equal to ['1 2 3', '4 5 6']
  864. var filledRows = rows.map(function (_, rowIndex) {
  865. return Array.from({
  866. length: columns.length
  867. }, function (v, k) {
  868. return k + rowIndex * columns.length + 1;
  869. }).join(' ');
  870. });
  871. var areas = parseGridAreas({
  872. rows: filledRows,
  873. gap: gap
  874. });
  875. var keys = Object.keys(areas);
  876. var items = keys.map(function (i) {
  877. return areas[i];
  878. }); // Change the order of cells if grid-auto-flow value is 'column'
  879. if (autoflowValue.includes('column')) {
  880. items = items.sort(function (a, b) {
  881. return a.column.start - b.column.start;
  882. });
  883. } // Insert new rules
  884. items.reverse().forEach(function (item, index) {
  885. var column = item.column,
  886. row = item.row;
  887. var nodeSelector = parent.selectors.map(function (sel) {
  888. return sel + (" > *:nth-child(" + (keys.length - index) + ")");
  889. }).join(', '); // create new rule
  890. var node = parent.clone().removeAll(); // change rule selector
  891. node.selector = nodeSelector; // insert prefixed row/column values
  892. node.append({
  893. prop: '-ms-grid-row',
  894. value: row.start
  895. });
  896. node.append({
  897. prop: '-ms-grid-column',
  898. value: column.start
  899. }); // insert rule
  900. parent.after(node);
  901. });
  902. return undefined;
  903. }
  904. module.exports = {
  905. parse: parse,
  906. translate: translate,
  907. parseTemplate: parseTemplate,
  908. parseGridAreas: parseGridAreas,
  909. warnMissedAreas: warnMissedAreas,
  910. insertAreas: insertAreas,
  911. insertDecl: insertDecl,
  912. prefixTrackProp: prefixTrackProp,
  913. prefixTrackValue: prefixTrackValue,
  914. getGridGap: getGridGap,
  915. warnGridGap: warnGridGap,
  916. warnTemplateSelectorNotFound: warnTemplateSelectorNotFound,
  917. warnIfGridRowColumnExists: warnIfGridRowColumnExists,
  918. inheritGridGap: inheritGridGap,
  919. autoplaceGridItems: autoplaceGridItems
  920. };