addons/isl/src/drawerState.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import type {AllDrawersState, DrawerState} from './Drawers';
b69ab319
b69ab3110import {localStorageBackedAtom, readAtom, writeAtom} from './jotaiUtils';
b69ab3111import {getWindowWidthInPixels, registerCleanup} from './utils';
b69ab3112
b69ab3113const AUTO_CLOSE_MAX_SIZE = 700;
b69ab3114const DEFAULT_RIGHT_DRAWER_WIDTH = 500;
b69ab3115
b69ab3116export const islDrawerState = localStorageBackedAtom<AllDrawersState>('isl.drawer-state', {
b69ab3117 right: {
b69ab3118 size: DEFAULT_RIGHT_DRAWER_WIDTH,
b69ab3119 collapsed: false,
b69ab3120 },
b69ab3121 left: {size: 200, collapsed: true},
b69ab3122 top: {size: 200, collapsed: true},
b69ab3123 bottom: {size: 200, collapsed: true},
b69ab3124});
b69ab3125
b69ab3126// On startup, override existing state to collapse the right sidebar if the screen is too small.
b69ab3127// This allows collapsing even if the size has been previous persisted.
b69ab3128function autoCloseBasedOnWindowWidth() {
b69ab3129 const windowWidth = getWindowWidthInPixels();
b69ab3130 if (windowWidth === 0) {
b69ab3131 // window not loaded yet
b69ab3132 return;
b69ab3133 }
b69ab3134
b69ab3135 const current = readAtom(islDrawerState).right.size;
b69ab3136 const setDrawer = (state: DrawerState) => {
b69ab3137 const oldValue = readAtom(islDrawerState);
b69ab3138 writeAtom(islDrawerState, {
b69ab3139 ...oldValue,
b69ab3140 right: state,
b69ab3141 });
b69ab3142 };
b69ab3143 if (windowWidth < AUTO_CLOSE_MAX_SIZE) {
b69ab3144 setDrawer({
b69ab3145 collapsed: true,
b69ab3146 size: Math.min(windowWidth, current ?? DEFAULT_RIGHT_DRAWER_WIDTH),
b69ab3147 });
b69ab3148 }
b69ab3149}
b69ab3150
b69ab3151const resizeFn = () => {
b69ab3152 autoCloseBasedOnWindowWidth();
b69ab3153};
b69ab3154window.addEventListener('resize', resizeFn);
b69ab3155
b69ab3156// check startup window size
b69ab3157window.addEventListener('load', resizeFn);
b69ab3158
b69ab3159registerCleanup(
b69ab3160 islDrawerState,
b69ab3161 () => {
b69ab3162 window.removeEventListener('resize', resizeFn);
b69ab3163 window.removeEventListener('load', resizeFn);
b69ab3164 },
b69ab3165 import.meta.hot,
b69ab3166);