virtual.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. export default function Virtual({
  2. swiper,
  3. extendParams,
  4. on
  5. }) {
  6. extendParams({
  7. virtual: {
  8. enabled: false,
  9. slides: [],
  10. cache: true,
  11. renderSlide: null,
  12. renderExternal: null,
  13. renderExternalUpdate: true,
  14. addSlidesBefore: 0,
  15. addSlidesAfter: 0,
  16. },
  17. });
  18. let cssModeTimeout;
  19. swiper.virtual = {
  20. cache: {},
  21. from: undefined,
  22. to: undefined,
  23. slides: [],
  24. offset: 0,
  25. slidesGrid: [],
  26. };
  27. function renderSlide(slide, index) {
  28. const params = swiper.params.virtual;
  29. if (params.cache && swiper.virtual.cache[index]) {
  30. return swiper.virtual.cache[index];
  31. }
  32. // const $slideEl = params.renderSlide ?
  33. // $(params.renderSlide.call(swiper, slide, index)) :
  34. // $(
  35. // `<div class="${swiper.params.slideClass}" data-swiper-slide-index="${index}">${slide}</div>`,
  36. // );
  37. // if (!$slideEl.attr('data-swiper-slide-index')) $slideEl.attr('data-swiper-slide-index', index);
  38. // if (params.cache) swiper.virtual.cache[index] = $slideEl;
  39. // return $slideEl;
  40. }
  41. function onRendered() {
  42. swiper.updateSlides();
  43. swiper.updateProgress();
  44. swiper.updateSlidesClasses();
  45. if (swiper.lazy && swiper.params.lazy.enabled) {
  46. swiper.lazy.load();
  47. }
  48. }
  49. async function update(force) {
  50. const {
  51. slidesPerView,
  52. slidesPerGroup,
  53. centeredSlides
  54. } = swiper.params;
  55. const {
  56. addSlidesBefore,
  57. addSlidesAfter
  58. } = swiper.params.virtual;
  59. const {
  60. from: previousFrom,
  61. to: previousTo,
  62. slides,
  63. slidesGrid: previousSlidesGrid,
  64. offset: previousOffset,
  65. } = swiper.virtual;
  66. if (!swiper.params.cssMode) {
  67. swiper.updateActiveIndex();
  68. }
  69. const activeIndex = swiper.activeIndex || 0;
  70. let offsetProp;
  71. if (swiper.rtlTranslate) offsetProp = 'right';
  72. else offsetProp = swiper.isHorizontal() ? 'left' : 'top';
  73. let slidesAfter;
  74. let slidesBefore;
  75. if (centeredSlides) {
  76. slidesAfter = Math.floor(slidesPerView / 2) + slidesPerGroup + addSlidesAfter;
  77. slidesBefore = Math.floor(slidesPerView / 2) + slidesPerGroup + addSlidesBefore;
  78. } else {
  79. slidesAfter = slidesPerView + (slidesPerGroup - 1) + addSlidesAfter;
  80. slidesBefore = slidesPerGroup + addSlidesBefore;
  81. }
  82. const from = Math.max((activeIndex || 0) - slidesBefore, 0);
  83. const to = Math.min((activeIndex || 0) + slidesAfter, slides.length - 1);
  84. const offset = (swiper.slidesGrid[from] || 0) - (swiper.slidesGrid[0] || 0);
  85. Object.assign(swiper.virtual, {
  86. from,
  87. to,
  88. offset,
  89. slidesGrid: swiper.slidesGrid,
  90. });
  91. function onRendered() {
  92. swiper.updateSlides();
  93. swiper.updateProgress();
  94. swiper.updateSlidesClasses();
  95. if (swiper.lazy && swiper.params.lazy.enabled) {
  96. swiper.lazy.load();
  97. }
  98. }
  99. if (previousFrom === from && previousTo === to && !force) {
  100. if (swiper.slidesGrid !== previousSlidesGrid && offset !== previousOffset) {
  101. swiper.slides.css(offsetProp, `${offset}px`);
  102. }
  103. swiper.updateProgress();
  104. return;
  105. }
  106. if (swiper.params.virtual.renderExternal) {
  107. swiper.params.virtual.renderExternal.call(swiper, {
  108. offset,
  109. from,
  110. to,
  111. slides: (function getSlides() {
  112. const slidesToRender = [];
  113. if (swiper.params.virtual.type == 'keep') {
  114. for (let i = 0; i < from; i += 1) {
  115. slidesToRender.push("");
  116. }
  117. }
  118. for (let i = from; i <= to; i += 1) {
  119. slidesToRender.push(slides[i]);
  120. }
  121. return slidesToRender;
  122. })(),
  123. });
  124. if (swiper.params.virtual.renderExternalUpdate) {
  125. onRendered();
  126. }
  127. return;
  128. }
  129. const prependIndexes = [];
  130. const appendIndexes = [];
  131. if (force) {
  132. swiper.$wrapperEl.find(`.${swiper.params.slideClass}`).remove();
  133. } else {
  134. for (let i = previousFrom; i <= previousTo; i += 1) {
  135. if (i < from || i > to) {
  136. swiper.virtualList.splice(swiper.virtualList.findIndex((item) => {
  137. return item == slides[i]
  138. }), 1)
  139. swiper.virtualIndexList.splice(swiper.virtualIndexList.findIndex((item) => {
  140. return item == i
  141. }), 1)
  142. // swiper.slides[i].virtualShow = false;
  143. }
  144. }
  145. }
  146. for (let i = 0; i < slides.length; i += 1) {
  147. if (i >= from && i <= to) {
  148. if (typeof previousTo === 'undefined' || force) {
  149. appendIndexes.push(i);
  150. } else {
  151. if (i > previousTo) appendIndexes.push(i);
  152. if (i < previousFrom) prependIndexes.push(i);
  153. }
  154. }
  155. }
  156. // let list = [];
  157. appendIndexes.forEach((index) => {
  158. // if (swiper.slides[index]) {
  159. // swiper.slides[index].virtualShow = true;
  160. // } else {
  161. swiper.virtualList.push(slides[index]);
  162. swiper.virtualIndexList.push(index)
  163. // }
  164. // renderSlide(slides[index], index)
  165. // renderSlide(slides[index], index)
  166. // swiper.$wrapperEl.append(renderSlide(slides[index], index));
  167. });
  168. prependIndexes
  169. .sort((a, b) => b - a)
  170. .forEach((index) => {
  171. // swiper.slides[index].virtualShow = true;
  172. swiper.virtualList.unshift(slides[index]);
  173. swiper.virtualIndexList.unshift(index)
  174. // swiper.$wrapperEl.prepend(renderSlide(slides[index], index));
  175. });
  176. swiper.native.emit("input", [swiper.virtualList])
  177. onRendered();
  178. }
  179. function appendSlide(slides) {
  180. if (typeof slides === 'object' && 'length' in slides) {
  181. for (let i = 0; i < slides.length; i += 1) {
  182. if (slides[i]) swiper.virtual.slides.push(slides[i]);
  183. }
  184. } else {
  185. swiper.virtual.slides.push(slides);
  186. }
  187. update(true);
  188. }
  189. function prependSlide(slides) {
  190. const activeIndex = swiper.activeIndex;
  191. let newActiveIndex = activeIndex + 1;
  192. let numberOfNewSlides = 1;
  193. if (Array.isArray(slides)) {
  194. for (let i = 0; i < slides.length; i += 1) {
  195. if (slides[i]) swiper.virtual.slides.unshift(slides[i]);
  196. }
  197. newActiveIndex = activeIndex + slides.length;
  198. numberOfNewSlides = slides.length;
  199. } else {
  200. swiper.virtual.slides.unshift(slides);
  201. }
  202. if (swiper.params.virtual.cache) {
  203. const cache = swiper.virtual.cache;
  204. const newCache = {};
  205. Object.keys(cache).forEach((cachedIndex) => {
  206. const $cachedEl = cache[cachedIndex];
  207. const cachedElIndex = $cachedEl.attr('data-swiper-slide-index');
  208. if (cachedElIndex) {
  209. $cachedEl.attr(
  210. 'data-swiper-slide-index',
  211. parseInt(cachedElIndex, 10) + numberOfNewSlides,
  212. );
  213. }
  214. newCache[parseInt(cachedIndex, 10) + numberOfNewSlides] = $cachedEl;
  215. });
  216. swiper.virtual.cache = newCache;
  217. }
  218. update(true);
  219. swiper.slideTo(newActiveIndex, 0);
  220. }
  221. function removeSlide(slidesIndexes) {
  222. if (typeof slidesIndexes === 'undefined' || slidesIndexes === null) return;
  223. let activeIndex = swiper.activeIndex;
  224. if (Array.isArray(slidesIndexes)) {
  225. for (let i = slidesIndexes.length - 1; i >= 0; i -= 1) {
  226. swiper.virtual.slides.splice(slidesIndexes[i], 1);
  227. if (swiper.params.virtual.cache) {
  228. delete swiper.virtual.cache[slidesIndexes[i]];
  229. }
  230. if (slidesIndexes[i] < activeIndex) activeIndex -= 1;
  231. activeIndex = Math.max(activeIndex, 0);
  232. }
  233. } else {
  234. swiper.virtual.slides.splice(slidesIndexes, 1);
  235. if (swiper.params.virtual.cache) {
  236. delete swiper.virtual.cache[slidesIndexes];
  237. }
  238. if (slidesIndexes < activeIndex) activeIndex -= 1;
  239. activeIndex = Math.max(activeIndex, 0);
  240. }
  241. update(true);
  242. swiper.slideTo(activeIndex, 0);
  243. }
  244. function removeAllSlides() {
  245. swiper.virtual.slides = [];
  246. if (swiper.params.virtual.cache) {
  247. swiper.virtual.cache = {};
  248. }
  249. update(true);
  250. swiper.slideTo(0, 0);
  251. }
  252. on('beforeInit', () => {
  253. if (!swiper.params.virtual.enabled) return;
  254. swiper.virtual.slides = swiper.params.virtual.slides;
  255. swiper.classNames.push(`${swiper.params.containerModifierClass}virtual`);
  256. swiper.params.watchSlidesProgress = true;
  257. swiper.originalParams.watchSlidesProgress = true;
  258. if (!swiper.params.initialSlide) {
  259. update();
  260. }
  261. });
  262. // on('beforeUpdate', () => {
  263. // if (!swiper.params.virtual.enabled) return;
  264. // let offsetProp;
  265. // if (swiper.rtlTranslate) offsetProp = 'right';
  266. // else offsetProp = swiper.isHorizontal() ? 'left' : 'top';
  267. // swiper.slides.forEach((item, index) => {
  268. // item.dataSwiperSlideIndex = swiper.virtualIndexList[index];
  269. // item.css({
  270. // [offsetProp]: `${swiper.virtual.offset}px`
  271. // })
  272. // })
  273. // })
  274. on('setTranslate', async () => {
  275. if (!swiper.params.virtual.enabled) return;
  276. if (swiper.params.cssMode && !swiper._immediateVirtual) {
  277. clearTimeout(cssModeTimeout);
  278. cssModeTimeout = setTimeout(() => {
  279. update();
  280. }, 100);
  281. } else {
  282. console.log("update==========")
  283. clearTimeout(cssModeTimeout);
  284. cssModeTimeout = setTimeout(() => {
  285. update();
  286. }, 100);
  287. // update();
  288. }
  289. });
  290. Object.assign(swiper.virtual, {
  291. appendSlide,
  292. prependSlide,
  293. removeSlide,
  294. removeAllSlides,
  295. update,
  296. });
  297. }