tailwind-ctp-intellisense/packages/tailwindcss-language-service/src/util/stringify.ts

83 lines
2.1 KiB
TypeScript
Raw Normal View History

2020-04-12 14:48:38 +00:00
import removeMeta from './removeMeta'
const dlv = require('dlv')
import escapeClassName from 'css.escape'
import { ensureArray } from './array'
import { remToPx } from './remToPx'
2020-04-12 14:48:38 +00:00
2020-04-11 21:20:45 +00:00
export function stringifyConfigValue(x: any): string {
if (typeof x === 'string') return x
if (typeof x === 'number') return x.toString()
if (Array.isArray(x)) {
return x
2020-04-12 14:48:38 +00:00
.filter((y) => typeof y === 'string')
2020-04-11 21:20:45 +00:00
.filter(Boolean)
.join(', ')
}
2020-04-12 16:53:22 +00:00
return null
2020-04-11 21:20:45 +00:00
}
2020-04-12 14:48:38 +00:00
export function stringifyCss(
className: string,
obj: any,
{
tabSize = 2,
showPixelEquivalents = false,
rootFontSize = 16,
}: Partial<{
tabSize: number
showPixelEquivalents: boolean
rootFontSize: number
}> = {}
): string {
if (obj.__rule !== true && !Array.isArray(obj)) return null
if (Array.isArray(obj)) {
const rules = obj
.map((x) =>
stringifyCss(className, x, {
tabSize,
showPixelEquivalents,
rootFontSize,
})
)
.filter(Boolean)
if (rules.length === 0) return null
return rules.join('\n\n')
}
let css = ``
const indent = ' '.repeat(tabSize)
const context = dlv(obj, '__context', [])
const props = Object.keys(removeMeta(obj))
if (props.length === 0) return null
for (let i = 0; i < context.length; i++) {
css += `${indent.repeat(i)}${context[i]} {\n`
2020-04-12 14:48:38 +00:00
}
const indentStr = indent.repeat(context.length)
const decls = props.reduce((acc, curr, i) => {
const propStr = ensureArray(obj[curr])
.map((val) => {
const px = showPixelEquivalents ? remToPx(val, rootFontSize) : undefined
return `${indentStr + indent}${curr}: ${val}${px ? `/* ${px} */` : ''};`
})
.join('\n')
return `${acc}${i === 0 ? '' : '\n'}${propStr}`
2020-04-12 14:48:38 +00:00
}, '')
2021-07-07 11:38:00 +00:00
css += `${indentStr}${augmentClassName(className, obj)} {\n${decls}\n${indentStr}}`
for (let i = context.length - 1; i >= 0; i--) {
css += `${indent.repeat(i)}\n}`
}
return css
}
function augmentClassName(className: string, obj: any): string {
const pseudo = obj.__pseudo.join('')
const scope = obj.__scope ? `${obj.__scope} ` : ''
return `${scope}.${escapeClassName(className)}${pseudo}`
2020-04-12 14:48:38 +00:00
}