tabs.js 11 KB

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