wishthis/node_modules/autoprefixer/lib/hacks/grid-utils.js

1114 lines
28 KiB
JavaScript
Raw Normal View History

2023-08-17 09:47:40 +00:00
let parser = require('postcss-value-parser')
let list = require('postcss').list
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let uniq = require('../utils').uniq
let escapeRegexp = require('../utils').escapeRegexp
let splitSelector = require('../utils').splitSelector
2022-01-21 08:28:41 +00:00
function convert(value) {
2023-08-17 09:47:40 +00:00
if (
value &&
value.length === 2 &&
value[0] === 'span' &&
parseInt(value[1], 10) > 0
) {
return [false, parseInt(value[1], 10)]
2022-01-21 08:28:41 +00:00
}
if (value && value.length === 1 && parseInt(value[0], 10) > 0) {
2023-08-17 09:47:40 +00:00
return [parseInt(value[0], 10), false]
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return [false, false]
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.translate = translate
2022-01-21 08:28:41 +00:00
function translate(values, startIndex, endIndex) {
2023-08-17 09:47:40 +00:00
let startValue = values[startIndex]
let endValue = values[endIndex]
2022-01-21 08:28:41 +00:00
if (!startValue) {
2023-08-17 09:47:40 +00:00
return [false, false]
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
let [start, spanStart] = convert(startValue)
let [end, spanEnd] = convert(endValue)
2022-01-21 08:28:41 +00:00
if (start && !endValue) {
2023-08-17 09:47:40 +00:00
return [start, false]
2022-01-21 08:28:41 +00:00
}
if (spanStart && end) {
2023-08-17 09:47:40 +00:00
return [end - spanStart, spanStart]
2022-01-21 08:28:41 +00:00
}
if (start && spanEnd) {
2023-08-17 09:47:40 +00:00
return [start, spanEnd]
2022-01-21 08:28:41 +00:00
}
if (start && end) {
2023-08-17 09:47:40 +00:00
return [start, end - start]
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return [false, false]
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.parse = parse
2022-01-21 08:28:41 +00:00
function parse(decl) {
2023-08-17 09:47:40 +00:00
let node = parser(decl.value)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let values = []
let current = 0
values[current] = []
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
for (let i of node.nodes) {
2022-01-21 08:28:41 +00:00
if (i.type === 'div') {
2023-08-17 09:47:40 +00:00
current += 1
values[current] = []
2022-01-21 08:28:41 +00:00
} else if (i.type === 'word') {
2023-08-17 09:47:40 +00:00
values[current].push(i.value)
2022-01-21 08:28:41 +00:00
}
}
2023-08-17 09:47:40 +00:00
return values
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.insertDecl = insertDecl
2022-01-21 08:28:41 +00:00
function insertDecl(decl, prop, value) {
2023-08-17 09:47:40 +00:00
if (value && !decl.parent.some(i => i.prop === `-ms-${prop}`)) {
2022-01-21 08:28:41 +00:00
decl.cloneBefore({
2023-08-17 09:47:40 +00:00
prop: `-ms-${prop}`,
2022-01-21 08:28:41 +00:00
value: value.toString()
2023-08-17 09:47:40 +00:00
})
2022-01-21 08:28:41 +00:00
}
}
2023-08-17 09:47:40 +00:00
// Track transforms
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
exports.prefixTrackProp = prefixTrackProp
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
function prefixTrackProp({ prefix, prop }) {
return prefix + prop.replace('template-', '')
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
function transformRepeat({ nodes }, { gap }) {
let { count, size } = nodes.reduce(
(result, node) => {
if (node.type === 'div' && node.value === ',') {
result.key = 'size'
} else {
result[result.key].push(parser.stringify(node))
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return result
},
{
count: [],
key: 'count',
size: []
}
)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// insert gap values
if (gap) {
size = size.filter(i => i.trim())
let val = []
for (let i = 1; i <= count; i++) {
size.forEach((item, index) => {
if (index > 0 || i > 1) {
val.push(gap)
}
val.push(item)
})
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
return val.join(' ')
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return `(${size.join('')})[${count.join('')}]`
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.prefixTrackValue = prefixTrackValue
function prefixTrackValue({ gap, value }) {
let result = parser(value).nodes.reduce((nodes, node) => {
2022-01-21 08:28:41 +00:00
if (node.type === 'function' && node.value === 'repeat') {
return nodes.concat({
type: 'word',
2023-08-17 09:47:40 +00:00
value: transformRepeat(node, { gap })
})
2022-01-21 08:28:41 +00:00
}
if (gap && node.type === 'space') {
2023-08-17 09:47:40 +00:00
return nodes.concat(
{
type: 'space',
value: ' '
},
{
type: 'word',
value: gap
},
node
)
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return nodes.concat(node)
}, [])
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
return parser.stringify(result)
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// Parse grid-template-areas
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let DOTS = /^\.+$/
2022-01-21 08:28:41 +00:00
function track(start, end) {
2023-08-17 09:47:40 +00:00
return { end, span: end - start, start }
2022-01-21 08:28:41 +00:00
}
function getColumns(line) {
2023-08-17 09:47:40 +00:00
return line.trim().split(/\s+/g)
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.parseGridAreas = parseGridAreas
function parseGridAreas({ gap, rows }) {
return rows.reduce((areas, line, rowIndex) => {
if (gap.row) rowIndex *= 2
if (line.trim() === '') return areas
getColumns(line).forEach((area, columnIndex) => {
if (DOTS.test(area)) return
if (gap.column) columnIndex *= 2
2022-01-21 08:28:41 +00:00
if (typeof areas[area] === 'undefined') {
areas[area] = {
column: track(columnIndex + 1, columnIndex + 2),
row: track(rowIndex + 1, rowIndex + 2)
2023-08-17 09:47:40 +00:00
}
2022-01-21 08:28:41 +00:00
} else {
2023-08-17 09:47:40 +00:00
let { column, row } = areas[area]
column.start = Math.min(column.start, columnIndex + 1)
column.end = Math.max(column.end, columnIndex + 2)
column.span = column.end - column.start
row.start = Math.min(row.start, rowIndex + 1)
row.end = Math.max(row.end, rowIndex + 2)
row.span = row.end - row.start
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
})
return areas
}, {})
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// Parse grid-template
2022-01-21 08:28:41 +00:00
function testTrack(node) {
2023-08-17 09:47:40 +00:00
return node.type === 'word' && /^\[.+]$/.test(node.value)
2022-01-21 08:28:41 +00:00
}
function verifyRowSize(result) {
if (result.areas.length > result.rows.length) {
2023-08-17 09:47:40 +00:00
result.rows.push('auto')
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return result
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.parseTemplate = parseTemplate
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
function parseTemplate({ decl, gap }) {
let gridTemplate = parser(decl.value).nodes.reduce(
(result, node) => {
let { type, value } = node
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
if (testTrack(node) || type === 'space') return result
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// area
if (type === 'string') {
result = verifyRowSize(result)
result.areas.push(value)
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// values and function
if (type === 'word' || type === 'function') {
result[result.key].push(parser.stringify(node))
}
// divider(/)
if (type === 'div' && value === '/') {
result.key = 'columns'
result = verifyRowSize(result)
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
return result
},
{
areas: [],
columns: [],
key: 'rows',
rows: []
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
)
2022-01-21 08:28:41 +00:00
return {
areas: parseGridAreas({
2023-08-17 09:47:40 +00:00
gap,
rows: gridTemplate.areas
2022-01-21 08:28:41 +00:00
}),
columns: prefixTrackValue({
2023-08-17 09:47:40 +00:00
gap: gap.column,
value: gridTemplate.columns.join(' ')
2022-01-21 08:28:41 +00:00
}),
rows: prefixTrackValue({
2023-08-17 09:47:40 +00:00
gap: gap.row,
value: gridTemplate.rows.join(' ')
2022-01-21 08:28:41 +00:00
})
2023-08-17 09:47:40 +00:00
}
}
// Insert parsed grid areas
2022-01-21 08:28:41 +00:00
/**
* Get an array of -ms- prefixed props and values
* @param {Object} [area] area object with column and row data
* @param {Boolean} [addRowSpan] should we add grid-column-row value?
* @param {Boolean} [addColumnSpan] should we add grid-column-span value?
* @return {Array<Object>}
*/
2023-08-17 09:47:40 +00:00
function getMSDecls(area, addRowSpan = false, addColumnSpan = false) {
let result = [
{
prop: '-ms-grid-row',
value: String(area.row.start)
}
]
if (area.row.span > 1 || addRowSpan) {
result.push({
prop: '-ms-grid-row-span',
value: String(area.row.span)
})
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
result.push({
2022-01-21 08:28:41 +00:00
prop: '-ms-grid-column',
value: String(area.column.start)
2023-08-17 09:47:40 +00:00
})
if (area.column.span > 1 || addColumnSpan) {
result.push({
prop: '-ms-grid-column-span',
value: String(area.column.span)
})
}
return result
2022-01-21 08:28:41 +00:00
}
function getParentMedia(parent) {
if (parent.type === 'atrule' && parent.name === 'media') {
2023-08-17 09:47:40 +00:00
return parent
2022-01-21 08:28:41 +00:00
}
if (!parent.parent) {
2023-08-17 09:47:40 +00:00
return false
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return getParentMedia(parent.parent)
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* change selectors for rules with duplicate grid-areas.
* @param {Array<Rule>} rules
* @param {Array<String>} templateSelectors
* @return {Array<Rule>} rules with changed selectors
*/
function changeDuplicateAreaSelectors(ruleSelectors, templateSelectors) {
2023-08-17 09:47:40 +00:00
ruleSelectors = ruleSelectors.map(selector => {
let selectorBySpace = list.space(selector)
let selectorByComma = list.comma(selector)
2022-01-21 08:28:41 +00:00
if (selectorBySpace.length > selectorByComma.length) {
2023-08-17 09:47:40 +00:00
selector = selectorBySpace.slice(-1).join('')
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return selector
})
return ruleSelectors.map(ruleSelector => {
let newSelector = templateSelectors.map((tplSelector, index) => {
let space = index === 0 ? '' : ' '
return `${space}${tplSelector} > ${ruleSelector}`
})
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
return newSelector
})
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* check if selector of rules are equal
* @param {Rule} ruleA
* @param {Rule} ruleB
* @return {Boolean}
*/
function selectorsEqual(ruleA, ruleB) {
2023-08-17 09:47:40 +00:00
return ruleA.selectors.some(sel => {
return ruleB.selectors.includes(sel)
})
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* Parse data from all grid-template(-areas) declarations
* @param {Root} css css root
* @return {Object} parsed data
*/
function parseGridTemplatesData(css) {
2023-08-17 09:47:40 +00:00
let parsed = []
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// we walk through every grid-template(-areas) declaration and store
// data with the same area names inside the item
css.walkDecls(/grid-template(-areas)?$/, d => {
let rule = d.parent
let media = getParentMedia(rule)
let gap = getGridGap(d)
let inheritedGap = inheritGridGap(d, gap)
let { areas } = parseTemplate({ decl: d, gap: inheritedGap || gap })
let areaNames = Object.keys(areas)
// skip node if it doesn't have areas
2022-01-21 08:28:41 +00:00
if (areaNames.length === 0) {
2023-08-17 09:47:40 +00:00
return true
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// check parsed array for item that include the same area names
// return index of that item
let index = parsed.reduce((acc, { allAreas }, idx) => {
let hasAreas = allAreas && areaNames.some(area => allAreas.includes(area))
return hasAreas ? idx : acc
}, null)
2022-01-21 08:28:41 +00:00
if (index !== null) {
// index is found, add the grid-template data to that item
2023-08-17 09:47:40 +00:00
let { allAreas, rules } = parsed[index]
// check if rule has no duplicate area names
let hasNoDuplicates = rules.some(r => {
return r.hasDuplicates === false && selectorsEqual(r, rule)
})
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let duplicatesFound = false
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// check need to gather all duplicate area names
let duplicateAreaNames = rules.reduce((acc, r) => {
2022-01-21 08:28:41 +00:00
if (!r.params && selectorsEqual(r, rule)) {
2023-08-17 09:47:40 +00:00
duplicatesFound = true
return r.duplicateAreaNames
2022-01-21 08:28:41 +00:00
}
if (!duplicatesFound) {
2023-08-17 09:47:40 +00:00
areaNames.forEach(name => {
2022-01-21 08:28:41 +00:00
if (r.areas[name]) {
2023-08-17 09:47:40 +00:00
acc.push(name)
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
})
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return uniq(acc)
}, [])
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// update grid-row/column-span values for areas with duplicate
2022-01-21 08:28:41 +00:00
// area names. @see #1084 and #1146
2023-08-17 09:47:40 +00:00
rules.forEach(r => {
areaNames.forEach(name => {
let area = r.areas[name]
2022-01-21 08:28:41 +00:00
if (area && area.row.span !== areas[name].row.span) {
2023-08-17 09:47:40 +00:00
areas[name].row.updateSpan = true
2022-01-21 08:28:41 +00:00
}
if (area && area.column.span !== areas[name].column.span) {
2023-08-17 09:47:40 +00:00
areas[name].column.updateSpan = true
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
})
})
parsed[index].allAreas = uniq([...allAreas, ...areaNames])
2022-01-21 08:28:41 +00:00
parsed[index].rules.push({
2023-08-17 09:47:40 +00:00
areas,
duplicateAreaNames,
2022-01-21 08:28:41 +00:00
hasDuplicates: !hasNoDuplicates,
node: rule,
2023-08-17 09:47:40 +00:00
params: media.params,
selectors: rule.selectors
})
2022-01-21 08:28:41 +00:00
} else {
// index is NOT found, push the new item to the parsed array
parsed.push({
allAreas: areaNames,
areasCount: 0,
2023-08-17 09:47:40 +00:00
rules: [
{
areas,
duplicateAreaNames: [],
duplicateRules: [],
hasDuplicates: false,
node: rule,
params: media.params,
selectors: rule.selectors
}
]
})
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return undefined
})
return parsed
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* insert prefixed grid-area declarations
* @param {Root} css css root
* @param {Function} isDisabled check if the rule is disabled
* @return {void}
*/
2023-08-17 09:47:40 +00:00
exports.insertAreas = insertAreas
2022-01-21 08:28:41 +00:00
function insertAreas(css, isDisabled) {
// parse grid-template declarations
2023-08-17 09:47:40 +00:00
let gridTemplatesData = parseGridTemplatesData(css)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// return undefined if no declarations found
2022-01-21 08:28:41 +00:00
if (gridTemplatesData.length === 0) {
2023-08-17 09:47:40 +00:00
return undefined
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// we need to store the rules that we will insert later
let rulesToInsert = {}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
css.walkDecls('grid-area', gridArea => {
let gridAreaRule = gridArea.parent
let hasPrefixedRow = gridAreaRule.first.prop === '-ms-grid-row'
let gridAreaMedia = getParentMedia(gridAreaRule)
2022-01-21 08:28:41 +00:00
if (isDisabled(gridArea)) {
2023-08-17 09:47:40 +00:00
return undefined
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
let gridAreaRuleIndex = css.index(gridAreaMedia || gridAreaRule)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let value = gridArea.value
// found the data that matches grid-area identifier
let data = gridTemplatesData.filter(d => d.allAreas.includes(value))[0]
2022-01-21 08:28:41 +00:00
if (!data) {
2023-08-17 09:47:40 +00:00
return true
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
let lastArea = data.allAreas[data.allAreas.length - 1]
let selectorBySpace = list.space(gridAreaRule.selector)
let selectorByComma = list.comma(gridAreaRule.selector)
let selectorIsComplex =
selectorBySpace.length > 1 &&
selectorBySpace.length > selectorByComma.length
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// prevent doubling of prefixes
2022-01-21 08:28:41 +00:00
if (hasPrefixedRow) {
2023-08-17 09:47:40 +00:00
return false
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// create the empty object with the key as the last area name
// e.g if we have templates with "a b c" values, "c" will be the last area
2022-01-21 08:28:41 +00:00
if (!rulesToInsert[lastArea]) {
2023-08-17 09:47:40 +00:00
rulesToInsert[lastArea] = {}
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
let lastRuleIsSet = false
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// walk through every grid-template rule data
for (let rule of data.rules) {
let area = rule.areas[value]
let hasDuplicateName = rule.duplicateAreaNames.includes(value)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// if we can't find the area name, update lastRule and continue
2022-01-21 08:28:41 +00:00
if (!area) {
2023-08-17 09:47:40 +00:00
let lastRule = rulesToInsert[lastArea].lastRule
let lastRuleIndex
if (lastRule) {
lastRuleIndex = css.index(lastRule)
} else {
/* c8 ignore next 2 */
lastRuleIndex = -1
}
2022-01-21 08:28:41 +00:00
if (gridAreaRuleIndex > lastRuleIndex) {
2023-08-17 09:47:40 +00:00
rulesToInsert[lastArea].lastRule = gridAreaMedia || gridAreaRule
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
continue
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// for grid-templates inside media rule we need to create empty
2022-01-21 08:28:41 +00:00
// array to push prefixed grid-area rules later
if (rule.params && !rulesToInsert[lastArea][rule.params]) {
2023-08-17 09:47:40 +00:00
rulesToInsert[lastArea][rule.params] = []
2022-01-21 08:28:41 +00:00
}
if ((!rule.hasDuplicates || !hasDuplicateName) && !rule.params) {
// grid-template has no duplicates and not inside media rule
2023-08-17 09:47:40 +00:00
getMSDecls(area, false, false)
.reverse()
.forEach(i =>
gridAreaRule.prepend(
Object.assign(i, {
raws: {
between: gridArea.raws.between
}
})
)
)
rulesToInsert[lastArea].lastRule = gridAreaRule
lastRuleIsSet = true
} else if (rule.hasDuplicates && !rule.params && !selectorIsComplex) {
// grid-template has duplicates and not inside media rule
let cloned = gridAreaRule.clone()
cloned.removeAll()
getMSDecls(area, area.row.updateSpan, area.column.updateSpan)
.reverse()
.forEach(i =>
cloned.prepend(
Object.assign(i, {
raws: {
between: gridArea.raws.between
}
})
)
)
cloned.selectors = changeDuplicateAreaSelectors(
cloned.selectors,
rule.selectors
)
if (rulesToInsert[lastArea].lastRule) {
rulesToInsert[lastArea].lastRule.after(cloned)
}
rulesToInsert[lastArea].lastRule = cloned
lastRuleIsSet = true
} else if (
rule.hasDuplicates &&
!rule.params &&
selectorIsComplex &&
gridAreaRule.selector.includes(rule.selectors[0])
) {
2022-01-21 08:28:41 +00:00
// grid-template has duplicates and not inside media rule
// and the selector is complex
2023-08-17 09:47:40 +00:00
gridAreaRule.walkDecls(/-ms-grid-(row|column)/, d => d.remove())
getMSDecls(area, area.row.updateSpan, area.column.updateSpan)
.reverse()
.forEach(i =>
gridAreaRule.prepend(
Object.assign(i, {
raws: {
between: gridArea.raws.between
}
})
)
)
2022-01-21 08:28:41 +00:00
} else if (rule.params) {
2023-08-17 09:47:40 +00:00
// grid-template is inside media rule
// if we're inside media rule, we need to store prefixed rules
// inside rulesToInsert object to be able to preserve the order of media
// rules and merge them easily
let cloned = gridAreaRule.clone()
cloned.removeAll()
getMSDecls(area, area.row.updateSpan, area.column.updateSpan)
.reverse()
.forEach(i =>
cloned.prepend(
Object.assign(i, {
raws: {
between: gridArea.raws.between
}
})
)
)
if (rule.hasDuplicates && hasDuplicateName) {
cloned.selectors = changeDuplicateAreaSelectors(
cloned.selectors,
rule.selectors
)
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
cloned.raws = rule.node.raws
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
if (css.index(rule.node.parent) > gridAreaRuleIndex) {
// append the prefixed rules right inside media rule
// with grid-template
rule.node.parent.append(cloned)
} else {
// store the rule to insert later
rulesToInsert[lastArea][rule.params].push(cloned)
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// set new rule as last rule ONLY if we didn't set lastRule for
// this grid-area before
if (!lastRuleIsSet) {
rulesToInsert[lastArea].lastRule = gridAreaMedia || gridAreaRule
}
2022-01-21 08:28:41 +00:00
}
}
2023-08-17 09:47:40 +00:00
return undefined
})
// append stored rules inside the media rules
Object.keys(rulesToInsert).forEach(area => {
let data = rulesToInsert[area]
let lastRule = data.lastRule
Object.keys(data)
.reverse()
.filter(p => p !== 'lastRule')
.forEach(params => {
if (data[params].length > 0 && lastRule) {
lastRule.after({ name: 'media', params })
lastRule.next().append(data[params])
}
})
})
return undefined
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* Warn user if grid area identifiers are not found
* @param {Object} areas
* @param {Declaration} decl
* @param {Result} result
* @return {void}
*/
2023-08-17 09:47:40 +00:00
exports.warnMissedAreas = warnMissedAreas
2022-01-21 08:28:41 +00:00
function warnMissedAreas(areas, decl, result) {
2023-08-17 09:47:40 +00:00
let missed = Object.keys(areas)
decl.root().walkDecls('grid-area', gridArea => {
missed = missed.filter(e => e !== gridArea.value)
})
2022-01-21 08:28:41 +00:00
if (missed.length > 0) {
2023-08-17 09:47:40 +00:00
decl.warn(result, 'Can not find grid areas: ' + missed.join(', '))
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return undefined
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* compare selectors with grid-area rule and grid-template rule
* show warning if grid-template selector is not found
* (this function used for grid-area rule)
* @param {Declaration} decl
* @param {Result} result
* @return {void}
*/
2023-08-17 09:47:40 +00:00
exports.warnTemplateSelectorNotFound = warnTemplateSelectorNotFound
2022-01-21 08:28:41 +00:00
function warnTemplateSelectorNotFound(decl, result) {
2023-08-17 09:47:40 +00:00
let rule = decl.parent
let root = decl.root()
let duplicatesFound = false
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// slice selector array. Remove the last part (for comparison)
let slicedSelectorArr = list
.space(rule.selector)
.filter(str => str !== '>')
.slice(0, -1)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// we need to compare only if selector is complex.
// e.g '.grid-cell' is simple, but '.parent > .grid-cell' is complex
2022-01-21 08:28:41 +00:00
if (slicedSelectorArr.length > 0) {
2023-08-17 09:47:40 +00:00
let gridTemplateFound = false
let foundAreaSelector = null
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
root.walkDecls(/grid-template(-areas)?$/, d => {
let parent = d.parent
let templateSelectors = parent.selectors
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let { areas } = parseTemplate({ decl: d, gap: getGridGap(d) })
let hasArea = areas[decl.value]
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// find the the matching selectors
for (let tplSelector of templateSelectors) {
2022-01-21 08:28:41 +00:00
if (gridTemplateFound) {
2023-08-17 09:47:40 +00:00
break
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
let tplSelectorArr = list.space(tplSelector).filter(str => str !== '>')
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
gridTemplateFound = tplSelectorArr.every(
(item, idx) => item === slicedSelectorArr[idx]
)
2022-01-21 08:28:41 +00:00
}
if (gridTemplateFound || !hasArea) {
2023-08-17 09:47:40 +00:00
return true
2022-01-21 08:28:41 +00:00
}
if (!foundAreaSelector) {
2023-08-17 09:47:40 +00:00
foundAreaSelector = parent.selector
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// if we found the duplicate area with different selector
2022-01-21 08:28:41 +00:00
if (foundAreaSelector && foundAreaSelector !== parent.selector) {
2023-08-17 09:47:40 +00:00
duplicatesFound = true
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return undefined
})
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// warn user if we didn't find template
2022-01-21 08:28:41 +00:00
if (!gridTemplateFound && duplicatesFound) {
2023-08-17 09:47:40 +00:00
decl.warn(
result,
'Autoprefixer cannot find a grid-template ' +
`containing the duplicate grid-area "${decl.value}" ` +
`with full selector matching: ${slicedSelectorArr.join(' ')}`
)
2022-01-21 08:28:41 +00:00
}
}
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* warn user if both grid-area and grid-(row|column)
* declarations are present in the same rule
* @param {Declaration} decl
* @param {Result} result
* @return {void}
*/
2023-08-17 09:47:40 +00:00
exports.warnIfGridRowColumnExists = warnIfGridRowColumnExists
2022-01-21 08:28:41 +00:00
function warnIfGridRowColumnExists(decl, result) {
2023-08-17 09:47:40 +00:00
let rule = decl.parent
let decls = []
rule.walkDecls(/^grid-(row|column)/, d => {
if (
!d.prop.endsWith('-end') &&
!d.value.startsWith('span') &&
!d.prop.endsWith('-gap')
) {
decls.push(d)
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
})
2022-01-21 08:28:41 +00:00
if (decls.length > 0) {
2023-08-17 09:47:40 +00:00
decls.forEach(d => {
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`
)
})
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return undefined
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// Gap utils
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
exports.getGridGap = getGridGap
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
function getGridGap(decl) {
let gap = {}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// try to find gap
let testGap = /^(grid-)?((row|column)-)?gap$/
decl.parent.walkDecls(testGap, ({ prop, value }) => {
2022-01-21 08:28:41 +00:00
if (/^(grid-)?gap$/.test(prop)) {
2023-08-17 09:47:40 +00:00
let [row, , column] = parser(value).nodes
gap.row = row && parser.stringify(row)
gap.column = column ? parser.stringify(column) : gap.row
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
if (/^(grid-)?row-gap$/.test(prop)) gap.row = value
if (/^(grid-)?column-gap$/.test(prop)) gap.column = value
})
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
return gap
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* parse media parameters (for example 'min-width: 500px')
* @param {String} params parameter to parse
* @return {}
*/
function parseMediaParams(params) {
if (!params) {
2023-08-17 09:47:40 +00:00
return []
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
let parsed = parser(params)
let prop
let value
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
parsed.walk(node => {
2022-01-21 08:28:41 +00:00
if (node.type === 'word' && /min|max/g.test(node.value)) {
2023-08-17 09:47:40 +00:00
prop = node.value
2022-01-21 08:28:41 +00:00
} else if (node.value.includes('px')) {
2023-08-17 09:47:40 +00:00
value = parseInt(node.value.replace(/\D/g, ''))
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
})
return [prop, value]
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* Compare the selectors and decide if we
* need to inherit gap from compared selector or not.
* @type {String} selA
* @type {String} selB
* @return {Boolean}
*/
function shouldInheritGap(selA, selB) {
2023-08-17 09:47:40 +00:00
let result
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// get arrays of selector split in 3-deep array
let splitSelectorArrA = splitSelector(selA)
let splitSelectorArrB = splitSelector(selB)
2022-01-21 08:28:41 +00:00
if (splitSelectorArrA[0].length < splitSelectorArrB[0].length) {
// abort if selectorA has lower descendant specificity then selectorB
// (e.g '.grid' and '.hello .world .grid')
2023-08-17 09:47:40 +00:00
return false
2022-01-21 08:28:41 +00:00
} else if (splitSelectorArrA[0].length > splitSelectorArrB[0].length) {
// if selectorA has higher descendant specificity then selectorB
// (e.g '.foo .bar .grid' and '.grid')
2023-08-17 09:47:40 +00:00
let idx = splitSelectorArrA[0].reduce((res, [item], index) => {
let firstSelectorPart = splitSelectorArrB[0][0][0]
2022-01-21 08:28:41 +00:00
if (item === firstSelectorPart) {
2023-08-17 09:47:40 +00:00
return index
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return false
}, false)
2022-01-21 08:28:41 +00:00
if (idx) {
2023-08-17 09:47:40 +00:00
result = splitSelectorArrB[0].every((arr, index) => {
return arr.every(
(part, innerIndex) =>
// because selectorA has more space elements, we need to slice
2022-01-21 08:28:41 +00:00
// selectorA array by 'idx' number to compare them
splitSelectorArrA[0].slice(idx)[index][innerIndex] === part
2023-08-17 09:47:40 +00:00
)
})
2022-01-21 08:28:41 +00:00
}
} else {
// if selectorA has the same descendant specificity as selectorB
// this condition covers cases such as: '.grid.foo.bar' and '.grid'
2023-08-17 09:47:40 +00:00
result = splitSelectorArrB.some(byCommaArr => {
return byCommaArr.every((bySpaceArr, index) => {
return bySpaceArr.every(
(part, innerIndex) => splitSelectorArrA[0][index][innerIndex] === part
)
})
})
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return result
2022-01-21 08:28:41 +00:00
}
/**
* inherit grid gap values from the closest rule above
* with the same selector
* @param {Declaration} decl
* @param {Object} gap gap values
* @return {Object | Boolean} return gap values or false (if not found)
*/
2023-08-17 09:47:40 +00:00
exports.inheritGridGap = inheritGridGap
2022-01-21 08:28:41 +00:00
function inheritGridGap(decl, gap) {
2023-08-17 09:47:40 +00:00
let rule = decl.parent
let mediaRule = getParentMedia(rule)
let root = rule.root()
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// get an array of selector split in 3-deep array
let splitSelectorArr = splitSelector(rule.selector)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// abort if the rule already has gaps
2022-01-21 08:28:41 +00:00
if (Object.keys(gap).length > 0) {
2023-08-17 09:47:40 +00:00
return false
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// e.g ['min-width']
let [prop] = parseMediaParams(mediaRule.params)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let lastBySpace = splitSelectorArr[0]
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// get escaped value from the selector
2022-01-21 08:28:41 +00:00
// if we have '.grid-2.foo.bar' selector, will be '\.grid\-2'
2023-08-17 09:47:40 +00:00
let escaped = escapeRegexp(lastBySpace[lastBySpace.length - 1][0])
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let regexp = new RegExp(`(${escaped}$)|(${escaped}[,.])`)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// find the closest rule with the same selector
let closestRuleGap
root.walkRules(regexp, r => {
let gridGap
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// abort if are checking the same rule
2022-01-21 08:28:41 +00:00
if (rule.toString() === r.toString()) {
2023-08-17 09:47:40 +00:00
return false
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// find grid-gap values
r.walkDecls('grid-gap', d => (gridGap = getGridGap(d)))
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// skip rule without gaps
2022-01-21 08:28:41 +00:00
if (!gridGap || Object.keys(gridGap).length === 0) {
2023-08-17 09:47:40 +00:00
return true
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// skip rules that should not be inherited from
2022-01-21 08:28:41 +00:00
if (!shouldInheritGap(rule.selector, r.selector)) {
2023-08-17 09:47:40 +00:00
return true
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
let media = getParentMedia(r)
2022-01-21 08:28:41 +00:00
if (media) {
// if we are inside media, we need to check that media props match
// e.g ('min-width' === 'min-width')
2023-08-17 09:47:40 +00:00
let propToCompare = parseMediaParams(media.params)[0]
2022-01-21 08:28:41 +00:00
if (propToCompare === prop) {
2023-08-17 09:47:40 +00:00
closestRuleGap = gridGap
return true
2022-01-21 08:28:41 +00:00
}
} else {
2023-08-17 09:47:40 +00:00
closestRuleGap = gridGap
return true
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return undefined
})
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// if we find the closest gap object
2022-01-21 08:28:41 +00:00
if (closestRuleGap && Object.keys(closestRuleGap).length > 0) {
2023-08-17 09:47:40 +00:00
return closestRuleGap
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return false
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.warnGridGap = warnGridGap
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
function warnGridGap({ decl, gap, hasColumns, result }) {
let hasBothGaps = gap.row && gap.column
if (!hasColumns && (hasBothGaps || (gap.column && !gap.row))) {
delete gap.column
decl.warn(
result,
'Can not implement grid-gap without grid-template-columns'
)
2022-01-21 08:28:41 +00:00
}
}
2023-08-17 09:47:40 +00:00
2022-01-21 08:28:41 +00:00
/**
* normalize the grid-template-rows/columns values
* @param {String} str grid-template-rows/columns value
* @return {Array} normalized array with values
* @example
* let normalized = normalizeRowColumn('1fr repeat(2, 20px 50px) 1fr')
* normalized // <= ['1fr', '20px', '50px', '20px', '50px', '1fr']
*/
function normalizeRowColumn(str) {
2023-08-17 09:47:40 +00:00
let normalized = parser(str).nodes.reduce((result, node) => {
2022-01-21 08:28:41 +00:00
if (node.type === 'function' && node.value === 'repeat') {
2023-08-17 09:47:40 +00:00
let key = 'count'
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let [count, value] = node.nodes.reduce(
(acc, n) => {
if (n.type === 'word' && key === 'count') {
acc[0] = Math.abs(parseInt(n.value))
return acc
}
if (n.type === 'div' && n.value === ',') {
key = 'value'
return acc
}
if (key === 'value') {
acc[1] += parser.stringify(n)
}
return acc
},
[0, '']
)
2022-01-21 08:28:41 +00:00
if (count) {
2023-08-17 09:47:40 +00:00
for (let i = 0; i < count; i++) {
result.push(value)
2022-01-21 08:28:41 +00:00
}
}
2023-08-17 09:47:40 +00:00
return result
2022-01-21 08:28:41 +00:00
}
if (node.type === 'space') {
2023-08-17 09:47:40 +00:00
return result
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
return result.concat(parser.stringify(node))
}, [])
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
return normalized
2022-01-21 08:28:41 +00:00
}
2023-08-17 09:47:40 +00:00
exports.autoplaceGridItems = autoplaceGridItems
2022-01-21 08:28:41 +00:00
/**
* Autoplace grid items
* @param {Declaration} decl
* @param {Result} result
* @param {Object} gap gap values
* @param {String} autoflowValue grid-auto-flow value
* @return {void}
* @see https://github.com/postcss/autoprefixer/issues/1148
*/
2023-08-17 09:47:40 +00:00
function autoplaceGridItems(decl, result, gap, autoflowValue = 'row') {
let { parent } = decl
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
let rowDecl = parent.nodes.find(i => i.prop === 'grid-template-rows')
let rows = normalizeRowColumn(rowDecl.value)
let columns = normalizeRowColumn(decl.value)
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// Build array of area names with dummy values. If we have 3 columns and
2022-01-21 08:28:41 +00:00
// 2 rows, filledRows will be equal to ['1 2 3', '4 5 6']
2023-08-17 09:47:40 +00:00
let filledRows = rows.map((_, rowIndex) => {
return Array.from(
{ length: columns.length },
(v, k) => k + rowIndex * columns.length + 1
).join(' ')
})
let areas = parseGridAreas({ gap, rows: filledRows })
let keys = Object.keys(areas)
let items = keys.map(i => areas[i])
// Change the order of cells if grid-auto-flow value is 'column'
2022-01-21 08:28:41 +00:00
if (autoflowValue.includes('column')) {
2023-08-17 09:47:40 +00:00
items = items.sort((a, b) => a.column.start - b.column.start)
}
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// Insert new rules
items.reverse().forEach((item, index) => {
let { column, row } = item
let nodeSelector = parent.selectors
.map(sel => sel + ` > *:nth-child(${keys.length - index})`)
.join(', ')
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// create new rule
let node = parent.clone().removeAll()
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// change rule selector
node.selector = nodeSelector
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// insert prefixed row/column values
node.append({ prop: '-ms-grid-row', value: row.start })
node.append({ prop: '-ms-grid-column', value: column.start })
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
// insert rule
parent.after(node)
})
2022-01-21 08:28:41 +00:00
2023-08-17 09:47:40 +00:00
return undefined
}