repeat.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. var _ = require('../util')
  2. var isObject = _.isObject
  3. var isPlainObject = _.isPlainObject
  4. var textParser = require('../parsers/text')
  5. var expParser = require('../parsers/expression')
  6. var templateParser = require('../parsers/template')
  7. var compiler = require('../compiler')
  8. var uid = 0
  9. // async component resolution states
  10. var UNRESOLVED = 0
  11. var PENDING = 1
  12. var RESOLVED = 2
  13. var ABORTED = 3
  14. module.exports = {
  15. /**
  16. * Setup.
  17. */
  18. bind: function () {
  19. // uid as a cache identifier
  20. this.id = '__v_repeat_' + (++uid)
  21. // setup anchor nodes
  22. this.start = _.createAnchor('v-repeat-start')
  23. this.end = _.createAnchor('v-repeat')
  24. _.replace(this.el, this.end)
  25. _.before(this.start, this.end)
  26. // check if this is a block repeat
  27. this.template = _.isTemplate(this.el)
  28. ? templateParser.parse(this.el, true)
  29. : this.el
  30. // check other directives that need to be handled
  31. // at v-repeat level
  32. this.checkIf()
  33. this.checkRef()
  34. this.checkComponent()
  35. // check for trackby param
  36. this.idKey =
  37. this._checkParam('track-by') ||
  38. this._checkParam('trackby') // 0.11.0 compat
  39. // check for transition stagger
  40. var stagger = +this._checkParam('stagger')
  41. this.enterStagger = +this._checkParam('enter-stagger') || stagger
  42. this.leaveStagger = +this._checkParam('leave-stagger') || stagger
  43. this.cache = Object.create(null)
  44. },
  45. /**
  46. * Warn against v-if usage.
  47. */
  48. checkIf: function () {
  49. if (_.attr(this.el, 'if') !== null) {
  50. _.warn(
  51. 'Don\'t use v-if with v-repeat. ' +
  52. 'Use v-show or the "filterBy" filter instead.'
  53. )
  54. }
  55. },
  56. /**
  57. * Check if v-ref/ v-el is also present.
  58. */
  59. checkRef: function () {
  60. var refID = _.attr(this.el, 'ref')
  61. this.refID = refID
  62. ? this.vm.$interpolate(refID)
  63. : null
  64. var elId = _.attr(this.el, 'el')
  65. this.elId = elId
  66. ? this.vm.$interpolate(elId)
  67. : null
  68. },
  69. /**
  70. * Check the component constructor to use for repeated
  71. * instances. If static we resolve it now, otherwise it
  72. * needs to be resolved at build time with actual data.
  73. */
  74. checkComponent: function () {
  75. this.componentState = UNRESOLVED
  76. var options = this.vm.$options
  77. var id = _.checkComponent(this.el, options)
  78. if (!id) {
  79. // default constructor
  80. this.Ctor = _.Vue
  81. // inline repeats should inherit
  82. this.inherit = true
  83. // important: transclude with no options, just
  84. // to ensure block start and block end
  85. this.template = compiler.transclude(this.template)
  86. var copy = _.extend({}, options)
  87. copy._asComponent = false
  88. this._linkFn = compiler.compile(this.template, copy)
  89. } else {
  90. this.Ctor = null
  91. this.asComponent = true
  92. // check inline-template
  93. if (this._checkParam('inline-template') !== null) {
  94. // extract inline template as a DocumentFragment
  95. this.inlineTempalte = _.extractContent(this.el, true)
  96. }
  97. var tokens = textParser.parse(id)
  98. if (tokens) {
  99. // dynamic component to be resolved later
  100. var ctorExp = textParser.tokensToExp(tokens)
  101. this.ctorGetter = expParser.parse(ctorExp).get
  102. } else {
  103. // static
  104. this.componentId = id
  105. this.pendingData = null
  106. }
  107. }
  108. },
  109. resolveComponent: function () {
  110. this.componentState = PENDING
  111. this.vm._resolveComponent(this.componentId, _.bind(function (Ctor) {
  112. if (this.componentState === ABORTED) {
  113. return
  114. }
  115. this.Ctor = Ctor
  116. this.componentState = RESOLVED
  117. this.realUpdate(this.pendingData)
  118. this.pendingData = null
  119. }, this))
  120. },
  121. /**
  122. * Resolve a dynamic component to use for an instance.
  123. * The tricky part here is that there could be dynamic
  124. * components depending on instance data.
  125. *
  126. * @param {Object} data
  127. * @param {Object} meta
  128. * @return {Function}
  129. */
  130. resolveDynamicComponent: function (data, meta) {
  131. // create a temporary context object and copy data
  132. // and meta properties onto it.
  133. // use _.define to avoid accidentally overwriting scope
  134. // properties.
  135. var context = Object.create(this.vm)
  136. var key
  137. for (key in data) {
  138. _.define(context, key, data[key])
  139. }
  140. for (key in meta) {
  141. _.define(context, key, meta[key])
  142. }
  143. var id = this.ctorGetter.call(context, context)
  144. var Ctor = _.resolveAsset(this.vm.$options, 'components', id)
  145. _.assertAsset(Ctor, 'component', id)
  146. if (!Ctor.options) {
  147. _.warn(
  148. 'Async resolution is not supported for v-repeat ' +
  149. '+ dynamic component. (component: ' + id + ')'
  150. )
  151. return _.Vue
  152. }
  153. return Ctor
  154. },
  155. /**
  156. * Update.
  157. * This is called whenever the Array mutates. If we have
  158. * a component, we might need to wait for it to resolve
  159. * asynchronously.
  160. *
  161. * @param {Array|Number|String} data
  162. */
  163. update: function (data) {
  164. if (this.componentId) {
  165. var state = this.componentState
  166. if (state === UNRESOLVED) {
  167. this.pendingData = data
  168. // once resolved, it will call realUpdate
  169. this.resolveComponent()
  170. } else if (state === PENDING) {
  171. this.pendingData = data
  172. } else if (state === RESOLVED) {
  173. this.realUpdate(data)
  174. }
  175. } else {
  176. this.realUpdate(data)
  177. }
  178. },
  179. /**
  180. * The real update that actually modifies the DOM.
  181. *
  182. * @param {Array|Number|String} data
  183. */
  184. realUpdate: function (data) {
  185. this.vms = this.diff(data, this.vms)
  186. // update v-ref
  187. if (this.refID) {
  188. this.vm.$[this.refID] = this.converted
  189. ? toRefObject(this.vms)
  190. : this.vms
  191. }
  192. if (this.elId) {
  193. this.vm.$$[this.elId] = this.vms.map(function (vm) {
  194. return vm.$el
  195. })
  196. }
  197. },
  198. /**
  199. * Diff, based on new data and old data, determine the
  200. * minimum amount of DOM manipulations needed to make the
  201. * DOM reflect the new data Array.
  202. *
  203. * The algorithm diffs the new data Array by storing a
  204. * hidden reference to an owner vm instance on previously
  205. * seen data. This allows us to achieve O(n) which is
  206. * better than a levenshtein distance based algorithm,
  207. * which is O(m * n).
  208. *
  209. * @param {Array} data
  210. * @param {Array} oldVms
  211. * @return {Array}
  212. */
  213. diff: function (data, oldVms) {
  214. var idKey = this.idKey
  215. var converted = this.converted
  216. var start = this.start
  217. var end = this.end
  218. var inDoc = _.inDoc(start)
  219. var alias = this.arg
  220. var init = !oldVms
  221. var vms = new Array(data.length)
  222. var obj, raw, vm, i, l, primitive
  223. // First pass, go through the new Array and fill up
  224. // the new vms array. If a piece of data has a cached
  225. // instance for it, we reuse it. Otherwise build a new
  226. // instance.
  227. for (i = 0, l = data.length; i < l; i++) {
  228. obj = data[i]
  229. raw = converted ? obj.$value : obj
  230. primitive = !isObject(raw)
  231. vm = !init && this.getVm(raw, i, converted ? obj.$key : null)
  232. if (vm) { // reusable instance
  233. vm._reused = true
  234. vm.$index = i // update $index
  235. // update data for track-by or object repeat,
  236. // since in these two cases the data is replaced
  237. // rather than mutated.
  238. if (idKey || converted || primitive) {
  239. if (alias) {
  240. vm[alias] = raw
  241. } else if (_.isPlainObject(raw)) {
  242. vm.$data = raw
  243. } else {
  244. vm.$value = raw
  245. }
  246. }
  247. } else { // new instance
  248. vm = this.build(obj, i, true)
  249. vm._reused = false
  250. }
  251. vms[i] = vm
  252. // insert if this is first run
  253. if (init) {
  254. vm.$before(end)
  255. }
  256. }
  257. // if this is the first run, we're done.
  258. if (init) {
  259. return vms
  260. }
  261. // Second pass, go through the old vm instances and
  262. // destroy those who are not reused (and remove them
  263. // from cache)
  264. var removalIndex = 0
  265. var totalRemoved = oldVms.length - vms.length
  266. for (i = 0, l = oldVms.length; i < l; i++) {
  267. vm = oldVms[i]
  268. if (!vm._reused) {
  269. this.uncacheVm(vm)
  270. vm.$destroy(false, true) // defer cleanup until removal
  271. this.remove(vm, removalIndex++, totalRemoved, inDoc)
  272. }
  273. }
  274. // final pass, move/insert new instances into the
  275. // right place.
  276. var targetPrev, prevEl, currentPrev
  277. var insertionIndex = 0
  278. for (i = 0, l = vms.length; i < l; i++) {
  279. vm = vms[i]
  280. // this is the vm that we should be after
  281. targetPrev = vms[i - 1]
  282. prevEl = targetPrev
  283. ? targetPrev._staggerCb
  284. ? targetPrev._staggerAnchor
  285. : targetPrev._blockEnd || targetPrev.$el
  286. : start
  287. if (vm._reused && !vm._staggerCb) {
  288. currentPrev = findPrevVm(vm, start)
  289. if (currentPrev !== targetPrev) {
  290. this.move(vm, prevEl)
  291. }
  292. } else {
  293. // new instance, or still in stagger.
  294. // insert with updated stagger index.
  295. this.insert(vm, insertionIndex++, prevEl, inDoc)
  296. }
  297. vm._reused = false
  298. }
  299. return vms
  300. },
  301. /**
  302. * Build a new instance and cache it.
  303. *
  304. * @param {Object} data
  305. * @param {Number} index
  306. * @param {Boolean} needCache
  307. */
  308. build: function (data, index, needCache) {
  309. var meta = { $index: index }
  310. if (this.converted) {
  311. meta.$key = data.$key
  312. }
  313. var raw = this.converted ? data.$value : data
  314. var alias = this.arg
  315. if (alias) {
  316. data = {}
  317. data[alias] = raw
  318. } else if (!isPlainObject(raw)) {
  319. // non-object values
  320. data = {}
  321. meta.$value = raw
  322. } else {
  323. // default
  324. data = raw
  325. }
  326. // resolve constructor
  327. var Ctor = this.Ctor || this.resolveDynamicComponent(data, meta)
  328. var vm = this.vm.$addChild({
  329. el: templateParser.clone(this.template),
  330. data: data,
  331. inherit: this.inherit,
  332. template: this.inlineTempalte,
  333. // repeater meta, e.g. $index, $key
  334. _meta: meta,
  335. // mark this as an inline-repeat instance
  336. _repeat: this.inherit,
  337. // is this a component?
  338. _asComponent: this.asComponent,
  339. // linker cachable if no inline-template
  340. _linkerCachable: !this.inlineTempalte,
  341. // transclusion host
  342. _host: this._host,
  343. // pre-compiled linker for simple repeats
  344. _linkFn: this._linkFn,
  345. }, Ctor)
  346. // cache instance
  347. if (needCache) {
  348. this.cacheVm(raw, vm, index, this.converted ? meta.$key : null)
  349. }
  350. // sync back changes for two-way bindings of primitive values
  351. var type = typeof raw
  352. var dir = this
  353. if (
  354. this.rawType === 'object' &&
  355. (type === 'string' || type === 'number')
  356. ) {
  357. vm.$watch(alias || '$value', function (val) {
  358. if (dir.filters) {
  359. _.warn(
  360. 'You seem to be mutating the $value reference of ' +
  361. 'a v-repeat instance (likely through v-model) ' +
  362. 'and filtering the v-repeat at the same time. ' +
  363. 'This will not work properly with an Array of ' +
  364. 'primitive values. Please use an Array of ' +
  365. 'Objects instead.'
  366. )
  367. }
  368. dir._withLock(function () {
  369. if (dir.converted) {
  370. dir.rawValue[vm.$key] = val
  371. } else {
  372. dir.rawValue.$set(vm.$index, val)
  373. }
  374. })
  375. })
  376. }
  377. return vm
  378. },
  379. /**
  380. * Unbind, teardown everything
  381. */
  382. unbind: function () {
  383. this.componentState = ABORTED
  384. if (this.refID) {
  385. this.vm.$[this.refID] = null
  386. }
  387. if (this.vms) {
  388. var i = this.vms.length
  389. var vm
  390. while (i--) {
  391. vm = this.vms[i]
  392. this.uncacheVm(vm)
  393. vm.$destroy()
  394. }
  395. }
  396. },
  397. /**
  398. * Cache a vm instance based on its data.
  399. *
  400. * If the data is an object, we save the vm's reference on
  401. * the data object as a hidden property. Otherwise we
  402. * cache them in an object and for each primitive value
  403. * there is an array in case there are duplicates.
  404. *
  405. * @param {Object} data
  406. * @param {Vue} vm
  407. * @param {Number} index
  408. * @param {String} [key]
  409. */
  410. cacheVm: function (data, vm, index, key) {
  411. var idKey = this.idKey
  412. var cache = this.cache
  413. var primitive = !isObject(data)
  414. var id
  415. if (key || idKey || primitive) {
  416. id = idKey
  417. ? idKey === '$index'
  418. ? index
  419. : data[idKey]
  420. : (key || index)
  421. if (!cache[id]) {
  422. cache[id] = vm
  423. } else if (!primitive && idKey !== '$index') {
  424. _.warn('Duplicate track-by key in v-repeat: ' + id)
  425. }
  426. } else {
  427. id = this.id
  428. if (data.hasOwnProperty(id)) {
  429. if (data[id] === null) {
  430. data[id] = vm
  431. } else {
  432. _.warn(
  433. 'Duplicate objects are not supported in v-repeat ' +
  434. 'when using components or transitions.'
  435. )
  436. }
  437. } else {
  438. _.define(data, id, vm)
  439. }
  440. }
  441. vm._raw = data
  442. },
  443. /**
  444. * Try to get a cached instance from a piece of data.
  445. *
  446. * @param {Object} data
  447. * @param {Number} index
  448. * @param {String} [key]
  449. * @return {Vue|undefined}
  450. */
  451. getVm: function (data, index, key) {
  452. var idKey = this.idKey
  453. var primitive = !isObject(data)
  454. if (key || idKey || primitive) {
  455. var id = idKey
  456. ? idKey === '$index'
  457. ? index
  458. : data[idKey]
  459. : (key || index)
  460. return this.cache[id]
  461. } else {
  462. return data[this.id]
  463. }
  464. },
  465. /**
  466. * Delete a cached vm instance.
  467. *
  468. * @param {Vue} vm
  469. */
  470. uncacheVm: function (vm) {
  471. var data = vm._raw
  472. var idKey = this.idKey
  473. var index = vm.$index
  474. var key = vm.$key
  475. var primitive = !isObject(data)
  476. if (idKey || key || primitive) {
  477. var id = idKey
  478. ? idKey === '$index'
  479. ? index
  480. : data[idKey]
  481. : (key || index)
  482. this.cache[id] = null
  483. } else {
  484. data[this.id] = null
  485. vm._raw = null
  486. }
  487. },
  488. /**
  489. * Pre-process the value before piping it through the
  490. * filters, and convert non-Array objects to arrays.
  491. *
  492. * This function will be bound to this directive instance
  493. * and passed into the watcher.
  494. *
  495. * @param {*} value
  496. * @return {Array}
  497. * @private
  498. */
  499. _preProcess: function (value) {
  500. // regardless of type, store the un-filtered raw value.
  501. this.rawValue = value
  502. var type = this.rawType = typeof value
  503. if (!isPlainObject(value)) {
  504. this.converted = false
  505. if (type === 'number') {
  506. value = range(value)
  507. } else if (type === 'string') {
  508. value = _.toArray(value)
  509. }
  510. return value || []
  511. } else {
  512. // convert plain object to array.
  513. var keys = Object.keys(value)
  514. var i = keys.length
  515. var res = new Array(i)
  516. var key
  517. while (i--) {
  518. key = keys[i]
  519. res[i] = {
  520. $key: key,
  521. $value: value[key]
  522. }
  523. }
  524. this.converted = true
  525. return res
  526. }
  527. },
  528. /**
  529. * Insert an instance.
  530. *
  531. * @param {Vue} vm
  532. * @param {Number} index
  533. * @param {Node} prevEl
  534. * @param {Boolean} inDoc
  535. */
  536. insert: function (vm, index, prevEl, inDoc) {
  537. if (vm._staggerCb) {
  538. vm._staggerCb.cancel()
  539. vm._staggerCb = null
  540. }
  541. var staggerAmount = this.getStagger(vm, index, null, 'enter')
  542. if (inDoc && staggerAmount) {
  543. // create an anchor and insert it synchronously,
  544. // so that we can resolve the correct order without
  545. // worrying about some elements not inserted yet
  546. var anchor = vm._staggerAnchor
  547. if (!anchor) {
  548. anchor = vm._staggerAnchor = _.createAnchor('stagger-anchor')
  549. anchor.__vue__ = vm
  550. }
  551. _.after(anchor, prevEl)
  552. var op = vm._staggerCb = _.cancellable(function () {
  553. vm._staggerCb = null
  554. vm.$before(anchor)
  555. _.remove(anchor)
  556. })
  557. setTimeout(op, staggerAmount)
  558. } else {
  559. vm.$after(prevEl)
  560. }
  561. },
  562. /**
  563. * Move an already inserted instance.
  564. *
  565. * @param {Vue} vm
  566. * @param {Node} prevEl
  567. */
  568. move: function (vm, prevEl) {
  569. vm.$after(prevEl, null, false)
  570. },
  571. /**
  572. * Remove an instance.
  573. *
  574. * @param {Vue} vm
  575. * @param {Number} index
  576. * @param {Boolean} inDoc
  577. */
  578. remove: function (vm, index, total, inDoc) {
  579. if (vm._staggerCb) {
  580. vm._staggerCb.cancel()
  581. vm._staggerCb = null
  582. // it's not possible for the same vm to be removed
  583. // twice, so if we have a pending stagger callback,
  584. // it means this vm is queued for enter but removed
  585. // before its transition started. Since it is already
  586. // destroyed, we can just leave it in detached state.
  587. return
  588. }
  589. var staggerAmount = this.getStagger(vm, index, total, 'leave')
  590. if (inDoc && staggerAmount) {
  591. var op = vm._staggerCb = _.cancellable(function () {
  592. vm._staggerCb = null
  593. remove()
  594. })
  595. setTimeout(op, staggerAmount)
  596. } else {
  597. remove()
  598. }
  599. function remove () {
  600. vm.$remove(function () {
  601. vm._cleanup()
  602. })
  603. }
  604. },
  605. /**
  606. * Get the stagger amount for an insertion/removal.
  607. *
  608. * @param {Vue} vm
  609. * @param {Number} index
  610. * @param {String} type
  611. * @param {Number} total
  612. */
  613. getStagger: function (vm, index, total, type) {
  614. type = type + 'Stagger'
  615. var transition = vm.$el.__v_trans
  616. var hooks = transition && transition.hooks
  617. var hook = hooks && (hooks[type] || hooks.stagger)
  618. return hook
  619. ? hook.call(vm, index, total)
  620. : index * this[type]
  621. }
  622. }
  623. /**
  624. * Helper to find the previous element that is an instance
  625. * root node. This is necessary because a destroyed vm's
  626. * element could still be lingering in the DOM before its
  627. * leaving transition finishes, but its __vue__ reference
  628. * should have been removed so we can skip them.
  629. *
  630. * @param {Vue} vm
  631. * @param {Comment|Text} anchor
  632. * @return {Vue}
  633. */
  634. function findPrevVm (vm, anchor) {
  635. var el = vm.$el.previousSibling
  636. while (!el.__vue__ && el !== anchor) {
  637. el = el.previousSibling
  638. }
  639. return el.__vue__
  640. }
  641. /**
  642. * Create a range array from given number.
  643. *
  644. * @param {Number} n
  645. * @return {Array}
  646. */
  647. function range (n) {
  648. var i = -1
  649. var ret = new Array(n)
  650. while (++i < n) {
  651. ret[i] = i
  652. }
  653. return ret
  654. }
  655. /**
  656. * Convert a vms array to an object ref for v-ref on an
  657. * Object value.
  658. *
  659. * @param {Array} vms
  660. * @return {Object}
  661. */
  662. function toRefObject (vms) {
  663. var ref = {}
  664. for (var i = 0, l = vms.length; i < l; i++) {
  665. ref[vms[i].$key] = vms[i]
  666. }
  667. return ref
  668. }