Completed
Push — master ( 0952ee...cac32e )
by
unknown
02:54 queued 29s
created

editor.js ➔ ... ➔ ???   A

Complexity

Conditions 1
Paths 2

Size

Total Lines 50

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 1
c 2
b 2
f 0
nc 2
dl 0
loc 50
rs 9.3333
nop 1
1
import {Promise} from 'bluebird'
2
import path from 'path'
3
4
import {
5
  cmsData,
6
  cmsEditor,
7
  abeEngine,
8
  cmsTemplates,
9
  abeExtend
10
} from '../../cli'
11
12
function add(obj, json, text, util) {
13
  var value = obj.value
14
  
15
  if(obj.key.indexOf('[') > -1) {
16
    var key = obj.key.split('[')[0]
17
    var index = obj.key.match(/[^\[]+?(?=\])/)[0]
18
    var prop = obj.key.replace(/[^\.]+?\./, '')
19
20
    if(typeof json[key] !== 'undefined' && json[key] !== null &&
21
       typeof json[key][index] !== 'undefined' && json[key][index] !== null &&
22
       typeof json[key][index][prop] !== 'undefined' && json[key][index][prop] !== null) {
23
      obj.value = json[getDataIdWithNoSlash(key)][index][prop]
24
    }else if(typeof value !== 'undefined' && value !== null && value !== '') {
25
      if(typeof json[key] === 'undefined' || json[key] === null){
26
        json[key] = []
27
      }
28
      if(typeof json[key][index] === 'undefined' || json[key][index] === null){
29
        json[key][index] = {}
30
      }
31
      json[key][index][prop] = value
32
    }
33
  }
34
35
  obj.key = getDataIdWithNoSlash(obj.key)
36
37
  util.add(obj)
38
39
  return value
40
}
41
42
function getDataIdWithNoSlash(key) {
43
  var trueKey = key
44
  if (trueKey.indexOf('/') > -1) {
45
    trueKey = trueKey.split('/')
46
    trueKey = trueKey[trueKey.length - 1]
47
  }
48
  return trueKey
49
}
50
51
function addToForm(match, text, json, util, arrayBlock, keyArray = null, i = 0) {
52
  var v = `{{${match}}}`,
53
    obj = cmsData.attributes.getAll(v, json)
54
55
  var realKey
56
  if(typeof keyArray !== 'undefined' && keyArray !== null) {
57
    realKey = obj.key.replace(/[^\.]+?\./, '')
58
59
    if(obj.key.indexOf(keyArray + '.') >= 0 && realKey.length > 0){
60
      obj.keyArray = keyArray
61
      obj.realKey = realKey
62
      obj.key = keyArray + '[' + i + '].' + realKey
63
      obj.desc = obj.desc + ' ' + i,
0 ignored issues
show
Comprehensibility introduced by
Usage of the sequence operator is discouraged, since it may lead to obfuscated code.

The sequence or comma operator allows the inclusion of multiple expressions where only is permitted. The result of the sequence is the value of the last expression.

This operator is most often used in for statements.

Used in another places it can make code hard to read, especially when people do not realize it even exists as a seperate operator.

This check looks for usage of the sequence operator in locations where it is not necessary and could be replaced by a series of expressions or statements.

var a,b,c;

a = 1, b = 1,  c= 3;

could just as well be written as:

var a,b,c;

a = 1;
b = 1;
c = 3;

To learn more about the sequence operator, please refer to the MDN.

Loading history...
64
      insertAbeEach(obj, text, json, util, arrayBlock)
65
66
    }else if(util.dontHaveKey(obj.key)) {
67
      obj.value = json[getDataIdWithNoSlash(obj.key)]
68
      json[getDataIdWithNoSlash(obj.key)] = add(obj, json, text, util)
69
    }
70
71
  }else if(util.dontHaveKey(obj.key) && cmsData.regex.isSingleAbe(v, text)) {
72
    realKey = obj.key.replace(/\./g, '-')
73
    obj.value = json[getDataIdWithNoSlash(realKey)]
74
    json[getDataIdWithNoSlash(obj.key)] = add(obj, json, text, util)
75
  }
76
}
77
78
function matchAttrAbe(text, json, util, arrayBlock) {
79
  var patt = /abe [^{{}}]+?(?=\}})/g,
80
    match
81
  // While regexp match HandlebarsJS template item => keepgoing
82
  while (match = patt.exec(text)) {
83
    addToForm(match[0], text, json, util, arrayBlock, null, null)
84
  }
85
}
86
87
function insertAbeEach (obj, text, json, util, arrayBlock) {
88
  if(typeof arrayBlock[obj.keyArray][obj.realKey] === 'undefined' || arrayBlock[obj.keyArray][obj.realKey] === null) {
89
    arrayBlock[obj.keyArray][obj.realKey] = []
90
  }
91
  var exist = false
92
  Array.prototype.forEach.call(arrayBlock[obj.keyArray][obj.realKey], (block) => {
93
    if(block.key === obj.key) {
94
      exist = true
95
    }
96
  })
97
  if(!exist) {
98
    arrayBlock[obj.keyArray][obj.realKey].push(obj)
99
  }
100
}
101
102
function each(text, json, util, arrayBlock) {
103
  let pattEach = /(\{\{#each (\r|\t|\n|.)*?\/each\}\})/g
104
  let patt = /abe [^{{}}]+?(?=\}})/g
105
  var textEach, match
106
107
  while (textEach = pattEach.exec(text)) {
108
    var i
109
    var keyArray = textEach[0].match(/#each (\n|.)*?\}/)
110
    keyArray = keyArray[0].slice(6, keyArray[0].length - 1)
111
112
    if(keyArray.split(' ').length > 1){
113
      keyArray = keyArray.split(' ')[0]
114
    }
115
    arrayBlock[keyArray] = []
116
    // ce while boucle sur les block de contenu {{abe}}
117
    while (match = patt.exec(textEach[0])) {
118
      var v = match[0]
119
120
      if(v.indexOf('abe') > -1){
121
        if(json[keyArray]){
122
          for (i = 0; i < json[keyArray].length; i++) {
123
            addToForm(v, text, json, util, arrayBlock, keyArray, i)
124
          }
125
        }else{
126
          addToForm(v, text, json, util, arrayBlock, keyArray, 0)
127
        }
128
      }
129
    }
130
131
    // ici on boucle a nouveau sur les champs pour les placer a la suite dans le formulaire
132
    var attrArray = [],
133
      length = 0
134
    for(var index in arrayBlock[keyArray]) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
135
      attrArray.push(index)
136
      length = arrayBlock[keyArray][index].length
137
    }
138
139
    for (i = 0; i < length; i++) {
140
      for (var j = 0; j < attrArray.length; j++) {
141
        add(arrayBlock[keyArray][attrArray[j]][i], json, text, util)
142
      }
143
    }
144
  }
145
}
146
147
function addSource(text, json, util) {
148
  var listReg = /({{abe.*type=[\'|\"]data.*}})/g
149
  var match
150
151
  while (match = listReg.exec(text)) {
152
    var obj = cmsData.attributes.getAll(match[0], json)
153
154
    if(obj.editable) {
155
      obj.value = json[getDataIdWithNoSlash(obj.key)]
156
      add(obj, json, text, util)
157
    }else {
158
      json[getDataIdWithNoSlash(obj.key)] = obj.source
159
    }
160
  }
161
}
162
163
function orderByTabindex(a, b) {
164
  if(a.order < b.order) {
165
    return -1
166
  }else if(a.order > b.order) {
167
    return 1
168
  }
169
170
  return 0
171
}
172
173
function orderBlock(util) {
174
    
175
  var formBlock = {}
176
177
  for(var tab in util.form) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
178
179
    var formBlockTab = {}
180
    for (var i = 0; i < util.form[tab].item.length; i++) {
181
      var blockName = (util.form[tab].item[i].block === '') ? 'default_' + i : util.form[tab].item[i].block
182
      if(util.form[tab].item[i].key.indexOf('[') > -1){
183
        blockName = util.form[tab].item[i].key.split('[')[0]
184
      }
185
      if(typeof formBlockTab[blockName] === 'undefined' || formBlockTab[blockName] === null) {
186
        formBlockTab[blockName] = []
187
      }
188
      formBlockTab[blockName].push(util.form[tab].item[i])
189
    }
190
    if(typeof blockName !== 'undefined' && blockName !== null) {
0 ignored issues
show
Bug introduced by
The variable blockName seems to not be initialized for all possible execution paths.
Loading history...
191
      formBlockTab[blockName].sort(orderByTabindex)
192
    }
193
    if(typeof formBlock[tab] === 'undefined' || formBlock[tab] === null) {
194
      formBlock[tab] = {}
195
    }
196
197
    var formBlockOrdered = {}
198
    var arKeys = Object.keys(formBlockTab).sort((a,b) => {
199
      if(parseFloat(formBlockTab[a][0].order) < parseFloat(formBlockTab[b][0].order)) {
0 ignored issues
show
Bug introduced by
The variable formBlockTab is changed as part of the for-each loop for example by {} on line 179. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
200
        return -1
201
      }else if(parseFloat(formBlockTab[a][0].order) > parseFloat(formBlockTab[b][0].order)) {
202
        return 1
203
      }
204
      return 0
205
    })
206
207
    Array.prototype.forEach.call(arKeys, (arKey) => {
208
      formBlockOrdered[arKey] = formBlockTab[arKey]
0 ignored issues
show
Bug introduced by
The variable formBlockOrdered is changed as part of the for-each loop for example by {} on line 197. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
Bug introduced by
The variable formBlockTab is changed as part of the for-each loop for example by {} on line 179. Only the value of the last iteration will be visible in this function if it is called after the loop.
Loading history...
209
    })
210
    formBlock[tab] = formBlockOrdered
211
  }
212
213
  var formTabsOrdered = {}
214
  var arKeysTabs = Object.keys(formBlock).sort((a,b) => {
215
    if(parseFloat(formBlock[a][Object.keys(formBlock[a])[0]][0].order) < parseFloat(formBlock[b][Object.keys(formBlock[b])[0]][0].order)) {
216
      return -1
217
    }else if(parseFloat(formBlock[a][Object.keys(formBlock[a])[0]][0].order) > parseFloat(formBlock[b][Object.keys(formBlock[b])[0]][0].order)) {
218
      return 1
219
    }
220
    return 0
221
  })
222
223
  Array.prototype.forEach.call(arKeysTabs, (arKeysTab) => {
224
    formTabsOrdered[arKeysTab] = formBlock[arKeysTab]
225
  })
226
227
  return formTabsOrdered
228
}
229
230
export function editor(text, json, documentLink, precontrib = false) {
231
  let p = new Promise((resolve) => {
232
    var util = new cmsEditor.form()
233
    var arrayBlock = []
234
    
235
    cmsData.source.getDataList(path.dirname(documentLink), text, json)
236
      .then(() => {
237
        addSource(text, json, util)
238
239
        text = cmsData.source.removeDataList(text)
240
241
        if (!precontrib) {
242
          text = cmsTemplates.template.setAbeSlugDefaultValueIfDoesntExist(text)
243
          text = cmsTemplates.template.setAbePrecontribDefaultValueIfDoesntExist(text)
244
        }
245
246
        matchAttrAbe(text, json, util, arrayBlock)
247
        arrayBlock = []
248
        each(text, json, util, arrayBlock)
249
250
        if(typeof json.abe_meta !== 'undefined' && json.abe_meta !== null) {
251
          var links = json.abe_meta.link.split('/')
252
          var link = links.pop()
253
          json.abe_meta.cleanName = link.replace(/\..+$/, '')
254
          json.abe_meta.cleanFilename = links.join('/').replace(/\..+$/, '')
255
        }
256
257
        if (!precontrib) {
258
          // HOOKS beforeEditorFormBlocks
259
          json = abeExtend.hooks.instance.trigger('beforeEditorFormBlocks', json, text)
260
        }
261
262
        var blocks = orderBlock(util)
263
264
265
        if (!precontrib) {
266
          // HOOKS afterEditorFormBlocks
267
          blocks = abeExtend.hooks.instance.trigger('afterEditorFormBlocks', blocks, json, text)
268
        }
269
270
        abeEngine.instance.content = json
271
272
        resolve({
273
          text: text,
274
          form: blocks,
275
          json: json
276
        })
277
      }).catch(function(e) {
278
        console.error(e)
279
      })
280
  })
281
282
  return p
283
}