foundation.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import BaseFoundation, { DefaultAdapter } from '../base/foundation';
  2. import { isArray, get } from 'lodash';
  3. import scrollIntoView, { CustomBehaviorOptions } from 'scroll-into-view-if-needed';
  4. import { cssClasses } from './constants';
  5. const prefixCls = cssClasses.PREFIX;
  6. export interface AnchorAdapter<P = Record<string, any>, S = Record<string, any>> extends DefaultAdapter<P, S> {
  7. addLink: (link: string) => void;
  8. removeLink: (link: string) => void;
  9. setChildMap: (value: Record<string, Set<string>>) => void;
  10. setScrollHeight: (heigh: string) => void;
  11. setSlideBarTop: (height: number) => void;
  12. setClickLink: (value: boolean) => void;
  13. setActiveLink: (link: string, cb: () => void) => void;
  14. setClickLinkWithCallBack: (value: boolean, link: string, cb: (link: string) => void) => void;
  15. getContainer: () => HTMLElement | Window;
  16. getContainerBoundingTop: () => number;
  17. getLinksBoundingTop: () => number[];
  18. getAnchorNode: (selector: string) => HTMLElement;
  19. getContentNode: (selector: string) => HTMLElement;
  20. notifyChange: (currentLink: string, previousLink: string) => void;
  21. notifyClick: (e: any, link: string) => void;
  22. canSmoothScroll: () => boolean
  23. }
  24. export default class AnchorFoundation<P = Record<string, any>, S = Record<string, any>> extends BaseFoundation<AnchorAdapter<P, S>, P, S> {
  25. constructor(adapter: AnchorAdapter<P, S>) {
  26. super({ ...AnchorFoundation.defaultAdapter, ...adapter });
  27. }
  28. // eslint-disable-next-line @typescript-eslint/no-empty-function
  29. init = () => {};
  30. // eslint-disable-next-line @typescript-eslint/no-empty-function
  31. destroy = () => {};
  32. addLink = (link: string) => {
  33. this._adapter.addLink(link);
  34. };
  35. removeLink = (link: string) => {
  36. this._adapter.removeLink(link);
  37. };
  38. setActiveLink = (link: string, prevLink: string, shouldNotify = true) => {
  39. const activeLink = this._adapter.getState('activeLink');
  40. const onChange = this._adapter.getProp('onChange');
  41. if (activeLink !== link) {
  42. this._adapter.setActiveLink(link, this._setActiveSlide);
  43. if (onChange && shouldNotify) {
  44. this._adapter.notifyChange(link, prevLink);
  45. }
  46. }
  47. };
  48. // Adjust rail height according to text link content height
  49. setScrollHeight = () => {
  50. const anchorWrapper = `.${prefixCls}-link-wrapper`;
  51. const anchorNode = this._adapter.getAnchorNode(anchorWrapper);
  52. if (anchorNode) {
  53. const scrollHeight = `${anchorNode.scrollHeight}px`;
  54. this._adapter.setScrollHeight(scrollHeight);
  55. }
  56. };
  57. updateScrollHeight = (prevState: any, state: any) => {
  58. const prevLinks = prevState.links.join('');
  59. const links = state.links.join('');
  60. if (prevLinks !== links) {
  61. this.setScrollHeight();
  62. }
  63. };
  64. setChildMap = () => {
  65. const children = this._adapter.getProp('children');
  66. const childMap = {};
  67. if (isArray(children)) {
  68. for (const link of children) {
  69. this._getLinkToMap(link, [], childMap);
  70. }
  71. } else {
  72. this._getLinkToMap(children, [], childMap);
  73. }
  74. this._adapter.setChildMap(childMap);
  75. };
  76. updateChildMap = (prevState: any, state: any) => {
  77. const prevLinks = prevState.links.join('');
  78. const links = state.links.join('');
  79. if (prevLinks !== links) {
  80. this.setChildMap();
  81. }
  82. };
  83. getLinksTop = () => this._adapter.getLinksBoundingTop();
  84. handleScroll = () => {
  85. const { clickLink, links, activeLink: prevActiveLink } = this.getStates(); // TODO check this._adapter -> this.
  86. // ActiveLink Determined by the clicked link
  87. if (clickLink) {
  88. return;
  89. }
  90. const elTop = this.getLinksTop();
  91. let lastNegative = -Infinity;
  92. let lastNegativeIndex = -1;
  93. for (let i = 0; i < elTop.length; i++) {
  94. if (elTop[i] < 0 && elTop[i] > lastNegative) {
  95. lastNegative = elTop[i];
  96. lastNegativeIndex = i;
  97. }
  98. }
  99. const activeLink = links[lastNegativeIndex];
  100. this.setActiveLink(activeLink, prevActiveLink);
  101. };
  102. handleClick = (e: any, link: string, shouldNotify = true) => {
  103. const destNode = this._adapter.getContentNode(link);
  104. const prevLink = this._adapter.getState('activeLink');
  105. this.setActiveLink(link, prevLink, shouldNotify);
  106. if (destNode) {
  107. try {
  108. this._adapter.setClickLinkWithCallBack(true, link, this._scrollIntoView);
  109. } catch (error) {}
  110. }
  111. shouldNotify && this._adapter.notifyClick(e, link);
  112. };
  113. handleClickLink = () => {
  114. this._adapter.setClickLink(false);
  115. };
  116. // Get the child nodes of each link
  117. _getLinkToMap = (link: any, parents: string[], linkMap: { [key: string]: Set<string> }) => {
  118. const node = link && link.props;
  119. if (!node || !node.href) {
  120. return;
  121. }
  122. if (!(node.href in linkMap)) {
  123. linkMap[node.href] = new Set();
  124. }
  125. // Every ancestor kept a map
  126. for (const parent of parents) {
  127. linkMap[parent].add(node.href);
  128. }
  129. if (node.children && node.children.length) {
  130. parents.push(node.href);
  131. // Maintain child node map
  132. for (const child of node.children) {
  133. this._getLinkToMap(child, parents, linkMap);
  134. }
  135. parents.pop();
  136. }
  137. };
  138. _scrollIntoView = (link: string) => {
  139. const { scrollMotion, targetOffset } = this.getProps(); // TODO check this._adapter -> this.
  140. const behavior = scrollMotion ? 'smooth' : 'auto';
  141. const canSmoothScroll = this._adapter.canSmoothScroll();
  142. if (link) {
  143. const destNode = this._adapter.getContentNode(link);
  144. const scrollOpts: CustomBehaviorOptions<void> = {
  145. /**
  146. * Behavior defines scrolling behavior
  147. * - Optional'auto '|' smooth '| Function
  148. * - Function Custom scrolling behavior
  149. * - Enter parameters as actions, each action contains an element that should be scrolled
  150. * - Actions include scrolling containers to the outermost scrollable container (document.body), the scrollable capacity needs to meet
  151. * 1. The parent of the scroll container (directly or indirectly)
  152. * 2. There is a scroll axis (clientHeight < scrollHeight | | clientWidth < scrollWidth)
  153. * 3.overflowX or overflowY has a value and is not visible or clip
  154. * For details, please see https://github.com/stipsan/compute-scroll-into-view
  155. *
  156. * behavior定义滚动行为
  157. * - 可选 'auto' | 'smooth' | Function
  158. * - Function 自定义滚动行为
  159. * - 入参为 actions,每个action包含一个应该滚动的元素
  160. * - actions包括滚动容器到最外层的可滚动容器(document.body),可滚动容需满足
  161. * 1. 滚动容器的父级(直接或间接)
  162. * 2. 有滚动轴(clientHeight < scrollHeight || clientWidth < scrollWidth)
  163. * 3. overflowX 或 overflowY 有值且不为 visible 或 clip
  164. * 详情请看https://github.com/stipsan/compute-scroll-into-view
  165. */
  166. behavior: actions => {
  167. // We just need to scroll the innermost target container
  168. const innermostAction = get(actions, '0');
  169. const el = get(innermostAction, 'el');
  170. const top = get(innermostAction, 'top');
  171. if (el) {
  172. const offsetTop = top - targetOffset;
  173. if (el.scroll && canSmoothScroll) {
  174. el.scroll({ top: offsetTop, behavior });
  175. } else {
  176. el.scrollTop = offsetTop;
  177. }
  178. }
  179. },
  180. block: 'start',
  181. };
  182. if (destNode) {
  183. scrollIntoView(destNode, scrollOpts);
  184. }
  185. }
  186. };
  187. _setActiveSlide = () => {
  188. const activeClass = `.${cssClasses.PREFIX}-link-title-active`;
  189. const linkNode = this._adapter.getAnchorNode(activeClass);
  190. if (linkNode) {
  191. const height = linkNode.offsetTop;
  192. this._adapter.setSlideBarTop(height);
  193. }
  194. };
  195. }