for.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. var _ = require('../../util')
  2. var FragmentFactory = require('../../fragment/factory')
  3. var isObject = _.isObject
  4. var uid = 0
  5. module.exports = {
  6. priority: 2000,
  7. bind: function () {
  8. // support "item in items" syntax
  9. var inMatch = this.expression.match(/(.*) in (.*)/)
  10. if (inMatch) {
  11. var itMatch = inMatch[1].match(/\((.*),(.*)\)/)
  12. if (itMatch) {
  13. this.iterator = itMatch[1].trim()
  14. this.alias = itMatch[2].trim()
  15. } else {
  16. this.alias = inMatch[1].trim()
  17. }
  18. this.expression = inMatch[2]
  19. }
  20. if (!this.alias) {
  21. process.env.NODE_ENV !== 'production' && _.warn(
  22. 'Alias is required in v-for.'
  23. )
  24. return
  25. }
  26. // uid as a cache identifier
  27. this.id = '__v-for__' + (++uid)
  28. // check if this is an option list,
  29. // so that we know if we need to update the <select>'s
  30. // v-model when the option list has changed.
  31. // because v-model has a lower priority than v-for,
  32. // the v-model is not bound here yet, so we have to
  33. // retrive it in the actual updateModel() function.
  34. var tag = this.el.tagName
  35. this.isOption =
  36. (tag === 'OPTION' || tag === 'OPTGROUP') &&
  37. this.el.parentNode.tagName === 'SELECT'
  38. // setup anchor nodes
  39. this.start = _.createAnchor('v-for-start')
  40. this.end = _.createAnchor('v-for-end')
  41. _.replace(this.el, this.end)
  42. _.before(this.start, this.end)
  43. // check for trackby param
  44. this.idKey = this.param('track-by')
  45. // check ref
  46. this.ref = _.findRef(this.el)
  47. // check for transition stagger
  48. var stagger = +this.param('stagger')
  49. this.enterStagger = +this.param('enter-stagger') || stagger
  50. this.leaveStagger = +this.param('leave-stagger') || stagger
  51. // cache
  52. this.cache = Object.create(null)
  53. // fragment factory
  54. this.factory = new FragmentFactory(this.vm, this.el)
  55. },
  56. update: function (data) {
  57. this.diff(data)
  58. this.updateRef()
  59. this.updateModel()
  60. },
  61. /**
  62. * Diff, based on new data and old data, determine the
  63. * minimum amount of DOM manipulations needed to make the
  64. * DOM reflect the new data Array.
  65. *
  66. * The algorithm diffs the new data Array by storing a
  67. * hidden reference to an owner vm instance on previously
  68. * seen data. This allows us to achieve O(n) which is
  69. * better than a levenshtein distance based algorithm,
  70. * which is O(m * n).
  71. *
  72. * @param {Array} data
  73. */
  74. diff: function (data) {
  75. // check if the Array was converted from an Object
  76. var item = data[0]
  77. var convertedFromObject = this.fromObject =
  78. isObject(item) &&
  79. item.hasOwnProperty('$key') &&
  80. item.hasOwnProperty('$value')
  81. var idKey = this.idKey
  82. var oldFrags = this.frags
  83. var frags = this.frags = new Array(data.length)
  84. var alias = this.alias
  85. var iterator = this.iterator
  86. var start = this.start
  87. var end = this.end
  88. var inDoc = _.inDoc(start)
  89. var init = !oldFrags
  90. var i, l, frag, key, value, primitive
  91. // First pass, go through the new Array and fill up
  92. // the new frags array. If a piece of data has a cached
  93. // instance for it, we reuse it. Otherwise build a new
  94. // instance.
  95. for (i = 0, l = data.length; i < l; i++) {
  96. item = data[i]
  97. key = convertedFromObject ? item.$key : null
  98. value = convertedFromObject ? item.$value : item
  99. primitive = !isObject(value)
  100. frag = !init && this.getCachedFrag(value, i, key)
  101. if (frag) { // reusable fragment
  102. frag.reused = true
  103. // update $index
  104. frag.scope.$index = i
  105. // update $key
  106. if (key) {
  107. frag.scope.$key = key
  108. if (iterator) {
  109. frag.scope[iterator] = key
  110. }
  111. }
  112. // update data for track-by, object repeat &
  113. // primitive values.
  114. if (idKey || convertedFromObject || primitive) {
  115. frag.scope[alias] = value
  116. }
  117. } else { // new isntance
  118. frag = this.create(value, alias, i, key)
  119. frag.fresh = !init
  120. }
  121. frags[i] = frag
  122. if (init) {
  123. frag.before(end)
  124. }
  125. }
  126. // we're done for the initial render.
  127. if (init) {
  128. return
  129. }
  130. // Second pass, go through the old fragments and
  131. // destroy those who are not reused (and remove them
  132. // from cache)
  133. var removalIndex = 0
  134. var totalRemoved = oldFrags.length - frags.length
  135. for (i = 0, l = oldFrags.length; i < l; i++) {
  136. frag = oldFrags[i]
  137. if (!frag.reused) {
  138. this.deleteCachedFrag(frag)
  139. this.remove(frag, removalIndex++, totalRemoved, inDoc)
  140. }
  141. }
  142. // Final pass, move/insert new fragments into the
  143. // right place.
  144. var targetPrev, prevEl, currentPrev
  145. var insertionIndex = 0
  146. for (i = 0, l = frags.length; i < l; i++) {
  147. frag = frags[i]
  148. // this is the frag that we should be after
  149. targetPrev = frags[i - 1]
  150. prevEl = targetPrev
  151. ? targetPrev.staggerCb
  152. ? targetPrev.staggerAnchor
  153. : targetPrev.end || targetPrev.node
  154. : start
  155. if (frag.reused && !frag.staggerCb) {
  156. currentPrev = findPrevFrag(frag, start, this.id)
  157. if (currentPrev !== targetPrev) {
  158. this.move(frag, prevEl)
  159. }
  160. } else {
  161. // new instance, or still in stagger.
  162. // insert with updated stagger index.
  163. this.insert(frag, insertionIndex++, prevEl, inDoc)
  164. }
  165. frag.reused = frag.fresh = false
  166. }
  167. },
  168. /**
  169. * Create a new fragment instance.
  170. *
  171. * @param {*} value
  172. * @param {String} alias
  173. * @param {Number} index
  174. * @param {String} [key]
  175. * @return {Fragment}
  176. */
  177. create: function (value, alias, index, key) {
  178. var host = this._host
  179. // create iteration scope
  180. var parentScope = this._scope || this.vm
  181. var scope = Object.create(parentScope)
  182. // ref holder for the scope
  183. scope.$refs = {}
  184. scope.$els = {}
  185. // make sure point $parent to parent scope
  186. scope.$parent = parentScope
  187. // for two-way binding on alias
  188. scope.$forContext = this
  189. // define scope properties
  190. _.defineReactive(scope, alias, value)
  191. _.defineReactive(scope, '$index', index)
  192. if (key) {
  193. _.defineReactive(scope, '$key', key)
  194. } else if (scope.$key) {
  195. // avoid accidental fallback
  196. _.define(scope, '$key', null)
  197. }
  198. if (this.iterator) {
  199. _.defineReactive(scope, this.iterator, key || index)
  200. }
  201. var frag = this.factory.create(host, scope, this._frag)
  202. frag.forId = this.id
  203. this.cacheFrag(value, frag, index, key)
  204. return frag
  205. },
  206. /**
  207. * Update the v-ref on owner vm.
  208. */
  209. updateRef: function () {
  210. var ref = this.ref
  211. if (!ref) return
  212. var hash = (this._scope || this.vm).$refs
  213. var refs
  214. if (!this.fromObject) {
  215. refs = this.frags.map(findVmFromFrag)
  216. } else {
  217. refs = {}
  218. this.frags.forEach(function (frag) {
  219. refs[frag.scope.$key] = findVmFromFrag(frag)
  220. })
  221. }
  222. if (!hash.hasOwnProperty(ref)) {
  223. _.defineReactive(hash, ref, refs)
  224. } else {
  225. hash[ref] = refs
  226. }
  227. },
  228. /**
  229. * For option lists, update the containing v-model on
  230. * parent <select>.
  231. */
  232. updateModel: function () {
  233. if (this.isOption) {
  234. var parent = this.start.parentNode
  235. var model = parent && parent.__v_model
  236. if (model) {
  237. model.forceUpdate()
  238. }
  239. }
  240. },
  241. /**
  242. * Insert a fragment. Handles staggering.
  243. *
  244. * @param {Fragment} frag
  245. * @param {Number} index
  246. * @param {Node} prevEl
  247. * @param {Boolean} inDoc
  248. */
  249. insert: function (frag, index, prevEl, inDoc) {
  250. if (frag.staggerCb) {
  251. frag.staggerCb.cancel()
  252. frag.staggerCb = null
  253. }
  254. var staggerAmount = this.getStagger(frag, index, null, 'enter')
  255. if (inDoc && staggerAmount) {
  256. // create an anchor and insert it synchronously,
  257. // so that we can resolve the correct order without
  258. // worrying about some elements not inserted yet
  259. var anchor = frag.staggerAnchor
  260. if (!anchor) {
  261. anchor = frag.staggerAnchor = _.createAnchor('stagger-anchor')
  262. anchor.__vfrag__ = frag
  263. }
  264. _.after(anchor, prevEl)
  265. var op = frag.staggerCb = _.cancellable(function () {
  266. frag.staggerCb = null
  267. frag.before(anchor)
  268. _.remove(anchor)
  269. })
  270. setTimeout(op, staggerAmount)
  271. } else {
  272. frag.before(prevEl.nextSibling)
  273. }
  274. },
  275. /**
  276. * Remove a fragment. Handles staggering.
  277. *
  278. * @param {Fragment} frag
  279. * @param {Number} index
  280. * @param {Number} total
  281. * @param {Boolean} inDoc
  282. */
  283. remove: function (frag, index, total, inDoc) {
  284. if (frag.staggerCb) {
  285. frag.staggerCb.cancel()
  286. frag.staggerCb = null
  287. // it's not possible for the same frag to be removed
  288. // twice, so if we have a pending stagger callback,
  289. // it means this frag is queued for enter but removed
  290. // before its transition started. Since it is already
  291. // destroyed, we can just leave it in detached state.
  292. return
  293. }
  294. var staggerAmount = this.getStagger(frag, index, total, 'leave')
  295. if (inDoc && staggerAmount) {
  296. var op = frag.staggerCb = _.cancellable(function () {
  297. frag.staggerCb = null
  298. frag.remove(true)
  299. })
  300. setTimeout(op, staggerAmount)
  301. } else {
  302. frag.remove(true)
  303. }
  304. },
  305. /**
  306. * Move a fragment to a new position.
  307. * Force no transition.
  308. *
  309. * @param {Fragment} frag
  310. * @param {Node} prevEl
  311. */
  312. move: function (frag, prevEl) {
  313. frag.before(prevEl.nextSibling, false)
  314. },
  315. /**
  316. * Cache a fragment using track-by or the object key.
  317. *
  318. * @param {*} value
  319. * @param {Fragment} frag
  320. * @param {Number} index
  321. * @param {String} [key]
  322. */
  323. cacheFrag: function (value, frag, index, key) {
  324. var idKey = this.idKey
  325. var cache = this.cache
  326. var primitive = !isObject(value)
  327. var id
  328. if (key || idKey || primitive) {
  329. id = idKey
  330. ? idKey === '$index'
  331. ? index
  332. : value[idKey]
  333. : (key || value)
  334. if (!cache[id]) {
  335. cache[id] = frag
  336. } else if (idKey !== '$index') {
  337. process.env.NODE_ENV !== 'production' &&
  338. this.warnDuplicate(value)
  339. }
  340. } else {
  341. id = this.id
  342. if (value.hasOwnProperty(id)) {
  343. if (value[id] === null) {
  344. value[id] = frag
  345. } else {
  346. process.env.NODE_ENV !== 'production' &&
  347. this.warnDuplicate(value)
  348. }
  349. } else {
  350. _.define(value, id, frag)
  351. }
  352. }
  353. frag.raw = value
  354. },
  355. /**
  356. * Get a cached fragment from the value/index/key
  357. *
  358. * @param {*} value
  359. * @param {Number} index
  360. * @param {String} key
  361. * @return {Fragment}
  362. */
  363. getCachedFrag: function (value, index, key) {
  364. var idKey = this.idKey
  365. var primitive = !isObject(value)
  366. var frag
  367. if (key || idKey || primitive) {
  368. var id = idKey
  369. ? idKey === '$index'
  370. ? index
  371. : value[idKey]
  372. : (key || value)
  373. frag = this.cache[id]
  374. } else {
  375. frag = value[this.id]
  376. }
  377. if (frag && (frag.reused || frag.fresh)) {
  378. process.env.NODE_ENV !== 'production' &&
  379. this.warnDuplicate(value)
  380. }
  381. return frag
  382. },
  383. /**
  384. * Delete a fragment from cache.
  385. *
  386. * @param {Fragment} frag
  387. */
  388. deleteCachedFrag: function (frag) {
  389. var value = frag.raw
  390. var idKey = this.idKey
  391. var scope = frag.scope
  392. var index = scope.$index
  393. // fix #948: avoid accidentally fall through to
  394. // a parent repeater which happens to have $key.
  395. var key = scope.hasOwnProperty('$key') && scope.$key
  396. var primitive = !isObject(value)
  397. if (idKey || key || primitive) {
  398. var id = idKey
  399. ? idKey === '$index'
  400. ? index
  401. : value[idKey]
  402. : (key || value)
  403. this.cache[id] = null
  404. } else {
  405. value[this.id] = null
  406. frag.raw = null
  407. }
  408. },
  409. /**
  410. * Get the stagger amount for an insertion/removal.
  411. *
  412. * @param {Fragment} frag
  413. * @param {Number} index
  414. * @param {Number} total
  415. * @param {String} type
  416. */
  417. getStagger: function (frag, index, total, type) {
  418. type = type + 'Stagger'
  419. var trans = frag.node.__v_trans
  420. var hooks = trans && trans.hooks
  421. var hook = hooks && (hooks[type] || hooks.stagger)
  422. return hook
  423. ? hook.call(frag, index, total)
  424. : index * this[type]
  425. },
  426. /**
  427. * Pre-process the value before piping it through the
  428. * filters. This is passed to and called by the watcher.
  429. */
  430. _preProcess: function (value) {
  431. // regardless of type, store the un-filtered raw value.
  432. this.rawValue = value
  433. return value
  434. },
  435. /**
  436. * Post-process the value after it has been piped through
  437. * the filters. This is passed to and called by the watcher.
  438. *
  439. * It is necessary for this to be called during the
  440. * wathcer's dependency collection phase because we want
  441. * the v-for to update when the source Object is mutated.
  442. */
  443. _postProcess: function (value) {
  444. if (_.isArray(value)) {
  445. return value
  446. } else if (_.isPlainObject(value)) {
  447. // convert plain object to array.
  448. var keys = Object.keys(value)
  449. var i = keys.length
  450. var res = new Array(i)
  451. var key
  452. while (i--) {
  453. key = keys[i]
  454. res[i] = {
  455. $key: key,
  456. $value: value[key]
  457. }
  458. }
  459. return res
  460. } else {
  461. var type = typeof value
  462. if (type === 'number') {
  463. value = range(value)
  464. } else if (type === 'string') {
  465. value = _.toArray(value)
  466. }
  467. return value || []
  468. }
  469. },
  470. unbind: function () {
  471. if (this.ref) {
  472. (this._scope || this.vm).$refs[this.ref] = null
  473. }
  474. if (this.frags) {
  475. var i = this.frags.length
  476. var frag
  477. while (i--) {
  478. frag = this.frags[i]
  479. this.deleteCachedFrag(frag)
  480. frag.destroy()
  481. }
  482. }
  483. }
  484. }
  485. /**
  486. * Helper to find the previous element that is a fragment
  487. * anchor. This is necessary because a destroyed frag's
  488. * element could still be lingering in the DOM before its
  489. * leaving transition finishes, but its inserted flag
  490. * should have been set to false so we can skip them.
  491. *
  492. * If this is a block repeat, we want to make sure we only
  493. * return frag that is bound to this v-for. (see #929)
  494. *
  495. * @param {Fragment} frag
  496. * @param {Comment|Text} anchor
  497. * @param {String} id
  498. * @return {Fragment}
  499. */
  500. function findPrevFrag (frag, anchor, id) {
  501. var el = frag.node.previousSibling
  502. /* istanbul ignore if */
  503. if (!el) return
  504. frag = el.__vfrag__
  505. while (
  506. (!frag || frag.forId !== id || !frag.inserted) &&
  507. el !== anchor
  508. ) {
  509. el = el.previousSibling
  510. /* istanbul ignore if */
  511. if (!el) return
  512. frag = el.__vfrag__
  513. }
  514. return frag
  515. }
  516. /**
  517. * Find a vm from a fragment.
  518. *
  519. * @param {Fragment} frag
  520. * @return {Vue|undefined}
  521. */
  522. function findVmFromFrag (frag) {
  523. return frag.node.__vue__ || frag.node.nextSibling.__vue__
  524. }
  525. /**
  526. * Create a range array from given number.
  527. *
  528. * @param {Number} n
  529. * @return {Array}
  530. */
  531. function range (n) {
  532. var i = -1
  533. var ret = new Array(n)
  534. while (++i < n) {
  535. ret[i] = i
  536. }
  537. return ret
  538. }
  539. if (process.env.NODE_ENV !== 'production') {
  540. module.exports.warnDuplicate = function (value) {
  541. _.warn(
  542. 'Duplicate value found in v-for="' + this.descriptor.raw + '": ' +
  543. JSON.stringify(value) + '. Use track-by="$index" if ' +
  544. 'you are expecting duplicate values.'
  545. )
  546. }
  547. }