Skip to content

WIP: Schema support #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7,681 changes: 3,351 additions & 4,330 deletions package-lock.json

Large diffs are not rendered by default.

48 changes: 26 additions & 22 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"README.md"
],
"engines": {
"node": ">=4.8.7"
"node": ">=10"
},
"keywords": [
"liquid",
Expand All @@ -36,35 +36,35 @@
},
"homepage": "https://github.com/harttle/liquidjs-section-tags#readme",
"devDependencies": {
"@semantic-release/changelog": "^3.0.2",
"@semantic-release/commit-analyzer": "^6.1.0",
"@semantic-release/git": "^7.0.8",
"@semantic-release/npm": "^5.1.8",
"@semantic-release/release-notes-generator": "^7.1.4",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/commit-analyzer": "^8.0.1",
"@semantic-release/git": "^9.0.0",
"@semantic-release/npm": "^7.0.8",
"@semantic-release/release-notes-generator": "^9.0.1",
"@types/chai": "^4.1.7",
"@types/chai-as-promised": "^7.1.0",
"@types/mocha": "^5.2.6",
"@typescript-eslint/eslint-plugin": "^1.11.0",
"@typescript-eslint/parser": "^1.11.0",
"@types/mocha": "^8.0.4",
"@typescript-eslint/eslint-plugin": "^4.8.1",
"@typescript-eslint/parser": "^4.8.1",
"benchmark": "^2.1.4",
"chai": "^4.2.0",
"chai-as-promised": "^7.1.1",
"coveralls": "^3.0.2",
"eslint": "^5.12.1",
"eslint-config-standard": "^12.0.0",
"eslint": "^7.14.0",
"eslint-config-standard": "^16.0.2",
"eslint-plugin-import": "^2.15.0",
"eslint-plugin-mocha": "^5.3.0",
"eslint-plugin-node": "^8.0.1",
"eslint-plugin-mocha": "^8.0.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-promise": "^4.0.1",
"eslint-plugin-standard": "^4.0.0",
"liquidjs": "^8.4.0",
"mocha": "^5.2.0",
"nyc": "^13.1.0",
"regenerator-runtime": "^0.12.1",
"semantic-release": "^15.13.14",
"ts-node": "^8.0.2",
"tslib": "^1.9.3",
"typescript": "^3.3.3"
"eslint-plugin-standard": "^4.1.0",
"liquidjs": "^9.16.1",
"mocha": "^8.2.1",
"nyc": "^15.1.0",
"regenerator-runtime": "^0.13.7",
"semantic-release": "^17.2.4",
"ts-node": "^9.0.0",
"tslib": "^2.0.3",
"typescript": "^4.1.2"
},
"release": {
"branch": "master",
Expand All @@ -82,6 +82,10 @@
".ts"
]
},
"mocha": {
"require": "ts-node/register/transpile-only",
"strict": "strict"
},
"dependencies": {
"sass": "^1.22.7"
}
Expand Down
5 changes: 5 additions & 0 deletions prettier.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
singleQuote: true,
semi: false,
trailingComma: 'none'
}
20 changes: 6 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,12 @@
import Liquid from 'liquidjs'
import { sectionTag } from './section'
import { Liquid } from 'liquidjs'
import { JavaScript } from './javascript'
import { Schema } from './schema'
import { Section } from './section'
import { StyleSheet } from './stylesheet'
import { JavaScript } from './javascript'

interface SectionOptions {
/* root directory for sections */
root?: string;
}

export function liquidSectionTags (options: Partial<SectionOptions> = {}) {
const opts = Object.assign({
root: 'sections'
}, options)
return function (this: Liquid) {
this.registerTag('section', sectionTag(opts.root))
export function liquidSectionTags () {
return function (this: Liquid): void {
this.registerTag('section', Section)
this.registerTag('schema', Schema)
this.registerTag('stylesheet', StyleSheet)
this.registerTag('javascript', JavaScript)
Expand Down
16 changes: 10 additions & 6 deletions src/javascript.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
export const JavaScript = {
parse: function (token, remainTokens) {
import { TagToken, TopLevelToken } from 'liquidjs'
import { TagImplOptions } from 'liquidjs/dist/template/tag/tag-impl-options'

export const JavaScript: TagImplOptions = {
parse: function (tagToken: TagToken, remainTokens: TopLevelToken[]): void {
this.tokens = []
const stream = this.liquid.parser.parseStream(remainTokens)
stream
.on('token', (token) => {
.on('token', (token: TagToken) => {
if (token.name === 'endjavascript') stream.stop()
else this.tokens.push(token)
})
.on('end', () => {
throw new Error(`tag ${token.raw} not closed`)
throw new Error(`tag ${tagToken.getText()} not closed`)
})
stream.start()
},
render: async function (ctx, hash) {
const text = this.tokens.map((token) => token.raw).join('')
render: function (): string {
const text = this.tokens.map((token) => token.getText()).join('')

return `<script>${text}</script>`
}
}
44 changes: 35 additions & 9 deletions src/schema.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,47 @@
export const Schema = {
parse: function (tagToken, remainTokens) {
import { TagToken, TopLevelToken } from 'liquidjs'
import { TagImplOptions } from 'liquidjs/dist/template/tag/tag-impl-options'

function generateSettingsObj (settings: any) {
if (!Array.isArray(settings)) {
return settings
}

return settings
.filter((entry) => !!entry.id)
.reduce((sectionSettings, entry) => {
sectionSettings[entry.id] = entry.default
return sectionSettings
}, {})
}

export const Schema: TagImplOptions = {
parse: function (tagToken: TagToken, remainTokens: TopLevelToken[]) {
this.tokens = []
const stream = this.liquid.parser.parseStream(remainTokens)
stream
.on('token', (token) => {
if (token.name === 'endschema') stream.stop()
else this.tokens.push(token)
.on('token', (token: TagToken) => {
if (token.name === 'endschema') {
stream.stop()
} else this.tokens.push(token)
})
.on('end', () => {
throw new Error(`tag ${tagToken.raw} not closed`)
throw new Error(`tag ${tagToken.getText()} not closed`)
})
stream.start()
},
render: function () {
const json = this.tokens.map((token) => token.raw).join('')
render: function (ctx) {
const json = this.tokens.map((token) => token.getText()).join('')
const schema = JSON.parse(json)
console.log('schema:', schema)

const scope = (ctx as any).scopes[(ctx as any).scopes.length - 1]
scope.section = {
settings: generateSettingsObj(schema.settings),
blocks: (schema.blocks || []).map((block) => ({
...block,
settings: generateSettingsObj(block.settings)
}))
}

return ''
}
}
42 changes: 25 additions & 17 deletions src/section.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,31 @@
import { join } from 'path'
import { Context, TagImplOptions } from 'liquidjs'

const quoted = /^'[^']*'|"[^"]*"$/

export function sectionTag (root: string) {
return {
parse: function (token) {
this.namestr = token.args
},
render: async function (ctx, hash) {
let name
if (quoted.exec(this.namestr)) {
const template = this.namestr.slice(1, -1)
name = await this.liquid.parseAndRender(template, ctx.getAll(), ctx.opts)
}
if (!name) throw new Error(`cannot include with empty filename`)

const filepath = join(root, name)
const templates = await this.liquid.getTemplate(filepath)
return this.liquid.render(templates)
export const Section: TagImplOptions = {
parse: function (token) {
this.namestr = token.args
},
render: function * (ctx: Context, emitter) {
let name
if (quoted.exec(this.namestr)) {
const template = this.namestr.slice(1, -1)
name = yield this.liquid._parseAndRender(template, ctx.getAll(), ctx.opts)
}
if (!name) throw new Error('cannot include with empty filename')
const templates = yield this.liquid._parseFile(name, ctx.opts, ctx.sync)

// Bubble up schema tag for allowing it's data available to the section
templates.sort((tagA) => {
return tagA.token.kind === 4 &&
(tagA.token as any).name === 'schema'
? -1
: 0
})

const scope = {}
ctx.push(scope)
yield this.liquid.renderer.renderTemplates(templates, ctx, emitter)
ctx.pop()
}
}
32 changes: 19 additions & 13 deletions src/stylesheet.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,42 @@
import { TagImplOptions, TagToken, TopLevelToken } from 'liquidjs'
import { render } from 'sass'

const quoted = /^'[^']*'|"[^"]*"$/

const processors = {
'': x => x,
'sass': sassProcessor,
'scss': sassProcessor
'': (x) => x,
sass: sassProcessor,
scss: sassProcessor
}

export const StyleSheet = {
parse: function (token, remainTokens) {
export const StyleSheet: TagImplOptions = {
parse: function (token: TagToken, remainTokens: TopLevelToken[]) {
this.processor = token.args

this.tokens = []
const stream = this.liquid.parser.parseStream(remainTokens)
stream
.on('token', (token) => {
.on('token', (token: TagToken) => {
if (token.name === 'endstylesheet') stream.stop()
else this.tokens.push(token)
})
.on('end', () => {
throw new Error(`tag ${token.raw} not closed`)
throw new Error(`tag ${token.getText()} not closed`)
})
stream.start()
},
render: async function (ctx, hash) {
render: async function (ctx) {
let processor = ''
if (quoted.exec(this.processor)) {
const template = this.processor.slice(1, -1)
processor = await this.liquid.parseAndRender(template, ctx.getAll(), ctx.opts)
processor = await this.liquid.parseAndRender(
template,
ctx.getAll(),
ctx.opts
)
}

const text = this.tokens.map((token) => token.raw).join('')
const text = this.tokens.map((token) => token.getText()).join('')

const p = processors[processor]
if (!p) throw new Error(`processor for ${processor} not found`)
Expand All @@ -41,8 +46,9 @@ export const StyleSheet = {
}

function sassProcessor (data: string) {
return new Promise((resolve, reject) => render(
{ data },
(err, result) => err ? reject(err) : resolve('' + result.css))
return new Promise((resolve, reject) =>
render({ data }, (err, result) =>
err ? reject(err) : resolve('' + result.css)
)
)
}
14 changes: 8 additions & 6 deletions test/javascript.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import Liquid from 'liquidjs'
import { expect } from 'chai'
import { liquidSectionTags } from '../src/index'
import { Liquid } from 'liquidjs'
import { resolve } from 'path'
import { liquidSectionTags } from '../src/index'

describe('javascript', function () {
let liquid: Liquid
before(function () {
liquid = new Liquid({ extname: '.liquid' })
liquid.plugin(liquidSectionTags({
root: resolve(__dirname, './stub/sections')
}))
liquid = new Liquid({
extname: '.liquid',
root: [resolve(__dirname, './stub/sections')]
})
liquid.plugin(liquidSectionTags())
})

it('should load javascript', async () => {
const html = await liquid.parseAndRender('{% section "js" %}')
expect(html).to.equal('<script>\nconsole.log("foo")\n</script>')
Expand Down
1 change: 0 additions & 1 deletion test/mocha.opts

This file was deleted.

25 changes: 19 additions & 6 deletions test/schema.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
import Liquid from 'liquidjs'
import { expect } from 'chai'
import { liquidSectionTags } from '../src/index'
import { Liquid } from 'liquidjs'
import { resolve } from 'path'
import { liquidSectionTags } from '../src/index'

describe('schema', function () {
let liquid: Liquid

before(function () {
liquid = new Liquid({ extname: '.liquid' })
liquid.plugin(liquidSectionTags({
root: resolve(__dirname, './stub/sections')
}))
liquid = new Liquid({
extname: '.liquid',
root: [resolve(__dirname, './stub/sections')]
})
liquid.plugin(liquidSectionTags())
})

it('should allow empty schema', async () => {
const html = await liquid.parseAndRender('{% section "empty-schema" %}')
expect(html).to.equal('BA')
})

it('should expose section schema settings in the scope', async () => {
const html = await liquid.parseAndRender('{% section "schema-settings" %}')
expect(html.trim()).to.equal('Menu 1, menu_enabled:true')
})

it('should expose section schema blocks in the scope', async () => {
const html = await liquid.parseAndRender('{% section "schema-blocks" %}')
expect(html.trim()).to.equal('quote, text, Once upon a time...')
})
})
Loading