Skip to content

Commit

Permalink
Merge pull request #67 from AdFabConnect/refactor_page
Browse files Browse the repository at this point in the history
Refactor page
  • Loading branch information
gregorybesson committed Dec 6, 2016
2 parents c3edb15 + 9e5425c commit 7cb6408
Show file tree
Hide file tree
Showing 14 changed files with 457 additions and 193 deletions.
200 changes: 9 additions & 191 deletions src/cli/cms/Page.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,76 +62,36 @@ export default class Page {
this.blockPattern = /(\{\{#each.*\}\}[\s\S]*?\{\{\/each\}\})/g

// Remove text with attribute "visible=false"
this._removeHidden()
this.template = cmsTemplates.prepare.removeHiddenAbeTag(this.template)

if(!this._onlyHTML) {

// Surrounds each Abe tag (which are text/rich/textarea and not in html attribute) with <abe> tag
// ie. <title><abe>{{abe type='text' key='meta_title' desc='Meta title' tab='Meta' order='4000'}}</abe></title>
this._encloseAbeTag()
this.template = cmsTemplates.prepare.addAbeHtmlTagBetweenAbeTags(this.template)
}
else {
this._removeHandlebarsRawFromHtml()
this.template = cmsTemplates.prepare.removeHandlebarsRawFromHtml(this.template)
this.template = cmsTemplates.prepare.addAbeHtmlTagBetweenAbeTags(this.template)
}

// je rajoute les index pour chaque bloc lié à un each
this._indexEachBlocks()
this.template = cmsTemplates.prepare.indexEachBlocks(this.template, this._onlyHTML)

if(!this._onlyHTML){

// Je maj les attributs associés aux Abe qui sont dans des attributs de tag HTML
this._updateAbeAsAttribute()
this.template = cmsTemplates.prepare.addAbeDataAttrForHtmlAttributes(this.template)

// je rajoute les attributs pour les tags Abe (qui ne sont pas dans un attribut HTML)
this._updateAbeAsTag()
this.template = cmsTemplates.prepare.addAbeDataAttrForHtmlTag(this.template)

// Don't know what it does...
var source = config.source.name
if(typeof json[source] !== 'undefined' && json[source] !== null) {
var keys = Object.keys(json[source])

for(var i in keys) {
var replaceEach = new RegExp(`<!-- \\[\\[${keys[i]}\\]\\][\\s\\S]*?-->`, 'g')
this.template = this.template.replace(replaceEach, '')

var patAttrSource = new RegExp(' ([A-Za-z0-9\-\_]+)=["|\'].*?({{' + keys[i] + '}}).*?["|\']', 'g')
var patAttrSourceMatch = this.template.match(patAttrSource)

if(patAttrSourceMatch != null) {
let checkEscapedRegex = /["|'](.*?)["|']/
let patAttrSourceInside = new RegExp('(\\S+)=["\']?((?:.(?!["\']?\\s+(?:\\S+)=|[>"\']))+.)["\']?({{' + keys[i] + '}}).*?["|\']', 'g')
Array.prototype.forEach.call(patAttrSourceMatch, (pat) => {
let patAttrSourceCheck = patAttrSourceInside.exec(pat)
if(patAttrSourceCheck != null) {

let checkEscaped = checkEscapedRegex.exec(patAttrSourceCheck[0])
if(checkEscaped != null && checkEscaped.length > 0) {
checkEscaped = escape(checkEscaped[1])
this.template = this.template.replace(
patAttrSourceCheck[0],
` data-abe-attr="${patAttrSourceCheck[1]}" data-abe-attr-escaped="${checkEscaped}" data-abe="${keys[i]}" ${patAttrSourceCheck[0]}`
)
}
}
})
}

var eachSource = new RegExp(`({{#each ${keys[i]}}[\\s\\S a-z]*?{{\/each}})`, 'g')
var matches = this.template.match(eachSource)
if(typeof matches !== 'undefined' && matches !== null) {
Array.prototype.forEach.call(matches, (match) => {
this.template = this.template.replace(match, `${match}<!-- [[${keys[i]}]] ${cmsTemplates.encodeAbeTagAsComment(match)} -->`)
})
}
}
}
this.template = cmsTemplates.prepare.addAbeSourceComment(this.template, json)
}

// We remove the {{abe type=data ...}} from the text
this.template = cmsData.source.removeDataList(this.template)

// It's time to replace the [index] by {{@index}} (concerning each blocks)
this.template = this.template.replace(/\[index\]\./g, '{{@index}}-')
this.template = cmsTemplates.prepare.replaceAbeEachIndex(this.template)

if(config.files.templates.precompile){
// Let's persist the precompiled template for future use (kind of cache)
Expand All @@ -152,146 +112,4 @@ export default class Page {
this.html = abeExtend.hooks.instance.trigger('afterPageEditorCompile', this.html, json)
}
}

_updateAbeAsAttribute() {
var match
while (match = this.abeAsAttributePattern.exec(this.template)) { // While regexp match {{attribut}}, ex: link, image ...
if(cmsData.regex.isSingleAbe(match[0], this.template)){
var more_attr = ''
var getattr = cmsData.regex.getAttr(match, 'key').replace(/\./g, '-')
this.template = this.template.replace(
new RegExp(match[0]),
' data-abe-attr-' + cmsData.regex.validDataAbe(getattr) + '="' + (match[0].split('=')[0]).trim() + '"' +
' data-abe-' + cmsData.regex.validDataAbe(getattr) + '="' + getattr + '"' +
more_attr + match[0].replace('}}', ' has-abe=1}}')
)
}
}

return this
}

_updateAbeAsTag() {
var match
while (match = this.abePattern.exec(this.template)) {
var getattr = cmsData.regex.getAttr(match, 'key').replace(/\./g, '-')
this.template = this.template.replace(
cmsData.regex.escapeTextToRegex(match[0], 'g'),
' data-abe-' + cmsData.regex.validDataAbe(getattr) + '="' + getattr + '" ' + match[0]
)
}

return this
}

/**
* [_indexEachBlocks description]
* @param {[type]} text [description]
* @param {[type]} blocks [description]
* @return {[type]} [description]
*/
_indexEachBlocks() {
// create an array of {{each}} blocks
var blocks = this._splitEachBlocks()

Array.prototype.forEach.call(blocks, (block) => {
var key = block.match(/#each (.*)\}\}/)
key = key[1]
var match

if(!this._onlyHTML) {

var voidData = {}
voidData[key] = [{}]
var blockCompiled = Handlebars.compile(block.replace(/{{abe (.*?)}}/g, '[[abe $1]]').replace(new RegExp(`\\.\\.\/${config.meta.name}`, 'g'), config.meta.name))
var blockHtml = blockCompiled(voidData, {data: {intl: config.intlData}}).replace(/\[\[abe (.*?)\]\]/g, '{{abe $1}}')

// je rajoute un data-abe-block avec index sur tous les tags html du bloc each
var textEachWithIndex = block.replace(/(<(?![\/])[A-Za-z0-9!-]*)/g, '$1 data-abe-block="' + key + '{{@index}}"')

// je remplace le block dans le texte par ça
this.template = this.template.replace(block, textEachWithIndex + `<!-- [[${key}]] ${cmsTemplates.encodeAbeTagAsComment(blockHtml)} -->`)
}

// Pour chaque tag Abe, je mets en forme ce tag avec des data- supplémentaires
while (match = this.abePattern.exec(block)) {
this._insertAbeEach(match, key, this.eachBlockPattern.lastIndex - block.length)
}

// Pour chaque tag Abe attribut de HTML, je mets en forme ce tag avec des data- supplémentaires sur le tag html parent
while (match = this.abeAsAttributePattern.exec(block)) {
this._insertAbeEach(match, key, this.eachBlockPattern.lastIndex - block.length)
}
})

return this
}

/**
* create an array of {{#each}} blocks from the html document
* @param {String} html the html document
* @return {Array} the array of {{#each}} blocks
*/
_splitEachBlocks() {
var block
var blocks = []

while (block = this.blockPattern.exec(this.template)) {
blocks.push(block[1])
}

return blocks
}

_insertAbeEach(theMatch, key, lastIndex) {
var matchBlock = theMatch[0]
if(cmsData.regex.isEachStatement(matchBlock)) return
if(cmsData.regex.isBlockAbe(matchBlock)){
var matchblockattr = (matchBlock.split('=')[0]).trim()
var getattr = cmsData.regex.getAttr(matchBlock, 'key').replace('.', '[index].')
var newMatchBlock = ((!this._onlyHTML) ?
(/=[\"\']\{\{(.*?)\}\}/g.test(matchBlock) ?
' data-abe-attr-' + cmsData.regex.validDataAbe(getattr) + '="' + matchblockattr + '"' :
'') +
' data-abe-' + cmsData.regex.validDataAbe(getattr) + '="' + getattr + '" ' + matchBlock :
matchBlock)
.replace(new RegExp('(key=[\'|"])' + key + '.', 'g'), '$1' + key + '[index].')
.replace(/\{\{abe/, '{{abe dictionnary=\'' + key + '\'')

this.template = this.template.replace(matchBlock, newMatchBlock)
}

return this
}

/**
* add <abe> tag around html tag
*/
_removeHidden() {
this.template = this.template.replace(/(\{\{abe.*visible=[\'|\"]false.*\}\})/g, '')

return this
}

/**
* add <abe> tag around html tag
* @param {String} text html string
*/
_encloseAbeTag() {
var match
while (match = this.abePattern.exec(this.template)) {
this.template = this.template.replace(cmsData.regex.escapeTextToRegex(match[1], 'g'), '<abe>' + match[1].trim() + '</abe>')
}

return this
}

/**
* remove {{{{raw}}}}{{{{/raw}}}} from html
*/
_removeHandlebarsRawFromHtml() {
this.template = this.template.replace(/\{\{\{\{\/?raw\}\}\}\}/g, '')

return this
}
}
9 changes: 9 additions & 0 deletions src/cli/cms/data/regex.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
export let abePattern = /[^"']({{abe.*?type=[\'|\"][text|rich|textarea]+[\'|\"][\s\S].*?}})/g;
// This pattern finds all abe tags enclosed in a HTML tag attribute
// export let abeAsAttributePattern = /( [A-Za-z0-9\-\_]+=["|']{1}{{abe.*?}})/g;
export let abeAsAttributePattern = /( [A-Za-z0-9\-\_]+=["|']{1}).*?({{abe.*?}})/g;
// This pattern finds all {{#each ...}}...{{/each}} blocks
export let eachBlockPattern = />\s*(\{\{#each (\r|\t|\n|.)*?\/each\}\})/g;
// This pattern finds all {{#each ...}}...{{/each}} blocks
export let blockPattern = /(\{\{#each.*\}\}[\s\S]*?\{\{\/each\}\})/g;

/**
* escape a regex
* @param {String} str
Expand Down
2 changes: 2 additions & 0 deletions src/cli/cms/templates/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import concat from './handlebars/concat'
import getCurrentuserRole from './handlebars/getCurrentuserRole'

import * as template from './template'
import * as prepare from './prepare'
import * as assets from './assets'
import encodeAbeTagAsComment from './encodeAbeTagAsComment'
import insertDebugtoolUtilities from './insertDebugtoolUtilities'
Expand Down Expand Up @@ -55,6 +56,7 @@ HandlebarsIntl.registerWith(Handlebars)
export {
Handlebars,
template,
prepare,
assets,
encodeAbeTagAsComment,
insertDebugtoolUtilities,
Expand Down
Loading

0 comments on commit 7cb6408

Please sign in to comment.