1.8 KB67 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8import type {AllDrawersState, DrawerState} from './Drawers';
9
10import {localStorageBackedAtom, readAtom, writeAtom} from './jotaiUtils';
11import {getWindowWidthInPixels, registerCleanup} from './utils';
12
13const AUTO_CLOSE_MAX_SIZE = 700;
14const DEFAULT_RIGHT_DRAWER_WIDTH = 500;
15
16export const islDrawerState = localStorageBackedAtom<AllDrawersState>('isl.drawer-state', {
17 right: {
18 size: DEFAULT_RIGHT_DRAWER_WIDTH,
19 collapsed: false,
20 },
21 left: {size: 200, collapsed: true},
22 top: {size: 200, collapsed: true},
23 bottom: {size: 200, collapsed: true},
24});
25
26// On startup, override existing state to collapse the right sidebar if the screen is too small.
27// This allows collapsing even if the size has been previous persisted.
28function autoCloseBasedOnWindowWidth() {
29 const windowWidth = getWindowWidthInPixels();
30 if (windowWidth === 0) {
31 // window not loaded yet
32 return;
33 }
34
35 const current = readAtom(islDrawerState).right.size;
36 const setDrawer = (state: DrawerState) => {
37 const oldValue = readAtom(islDrawerState);
38 writeAtom(islDrawerState, {
39 ...oldValue,
40 right: state,
41 });
42 };
43 if (windowWidth < AUTO_CLOSE_MAX_SIZE) {
44 setDrawer({
45 collapsed: true,
46 size: Math.min(windowWidth, current ?? DEFAULT_RIGHT_DRAWER_WIDTH),
47 });
48 }
49}
50
51const resizeFn = () => {
52 autoCloseBasedOnWindowWidth();
53};
54window.addEventListener('resize', resizeFn);
55
56// check startup window size
57window.addEventListener('load', resizeFn);
58
59registerCleanup(
60 islDrawerState,
61 () => {
62 window.removeEventListener('resize', resizeFn);
63 window.removeEventListener('load', resizeFn);
64 },
65 import.meta.hot,
66);
67