@maizzle/framework 3.7.2 → 4.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/.github/workflows/nodejs.yml +28 -29
  2. package/bin/maizzle +3 -0
  3. package/package.json +91 -84
  4. package/src/commands/build.js +32 -0
  5. package/src/commands/serve.js +156 -0
  6. package/src/functions/plaintext.js +5 -0
  7. package/src/functions/render.js +5 -0
  8. package/src/generators/output/to-disk.js +120 -79
  9. package/src/generators/output/to-string.js +7 -8
  10. package/src/generators/plaintext.js +49 -52
  11. package/src/generators/postcss.js +29 -0
  12. package/src/generators/posthtml.js +66 -60
  13. package/src/generators/tailwindcss.js +116 -84
  14. package/src/index.js +14 -160
  15. package/src/transformers/{attribute-to-style.js → attributeToStyle.js} +0 -0
  16. package/src/transformers/baseUrl.js +69 -0
  17. package/src/transformers/{extra-attributes.js → extraAttributes.js} +0 -0
  18. package/src/transformers/filters/defaultFilters.js +126 -0
  19. package/src/transformers/filters/index.js +55 -0
  20. package/src/transformers/index.js +63 -57
  21. package/src/transformers/{inline.js → inlineCss.js} +1 -14
  22. package/src/transformers/minify.js +1 -1
  23. package/src/transformers/{posthtml-mso.js → posthtmlMso.js} +0 -0
  24. package/src/transformers/prettify.js +16 -9
  25. package/src/transformers/{prevent-widows.js → preventWidows.js} +0 -0
  26. package/src/transformers/{remove-attributes.js → removeAttributes.js} +1 -1
  27. package/src/transformers/{remove-inline-bgcolor.js → removeInlineBackgroundColor.js} +1 -1
  28. package/src/transformers/{remove-inline-sizes.js → removeInlineSizes.js} +0 -0
  29. package/src/transformers/removeInlinedSelectors.js +70 -0
  30. package/src/transformers/removeUnusedCss.js +40 -0
  31. package/src/transformers/{replace-strings.js → replaceStrings.js} +0 -0
  32. package/src/transformers/{safe-class-names.js → safeClassNames.js} +8 -2
  33. package/src/transformers/shorthandInlineCSS.js +19 -0
  34. package/src/transformers/sixHex.js +33 -0
  35. package/src/transformers/{url-params.js → urlParameters.js} +0 -0
  36. package/src/utils/helpers.js +2 -8
  37. package/test/expected/posthtml/component.html +13 -0
  38. package/test/expected/{inheritance.html → posthtml/extend-template.html} +2 -2
  39. package/test/expected/posthtml/fetch.html +5 -0
  40. package/test/expected/posthtml/layout.html +3 -0
  41. package/test/expected/transformers/atimport-in-style.html +15 -0
  42. package/test/expected/transformers/base-url.html +99 -0
  43. package/test/expected/transformers/filters.html +81 -0
  44. package/test/expected/transformers/preserve-transform-css.html +36 -0
  45. package/test/expected/useConfig.html +9 -0
  46. package/test/fixtures/basic.html +9 -9
  47. package/test/fixtures/posthtml/component.html +19 -0
  48. package/test/fixtures/{inheritance.html → posthtml/extend-template.html} +7 -7
  49. package/test/fixtures/posthtml/fetch.html +9 -0
  50. package/test/fixtures/posthtml/layout.html +11 -0
  51. package/test/fixtures/transformers/atimport-in-style.html +11 -0
  52. package/test/fixtures/transformers/base-url.html +101 -0
  53. package/test/fixtures/transformers/filters.html +87 -0
  54. package/test/fixtures/transformers/preserve-transform-css.html +25 -0
  55. package/test/fixtures/useConfig.html +9 -0
  56. package/test/stubs/components/component.html +5 -0
  57. package/test/stubs/data.json +14 -0
  58. package/test/stubs/layouts/basic.html +1 -0
  59. package/test/stubs/{layout.html → layouts/full.html} +0 -0
  60. package/test/stubs/{layout-basic.html → layouts/template.html} +5 -5
  61. package/test/stubs/post.css +6 -0
  62. package/test/stubs/tailwind/content-source.html +1 -0
  63. package/test/stubs/tailwind/tailwind.css +3 -0
  64. package/test/stubs/template.html +10 -10
  65. package/test/stubs/templates/1.html +1 -1
  66. package/test/stubs/templates/2.test +1 -0
  67. package/test/test-config.js +19 -19
  68. package/test/test-misc.js +8 -8
  69. package/test/test-postcss.js +8 -0
  70. package/test/test-posthtml.js +72 -0
  71. package/test/test-tailwindcss.js +117 -0
  72. package/test/test-todisk.js +142 -49
  73. package/test/test-tostring.js +148 -124
  74. package/test/test-transformers.js +510 -320
  75. package/xo.config.js +22 -19
  76. package/src/transformers/base-image-url.js +0 -9
  77. package/src/transformers/remove-unused-css.js +0 -20
  78. package/src/transformers/six-hex.js +0 -10
  79. package/src/transformers/transform.js +0 -24
  80. package/test/expected/transformers/base-image-url.html +0 -7
  81. package/test/fixtures/transformers/base-image-url.html +0 -7
  82. package/test/stubs/templates/2.html +0 -1
  83. package/test/stubs/templates/3.mzl +0 -1
  84. package/test/test-tailwind.js +0 -73
@@ -1,84 +1,116 @@
1
- const path = require('path')
2
- const fs = require('fs-extra')
3
- const postcss = require('postcss')
4
- const tailwindcss = require('tailwindcss')
5
- const postcssImport = require('postcss-import')
6
- const postcssNested = require('tailwindcss/nesting')
7
- const {requireUncached} = require('../utils/helpers')
8
- const mergeLonghand = require('postcss-merge-longhand')
9
- const {get, isObject, isEmpty, merge} = require('lodash')
10
-
11
- module.exports = {
12
- compile: async (css = '', html = '', tailwindConfig = {}, maizzleConfig = {}) => {
13
- tailwindConfig = (isObject(tailwindConfig) && !isEmpty(tailwindConfig)) ? tailwindConfig : get(maizzleConfig, 'build.tailwind.config', 'tailwind.config.js')
14
-
15
- // Compute the Tailwind config to use
16
- const userConfig = () => {
17
- // If a custom config object was passed, use that
18
- if (isObject(tailwindConfig) && !isEmpty(tailwindConfig)) {
19
- return tailwindConfig
20
- }
21
-
22
- /**
23
- * Try loading a fresh tailwind.config.js, with fallback to an empty object.
24
- * This will use the default Tailwind config (with rem units etc)
25
- */
26
- try {
27
- return requireUncached(path.resolve(process.cwd(), tailwindConfig))
28
- } catch {
29
- return {}
30
- }
31
- }
32
-
33
- // Merge user's Tailwind config on top of a 'base' config
34
- const config = merge({
35
- important: true,
36
- purge: {
37
- enabled: maizzleConfig.env !== 'local',
38
- content: [
39
- 'src/**/*.*',
40
- {raw: html}
41
- ],
42
- options: get(maizzleConfig, 'purgeCSS', {})
43
- },
44
- corePlugins: {
45
- animation: false,
46
- backgroundOpacity: false,
47
- borderOpacity: false,
48
- boxShadow: false,
49
- divideOpacity: false,
50
- placeholderOpacity: false,
51
- ringColor: false,
52
- ringWidth: false,
53
- ringOpacity: false,
54
- ringOffsetColor: false,
55
- textOpacity: false
56
- },
57
- plugins: []
58
- }, userConfig())
59
-
60
- // Merge user's Tailwind plugins with our default ones
61
- config.plugins.push(require('tailwindcss-box-shadow'))
62
-
63
- const userFilePath = get(maizzleConfig, 'build.tailwind.css', path.join(process.cwd(), 'src/css/tailwind.css'))
64
-
65
- css = await fs.pathExists(userFilePath).then(async exists => {
66
- if (exists) {
67
- const userFileCSS = await fs.readFile(path.resolve(userFilePath), 'utf8')
68
- return userFileCSS
69
- }
70
-
71
- return css
72
- })
73
-
74
- return postcss([
75
- postcssImport({path: userFilePath ? path.dirname(userFilePath) : []}),
76
- postcssNested(),
77
- tailwindcss(config),
78
- maizzleConfig.env === 'local' ? () => {} : mergeLonghand(),
79
- ...get(maizzleConfig, 'build.postcss.plugins', [])
80
- ])
81
- .process(css, {from: undefined})
82
- .then(result => result.css)
83
- }
84
- }
1
+ const path = require('path')
2
+ const fs = require('fs-extra')
3
+ const postcss = require('postcss')
4
+ const tailwindcss = require('tailwindcss')
5
+ const postcssImport = require('postcss-import')
6
+ const postcssNested = require('tailwindcss/nesting')
7
+ const {requireUncached} = require('../utils/helpers')
8
+ const mergeLonghand = require('postcss-merge-longhand')
9
+ const {get, isObject, isEmpty, merge} = require('lodash')
10
+
11
+ module.exports = {
12
+ compile: async (css = '', html = '', tailwindConfig = {}, maizzleConfig = {}, spinner = null) => {
13
+ tailwindConfig = (isObject(tailwindConfig) && !isEmpty(tailwindConfig)) ? tailwindConfig : get(maizzleConfig, 'build.tailwind.config', 'tailwind.config.js')
14
+
15
+ // Compute the Tailwind config to use
16
+ const userConfig = () => {
17
+ // If a custom config object was passed, use that
18
+ if (isObject(tailwindConfig) && !isEmpty(tailwindConfig)) {
19
+ return tailwindConfig
20
+ }
21
+
22
+ /**
23
+ * Try loading a fresh tailwind.config.js, with fallback to an empty object.
24
+ * This will use the default Tailwind config (with rem units etc)
25
+ */
26
+ try {
27
+ return requireUncached(path.resolve(process.cwd(), tailwindConfig))
28
+ } catch {
29
+ return {}
30
+ }
31
+ }
32
+
33
+ // Merge user's Tailwind config on top of a 'base' config
34
+ const config = merge({
35
+ important: true,
36
+ content: {
37
+ files: [
38
+ './src/**/*.*',
39
+ {raw: html, extension: 'html'}
40
+ ]
41
+ }
42
+ }, userConfig())
43
+
44
+ // Add back the `{raw: html}` option if user provided own config
45
+ if (Array.isArray(config.content)) {
46
+ config.content = {
47
+ files: [
48
+ ...config.content,
49
+ './src/**/*.*',
50
+ {raw: html, extension: 'html'}
51
+ ]
52
+ }
53
+ }
54
+
55
+ // Include all `build.templates.source` paths when scanning for selectors to preserve
56
+ const buildTemplates = get(maizzleConfig, 'build.templates')
57
+
58
+ if (buildTemplates) {
59
+ const templateObjects = Array.isArray(buildTemplates) ? buildTemplates : [buildTemplates]
60
+ const templateSources = templateObjects.map(template => {
61
+ const source = get(template, 'source')
62
+
63
+ if (typeof source === 'function') {
64
+ const sources = source(maizzleConfig)
65
+
66
+ if (Array.isArray(sources)) {
67
+ sources.map(s => config.content.files.push(s))
68
+ } else if (typeof sources === 'string') {
69
+ config.content.files.push(sources)
70
+ }
71
+
72
+ // Must return a valid `content` entry
73
+ return {raw: '', extension: 'html'}
74
+ }
75
+
76
+ // Support single-file sources i.e. src/templates/index.html
77
+ if (typeof source === 'string' && Boolean(path.extname(source))) {
78
+ config.content.files.push(source)
79
+
80
+ return {raw: '', extension: 'html'}
81
+ }
82
+
83
+ return `${source}/**/*.*`
84
+ })
85
+
86
+ config.content.files.push(...templateSources)
87
+ }
88
+
89
+ const userFilePath = get(maizzleConfig, 'build.tailwind.css', path.join(process.cwd(), 'src/css/tailwind.css'))
90
+ const userFileExists = await fs.pathExists(userFilePath)
91
+
92
+ if (userFileExists) {
93
+ css = await fs.readFile(path.resolve(userFilePath), 'utf8') + css
94
+ } else {
95
+ css = `@import "tailwindcss/components"; @import "tailwindcss/utilities"; ${css}`
96
+ }
97
+
98
+ return postcss([
99
+ postcssImport({path: path.dirname(userFilePath)}),
100
+ postcssNested(),
101
+ tailwindcss(config),
102
+ maizzleConfig.env === 'local' ? () => {} : mergeLonghand(),
103
+ ...get(maizzleConfig, 'build.postcss.plugins', [])
104
+ ])
105
+ .process(css, {from: undefined})
106
+ .then(result => result.css)
107
+ .catch(error => {
108
+ console.error(error)
109
+ if (spinner) {
110
+ spinner.stop()
111
+ }
112
+
113
+ throw new Error(`Tailwind CSS compilation failed`)
114
+ })
115
+ }
116
+ }
package/src/index.js CHANGED
@@ -1,163 +1,17 @@
1
- const ora = require('ora')
2
- const path = require('path')
3
- const fs = require('fs-extra')
4
- const {get, merge} = require('lodash')
5
- const bs = require('browser-sync').create()
6
- const Config = require('./generators/config')
7
- const Output = require('./generators/output')
1
+ const serve = require('./commands/serve')
2
+ const toFile = require('./commands/build')
8
3
  const transformers = require('./transformers')
9
- const {clearConsole} = require('./utils/helpers')
10
- const Plaintext = require('./generators/plaintext')
11
- const Tailwind = require('./generators/tailwindcss')
12
-
13
- const self = module.exports = { // eslint-disable-line
4
+ const toString = require('./functions/render')
5
+ const PostCSS = require('./generators/postcss')
6
+ const toPlaintext = require('./functions/plaintext')
7
+ const TailwindCSS = require('./generators/tailwindcss')
8
+
9
+ module.exports = {
10
+ serve,
11
+ build: toFile,
14
12
  ...transformers,
15
- render: async (html, options) => Output.toString(html, options),
16
- plaintext: async (html, config = {}) => Plaintext.generate(html, false, config),
17
- build: async (env = 'local', config = {}) => {
18
- const start = new Date()
19
- const spinner = ora('Building emails...').start()
20
-
21
- return Output.toDisk(env, spinner, config)
22
- .then(({files, parsed}) => {
23
- const elapsedSeconds = (Date.now() - start) / 1000
24
-
25
- if (get(config, 'build.command') === 'serve') {
26
- clearConsole()
27
- spinner.succeed(`Re-built ${parsed.length} templates in ${elapsedSeconds}s`)
28
- } else {
29
- spinner.succeed(`Built ${parsed.length} templates in ${elapsedSeconds}s`)
30
- }
31
-
32
- return {files}
33
- })
34
- .catch(error => {
35
- throw error
36
- })
37
- },
38
- serve: async (env = 'local', config = {}) => {
39
- config = merge(
40
- config,
41
- await Config.getMerged(env),
42
- {
43
- build: {
44
- command: 'serve'
45
- }
46
- }
47
- )
48
-
49
- await self
50
- .build(env, config)
51
- .then(async () => {
52
- let templates = get(config, 'build.templates')
53
- templates = Array.isArray(templates) ? templates : [templates]
54
-
55
- const templatePaths = [...new Set(templates.map(config => `${get(config, 'source', 'src')}/**`))]
56
- const globalPaths = [
57
- 'src/**',
58
- get(config, 'build.tailwind.config', 'tailwind.config.js'),
59
- [...new Set(get(config, 'build.browsersync.watch', []))]
60
- ]
61
-
62
- // Pre-compile Tailwind so that updates to tailwind.config.js are reflected
63
- const cssString = fs.existsSync(get(config, 'build.tailwind.css')) ? fs.readFileSync(get(config, 'build.tailwind.css'), 'utf8') : '@tailwind components; @tailwind utilities;'
64
- const css = await Tailwind.compile(cssString, '', {}, config)
65
-
66
- const spinner = ora()
67
-
68
- // Watch for Template file changes
69
- bs.watch(templatePaths)
70
- .on('change', async file => {
71
- clearConsole()
72
-
73
- const start = new Date()
74
-
75
- spinner.start('Building email...')
76
-
77
- file = file.replace(/\\/g, '/')
78
-
79
- const destination = get(config, 'build.currentTemplates.destination.path', 'build_local')
80
- const extension = get(config, 'build.currentTemplates.destination.extension', 'html')
81
- const fileSource = get(config, 'build.currentTemplates.source')
82
- const parts = path.parse(path.join(destination, file.replace(fileSource, '')))
83
- const finalDestination = path.join(parts.dir, `${parts.name}.${extension}`)
84
-
85
- if (config.events && typeof config.events.beforeCreate === 'function') {
86
- await config.events.beforeCreate(config)
87
- }
88
-
89
- /**
90
- * Tailwind CSS compiler
91
- *
92
- * Use the Just-In-Time engine if the user enabled it
93
- * Fall back to the classic Always-On-Time engine
94
- */
95
- let mode = 'aot'
96
-
97
- try {
98
- const tailwindConfig = require(path.resolve(process.cwd(), get(config, 'build.currentTemplates.tailwind.config', 'tailwind.config.js')))
99
- mode = get(tailwindConfig, 'mode')
100
- } catch {}
101
-
102
- const renderOptions = {
103
- maizzle: config,
104
- ...config.events
105
- }
106
-
107
- // AOT: fall back to pre-compiled CSS
108
- if (mode !== 'jit') {
109
- renderOptions.tailwind = {
110
- compiled: css
111
- }
112
- }
113
-
114
- self
115
- .render(await fs.readFile(file, 'utf8'), renderOptions)
116
- .then(({html, config}) => fs.outputFile(config.permalink || finalDestination, html))
117
- .then(() => {
118
- bs.reload()
119
- spinner.succeed(`Compiled in ${(Date.now() - start) / 1000}s [${file}]`)
120
- })
121
- .catch(() => spinner.warn(`Received empty HTML, please save your file again [${file}]`))
122
- })
123
-
124
- // Watch for changes in all other files
125
- bs.watch(globalPaths, {ignored: templatePaths})
126
- .on('change', () => self.build(env, config).then(() => bs.reload()))
127
- .on('unlink', () => self.build(env, config).then(() => bs.reload()))
128
-
129
- // Watch for changes in config files
130
- bs.watch('config*.js')
131
- .on('change', async file => {
132
- const parsedEnv = path.parse(file).name.split('.')[1] || 'local'
133
-
134
- Config
135
- .getMerged(parsedEnv)
136
- .then(config => self.build(parsedEnv, config).then(() => bs.reload()))
137
- })
138
-
139
- // Browsersync options
140
- const baseDir = templates.map(t => t.destination.path)
141
-
142
- const bsOptions = {
143
- notify: false,
144
- open: false,
145
- port: 3000,
146
- server: {
147
- baseDir,
148
- directory: true
149
- },
150
- tunnel: false,
151
- ui: {port: 3001},
152
- logFileChanges: false,
153
- ...get(config, 'build.browsersync', {})
154
- }
155
-
156
- // Initialize Browsersync
157
- bs.init(bsOptions, () => {})
158
- })
159
- .catch(error => {
160
- throw error
161
- })
162
- }
13
+ render: toString,
14
+ postcss: PostCSS,
15
+ plaintext: toPlaintext,
16
+ tailwindcss: TailwindCSS
163
17
  }
@@ -0,0 +1,69 @@
1
+ const posthtml = require('posthtml')
2
+ const isUrl = require('is-url-superb')
3
+ const baseUrl = require('posthtml-base-url')
4
+ const {get, isObject, isEmpty} = require('lodash')
5
+
6
+ /**
7
+ * VML backgrounds must be handled with regex because
8
+ * they're inside HTML comments.
9
+ */
10
+ const rewriteVMLs = (html, url) => {
11
+ // Handle <v:image>
12
+ const vImageMatches = html.match(/<v:image[^>]+src="?([^"\s]+)"/g)
13
+
14
+ if (vImageMatches) {
15
+ vImageMatches.forEach(match => {
16
+ const vImage = match.match(/<v:image[^>]+src="?([^"\s]+)"/)
17
+ const vImageSrc = vImage[1]
18
+
19
+ if (!isUrl(vImageSrc)) {
20
+ const vImageSrcUrl = url + vImageSrc
21
+ const vImageReplace = vImage[0].replace(vImageSrc, vImageSrcUrl)
22
+ html = html.replace(vImage[0], vImageReplace)
23
+ }
24
+ })
25
+ }
26
+
27
+ // Handle <v:fill>
28
+ const vFillMatches = html.match(/<v:fill[^>]+src="?([^"\s]+)"/g)
29
+
30
+ if (vFillMatches) {
31
+ vFillMatches.forEach(match => {
32
+ const vFill = match.match(/<v:fill[^>]+src="?([^"\s]+)"/)
33
+ const vFillSrc = vFill[1]
34
+
35
+ if (!isUrl(vFillSrc)) {
36
+ const vFillSrcUrl = url + vFillSrc
37
+ const vFillReplace = vFill[0].replace(vFillSrc, vFillSrcUrl)
38
+ html = html.replace(vFill[0], vFillReplace)
39
+ }
40
+ })
41
+ }
42
+
43
+ return html
44
+ }
45
+
46
+ module.exports = async (html, config = {}, direct = false) => {
47
+ const url = direct ? config : get(config, 'baseURL')
48
+ const posthtmlOptions = get(config, 'build.posthtml.options', {})
49
+
50
+ // Handle `baseUrl` as a string
51
+ if (typeof url === 'string' && url.length > 0) {
52
+ html = rewriteVMLs(html, url)
53
+
54
+ return posthtml([
55
+ baseUrl({url, allTags: true, styleTag: true, inlineCss: true})
56
+ ])
57
+ .process(html, posthtmlOptions)
58
+ .then(result => result.html)
59
+ }
60
+
61
+ // Handle `baseUrl` as an object
62
+ if (isObject(url) && !isEmpty(url)) {
63
+ html = rewriteVMLs(html, url.url)
64
+
65
+ return posthtml([baseUrl(url)]).process(html, posthtmlOptions).then(result => result.html)
66
+ }
67
+
68
+ return html
69
+ }
@@ -0,0 +1,126 @@
1
+ const escapeMap = {
2
+ '&': '&amp;',
3
+ '<': '&lt;',
4
+ '>': '&gt;',
5
+ '"': '&#34;',
6
+ '\'': '&#39;'
7
+ }
8
+
9
+ const unescapeMap = {
10
+ '&amp;': '&',
11
+ '&lt;': '<',
12
+ '&gt;': '>',
13
+ '&#34;': '"',
14
+ '&#39;': '\''
15
+ }
16
+
17
+ const unescape = string => string.replace(/&(amp|lt|gt|#34|#39);/g, m => unescapeMap[m])
18
+
19
+ const append = (content, attribute) => content + attribute
20
+ const capitalize = content => content.charAt(0).toUpperCase() + content.slice(1)
21
+ const ceil = content => Math.ceil(Number.parseFloat(content))
22
+ const divide = (content, attribute) => Number.parseFloat(content) / Number.parseFloat(attribute)
23
+ const escape = content => content.replace(/["&'<>]/g, m => escapeMap[m])
24
+ const escapeOnce = content => escape(unescape(content))
25
+ const floor = content => Math.floor(Number.parseFloat(content))
26
+ const lowercase = content => content.toLowerCase()
27
+ const lstrip = content => content.replace(/^\s+/, '')
28
+ const minus = (content, attribute) => Number.parseFloat(content) - Number.parseFloat(attribute)
29
+ const modulo = (content, attribute) => Number.parseFloat(content) % Number.parseFloat(attribute)
30
+ const multiply = (content, attribute) => Number.parseFloat(content) * Number.parseFloat(attribute)
31
+ const newlineToBr = content => content.replace(/\n/g, '<br>')
32
+ const plus = (content, attribute) => Number.parseFloat(content) + Number.parseFloat(attribute)
33
+ const prepend = (content, attribute) => attribute + content
34
+
35
+ const remove = (content, attribute) => {
36
+ const regex = new RegExp(attribute, 'g')
37
+ return content.replace(regex, '')
38
+ }
39
+
40
+ const removeFirst = (content, attribute) => content.replace(attribute, '')
41
+ const replace = (content, attribute) => {
42
+ const [search, replace] = attribute.split('|')
43
+ const regex = new RegExp(search, 'g')
44
+ return content.replace(regex, replace)
45
+ }
46
+
47
+ const replaceFirst = (content, attribute) => {
48
+ const [search, replace] = attribute.split('|')
49
+ return content.replace(search, replace)
50
+ }
51
+
52
+ const round = content => Math.round(Number.parseFloat(content))
53
+ const rstrip = content => content.replace(/\s+$/, '')
54
+ const uppercase = content => content.toUpperCase()
55
+ const size = content => content.length
56
+ const slice = (content, attribute) => {
57
+ try {
58
+ const [start, end] = attribute.split(',')
59
+ return content.slice(start, end)
60
+ } catch {
61
+ return content.slice(attribute)
62
+ }
63
+ }
64
+
65
+ const stripNewlines = content => content.replace(/\n/g, '')
66
+ const trim = content => content.trim()
67
+ const truncate = (content, attribute) => {
68
+ try {
69
+ const [length, omission] = attribute.split(',')
70
+ return content.length > Number.parseInt(length, 10) ?
71
+ content.slice(0, length) + (omission || '...') :
72
+ content
73
+ } catch {
74
+ const length = Number.parseInt(attribute, 10)
75
+ return content.length > length ? content.slice(0, length) + '...' : content
76
+ }
77
+ }
78
+
79
+ const truncateWords = (content, attribute) => {
80
+ try {
81
+ const [length, omission] = attribute.split(',')
82
+ return content.split(' ').slice(0, Number.parseInt(length, 10)).join(' ') + (omission || '...')
83
+ } catch {
84
+ const length = Number.parseInt(attribute, 10)
85
+ return content.split(' ').slice(0, length).join(' ') + '...'
86
+ }
87
+ }
88
+
89
+ // eslint-disable-next-line
90
+ const urlDecode = content => content.split('+').map(decodeURIComponent).join(' ')
91
+ // eslint-disable-next-line
92
+ const urlEncode = content => content.split(' ').map(encodeURIComponent).join('+')
93
+
94
+ exports.append = append
95
+ exports.capitalize = capitalize
96
+ exports.ceil = ceil
97
+ exports['divide-by'] = divide
98
+ exports.divide = divide
99
+ exports.escape = escape
100
+ exports['escape-once'] = escapeOnce
101
+ exports.floor = floor
102
+ exports.lowercase = lowercase
103
+ exports.lstrip = lstrip
104
+ exports.minus = minus
105
+ exports.modulo = modulo
106
+ exports.multiply = multiply
107
+ exports['newline-to-br'] = newlineToBr
108
+ exports.plus = plus
109
+ exports.prepend = prepend
110
+ exports.remove = remove
111
+ exports['remove-first'] = removeFirst
112
+ exports.replace = replace
113
+ exports['replace-first'] = replaceFirst
114
+ exports.round = round
115
+ exports.rstrip = rstrip
116
+ exports.uppercase = uppercase
117
+ exports.size = size
118
+ exports.slice = slice
119
+ exports.strip = trim
120
+ exports['strip-newlines'] = stripNewlines
121
+ exports.times = multiply
122
+ exports.trim = trim
123
+ exports.truncate = truncate
124
+ exports['truncate-words'] = truncateWords
125
+ exports['url-decode'] = urlDecode
126
+ exports['url-encode'] = urlEncode
@@ -0,0 +1,55 @@
1
+ const posthtml = require('posthtml')
2
+ const {get, omit, has, merge} = require('lodash')
3
+ const defaultFilters = require('./defaultFilters')
4
+ const PostCSS = require('../../generators/postcss')
5
+ const posthtmlContent = require('posthtml-content')
6
+ const Tailwind = require('../../generators/tailwindcss')
7
+ const safeClassNames = require('posthtml-safe-class-names')
8
+
9
+ module.exports = async (html, config = {}, direct = false) => {
10
+ const filters = direct ?
11
+ merge(defaultFilters, config) :
12
+ merge(defaultFilters, get(config, 'filters', {}))
13
+
14
+ const posthtmlOptions = get(config, 'build.posthtml.options', {})
15
+
16
+ /**
17
+ * Compile CSS in <style {post|tailwind}css> tags
18
+ */
19
+ const maizzleConfig = omit(config, ['build.tailwind.css', 'css'])
20
+ const tailwindConfig = get(config, 'build.tailwind.config', 'tailwind.config.js')
21
+
22
+ filters.postcss = css => PostCSS.process(css, maizzleConfig)
23
+ filters.tailwindcss = css => Tailwind.compile(css, html, tailwindConfig, maizzleConfig)
24
+
25
+ return posthtml([
26
+ styleDataEmbed(),
27
+ posthtmlContent(filters),
28
+ safeClassNames()
29
+ ])
30
+ .process(html, posthtmlOptions)
31
+ .then(result => result.html)
32
+ }
33
+
34
+ /**
35
+ * Prevent CSS inlining
36
+ *
37
+ * Add a `data-embed` attribute to <style> tags that we want to preserve.
38
+ * Can be used for HTML email client targeting hacks.
39
+ */
40
+ const styleDataEmbed = () => tree => {
41
+ const process = node => {
42
+ if (
43
+ node.tag === 'style'
44
+ && node.attrs
45
+ && (has(node.attrs, 'preserve') || has(node.attrs, 'embed'))) {
46
+ node.attrs = {...node.attrs, 'data-embed': true}
47
+ node.attrs.preserve = false
48
+ node.attrs.embed = false
49
+ }
50
+
51
+ return node
52
+ }
53
+
54
+ return tree.walk(process)
55
+ }