tabs.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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, reject) => {
  135. if (this.trackWidth) {
  136. resolve(this.trackWidth);
  137. return;
  138. }
  139. getRect(this, `.${prefix}-tabs__track`)
  140. .then((res) => {
  141. if (res) {
  142. this.trackWidth = res.width;
  143. resolve(this.trackWidth);
  144. }
  145. })
  146. .catch(reject);
  147. });
  148. },
  149. setTrack() {
  150. return __awaiter(this, void 0, void 0, function* () {
  151. if (!this.properties.showBottomLine)
  152. return;
  153. const { children } = this;
  154. if (!children)
  155. return;
  156. const { currentIndex, isScrollX, direction } = this.data;
  157. if (currentIndex <= -1)
  158. return;
  159. try {
  160. const res = yield getRect(this, `.${prefix}-tabs__item`, true);
  161. const rect = res[currentIndex];
  162. if (!rect)
  163. return;
  164. let count = 0;
  165. let distance = 0;
  166. let totalSize = 0;
  167. res.forEach((item) => {
  168. if (count < currentIndex) {
  169. distance += isScrollX ? item.width : item.height;
  170. count += 1;
  171. }
  172. totalSize += isScrollX ? item.width : item.height;
  173. });
  174. if (this.containerWidth) {
  175. const offset = this.calcScrollOffset(this.containerWidth, rect.left, rect.width, this.data.offset);
  176. const maxOffset = totalSize - this.containerWidth;
  177. this.setData({
  178. offset: Math.min(Math.max(offset, 0), maxOffset),
  179. });
  180. }
  181. if (isScrollX && this.data.theme === 'line') {
  182. const trackLineWidth = yield this.getTrackSize();
  183. distance += (rect.width - trackLineWidth) / 2;
  184. }
  185. let trackStyle = `-webkit-transform: translate${direction}(${distance}px);
  186. transform: translate${direction}(${distance}px);
  187. `;
  188. if (!isScrollX) {
  189. trackStyle += `height: ${rect.height}px;`;
  190. }
  191. this.setData({
  192. trackStyle,
  193. });
  194. }
  195. catch (err) {
  196. this.triggerEvent('error', err);
  197. }
  198. });
  199. },
  200. onTabTap(event) {
  201. const { index } = event.currentTarget.dataset;
  202. this.changeIndex(index);
  203. },
  204. onTouchStart(event) {
  205. if (!this.properties.swipeable)
  206. return;
  207. this.touchStart(event);
  208. },
  209. onTouchMove(event) {
  210. if (!this.properties.swipeable)
  211. return;
  212. this.touchMove(event);
  213. },
  214. onTouchEnd() {
  215. if (!this.properties.swipeable)
  216. return;
  217. const { direction, deltaX, offsetX } = this;
  218. const minSwipeDistance = 50;
  219. if (direction === 'horizontal' && offsetX >= minSwipeDistance) {
  220. const index = this.getAvailableTabIndex(deltaX);
  221. if (index !== -1) {
  222. this.changeIndex(index);
  223. }
  224. }
  225. },
  226. onTouchScroll(event) {
  227. this._trigger('scroll', event.detail);
  228. },
  229. changeIndex(index) {
  230. const currentTab = this.data.tabs[index];
  231. const { value, label } = currentTab;
  232. if (!(currentTab === null || currentTab === void 0 ? void 0 : currentTab.disabled) && index !== this.data.currentIndex) {
  233. this._trigger('change', { value, label });
  234. }
  235. this._trigger('click', { value, label });
  236. },
  237. getAvailableTabIndex(deltaX) {
  238. const step = deltaX > 0 ? -1 : 1;
  239. const { currentIndex, tabs } = this.data;
  240. const len = tabs.length;
  241. for (let i = step; currentIndex + step >= 0 && currentIndex + step < len; i += step) {
  242. const newIndex = currentIndex + i;
  243. if (newIndex >= 0 && newIndex < len && tabs[newIndex] && !tabs[newIndex].disabled) {
  244. return newIndex;
  245. }
  246. }
  247. return -1;
  248. },
  249. };
  250. }
  251. initChildId() {
  252. this.children.forEach((item, index) => {
  253. item.setId(`${this.data.tabID}_panel_${index}`);
  254. });
  255. }
  256. };
  257. Tabs = __decorate([
  258. wxComponent()
  259. ], Tabs);
  260. export default Tabs;