(str, tagName)
| 22 | // Return an array of objects, where the `conditional` prop contains the conditional string, |
| 23 | // and the `text` prop contains the contents between the start tag and the end tag. |
| 24 | function getLiquidConditionalsWithContent(str, tagName) { |
| 25 | if (!tagName) throw new Error(`Must provide a tag name!`) |
| 26 | if (typeof tagName !== 'string') throw new Error(`Must provide a single tag name as a string!`) |
| 27 | |
| 28 | const numberOfTags = (str.match(new RegExp(`{%-? ${tagName}`, 'g')) || []).length |
| 29 | if (!numberOfTags) return [] |
| 30 | |
| 31 | const endTagName = tagName === 'ifversion' || tagName === 'elsif' ? 'endif' : `end${tagName}` |
| 32 | |
| 33 | // Get the raw tokens, which includes versions, data tags, etc., |
| 34 | // Also this captures start tags, content, and end tags as _individual_ tokens, but we want to group them. |
| 35 | const tokens = tokenize(str).map((token) => { |
| 36 | return { |
| 37 | conditional: token.name, |
| 38 | text: token.getText(), |
| 39 | position: token.getPosition(), |
| 40 | } |
| 41 | }) |
| 42 | |
| 43 | // Parse the raw tokens and group them, so that start tags, content, and end tags are |
| 44 | // all considered to be part of the same block, and return that block. |
| 45 | const grouped = groupTokens(tokens, tagName, endTagName) |
| 46 | |
| 47 | // Run recursively so we can also capture nested conditionals. |
| 48 | const nestedConditionals = grouped.flatMap((group) => { |
| 49 | // Remove the start tag and the end tag so we are left with nested tags, if any. |
| 50 | const nested = group.text |
| 51 | .replace(group.conditional, '') |
| 52 | .split('') |
| 53 | .reverse() |
| 54 | .join('') |
| 55 | .replace(new RegExp(`{%-? ${endTagName} -?%}`), '') |
| 56 | .split('') |
| 57 | .reverse() |
| 58 | .join('') |
| 59 | |
| 60 | const nestedGroups = getLiquidConditionalsWithContent(nested, tagName) |
| 61 | |
| 62 | // Remove the start tag but NOT the end tag, so we are left with elsif tags and their endifs, if any. |
| 63 | const elsifs = group.text.replace(group.conditional, '') |
| 64 | |
| 65 | const elsifGroups = getLiquidConditionalsWithContent(elsifs, 'elsif') |
| 66 | |
| 67 | return [group].concat(nestedGroups, elsifGroups) |
| 68 | }) |
| 69 | |
| 70 | return nestedConditionals |
| 71 | } |
| 72 | |
| 73 | function groupTokens(tokens, tagName, endTagName, newArray = []) { |
| 74 | const startIndex = tokens.findIndex((token) => token.conditional === tagName) |
no test coverage detected