index.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import { decodeHTML } from 'entities'
  2. import { parseHTML } from './html-parser'
  3. import { parseText } from './text-parser'
  4. import { addHandler } from '../helpers'
  5. import { hyphenate, makeMap } from '../../shared/util'
  6. const dirRE = /^v-|^@|^:/
  7. const bindRE = /^:|^v-bind:/
  8. const onRE = /^@|^v-on:/
  9. const argRE = /:(.*)$/
  10. const modifierRE = /\.[^\.]+/g
  11. const forAliasRE = /(.*)\s+(?:in|of)\s+(.*)/
  12. const forIteratorRE = /\((.*),(.*)\)/
  13. const camelRE = /[a-z\d][A-Z]/
  14. // attributes that should be using props for binding
  15. const mustUseProp = makeMap('value,selected,checked,muted')
  16. // this map covers SVG elements that can appear as template root nodes
  17. const isSVG = makeMap('svg,g,defs,symbol,use,image,text,circle,ellipse,line,path,polygon,polyline,rect', true)
  18. // make warning customizable depending on environment.
  19. let warn
  20. const baseWarn = msg => console.error(`[Vue parser]: ${msg}`)
  21. /**
  22. * Convert HTML string to AST
  23. *
  24. * @param {String} template
  25. * @param {Object} options
  26. * @return {Object}
  27. */
  28. export function parse (template, options) {
  29. options = options || {}
  30. warn = options.warn || baseWarn
  31. const stack = []
  32. let root
  33. let currentParent
  34. let inSvg = false
  35. let svgIndex = -1
  36. let warned = false
  37. parseHTML(template, {
  38. html5: true,
  39. start (tag, attrs, unary) {
  40. // check camelCase tag
  41. if (camelRE.test(tag)) {
  42. process.env.NODE_ENV !== 'production' && warn(
  43. `Found camelCase tag in template: <${tag}>. ` +
  44. `I've converted it to <${hyphenate(tag)}> for you.`
  45. )
  46. tag = hyphenate(tag)
  47. }
  48. tag = tag.toLowerCase()
  49. const element = {
  50. tag,
  51. plain: !attrs.length,
  52. attrsList: attrs,
  53. attrsMap: makeAttrsMap(attrs),
  54. parent: currentParent,
  55. children: []
  56. }
  57. // check svg
  58. if (inSvg) {
  59. element.svg = true
  60. } else if (isSVG(tag)) {
  61. element.svg = true
  62. inSvg = true
  63. svgIndex = stack.length
  64. }
  65. processFor(element)
  66. processIf(element)
  67. processRender(element)
  68. processSlot(element)
  69. processClassBinding(element)
  70. processStyleBinding(element)
  71. processAttributes(element)
  72. // tree management
  73. if (!root) {
  74. root = element
  75. } else if (process.env.NODE_ENV !== 'production' && !stack.length && !warned) {
  76. warned = true
  77. warn(
  78. `Component template should contain exactly one root element:\n\n${template}`
  79. )
  80. }
  81. if (currentParent && tag !== 'script') {
  82. if (element.else) {
  83. processElse(element, currentParent)
  84. } else {
  85. currentParent.children.push(element)
  86. }
  87. }
  88. if (!unary) {
  89. currentParent = element
  90. stack.push(element)
  91. }
  92. },
  93. end (tag) {
  94. // remove trailing whitespace
  95. const element = stack[stack.length - 1]
  96. const lastNode = element.children[element.children.length - 1]
  97. if (lastNode && lastNode.text === ' ') element.children.pop()
  98. // pop stack
  99. stack.length -= 1
  100. currentParent = stack[stack.length - 1]
  101. // check svg state
  102. if (inSvg && stack.length <= svgIndex) {
  103. inSvg = false
  104. svgIndex = -1
  105. }
  106. },
  107. chars (text) {
  108. if (!currentParent) {
  109. if (process.env.NODE_ENV !== 'production' && !warned) {
  110. warned = true
  111. warn(
  112. 'Component template should contain exactly one root element:\n\n' + template
  113. )
  114. }
  115. return
  116. }
  117. text = currentParent.tag === 'pre' || text.trim()
  118. ? decodeHTML(text)
  119. // only preserve whitespace if its not right after a starting tag
  120. : options.preserveWhitespace && currentParent.children.length
  121. ? ' '
  122. : null
  123. if (text) {
  124. let expression
  125. if (text !== ' ' && (expression = parseText(text))) {
  126. currentParent.children.push({ expression })
  127. } else {
  128. currentParent.children.push({ text })
  129. }
  130. }
  131. }
  132. })
  133. return root
  134. }
  135. function processFor (el) {
  136. let exp
  137. if ((exp = getAndRemoveAttr(el, 'v-for'))) {
  138. const inMatch = exp.match(forAliasRE)
  139. if (!inMatch) {
  140. process.env.NODE_ENV !== 'production' && warn(
  141. `Invalid v-for expression: ${exp}`
  142. )
  143. return
  144. }
  145. el.for = inMatch[2].trim()
  146. const alias = inMatch[1].trim()
  147. const iteratorMatch = alias.match(forIteratorRE)
  148. if (iteratorMatch) {
  149. el.iterator = iteratorMatch[1].trim()
  150. el.alias = iteratorMatch[2].trim()
  151. } else {
  152. el.alias = alias
  153. }
  154. if ((exp = getAndRemoveAttr(el, 'track-by'))) {
  155. el.key = exp === '$index'
  156. ? exp
  157. : el.alias + '["' + exp + '"]'
  158. }
  159. }
  160. }
  161. function processIf (el) {
  162. let exp = getAndRemoveAttr(el, 'v-if')
  163. if (exp) {
  164. el.if = exp
  165. }
  166. if (getAndRemoveAttr(el, 'v-else') != null) {
  167. el.else = true
  168. }
  169. }
  170. function processElse (el, parent) {
  171. const prev = findPrevElement(parent.children)
  172. if (prev && (prev.if || prev.attrsMap['v-show'])) {
  173. prev.elseBlock = el
  174. if (!prev.if) {
  175. parent.children.push(el)
  176. }
  177. } else if (process.env.NODE_ENV !== 'production') {
  178. warn(
  179. `v-else used on element <${el.tag}> without corresponding v-if/v-show.`
  180. )
  181. }
  182. }
  183. function processRender (el) {
  184. if (el.tag === 'render') {
  185. el.render = true
  186. el.method = el.attrsMap.method
  187. el.args = el.attrsMap.args
  188. if (process.env.NODE_ENV !== 'production' && !el.method) {
  189. warn('method attribute is required on <render>.')
  190. }
  191. }
  192. }
  193. function processSlot (el) {
  194. if (el.tag === 'slot') {
  195. el.name = el.attrsMap.name
  196. el.dynamicName =
  197. el.attrsMap[':name'] ||
  198. el.attrsMap['v-bind:name']
  199. }
  200. }
  201. function processClassBinding (el) {
  202. const staticClass = getAndRemoveAttr(el, 'class')
  203. el.staticClass = parseText(staticClass) || JSON.stringify(staticClass)
  204. el.classBinding =
  205. getAndRemoveAttr(el, ':class') ||
  206. getAndRemoveAttr(el, 'v-bind:class')
  207. }
  208. function processStyleBinding (el) {
  209. el.styleBinding =
  210. getAndRemoveAttr(el, ':style') ||
  211. getAndRemoveAttr(el, 'v-bind:style')
  212. }
  213. function processAttributes (el) {
  214. const list = el.attrsList
  215. let i, l, name, value, arg, modifiers
  216. for (i = 0, l = list.length; i < l; i++) {
  217. name = list[i].name
  218. value = list[i].value
  219. if (dirRE.test(name)) {
  220. // modifiers
  221. modifiers = parseModifiers(name)
  222. if (modifiers) {
  223. name = name.replace(modifierRE, '')
  224. }
  225. if (bindRE.test(name)) { // v-bind
  226. name = name.replace(bindRE, '')
  227. if (mustUseProp(name)) {
  228. (el.props || (el.props = [])).push({ name, value })
  229. } else {
  230. (el.attrs || (el.attrs = [])).push({ name, value })
  231. }
  232. } else if (onRE.test(name)) { // v-on
  233. name = name.replace(onRE, '')
  234. addHandler((el.events || (el.events = {})), name, value, modifiers)
  235. } else { // normal directives
  236. name = name.replace(dirRE, '')
  237. // parse arg
  238. if ((arg = name.match(argRE)) && (arg = arg[1])) {
  239. name = name.slice(0, -(arg.length + 1))
  240. }
  241. ;(el.directives || (el.directives = [])).push({
  242. name,
  243. value,
  244. arg,
  245. modifiers
  246. })
  247. }
  248. } else {
  249. // literal attribute
  250. (el.attrs || (el.attrs = [])).push({
  251. name,
  252. value: parseText(value) || JSON.stringify(value)
  253. })
  254. }
  255. }
  256. }
  257. function parseModifiers (name) {
  258. const match = name.match(modifierRE)
  259. if (match) {
  260. const ret = {}
  261. match.forEach(m => { ret[m.slice(1)] = true })
  262. return ret
  263. }
  264. }
  265. function makeAttrsMap (attrs) {
  266. const map = {}
  267. for (let i = 0, l = attrs.length; i < l; i++) {
  268. if (process.env.NODE_ENV !== 'production' && map[attrs[i].name]) {
  269. warn('duplicate attribute: ' + attrs[i].name)
  270. }
  271. map[attrs[i].name] = attrs[i].value
  272. }
  273. return map
  274. }
  275. function getAndRemoveAttr (el, attr) {
  276. let val
  277. if ((val = el.attrsMap[attr]) != null) {
  278. el.attrsMap[attr] = null
  279. const list = el.attrsList
  280. for (let i = 0, l = list.length; i < l; i++) {
  281. if (list[i].name === attr) {
  282. list.splice(i, 1)
  283. break
  284. }
  285. }
  286. }
  287. return val
  288. }
  289. function findPrevElement (children) {
  290. let i = children.length
  291. while (i--) {
  292. if (children[i].tag) return children[i]
  293. }
  294. }