tabs.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  8. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  9. return new (P || (P = Promise))(function (resolve, reject) {
  10. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  11. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  12. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  13. step((generator = generator.apply(thisArg, _arguments || [])).next());
  14. });
  15. };
  16. import { SuperComponent, wxComponent } from '../common/src/index';
  17. import props from './props';
  18. import config from '../common/config';
  19. import touch from '../mixins/touch';
  20. import { getRect, uniqueFactory } from '../common/utils';
  21. const { prefix } = config;
  22. const name = `${prefix}-tabs`;
  23. const getUniqueID = uniqueFactory('tabs');
  24. let Tabs = class Tabs extends SuperComponent {
  25. constructor() {
  26. super(...arguments);
  27. this.behaviors = [touch];
  28. this.externalClasses = [`${prefix}-class`, `${prefix}-class-item`, `${prefix}-class-active`, `${prefix}-class-track`];
  29. this.relations = {
  30. '../tab-panel/tab-panel': {
  31. type: 'descendant',
  32. linked(target) {
  33. this.children.push(target);
  34. this.initChildId();
  35. target.index = this.children.length - 1;
  36. this.updateTabs();
  37. },
  38. unlinked(target) {
  39. this.children = this.children.filter((item) => item.index !== target.index);
  40. this.updateTabs(() => this.setTrack());
  41. this.initChildId();
  42. },
  43. },
  44. };
  45. this.properties = props;
  46. this.controlledProps = [
  47. {
  48. key: 'value',
  49. event: 'change',
  50. },
  51. ];
  52. this.observers = {
  53. value(name) {
  54. if (name !== this.getCurrentName()) {
  55. this.setCurrentIndexByName(name);
  56. }
  57. },
  58. };
  59. this.data = {
  60. prefix,
  61. classPrefix: name,
  62. tabs: [],
  63. currentIndex: -1,
  64. trackStyle: '',
  65. isScrollX: true,
  66. direction: 'X',
  67. offset: 0,
  68. tabID: '',
  69. placement: 'top',
  70. };
  71. this.lifetimes = {
  72. created() {
  73. this.children = this.children || [];
  74. },
  75. attached() {
  76. wx.nextTick(() => {
  77. this.setTrack();
  78. });
  79. getRect(this, `.${name}`).then((rect) => {
  80. this.containerWidth = rect.width;
  81. });
  82. this.setData({
  83. tabID: getUniqueID(),
  84. });
  85. },
  86. };
  87. this.methods = {
  88. updateTabs(cb) {
  89. const { children } = this;
  90. const tabs = children.map((child) => child.data);
  91. tabs.forEach((item) => {
  92. if (typeof item.icon === 'string') {
  93. item.icon = { name: item.icon };
  94. }
  95. });
  96. this.setData({ tabs }, cb);
  97. this.setCurrentIndexByName(this.properties.value);
  98. },
  99. setCurrentIndexByName(name) {
  100. const { children } = this;
  101. const index = children.findIndex((child) => child.getComputedName() === `${name}`);
  102. if (index > -1) {
  103. this.setCurrentIndex(index);
  104. }
  105. },
  106. setCurrentIndex(index) {
  107. if (index <= -1 || index >= this.children.length)
  108. return;
  109. this.children.forEach((child, idx) => {
  110. const isActive = index === idx;
  111. if (isActive !== child.data.active) {
  112. child.render(isActive, this);
  113. }
  114. });
  115. if (this.data.currentIndex === index)
  116. return;
  117. this.setData({
  118. currentIndex: index,
  119. });
  120. this.setTrack();
  121. },
  122. getCurrentName() {
  123. if (this.children) {
  124. const activeTab = this.children[this.data.currentIndex];
  125. if (activeTab) {
  126. return activeTab.getComputedName();
  127. }
  128. }
  129. },
  130. calcScrollOffset(containerWidth, targetLeft, targetWidth, offset) {
  131. return offset + targetLeft - (1 / 2) * containerWidth + targetWidth / 2;
  132. },
  133. getTrackSize() {
  134. return new Promise((resolve) => {
  135. if (this.trackWidth) {
  136. resolve(this.trackWidth);
  137. return;
  138. }
  139. getRect(this, `.${prefix}-tabs__track`).then((res) => {
  140. if (res) {
  141. this.trackWidth = res.width;
  142. resolve(this.trackWidth);
  143. }
  144. });
  145. });
  146. },
  147. setTrack() {
  148. return __awaiter(this, void 0, void 0, function* () {
  149. if (!this.properties.showBottomLine)
  150. return;
  151. const { children } = this;
  152. if (!children)
  153. return;
  154. const { currentIndex, isScrollX, direction } = this.data;
  155. if (currentIndex <= -1)
  156. return;
  157. try {
  158. const res = yield getRect(this, `.${prefix}-tabs__item`, true);
  159. const rect = res[currentIndex];
  160. if (!rect)
  161. return;
  162. let count = 0;
  163. let distance = 0;
  164. let totalSize = 0;
  165. res.forEach((item) => {
  166. if (count < currentIndex) {
  167. distance += isScrollX ? item.width : item.height;
  168. count += 1;
  169. }
  170. totalSize += isScrollX ? item.width : item.height;
  171. });
  172. if (this.containerWidth) {
  173. const offset = this.calcScrollOffset(this.containerWidth, rect.left, rect.width, this.data.offset);
  174. const maxOffset = totalSize - this.containerWidth;
  175. this.setData({
  176. offset: Math.min(Math.max(offset, 0), maxOffset),
  177. });
  178. }
  179. if (isScrollX) {
  180. const trackLineWidth = yield this.getTrackSize();
  181. distance += (rect.width - trackLineWidth) / 2;
  182. }
  183. let trackStyle = `-webkit-transform: translate${direction}(${distance}px);
  184. transform: translate${direction}(${distance}px);
  185. `;
  186. if (!isScrollX) {
  187. trackStyle += `height: ${rect.height}px;`;
  188. }
  189. this.setData({
  190. trackStyle,
  191. });
  192. }
  193. catch (err) {
  194. this.triggerEvent('error', err);
  195. }
  196. });
  197. },
  198. onTabTap(event) {
  199. const { index } = event.currentTarget.dataset;
  200. this.changeIndex(index);
  201. },
  202. onTouchStart(event) {
  203. if (!this.properties.swipeable)
  204. return;
  205. this.touchStart(event);
  206. },
  207. onTouchMove(event) {
  208. if (!this.properties.swipeable)
  209. return;
  210. this.touchMove(event);
  211. },
  212. onTouchEnd() {
  213. if (!this.properties.swipeable)
  214. return;
  215. const { direction, deltaX, offsetX } = this;
  216. const minSwipeDistance = 50;
  217. if (direction === 'horizontal' && offsetX >= minSwipeDistance) {
  218. const index = this.getAvailableTabIndex(deltaX);
  219. if (index !== -1) {
  220. this.changeIndex(index);
  221. }
  222. }
  223. },
  224. onTouchScroll(event) {
  225. this._trigger('scroll', event.detail);
  226. },
  227. changeIndex(index) {
  228. const currentTab = this.data.tabs[index];
  229. const { value, label } = currentTab;
  230. if (!(currentTab === null || currentTab === void 0 ? void 0 : currentTab.disabled) && index !== this.data.currentIndex) {
  231. this._trigger('change', { value, label });
  232. }
  233. this._trigger('click', { value, label });
  234. },
  235. getAvailableTabIndex(deltaX) {
  236. const step = deltaX > 0 ? -1 : 1;
  237. const { currentIndex, tabs } = this.data;
  238. const len = tabs.length;
  239. for (let i = step; currentIndex + step >= 0 && currentIndex + step < len; i += step) {
  240. const newIndex = currentIndex + i;
  241. if (newIndex >= 0 && newIndex < len && tabs[newIndex] && !tabs[newIndex].disabled) {
  242. return newIndex;
  243. }
  244. }
  245. return -1;
  246. },
  247. };
  248. }
  249. initChildId() {
  250. this.children.forEach((item, index) => {
  251. item.setId(`${this.data.tabID}_panel_${index}`);
  252. });
  253. }
  254. };
  255. Tabs = __decorate([
  256. wxComponent()
  257. ], Tabs);
  258. export default Tabs;