Skip to content

Commit

Permalink
feat: refactor and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
lubomirblazekcz committed Aug 25, 2022
1 parent 2cd37bd commit 34eb986
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 29 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2022 Vituum

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,38 @@
# ⚡️🌱 ViteTwig

```js
import twig from '@vituum/vite-plugin-twig'

export default {
plugins: [
twig({
reload: true,
root: null,
filters: {},
functions: {},
extensions: [],
namespaces: {},
data: '*.json',
globals: {
template: 'path/to/template.twig'
},
data: '*.json',
filetypes: {
html: /.(json.html|twig.json.html|twig.html)$/,
json: /.(json.twig.html)$/
},
twig: {
compileOptions: {},
renderOptions: {}
}
})
]
}
```

Read the [docs](https://vituum.dev/config/integrations-options.html#vituum-twig) to learn more about plugin options

## Basic usage

```html
<!-- index.html -->
<script type="application/json" data-format="twig">
Expand All @@ -50,3 +62,4 @@ or
### Requirements

- [Node.js LTS (16.x)](https://nodejs.org/en/download/)
- [Vite](https://vitejs.dev/) or [Vituum](https://vituum.dev/)
67 changes: 41 additions & 26 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { dirname, extname, resolve, relative } from 'path'
import { dirname, resolve, relative } from 'path'
import fs from 'fs'
import process from 'node:process'
import FastGlob from 'fast-glob'
Expand All @@ -9,15 +9,21 @@ import { fileURLToPath } from 'url'

const { name } = JSON.parse(fs.readFileSync(resolve(dirname((fileURLToPath(import.meta.url))), 'package.json')).toString())
const defaultOptions = {
reload: true,
root: null,
filters: {},
functions: {},
extensions: [],
globals: {},
namespaces: {},
globals: {},
data: '',
filetypes: {
html: /.(json.html|twig.json.html|twig.html)$/,
json: /.(json.twig.html)$/
},
twig: {
compileOptions: {},
renderOptions: {}
}
}

Expand All @@ -37,7 +43,23 @@ function processData(paths, data = {}) {

const renderTemplate = async(filename, content, options) => {
const output = {}
const context = processData(options.data, options.globals)
const context = options.data ? processData(options.data, options.globals) : options.globals

const isJson = filename.endsWith('.json.html') || filename.endsWith('.json')
const isHtml = filename.endsWith('.html') && !filename.endsWith('.json.html')

if (isJson || isHtml) {
lodash.merge(context, isHtml ? content : JSON.parse(fs.readFileSync(filename).toString()))

content = '{% include template %}'
filename = options.root + '/'

context.template = relative(process.cwd(), context.template).startsWith(relative(process.cwd(), options.root)) ? resolve(process.cwd(), context.template) : resolve(options.root, context.template)

context.template = relative(options.root, context.template)
} else if (fs.existsSync(filename + '.json')) {
lodash.merge(context, JSON.parse(fs.readFileSync(filename + '.json').toString()))
}

Twig.cache(false)

Expand Down Expand Up @@ -65,27 +87,13 @@ const renderTemplate = async(filename, content, options) => {
Twig.extendFilter(name, options.filters[name])
})

if (
filename.endsWith('.json.html') ||
filename.endsWith('.json')
) {
lodash.merge(context, JSON.parse(fs.readFileSync(filename).toString()))

content = '{% include template %}'
filename = options.root

context.template = relative(process.cwd(), context.template)
} else if (fs.existsSync(filename + '.json')) {
lodash.merge(context, JSON.parse(fs.readFileSync(filename + '.json').toString()))
}

output.content = await Twig.twig({
output.content = await Twig.twig(Object.assign({
allowAsync: true,
data: content,
path: filename,
namespaces: options.namespaces,
rethrow: true
}).renderAsync(context).catch((error) => {
}, options.twig.compileOptions)).renderAsync(context, options.twig.renderOptions).catch((error) => {
output.error = error
})

Expand All @@ -98,21 +106,27 @@ const plugin = (options = {}) => {
return {
name,
config: ({ root }) => {
options.root = root
if (!options.root) {
options.root = root
}
},
transformIndexHtml: {
enforce: 'pre',
async transform(content, { path, filename, server }) {
if (
!options.filetypes.html.test(path) &&
!options.filetypes.json.test(path) &&
!content.startsWith('<script type="application/json"')
!content.startsWith('<script type="application/json" data-format="twig"')
) {
return content
}

if (content.startsWith('<script type="application/json"') && !content.includes('data-format="twig"')) {
return content
if (content.startsWith('<script type="application/json" data-format="twig"')) {
const matches = content.matchAll(/<script\b[^>]*data-format="(?<format>[^>]+)"[^>]*>(?<data>[\s\S]+?)<\/script>/gmi)

for (const match of matches) {
content = JSON.parse(match.groups.data)
}
}

const render = await renderTemplate(filename, content, options)
Expand All @@ -130,15 +144,16 @@ const plugin = (options = {}) => {
plugin: name
}
})

return '<html style="background: #222"><head></head><body></body></html>'
}

return render.content
}
},
handleHotUpdate({ file, server }) {
if (extname(file) === '.twig' || extname(file) === '.html' || extname(file) === '.json') {
if (
(typeof options.reload === 'function' && options.reload(file)) ||
(options.reload && (options.filetypes.html.test(file) || options.filetypes.json.test(file)))
) {
server.ws.send({ type: 'full-reload' })
}
}
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@vituum/vite-plugin-twig",
"version": "0.1.1",
"version": "0.1.2",
"type": "module",
"main": "index.js",
"dependencies": {
Expand All @@ -10,7 +10,7 @@
"fast-glob": "^3.2.11"
},
"devDependencies": {
"eslint": "^8.21.0",
"eslint": "^8.22.0",
"eslint-config-standard": "^17.0.0"
},
"files": [
Expand Down

0 comments on commit 34eb986

Please sign in to comment.