summaryrefslogtreecommitdiffhomepage
path: root/desktop/packages/mullvad-vpn/src/renderer/components/PageSlider.tsx
blob: a603eee7bb2e5aae2a0e9fe66e62295b0446966c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
import { useCallback, useEffect, useState } from 'react';
import styled from 'styled-components';

import { NonEmptyArray } from '../../shared/utils';
import { IconButton } from '../lib/components';
import { colors } from '../lib/foundations';
import { useStyledRef } from '../lib/utility-hooks';

const PAGE_GAP = 16;

const StyledPageSliderContainer = styled.div({
  display: 'flex',
  flexDirection: 'column',
});

const StyledPageSlider = styled.div({
  whiteSpace: 'nowrap',
  overflow: 'scroll hidden',
  scrollSnapType: 'x mandatory',
  scrollBehavior: 'smooth',

  '&&::-webkit-scrollbar': {
    display: 'none',
  },
});

const StyledPage = styled.div({
  display: 'inline-block',
  width: '100%',
  whiteSpace: 'normal',
  verticalAlign: 'top',
  scrollSnapAlign: 'start',

  '&&:not(:last-child)': {
    marginRight: `${PAGE_GAP}px`,
  },
});

interface PageSliderProps {
  content: NonEmptyArray<React.ReactNode>;
}

export default function PageSlider(props: PageSliderProps) {
  // A state is needed to trigger a rerender. This is needed to update the "disabled" and "$current"
  // props of the arrows and page indicators.
  const [, setPageNumberState] = useState(0);
  const pageContainerRef = useStyledRef<HTMLDivElement>();

  // Calculate the page number based on the scroll position.
  const getPageNumber = useCallback(() => {
    if (pageContainerRef.current) {
      const scrollLeft = pageContainerRef.current.scrollLeft;
      const pageWidth = pageContainerRef.current.offsetWidth + PAGE_GAP;
      // Clamp it between 0 and props.content.length-1 to make sure it will correspond to a page.
      return Math.max(0, Math.min(Math.round(scrollLeft / pageWidth), props.content.length - 1));
    } else {
      return 0;
    }
  }, [pageContainerRef, props.content.length]);

  // These values are only intended to be used for display purposes. Using them when calculating
  // next or prev page would increase the risk of race conditions.
  const pageNumber = getPageNumber();
  const hasNext = pageNumber < props.content.length - 1;
  const hasPrev = pageNumber > 0;

  // Scroll to a specific page.
  const goToPage = useCallback(
    (page: number) => {
      if (pageContainerRef.current) {
        const width = pageContainerRef.current.offsetWidth;
        pageContainerRef.current.scrollTo({ left: width * page });
      }
    },
    [pageContainerRef],
  );

  const next = useCallback(() => goToPage(getPageNumber() + 1), [goToPage, getPageNumber]);
  const prev = useCallback(() => goToPage(getPageNumber() - 1), [goToPage, getPageNumber]);

  // Callback that navigates when left and right arrows are pressed.
  const handleKeyDown = useCallback(
    (event: KeyboardEvent) => {
      if (event.key === 'ArrowLeft') {
        prev();
      } else if (event.key === 'ArrowRight') {
        next();
      }
    },
    [next, prev],
  );

  // Trigger a rerender when the page number has changed. This needs to be done to update the
  // states of the arrows and page indicators.
  const handleScroll = useCallback(() => setPageNumberState(getPageNumber()), [getPageNumber]);

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  return (
    <StyledPageSliderContainer>
      <StyledPageSlider ref={pageContainerRef} onScroll={handleScroll}>
        {props.content.map((page, i) => (
          <StyledPage key={`page-${i}`}>{page}</StyledPage>
        ))}
      </StyledPageSlider>
      <Controls
        goToPage={goToPage}
        hasNext={hasNext}
        hasPrev={hasPrev}
        next={next}
        prev={prev}
        pageNumber={pageNumber}
        numberOfPages={props.content.length}
      />
    </StyledPageSliderContainer>
  );
}

const StyledControlsContainer = styled.div({
  display: 'flex',
  marginTop: '12px',
  alignItems: 'center',
});

const StyledControlElement = styled.div({
  flex: '1 0 60px',
  display: 'flex',
});

const StyledArrows = styled(StyledControlElement)({
  display: 'flex',
  justifyContent: 'right',
  gap: '12px',
});

const StyledPageIndicators = styled(StyledControlElement)({
  display: 'flex',
  flexGrow: 2,
  justifyContent: 'center',
});

const StyledTransparentButton = styled.button({
  border: 'none',
  background: colors.transparent,
  padding: '4px',
  margin: 0,
});

const StyledPageIndicator = styled.div<{ $current: boolean }>((props) => ({
  width: '8px',
  height: '8px',
  borderRadius: '50%',
  backgroundColor: props.$current ? colors.whiteAlpha80 : colors.whiteAlpha40,

  [`${StyledTransparentButton}:hover &&`]: {
    backgroundColor: colors.whiteAlpha80,
  },
}));

interface ControlsProps {
  pageNumber: number;
  numberOfPages: number;
  hasNext: boolean;
  hasPrev: boolean;
  next: () => void;
  prev: () => void;
  goToPage: (page: number) => void;
}

function Controls(props: ControlsProps) {
  return (
    <StyledControlsContainer>
      <StyledControlElement>{/* spacer to make page indicators centered */}</StyledControlElement>
      <StyledPageIndicators>
        {[...Array(props.numberOfPages)].map((_, i) => (
          <PageIndicator
            key={i}
            current={i === props.pageNumber}
            pageNumber={i}
            goToPage={props.goToPage}
          />
        ))}
      </StyledPageIndicators>
      <StyledArrows>
        <IconButton disabled={!props.hasPrev} onClick={props.prev}>
          <IconButton.Icon icon="chevron-left" />
        </IconButton>
        <IconButton disabled={!props.hasNext} onClick={props.next}>
          <IconButton.Icon icon="chevron-right" />
        </IconButton>
      </StyledArrows>
    </StyledControlsContainer>
  );
}

interface PageIndicatorProps {
  pageNumber: number;
  goToPage: (page: number) => void;
  current: boolean;
}

function PageIndicator(props: PageIndicatorProps) {
  const { goToPage } = props;

  const onClick = useCallback(() => {
    goToPage(props.pageNumber);
  }, [goToPage, props.pageNumber]);

  return (
    <StyledTransparentButton onClick={onClick}>
      <StyledPageIndicator $current={props.current} />
    </StyledTransparentButton>
  );
}