1 |
|
2 | {TaskGroup} = require('taskgroup')
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 | balUtilHTML =
|
9 |
|
10 |
|
11 | getAttribute: (attributes,attribute) ->
|
12 | regex = new RegExp("""(#{attribute})\\s*=\\s*('[^']+'|\\"[^\\"]+\\"|[^'\\"\\s]\\S*)""",'ig')
|
13 | value = null
|
14 | while match = regex.exec(attributes)
|
15 | value = match[2].trim().replace(/(^['"]\s*|\s*['"]$)/g, '')
|
16 | return value
|
17 |
|
18 |
|
19 | detectIndentation: (source) ->
|
20 | result = /\n([ \t]*)\S/m.exec(source)
|
21 | indentation = result?[1] or ''
|
22 | return indentation
|
23 |
|
24 |
|
25 | removeIndentation: (source) ->
|
26 | indentation = balUtilHTML.detectIndentation(source)
|
27 | regexString = indentation.replace(/\t/g,'\\t')
|
28 | regex = new RegExp("""^#{regexString}""",'gm')
|
29 | result = source.replace(regex,'').trim()
|
30 | return result
|
31 |
|
32 |
|
33 |
|
34 |
|
35 | replaceElement: (args...) ->
|
36 |
|
37 | if args.length is 1
|
38 | {html, element, removeIndentation, replace} = args[0]
|
39 | else
|
40 | [html, element, replace] = args
|
41 |
|
42 |
|
43 | regex = new RegExp("""<(#{element}(?:\\:[-:_a-z0-9]+)?)(\\s+[^>]+)?>([\\s\\S]+?)<\\/\\1>""",'ig')
|
44 | result = html.replace regex, (outerHTML, element, attributes, innerHTML) ->
|
45 |
|
46 | innerHTML = balUtilHTML.removeIndentation(innerHTML) if removeIndentation isnt false
|
47 |
|
48 | return replace(outerHTML, element, attributes, innerHTML)
|
49 |
|
50 |
|
51 | return result
|
52 |
|
53 |
|
54 |
|
55 |
|
56 | replaceElementAsync: (args...) ->
|
57 |
|
58 | if args.length is 1
|
59 | {html, element, removeIndentation, replace, next} = args[0]
|
60 | else
|
61 | [html, element, replace, next] = args
|
62 |
|
63 |
|
64 | tasks = new TaskGroup(concurrency:0).done (err) ->
|
65 | return next(err) if err
|
66 | return next(null,result)
|
67 |
|
68 |
|
69 | result = balUtilHTML.replaceElement(
|
70 | html: html
|
71 | element: element
|
72 | removeIndentation: removeIndentation
|
73 | replace: (outerHTML, element, attributes, innerHTML) ->
|
74 |
|
75 | random = Math.random()
|
76 |
|
77 |
|
78 | tasks.addTask (complete) ->
|
79 | replace outerHTML, element, attributes, innerHTML, (err,replaceElementResult) ->
|
80 | return complete(err) if err
|
81 | result = result.replace(random,replaceElementResult)
|
82 | return complete()
|
83 |
|
84 |
|
85 | return random
|
86 | )
|
87 |
|
88 |
|
89 | tasks.run()
|
90 |
|
91 |
|
92 | @
|
93 |
|
94 |
|
95 |
|
96 |
|
97 |
|
98 | module.exports = balUtilHTML |
\ | No newline at end of file |