UNPKG

@amaui/ui-react

Version:
414 lines (409 loc) 17 kB
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; const _excluded = ["tonal", "color", "valueDefault", "value", "onChange", "version", "orientation", "divider", "onFocus", "onBlur", "onMouseEnter", "onMouseLeave", "iconButtonComponent", "iconOrientationHorizontal", "iconOrientationVertical", "IconButtonProps", "SeparatorProps", "DividerProps", "Component", "className", "children"]; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } import React from 'react'; import { is, clamp, valueFromPercentageWithinRange, isEnvironment } from '@amaui/utils'; import { classNames, style as styleMethod, useAmauiTheme } from '@amaui/style-react'; import IconMaterialSwapHoriz from '@amaui/icons-material-rounded-react/IconMaterialSwapHorizW100'; import IconMaterialSwapVert from '@amaui/icons-material-rounded-react/IconMaterialSwapVertW100'; import LineElement from '../Line'; import DividerElement from '../Divider'; import IconButtonElement from '../IconButton'; import { staticClassName } from '../utils'; const useStyle = styleMethod(theme => ({ root: { position: 'relative', color: theme.palette.text.default.primary, touchAction: 'none', overflow: 'hidden' }, mouseDown_orientation_horizontal: { '& *': { cursor: 'ew-resize !important' } }, mouseDown_orientation_vertical: { '& *': { cursor: 'ns-resize !important' } }, focus: { outline: '4px solid currentColor', outlineOffset: '8px' }, hidden: { lineHeight: '0', visibility: 'hidden' }, item: { lineHeight: '0', overflow: 'hidden' }, start: { position: 'absolute', inset: '0', zIndex: '1', '& > *': { maxWidth: 'unset !important' } }, end: { position: 'absolute', inset: '0', zIndex: '0' }, iconButton: { position: 'absolute', userSelect: 'none', zIndex: '4' }, iconButton_manual_orientation_horizontal: { cursor: 'ew-resize' }, iconButton_manual_orientation_vertical: { cursor: 'ns-resize' }, iconButton_orientation_horizontal: { transform: `translateX(${theme.direction === 'rtl' ? '-' : ''}50%)` }, iconButton_orientation_vertical: { transform: `translateY(50%)` }, divider: { position: 'absolute', userSelect: 'none', zIndex: '3', borderRadius: theme.methods.shape.radius.value('lg', 'px'), '&.amaui-Divider-root': { margin: '0px' } }, divider_manual_orientation_horizontal: { cursor: 'ew-resize' }, divider_manual_orientation_vertical: { cursor: 'ns-resize' }, divider_orientation_horizontal: { insetBlock: '0', transform: `translateX(${theme.direction === 'rtl' ? '-' : ''}50%)`, '&.amaui-Divider-root': { width: '8px' } }, divider_orientation_vertical: { insetInline: '0', transform: `translateY(50%)`, '&.amaui-Divider-root': { height: '8px' } } }), { name: 'amaui-ViewSplit' }); const ViewSplit = /*#__PURE__*/React.forwardRef((props_, ref) => { const theme = useAmauiTheme(); const props = React.useMemo(() => _objectSpread(_objectSpread(_objectSpread({}, theme?.ui?.elements?.all?.props?.default), theme?.ui?.elements?.amauiViewSplit?.props?.default), props_), [props_]); const Line = React.useMemo(() => theme?.elements?.Line || LineElement, [theme]); const IconButton = React.useMemo(() => theme?.elements?.IconButton || IconButtonElement, [theme]); const Divider = React.useMemo(() => theme?.elements?.Divider || DividerElement, [theme]); const { tonal = true, color = 'primary', valueDefault, value: value_ = 50, onChange: onChange_, version = 'auto', orientation = 'horizontal', divider = props.version === 'manual', onFocus: onFocus_, onBlur: onBlur_, onMouseEnter: onMouseEnter_, onMouseLeave: onMouseLeave_, iconButtonComponent, iconOrientationHorizontal = /*#__PURE__*/React.createElement(IconMaterialSwapHoriz, null), iconOrientationVertical = /*#__PURE__*/React.createElement(IconMaterialSwapVert, null), IconButtonProps = { version: 'filled', elevation: false }, SeparatorProps: SeparatorProps_, DividerProps = {}, Component = 'div', className, children: children_ } = props, other = _objectWithoutProperties(props, _excluded); const { classes } = useStyle(); const [init, setInit] = React.useState(false); const [rect, setRect] = React.useState(); const [hover, setHover] = React.useState(); const [focus, setFocus] = React.useState(); const [mouseDown, setMouseDown] = React.useState(); const [value, setValue] = React.useState(valueDefault !== undefined ? valueDefault : value_); const refs = { root: React.useRef(undefined), value: React.useRef(undefined), mouseDown: React.useRef(undefined), hover: React.useRef(undefined), props: React.useRef(undefined), orientation: React.useRef(undefined), version: React.useRef(undefined), direction: React.useRef(undefined), ids: { root: React.useId() } }; refs.value.current = value; refs.mouseDown.current = mouseDown; refs.hover.current = hover; refs.props.current = props; refs.orientation.current = orientation; refs.version.current = version; refs.direction.current = theme.direction; const styles = { start: { [orientation === 'horizontal' ? 'insetInlineEnd' : 'insetBlockEnd']: `${value}%` }, startItem: { width: rect?.width }, divider: { [orientation === 'horizontal' ? 'insetInlineEnd' : 'insetBlockEnd']: `${value}%` } }; IconButtonProps.tonal = IconButtonProps.tonal !== undefined ? IconButtonProps.tonal : tonal; IconButtonProps.color = IconButtonProps.color !== undefined ? IconButtonProps.color : color; DividerProps.tonal = DividerProps.tonal !== undefined ? DividerProps.tonal : tonal; DividerProps.color = DividerProps.color !== undefined ? DividerProps.color : color; const min = 0; const max = 100; const valuePrecision = valueMouse => { let valueNew = max + min - valueFromPercentageWithinRange(valueMouse * 100, min, max); if (refs.direction.current === 'rtl' && refs.orientation.current === 'horizontal') valueNew = max + min - valueNew; if (valueNew <= min) return min; if (valueNew >= max) return max; return valueNew; }; React.useEffect(() => { const onMouseUp = () => { setMouseDown(false); setFocus(false); }; const onMouseMove = event => { if (refs.version.current === 'auto' && refs.hover.current || refs.version.current === 'manual' && refs.mouseDown.current) { const x = event.clientX; const y = event.clientY; const rect_ = refs.root.current.getBoundingClientRect(); const { width, height } = rect_; // Value to the precision point value let valueNew = refs.orientation.current === 'horizontal' ? (x - rect_.x) / width : (y - rect_.y) / height; valueNew = valuePrecision(valueNew); onChange(valueNew); } }; const onTouchMove = event => { if (refs.mouseDown.current) { const x = event.touches[0].clientX; const y = event.touches[0].clientY; const rect_ = refs.root.current.getBoundingClientRect(); const { width, height } = rect_; // Value to the precision point value let valueNew = refs.orientation.current === 'horizontal' ? (x - rect_.x) / width : (y - rect_.y) / height; valueNew = valuePrecision(valueNew); onChange(valueNew); } }; const method = () => { if (refs.root.current) { const rect_ = refs.root.current.getBoundingClientRect(); setRect(rect_); } }; const observer = new ResizeObserver(method); observer.observe(refs.root.current); method(); const rootDocument = isEnvironment('browser') ? refs.root.current?.ownerDocument || window.document : undefined; rootDocument.addEventListener('mouseup', onMouseUp); rootDocument.addEventListener('mousemove', onMouseMove); rootDocument.addEventListener('touchend', onMouseUp, { passive: true }); rootDocument.addEventListener('touchmove', onTouchMove); setInit(true); return () => { // Clean up observer.disconnect(); rootDocument.removeEventListener('mouseup', onMouseUp); rootDocument.removeEventListener('touchend', onMouseUp); rootDocument.removeEventListener('mousemove', onMouseMove); rootDocument.removeEventListener('touchmove', onTouchMove); }; }, []); React.useEffect(() => { if (init) { if (value_ !== value) setValue(value_); } }, [value_]); const onTouchStart = event => { const x = event.touches[0].clientX; const y = event.touches[0].clientY; const rect_ = refs.root.current.getBoundingClientRect(); const { width, height } = rect_; // Value to the precision point value let valueNew = refs.orientation.current === 'horizontal' ? (x - rect_.x) / width : (y - rect_.y) / height; valueNew = valuePrecision(valueNew); onChange(valueNew); setMouseDown(true); }; const onFocus = React.useCallback(event => { setFocus(true); if (is('function', onFocus_)) onFocus_(event); }, []); const onBlur = React.useCallback(event => { setFocus(false); if (is('function', onBlur_)) onBlur_(event); }, []); const onFocusIconButton = React.useCallback(event => { setFocus(true); }, []); const onBlurIconButton = React.useCallback(event => { setFocus(false); }, []); const onMouseEnter = React.useCallback(event => { setHover(true); if (is('function', onMouseEnter_)) onMouseEnter_(event); }, []); const onMouseLeave = React.useCallback(event => { setHover(false); setFocus(false); if (is('function', onMouseLeave_)) onMouseLeave_(event); }, []); const onMouseDown = React.useCallback(() => { setMouseDown(true); }, []); const move = function () { let forward_ = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; let forward = forward_; if (refs.orientation.current === 'horizontal') { if (refs.direction.current === 'rtl') forward = !forward; } let valueNew = refs.value.current || 0; valueNew = clamp(valueNew + (forward ? 1 : -1), 0, 100); // Update onChange(valueNew); }; const onKeyDown = React.useCallback(event => { if (['ArrowUp', 'ArrowRight', 'ArrowLeft', 'ArrowDown', 'Home', 'End'].includes(event.key)) { if (['Home', 'End'].includes(event.key) || ['ArrowLeft', 'ArrowRight'].includes(event.key) && refs.orientation.current === 'horizontal' || ['ArrowUp', 'ArrowDown'].includes(event.key) && refs.orientation.current === 'vertical') { // Prevent default event.preventDefault(); let valueNew; switch (event.key) { case 'Home': valueNew = refs.orientation.current !== 'vertical' ? 0 : 100; return onChange(valueNew); case 'End': valueNew = refs.orientation.current !== 'vertical' ? 100 : 0; return onChange(valueNew); case 'ArrowUp': case 'ArrowLeft': return move(); case 'ArrowDown': case 'ArrowRight': return move(false); default: break; } } } }, []); const onChange = valueItem => { // Update inner or controlled if (!props.hasOwnProperty('value')) setValue(valueItem); if (is('function', onChange_)) onChange_(valueItem); }; const SeparatorProps = _objectSpread(_objectSpread({}, SeparatorProps_), {}, { role: 'separator', 'aria-label': 'View separator', 'aria-valuenow': value, 'aria-valuemin': 0, 'aria-valuemax': 100, 'aria-valuetext': `${value}%`, 'aria-controls': refs.ids.root }); const direction = orientation === 'horizontal' ? 'row' : 'column'; // Only 2 children to use const children = React.Children.toArray(children_).slice(0, 2); return /*#__PURE__*/React.createElement(Line, _extends({ ref: item => { if (ref) { if (is('function', ref)) ref(item);else ref.current = item; } refs.root.current = item; }, tabIndex: version === 'auto' ? 0 : undefined, gap: 0, direction: direction, align: "center", justify: "center", onFocus: onFocus, onBlur: onBlur, onMouseEnter: onMouseEnter, onMouseLeave: onMouseLeave, onTouchStart: onTouchStart, onKeyDown: onKeyDown, id: refs.ids.root, "aria-orientation": orientation, Component: Component, className: classNames([staticClassName('ViewSplit', theme) && ['amaui-ViewSplit-root', `amaui-ViewSplit-version-${version}`, hover && `amaui-ViewSplit-hover`, focus && `amaui-ViewSplit-focus`, mouseDown && `amaui-ViewSplit-mouse-down`], className, classes.root, version === 'manual' && mouseDown && classes[`mouseDown_orientation_${orientation}`], focus && !(hover || mouseDown) && classes.focus]) }, other), children[0] && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", { className: classNames([staticClassName('ViewSplit', theme) && ['amaui-ViewSplit-hidden'], classes.hidden]) }, children[0]), /*#__PURE__*/React.createElement("div", { className: classNames([staticClassName('ViewSplit', theme) && ['amaui-ViewSplit-start'], classes.item, classes.start]), style: _objectSpread({}, styles.start) }, /*#__PURE__*/React.cloneElement(children[0], { style: _objectSpread(_objectSpread({}, styles.startItem), children[0].props.style) }))), divider && /*#__PURE__*/React.createElement(Divider, _extends({ onMouseDown: event => { onMouseDown(); if (is('function', DividerProps?.onMouseDown)) IconButtonProps.onMouseDown(event); }, orientation: orientation === 'vertical' ? 'horizontal' : 'vertical' }, DividerProps, { className: classNames([staticClassName('ViewSplit', theme) && ['amaui-ViewSplit-divider'], DividerProps?.className, classes.divider, classes[`divider_orientation_${orientation}`], version === 'manual' && classes[`divider_manual_orientation_${orientation}`]]), style: _objectSpread(_objectSpread({}, styles.divider), DividerProps?.style) })), version === 'manual' && (iconButtonComponent && /*#__PURE__*/React.cloneElement(iconButtonComponent, _objectSpread({ className: classNames([staticClassName('ViewSplit', theme) && ['amaui-ViewSplit-icon-button'], classes.iconButton, classes[`iconButton_orientation_${orientation}`], version === 'manual' && classes[`iconButton_manual_orientation_${orientation}`]]) }, SeparatorProps)) || /*#__PURE__*/React.createElement(IconButton, _extends({ onFocus: onFocusIconButton, onBlur: onBlurIconButton, onMouseDown: event => { onMouseDown(); if (is('function', IconButtonProps?.onMouseDown)) IconButtonProps.onMouseDown(event); } }, SeparatorProps, IconButtonProps, { className: classNames([staticClassName('ViewSplit', theme) && ['amaui-ViewSplit-icon-button'], IconButtonProps?.className, classes.iconButton, classes[`iconButton_orientation_${orientation}`], version === 'manual' && classes[`iconButton_manual_orientation_${orientation}`]]), style: _objectSpread(_objectSpread({}, styles.start), IconButtonProps?.style) }), orientation === 'horizontal' ? iconOrientationHorizontal : orientation === 'vertical' ? iconOrientationVertical : undefined)), children[1] && /*#__PURE__*/React.createElement("div", { className: classNames([staticClassName('ViewSplit', theme) && ['amaui-ViewSplit-end'], classes.item, classes.end]) }, /*#__PURE__*/React.cloneElement(children[1], { style: _objectSpread(_objectSpread({}, styles.endItem), children[1].props.style) }))); }); ViewSplit.displayName = 'amaui-ViewSplit'; export default ViewSplit;