feat(core): adjust split view ui (#6076)

This commit is contained in:
Cats Juice
2024-03-14 06:41:28 +00:00
parent b9fc848824
commit 7fdb1f2d97
14 changed files with 336 additions and 105 deletions

View File

@@ -8,15 +8,24 @@ export const sidebarContainerInner = style({
overflow: 'hidden',
height: '100%',
width: '100%',
borderRadius: 'inherit',
selectors: {
['[data-client-border=true][data-is-floating="true"] &']: {
boxShadow: cssVar('shadow3'),
border: `1px solid ${cssVar('borderColor')}`,
},
},
});
export const sidebarContainer = style({
display: 'flex',
flexShrink: 0,
height: '100%',
right: 0,
selectors: {
[`&[data-client-border=true]`]: {
paddingLeft: 9,
paddingLeft: 8,
borderRadius: 6,
},
[`&[data-client-border=false]`]: {
borderLeft: `1px solid ${cssVar('borderColor')}`,

View File

@@ -1,9 +1,10 @@
import { ResizePanel } from '@affine/component/resize-panel';
import { appSidebarOpenAtom } from '@affine/core/components/app-sidebar';
import { appSettingAtom } from '@toeverything/infra/atom';
import { useService } from '@toeverything/infra/di';
import { useLiveData } from '@toeverything/infra/livedata';
import { useAtomValue } from 'jotai';
import { useCallback, useState } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { RightSidebar } from '../entities/right-sidebar';
import * as styles from './container.css';
@@ -20,6 +21,18 @@ export const RightSidebarContainer = () => {
const frontView = useLiveData(rightSidebar.front);
const open = useLiveData(rightSidebar.isOpen) && frontView !== undefined;
const [floating, setFloating] = useState(false);
const appSidebarOpened = useAtomValue(appSidebarOpenAtom);
useEffect(() => {
const onResize = () =>
setFloating(!!(window.innerWidth < 1200 && appSidebarOpened));
onResize();
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
}, [appSidebarOpened]);
const handleOpenChange = useCallback(
(open: boolean) => {
@@ -38,8 +51,9 @@ export const RightSidebarContainer = () => {
return (
<ResizePanel
floating={floating}
resizeHandlePos="left"
resizeHandleOffset={clientBorder ? 4 : 0}
resizeHandleOffset={clientBorder ? 3.5 : 0}
width={width}
resizing={resizing}
onResizing={setResizing}

View File

@@ -5,7 +5,12 @@ import { combineLatest, map, switchMap } from 'rxjs';
import { View } from './view';
export type WorkbenchPosition = 'beside' | 'active' | number;
export type WorkbenchPosition = 'beside' | 'active' | 'head' | 'tail' | number;
interface WorkbenchOpenOptions {
at?: WorkbenchPosition;
replaceHistory?: boolean;
}
export class Workbench {
readonly views = new LiveData([new View()]);
@@ -37,10 +42,7 @@ export class Workbench {
open(
to: To,
{
at = 'active',
replaceHistory = false,
}: { at?: WorkbenchPosition; replaceHistory?: boolean } = {}
{ at = 'active', replaceHistory = false }: WorkbenchOpenOptions = {}
) {
let view = this.viewAt(at);
if (!view) {
@@ -58,32 +60,32 @@ export class Workbench {
}
}
openPage(pageId: string) {
this.open(`/${pageId}`);
openPage(pageId: string, options?: WorkbenchOpenOptions) {
this.open(`/${pageId}`, options);
}
openCollections() {
this.open('/collection');
openCollections(options?: WorkbenchOpenOptions) {
this.open('/collection', options);
}
openCollection(collectionId: string) {
this.open(`/collection/${collectionId}`);
openCollection(collectionId: string, options?: WorkbenchOpenOptions) {
this.open(`/collection/${collectionId}`, options);
}
openAll() {
this.open('/all');
openAll(options?: WorkbenchOpenOptions) {
this.open('/all', options);
}
openTrash() {
this.open('/trash');
openTrash(options?: WorkbenchOpenOptions) {
this.open('/trash', options);
}
openTags() {
this.open('/tag');
openTags(options?: WorkbenchOpenOptions) {
this.open('/tag', options);
}
openTag(tagId: string) {
this.open(`/tag/${tagId}`);
openTag(tagId: string, options?: WorkbenchOpenOptions) {
this.open(`/tag/${tagId}`, options);
}
viewAt(positionIndex: WorkbenchPosition): View | undefined {
@@ -96,12 +98,16 @@ export class Workbench {
if (index === -1) return;
const newViews = [...this.views.value];
newViews.splice(index, 1);
if (index !== 0) {
this.active(index - 1);
}
this.views.next(newViews);
}
closeOthers(view: View) {
view.size.next(100);
this.views.next([view]);
this.active(0);
}
moveView(from: number, to: number) {
@@ -128,8 +134,15 @@ export class Workbench {
0
);
const percentOfTotal = totalViewSize * percent;
view.setSize(Number((view.size.value + percentOfTotal).toFixed(4)));
nextView.setSize(Number((nextView.size.value - percentOfTotal).toFixed(4)));
const newSize = Number((view.size.value + percentOfTotal).toFixed(4));
const newNextSize = Number(
(nextView.size.value - percentOfTotal).toFixed(4)
);
// TODO: better strategy to limit size
if (newSize / totalViewSize < 0.2 || newNextSize / totalViewSize < 0.2)
return;
view.setSize(newSize);
nextView.setSize(newNextSize);
}
private indexAt(positionIndex: WorkbenchPosition): number {
@@ -139,6 +152,12 @@ export class Workbench {
if (positionIndex === 'beside') {
return this.activeViewIndex.value + 1;
}
if (positionIndex === 'head') {
return 0;
}
if (positionIndex === 'tail') {
return this.views.value.length;
}
return positionIndex;
}
}

View File

@@ -1,13 +1,35 @@
import { cssVar } from '@toeverything/theme';
import { style } from '@vanilla-extract/css';
export const indicatorWrapper = style({
position: 'absolute',
zIndex: 4,
top: 0,
left: '50%',
transform: 'translateX(-50%)',
width: '50%',
maxWidth: 300,
minWidth: 120,
height: 15,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
['WebkitAppRegion' as string]: 'no-drag',
});
export const menuTrigger = style({
position: 'absolute',
width: 0,
height: 0,
pointerEvents: 'none',
});
export const indicator = style({
width: 29,
height: 14,
height: 15,
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
cursor: 'pointer',
cursor: 'grab',
['WebkitAppRegion' as string]: 'no-drag',
color: cssVar('placeholderColor'),
@@ -19,8 +41,16 @@ export const indicator = style({
});
export const indicatorInner = style({
width: 15,
width: 16,
height: 3,
borderRadius: 10,
backgroundColor: 'currentColor',
transition: 'all 0.5s cubic-bezier(0.16, 1, 0.3, 1)',
selectors: {
'[data-is-dragging="true"] &': {
width: 24,
height: 2,
},
},
});

View File

@@ -1,23 +1,61 @@
import { Menu, type MenuProps } from '@affine/component';
import clsx from 'clsx';
import { forwardRef, type HTMLAttributes, memo } from 'react';
import {
forwardRef,
type HTMLAttributes,
memo,
type MouseEventHandler,
useCallback,
useMemo,
useState,
} from 'react';
import * as styles from './indicator.css';
export interface SplitViewMenuProps extends HTMLAttributes<HTMLDivElement> {
active?: boolean;
open?: boolean;
onOpenMenu?: () => void;
setPressed: (v: boolean) => void;
}
export const SplitViewMenuIndicator = memo(
forwardRef<HTMLDivElement, SplitViewMenuProps>(
function SplitViewMenuIndicator(
{ className, active, ...attrs }: SplitViewMenuProps,
{
className,
active,
open,
setPressed,
onOpenMenu,
...attrs
}: SplitViewMenuProps,
ref
) {
// dnd's `isDragging` changes after mouseDown and mouseMoved
const onMouseDown = useCallback(() => {
const t = setTimeout(() => setPressed(true), 100);
window.addEventListener(
'mouseup',
() => {
clearTimeout(t);
setPressed(false);
},
{ once: true }
);
}, [setPressed]);
const onClick: MouseEventHandler = useCallback(() => {
!open && onOpenMenu?.();
}, [onOpenMenu, open]);
return (
<div
ref={ref}
data-active={active}
className={clsx(className, styles.indicator)}
onClick={onClick}
onMouseDown={onMouseDown}
{...attrs}
>
<div className={styles.indicatorInner} />
@@ -26,3 +64,66 @@ export const SplitViewMenuIndicator = memo(
}
)
);
interface SplitViewIndicatorProps extends HTMLAttributes<HTMLDivElement> {
isDragging?: boolean;
isActive?: boolean;
menuItems?: React.ReactNode;
// import type { SyntheticListenerMap } from '@dnd-kit/core/dist/hooks/utilities' is not allowed
listeners?: any;
setPressed?: (pressed: boolean) => void;
}
export const SplitViewIndicator = ({
isDragging,
isActive,
menuItems,
listeners,
setPressed,
}: SplitViewIndicatorProps) => {
const active = isActive || isDragging;
const [menuOpen, setMenuOpen] = useState(false);
// prevent menu from opening when dragging
const setOpenMenuManually = useCallback((open: boolean) => {
if (open) return;
setMenuOpen(open);
}, []);
const openMenu = useCallback(() => {
setMenuOpen(true);
}, []);
const menuRootOptions = useMemo(
() =>
({
open: menuOpen,
onOpenChange: setOpenMenuManually,
}) satisfies MenuProps['rootOptions'],
[menuOpen, setOpenMenuManually]
);
const menuContentOptions = useMemo(
() =>
({
align: 'center',
}) satisfies MenuProps['contentOptions'],
[]
);
return (
<div data-is-dragging={isDragging} className={styles.indicatorWrapper}>
<Menu
contentOptions={menuContentOptions}
items={menuItems}
rootOptions={menuRootOptions}
>
<div className={styles.menuTrigger} />
</Menu>
<SplitViewMenuIndicator
open={menuOpen}
onOpenMenu={openMenu}
active={active}
setPressed={setPressed}
{...listeners}
/>
</div>
);
};

View File

@@ -1,10 +1,10 @@
import { Menu, MenuIcon, MenuItem, type MenuProps } from '@affine/component';
import { MenuIcon, MenuItem } from '@affine/component';
import { useAFFiNEI18N } from '@affine/i18n/hooks';
import {
CloseIcon,
ExpandFullIcon,
InsertLeftIcon,
InsertRightIcon,
ExpandCloseIcon,
KeepThisOneIcon,
MoveToLeftIcon,
MoveToRightIcon,
} from '@blocksuite/icons';
import { useSortable } from '@dnd-kit/sortable';
import { useService } from '@toeverything/infra/di';
@@ -26,7 +26,7 @@ import {
import type { View } from '../../entities/view';
import { Workbench } from '../../entities/workbench';
import { SplitViewMenuIndicator } from './indicator';
import { SplitViewIndicator } from './indicator';
import * as styles from './split-view.css';
export interface SplitViewPanelProps
@@ -43,22 +43,24 @@ export const SplitViewPanel = memo(function SplitViewPanel({
view,
setSlots,
}: SplitViewPanelProps) {
const [indicatorPressed, setIndicatorPressed] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const size = useLiveData(view.size);
const [menuOpen, setMenuOpen] = useState(false);
const workbench = useService(Workbench);
const activeView = useLiveData(workbench.activeView);
const views = useLiveData(workbench.views);
const isLast = views[views.length - 1] === view;
const {
attributes,
listeners,
transform,
transition,
isDragging,
isDragging: dndIsDragging,
setNodeRef,
setActivatorNodeRef,
} = useSortable({ id: view.id, attributes: { role: 'group' } });
const isDragging = dndIsDragging || indicatorPressed;
const isActive = activeView === view;
useEffect(() => {
@@ -67,12 +69,6 @@ export const SplitViewPanel = memo(function SplitViewPanel({
}
}, [setSlots, view.id]);
useEffect(() => {
if (isDragging) {
setMenuOpen(false);
}
}, [isDragging]);
const style = useMemo(
() => ({
...assignInlineVars({ '--size': size.toString() }),
@@ -86,27 +82,14 @@ export const SplitViewPanel = memo(function SplitViewPanel({
}),
[transform, transition]
);
const menuRootOptions = useMemo(
() =>
({
open: menuOpen,
onOpenChange: setMenuOpen,
}) satisfies MenuProps['rootOptions'],
[menuOpen]
);
const menuContentOptions = useMemo(
() =>
({
align: 'center',
}) satisfies MenuProps['contentOptions'],
[]
);
return (
<div
style={style}
className={styles.splitViewPanel}
data-is-dragging={isDragging}
data-is-active={isActive && views.length > 1}
data-is-last={isLast}
>
<div
ref={setNodeRef}
@@ -116,18 +99,13 @@ export const SplitViewPanel = memo(function SplitViewPanel({
>
<div className={styles.splitViewPanelContent} ref={ref} />
{views.length > 1 ? (
<Menu
contentOptions={menuContentOptions}
items={<SplitViewMenu view={view} />}
rootOptions={menuRootOptions}
>
<SplitViewMenuIndicator
ref={setActivatorNodeRef}
active={isDragging || isActive}
className={styles.menuTrigger}
{...listeners}
/>
</Menu>
<SplitViewIndicator
listeners={listeners}
isDragging={isDragging}
isActive={isActive}
menuItems={<SplitViewMenu view={view} />}
setPressed={setIndicatorPressed}
/>
) : null}
</div>
{children}
@@ -135,10 +113,7 @@ export const SplitViewPanel = memo(function SplitViewPanel({
);
});
interface SplitViewMenuProps {
view: View;
}
const SplitViewMenu = ({ view }: SplitViewMenuProps) => {
const SplitViewMenu = ({ view }: { view: View }) => {
const t = useAFFiNEI18N();
const workbench = useService(Workbench);
const views = useLiveData(workbench.views);
@@ -155,14 +130,14 @@ const SplitViewMenu = ({ view }: SplitViewMenuProps) => {
const handleMoveRight = useCallback(() => {
workbench.moveView(viewIndex, viewIndex + 1);
}, [viewIndex, workbench]);
const handleFullScreen = useCallback(() => {
const handleCloseOthers = useCallback(() => {
workbench.closeOthers(view);
}, [view, workbench]);
const CloseItem =
views.length > 1 ? (
<MenuItem
preFix={<MenuIcon icon={<CloseIcon />} />}
preFix={<MenuIcon icon={<ExpandCloseIcon />} />}
onClick={handleClose}
>
{t['com.affine.workbench.split-view-menu.close']()}
@@ -173,7 +148,7 @@ const SplitViewMenu = ({ view }: SplitViewMenuProps) => {
viewIndex > 0 && views.length > 1 ? (
<MenuItem
onClick={handleMoveLeft}
preFix={<MenuIcon icon={<InsertLeftIcon />} />}
preFix={<MenuIcon icon={<MoveToLeftIcon />} />}
>
{t['com.affine.workbench.split-view-menu.move-left']()}
</MenuItem>
@@ -182,10 +157,10 @@ const SplitViewMenu = ({ view }: SplitViewMenuProps) => {
const FullScreenItem =
views.length > 1 ? (
<MenuItem
onClick={handleFullScreen}
preFix={<MenuIcon icon={<ExpandFullIcon />} />}
onClick={handleCloseOthers}
preFix={<MenuIcon icon={<KeepThisOneIcon />} />}
>
{t['com.affine.workbench.split-view-menu.full-screen']()}
{t['com.affine.workbench.split-view-menu.keep-this-one']()}
</MenuItem>
) : null;
@@ -193,7 +168,7 @@ const SplitViewMenu = ({ view }: SplitViewMenuProps) => {
viewIndex < views.length - 1 ? (
<MenuItem
onClick={handleMoveRight}
preFix={<MenuIcon icon={<InsertRightIcon />} />}
preFix={<MenuIcon icon={<MoveToRightIcon />} />}
>
{t['com.affine.workbench.split-view-menu.move-right']()}
</MenuItem>

View File

@@ -17,7 +17,7 @@ export const splitViewRoot = style({
selectors: {
'&[data-client-border="true"]': {
vars: {
[gap]: '6px',
[gap]: '8px',
[borderRadius]: '6px',
},
},
@@ -40,7 +40,7 @@ export const splitViewPanel = style({
'[data-orientation="horizontal"] &': {
width: 0,
},
'[data-client-border="false"] &:not(:last-child):not([data-is-dragging="true"])':
'[data-client-border="false"] &:not([data-is-last="true"]):not([data-is-dragging="true"])':
{
borderRight: `1px solid ${cssVar('borderColor')}`,
},
@@ -63,6 +63,10 @@ export const splitViewPanelDrag = style({
borderRadius: 'inherit',
pointerEvents: 'none',
zIndex: 10,
// animate border in/out
boxShadow: `inset 0 0 0 0 transparent`,
transition: 'box-shadow 0.5s cubic-bezier(0.16, 1, 0.3, 1)',
},
'[data-is-dragging="true"] &::after': {
@@ -125,11 +129,3 @@ export const resizeHandle = style({
// TODO
},
});
export const menuTrigger = style({
position: 'absolute',
left: '50%',
top: 3,
transform: 'translateX(-50%)',
zIndex: 10,
});

View File

@@ -58,7 +58,7 @@ export const SplitView = ({
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 2,
distance: 0,
},
})
);