储能智慧云小程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tabs.js 11KB

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