import {isNil} from 'lodash-es' import { addClass, getBrowserScrollBarWidth, hasClass, removeClass } from './index' interface FullWidthElementObject { originStyle: { width: string } element: HTMLElement } const IS_MODAL_OPEN_CLASS_NAME = 'has-brick-modal-visible' let isBodyHasScrollbar = false let fullWidthElementList: FullWidthElementObject[] | null = null let scrollBarWidth: number | null = null function getScrollBarWidth() { if (isNil(scrollBarWidth)) { scrollBarWidth = getBrowserScrollBarWidth() } return scrollBarWidth } function checkBodyScrollbar() { // let fullWindowWidth = window.innerWidth // workaround for missing window.innerWidth in IE8 // if (!fullWindowWidth) { // const documentElementRect = document.documentElement.getBoundingClientRect() // fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left) // } isBodyHasScrollbar = document.body.clientWidth < window.innerWidth } function getFullWidthElements(): FullWidthElementObject[] { if (fullWidthElementList) { return fullWidthElementList } const elementList: FullWidthElementObject[] = [{ element: document.body, originStyle: { width: document.body.style.width, }, }] // 把宽度宽度与 body 一致的 fixed 元素也加入处理 const eleList = document.body.getElementsByTagName('*') as HTMLCollectionOf for (let i = eleList.length; i-- > 0;) { const elem = eleList[i] if (hasClass(elem, 'brick-modal-mask') || hasClass(elem, 'brick-modal-wrap')) { continue } const elemStyle = window.getComputedStyle(elem) if (elemStyle.getPropertyValue('position') === 'fixed' && elem.getBoundingClientRect().width === document.body.clientWidth ) { elementList.push({ originStyle: { width: elem.style.width, }, element: elem, }) } } return elementList } function setFullWidthElementsStyle() { if (!isBodyHasScrollbar) { return } fullWidthElementList = getFullWidthElements() fullWidthElementList.forEach(item => { const {element} = item element.style.width = `calc(100% - ${getScrollBarWidth()}px)` }) } function resetFullWidthElementsStyle() { if (!fullWidthElementList) { return } fullWidthElementList.forEach(item => { const {element, originStyle} = item Object.assign(element.style, originStyle) }) fullWidthElementList = null } export const CONST_modal = 'modal'; export const CONST_imagePreview = 'image-preview'; type MaskType = | typeof CONST_modal | typeof CONST_imagePreview; const CONST_openedMask = new Map< MaskType, number >() export function resetScrollingBehaviourOnMaskShown( type: MaskType, count: number ) { CONST_openedMask.set(type, count); const total = Array.from( CONST_openedMask.values() ).reduce((total, count) => { if (count > 0) { total += count } return total }, 0) if (total) { checkBodyScrollbar() addClass(document.body, IS_MODAL_OPEN_CLASS_NAME) setFullWidthElementsStyle() } else { removeClass(document.body, IS_MODAL_OPEN_CLASS_NAME) resetFullWidthElementsStyle() } }