Direction.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { ARROW_DOWN, ARROW_LEFT, ARROW_RIGHT, ARROW_UP } from '../../constants/arrows';
  2. import { RTL, TTB } from '../../constants/directions';
  3. import { Splide } from '../../core/Splide/Splide';
  4. import { BaseComponent, ComponentConstructor, Components, Options } from '../../types';
  5. /**
  6. * The interface for the Direction component.
  7. *
  8. * @since 3.0.0
  9. */
  10. export interface DirectionComponent extends BaseComponent {
  11. resolve<R extends string>( prop: string, axisOnly?: boolean, direction?: Options['direction'] ): R;
  12. orient( value: number ): number;
  13. }
  14. /**
  15. * The translation map for directions.
  16. *
  17. * @since 3.0.0
  18. */
  19. export const ORIENTATION_MAP = {
  20. width : [ 'height' ],
  21. left : [ 'top', 'right' ],
  22. right : [ 'bottom', 'left' ],
  23. x : [ 'y' ],
  24. X : [ 'Y' ],
  25. Y : [ 'X' ],
  26. ArrowLeft : [ ARROW_UP, ARROW_RIGHT ],
  27. ArrowRight: [ ARROW_DOWN, ARROW_LEFT ],
  28. };
  29. /**
  30. * The component that absorbs the difference among directions.
  31. *
  32. * @since 3.0.0
  33. *
  34. * @param Splide - A Splide instance.
  35. * @param Components - A collection of components.
  36. * @param options - Options.
  37. *
  38. * @return A Direction component object.
  39. */
  40. export const Direction: ComponentConstructor<DirectionComponent> = ( Splide: Splide, Components: Components, options: Options ) => {
  41. /**
  42. * Resolves the provided property name.
  43. *
  44. * @param prop - A property name to translate.
  45. * @param axisOnly - Optional. If `ture`, returns the same property for LTR and RTL.
  46. * @param direction - Optional. Specify the direction. The default value is the `direction` option.
  47. */
  48. function resolve<R extends string>( prop: string, axisOnly?: boolean, direction?: Options['direction'] ): R {
  49. direction = direction || options.direction;
  50. const index = direction === RTL && ! axisOnly ? 1 : direction === TTB ? 0 : -1;
  51. return ORIENTATION_MAP[ prop ] && ORIENTATION_MAP[ prop ][ index ]
  52. || prop.replace( /width|left|right/i, ( match, offset ) => {
  53. const replacement = ORIENTATION_MAP[ match.toLowerCase() ][ index ] || match;
  54. return offset > 0 ? replacement.charAt( 0 ).toUpperCase() + replacement.slice( 1 ) : replacement;
  55. } );
  56. }
  57. /**
  58. * Orients the value towards the current direction.
  59. *
  60. * @param value - A value to orient.
  61. *
  62. * @return The oriented value.
  63. */
  64. function orient( value: number ): number {
  65. return value * ( options.direction === RTL ? 1 : -1 );
  66. }
  67. return {
  68. resolve,
  69. orient,
  70. };
  71. };