index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. /* @flow */
  2. import { decodeHTML } from 'entities'
  3. import { parseHTML } from './html-parser'
  4. import { parseText } from './text-parser'
  5. import { cached, no } from 'shared/util'
  6. import {
  7. pluckModuleFunction,
  8. getAndRemoveAttr,
  9. addProp,
  10. addAttr,
  11. addStaticAttr,
  12. addHandler,
  13. addDirective,
  14. getBindingAttr,
  15. baseWarn
  16. } from '../helpers'
  17. export const dirRE = /^v-|^@|^:/
  18. export const forAliasRE = /(.*)\s+(?:in|of)\s+(.*)/
  19. export const forIteratorRE = /\(([^,]*),([^,]*)(?:,([^,]*))?\)/
  20. const bindRE = /^:|^v-bind:/
  21. const onRE = /^@|^v-on:/
  22. const argRE = /:(.*)$/
  23. const modifierRE = /\.[^\.]+/g
  24. const decodeHTMLCached = cached(decodeHTML)
  25. // configurable state
  26. let warn
  27. let platformGetTagNamespace
  28. let platformMustUseProp
  29. let transforms
  30. let delimiters
  31. /**
  32. * Convert HTML string to AST.
  33. */
  34. export function parse (
  35. template: string,
  36. options: CompilerOptions
  37. ): ASTElement | void {
  38. warn = options.warn || baseWarn
  39. platformGetTagNamespace = options.getTagNamespace || no
  40. platformMustUseProp = options.mustUseProp || no
  41. transforms = pluckModuleFunction(options.modules, 'transformNode')
  42. delimiters = options.delimiters
  43. const stack = []
  44. const preserveWhitespace = options.preserveWhitespace !== false
  45. let root
  46. let currentParent
  47. let inPre = false
  48. let warned = false
  49. parseHTML(template, {
  50. expectHTML: options.expectHTML,
  51. isUnaryTag: options.isUnaryTag,
  52. start (tag, attrs, unary) {
  53. // check namespace.
  54. // inherit parent ns if there is one
  55. const ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag)
  56. // handle IE svg bug
  57. /* istanbul ignore if */
  58. if (options.isIE && ns === 'svg') {
  59. attrs = guardIESVGBug(attrs)
  60. }
  61. const element: ASTElement = {
  62. type: 1,
  63. tag,
  64. attrsList: attrs,
  65. attrsMap: makeAttrsMap(attrs),
  66. parent: currentParent,
  67. children: []
  68. }
  69. if (ns) {
  70. element.ns = ns
  71. }
  72. if (isForbiddenTag(element)) {
  73. element.forbidden = true
  74. process.env.NODE_ENV !== 'production' && warn(
  75. 'Templates should only be responsbile for mapping the state to the ' +
  76. 'UI. Avoid placing tags with side-effects in your templates, such as ' +
  77. `<${tag}>.`
  78. )
  79. }
  80. if (!inPre) {
  81. processPre(element)
  82. if (element.pre) {
  83. inPre = true
  84. }
  85. }
  86. if (inPre) {
  87. processRawAttrs(element)
  88. } else {
  89. processFor(element)
  90. processIf(element)
  91. processOnce(element)
  92. // determine whether this is a plain element after
  93. // removing structural attributes
  94. element.plain = !element.key && !attrs.length
  95. processKey(element)
  96. processRef(element)
  97. processSlot(element)
  98. processComponent(element)
  99. for (let i = 0; i < transforms.length; i++) {
  100. transforms[i](element, options)
  101. }
  102. processAttrs(element)
  103. }
  104. // tree management
  105. if (!root) {
  106. root = element
  107. // check root element constraints
  108. if (process.env.NODE_ENV !== 'production') {
  109. if (tag === 'slot' || tag === 'template') {
  110. warn(
  111. `Cannot use <${tag}> as component root element because it may ` +
  112. 'contain multiple nodes:\n' + template
  113. )
  114. }
  115. if (element.attrsMap.hasOwnProperty('v-for')) {
  116. warn(
  117. 'Cannot use v-for on stateful component root element because ' +
  118. 'it renders multiple elements:\n' + template
  119. )
  120. }
  121. }
  122. } else if (process.env.NODE_ENV !== 'production' && !stack.length && !warned) {
  123. warned = true
  124. warn(
  125. `Component template should contain exactly one root element:\n\n${template}`
  126. )
  127. }
  128. if (currentParent && !element.forbidden) {
  129. if (element.else) {
  130. processElse(element, currentParent)
  131. } else {
  132. currentParent.children.push(element)
  133. element.parent = currentParent
  134. }
  135. }
  136. if (!unary) {
  137. currentParent = element
  138. stack.push(element)
  139. }
  140. },
  141. end () {
  142. // remove trailing whitespace
  143. const element = stack[stack.length - 1]
  144. const lastNode = element.children[element.children.length - 1]
  145. if (lastNode && lastNode.type === 3 && lastNode.text === ' ') {
  146. element.children.pop()
  147. }
  148. // pop stack
  149. stack.length -= 1
  150. currentParent = stack[stack.length - 1]
  151. // check pre state
  152. if (element.pre) {
  153. inPre = false
  154. }
  155. },
  156. chars (text: string) {
  157. if (!currentParent) {
  158. if (process.env.NODE_ENV !== 'production' && !warned) {
  159. warned = true
  160. warn(
  161. 'Component template should contain exactly one root element:\n\n' + template
  162. )
  163. }
  164. return
  165. }
  166. text = currentParent.tag === 'pre' || text.trim()
  167. ? decodeHTMLCached(text)
  168. // only preserve whitespace if its not right after a starting tag
  169. : preserveWhitespace && currentParent.children.length ? ' ' : ''
  170. if (text) {
  171. let expression
  172. if (!inPre && text !== ' ' && (expression = parseText(text, delimiters))) {
  173. currentParent.children.push({
  174. type: 2,
  175. expression,
  176. text
  177. })
  178. } else {
  179. currentParent.children.push({
  180. type: 3,
  181. text
  182. })
  183. }
  184. }
  185. }
  186. })
  187. return root
  188. }
  189. function processPre (el) {
  190. if (getAndRemoveAttr(el, 'v-pre') != null) {
  191. el.pre = true
  192. }
  193. }
  194. function processRawAttrs (el) {
  195. const l = el.attrsList.length
  196. if (l) {
  197. const attrs = el.staticAttrs = new Array(l)
  198. for (let i = 0; i < l; i++) {
  199. attrs[i] = {
  200. name: el.attrsList[i].name,
  201. value: JSON.stringify(el.attrsList[i].value)
  202. }
  203. }
  204. } else if (!el.pre) {
  205. // non root node in pre blocks with no attributes
  206. el.plain = true
  207. }
  208. }
  209. function processKey (el) {
  210. const exp = getBindingAttr(el, 'key')
  211. if (exp) {
  212. el.key = exp
  213. }
  214. }
  215. function processRef (el) {
  216. const ref = getBindingAttr(el, 'ref')
  217. if (ref) {
  218. el.ref = ref
  219. let parent = el
  220. while (parent) {
  221. if (parent.for !== undefined) {
  222. el.refInFor = true
  223. break
  224. }
  225. parent = parent.parent
  226. }
  227. }
  228. }
  229. function processFor (el) {
  230. let exp
  231. if ((exp = getAndRemoveAttr(el, 'v-for'))) {
  232. const inMatch = exp.match(forAliasRE)
  233. if (!inMatch) {
  234. process.env.NODE_ENV !== 'production' && warn(
  235. `Invalid v-for expression: ${exp}`
  236. )
  237. return
  238. }
  239. el.for = inMatch[2].trim()
  240. const alias = inMatch[1].trim()
  241. const iteratorMatch = alias.match(forIteratorRE)
  242. if (iteratorMatch) {
  243. el.alias = iteratorMatch[1].trim()
  244. el.iterator1 = iteratorMatch[2].trim()
  245. if (iteratorMatch[3]) {
  246. el.iterator2 = iteratorMatch[3].trim()
  247. }
  248. } else {
  249. el.alias = alias
  250. }
  251. }
  252. }
  253. function processIf (el) {
  254. const exp = getAndRemoveAttr(el, 'v-if')
  255. if (exp) {
  256. el.if = exp
  257. }
  258. if (getAndRemoveAttr(el, 'v-else') != null) {
  259. el.else = true
  260. }
  261. }
  262. function processElse (el, parent) {
  263. const prev = findPrevElement(parent.children)
  264. if (prev && prev.if) {
  265. prev.elseBlock = el
  266. } else if (process.env.NODE_ENV !== 'production') {
  267. warn(
  268. `v-else used on element <${el.tag}> without corresponding v-if.`
  269. )
  270. }
  271. }
  272. function processOnce (el) {
  273. const once = getAndRemoveAttr(el, 'v-once')
  274. if (once != null) {
  275. el.once = true
  276. }
  277. }
  278. function processSlot (el) {
  279. if (el.tag === 'slot') {
  280. el.slotName = getBindingAttr(el, 'name')
  281. } else {
  282. const slotTarget = getBindingAttr(el, 'slot')
  283. if (slotTarget) {
  284. el.slotTarget = slotTarget
  285. }
  286. }
  287. }
  288. function processComponent (el) {
  289. let binding
  290. if ((binding = getBindingAttr(el, 'is'))) {
  291. el.component = binding
  292. }
  293. if (getAndRemoveAttr(el, 'keep-alive') != null) {
  294. el.keepAlive = true
  295. }
  296. if (getAndRemoveAttr(el, 'inline-template') != null) {
  297. el.inlineTemplate = true
  298. }
  299. }
  300. function processAttrs (el) {
  301. const list = el.attrsList
  302. let i, l, name, value, arg, modifiers
  303. for (i = 0, l = list.length; i < l; i++) {
  304. name = list[i].name
  305. value = list[i].value
  306. if (dirRE.test(name)) {
  307. // modifiers
  308. modifiers = parseModifiers(name)
  309. if (modifiers) {
  310. name = name.replace(modifierRE, '')
  311. }
  312. if (bindRE.test(name)) { // v-bind
  313. name = name.replace(bindRE, '')
  314. if (platformMustUseProp(name)) {
  315. addProp(el, name, value)
  316. } else {
  317. addAttr(el, name, value)
  318. }
  319. } else if (onRE.test(name)) { // v-on
  320. name = name.replace(onRE, '')
  321. addHandler(el, name, value, modifiers)
  322. } else { // normal directives
  323. name = name.replace(dirRE, '')
  324. // parse arg
  325. const argMatch = name.match(argRE)
  326. if (argMatch && (arg = argMatch[1])) {
  327. name = name.slice(0, -(arg.length + 1))
  328. }
  329. addDirective(el, name, value, arg, modifiers)
  330. }
  331. } else {
  332. // literal attribute
  333. if (process.env.NODE_ENV !== 'production') {
  334. const expression = parseText(value, delimiters)
  335. if (expression) {
  336. warn(
  337. `${name}="${value}": ` +
  338. 'Interpolation inside attributes has been deprecated. ' +
  339. 'Use v-bind or the colon shorthand instead.'
  340. )
  341. }
  342. }
  343. addStaticAttr(el, name, JSON.stringify(value))
  344. }
  345. }
  346. }
  347. function parseModifiers (name: string): Object | void {
  348. const match = name.match(modifierRE)
  349. if (match) {
  350. const ret = {}
  351. match.forEach(m => { ret[m.slice(1)] = true })
  352. return ret
  353. }
  354. }
  355. function makeAttrsMap (attrs: Array<Object>): Object {
  356. const map = {}
  357. for (let i = 0, l = attrs.length; i < l; i++) {
  358. if (process.env.NODE_ENV !== 'production' && map[attrs[i].name]) {
  359. warn('duplicate attribute: ' + attrs[i].name)
  360. }
  361. map[attrs[i].name] = attrs[i].value
  362. }
  363. return map
  364. }
  365. function findPrevElement (children: Array<any>): ASTElement | void {
  366. let i = children.length
  367. while (i--) {
  368. if (children[i].tag) return children[i]
  369. }
  370. }
  371. function isForbiddenTag (el): boolean {
  372. return (
  373. el.tag === 'style' ||
  374. (el.tag === 'script' && (
  375. !el.attrsMap.type ||
  376. el.attrsMap.type === 'text/javascript'
  377. ))
  378. )
  379. }
  380. const ieNSBug = /^xmlns:NS\d+/
  381. const ieNSPrefix = /^NS\d+:/
  382. /* istanbul ignore next */
  383. function guardIESVGBug (attrs) {
  384. const res = []
  385. for (let i = 0; i < attrs.length; i++) {
  386. const attr = attrs[i]
  387. if (!ieNSBug.test(attr.name)) {
  388. attr.name = attr.name.replace(ieNSPrefix, '')
  389. res.push(attr)
  390. }
  391. }
  392. return res
  393. }