tiptap: add center method in mind

This commit is contained in:
fantasticit 2022-04-26 19:13:37 +08:00
parent 08860dffee
commit 2e6a013203
11 changed files with 750 additions and 3818 deletions

3
packages/client/global.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
interface Window {
kityminder: any;
}

View File

@ -7,14 +7,15 @@ import styles from './style.module.scss';
interface IProps {
width: number;
height: number;
onChange: (arg: { width: number; height: number }) => void;
onChange?: (arg: { width: number; height: number }) => void;
onChangeEnd?: (arg: { width: number; height: number }) => void;
className?: string;
}
const MIN_WIDTH = 50;
const MIN_HEIGHT = 50;
export const Resizeable: React.FC<IProps> = ({ width, height, className, onChange, children }) => {
export const Resizeable: React.FC<IProps> = ({ width, height, className, onChange, onChangeEnd, children }) => {
const $container = useRef<HTMLDivElement>(null);
const $topLeft = useRef<HTMLDivElement>(null);
const $topRight = useRef<HTMLDivElement>(null);
@ -52,6 +53,10 @@ export const Resizeable: React.FC<IProps> = ({ width, height, className, onChang
Object.assign(event.target.dataset, { x, y });
onChange && onChange({ width, height });
},
end: function (event) {
let { width, height } = event.rect;
onChangeEnd && onChangeEnd({ width, height });
},
},
});
}, []);

View File

@ -51,6 +51,10 @@ export const Mind = Node.create({
default: 100,
parseHTML: getDatasetAttribute('zoom'),
},
callCenterCount: {
default: 0,
parseHTML: (element) => Number(getDatasetAttribute('callcentercount')(element)),
},
};
},

View File

@ -1,8 +1,7 @@
import { useCallback } from 'react';
import { useRouter } from 'next/router';
import cls from 'classnames';
import { Space, Button, List, Popover, Typography, RadioGroup, Radio } from '@douyinfe/semi-ui';
import { IconEdit, IconDelete } from '@douyinfe/semi-icons';
import { Space, Button, Popover, Typography } from '@douyinfe/semi-ui';
import { IconAlignCenter, IconDelete } from '@douyinfe/semi-icons';
import { Tooltip } from 'components/tooltip';
import { IconStructure, IconDrawBoard, IconZoomIn, IconZoomOut } from 'components/icons';
import { BubbleMenu } from '../../views/bubble-menu';
@ -15,7 +14,7 @@ import styles from './bubble.module.scss';
const { Text } = Typography;
export const MindBubbleMenu = ({ editor }) => {
const { template, theme, zoom } = editor.getAttributes(Mind.name);
const { template, theme, zoom, callCenterCount } = editor.getAttributes(Mind.name);
const setZoom = useCallback(
(type: 'minus' | 'plus') => {
@ -32,6 +31,18 @@ export const MindBubbleMenu = ({ editor }) => {
[editor, zoom]
);
const setCenter = useCallback(() => {
const nextValue = Number.isNaN(callCenterCount) ? 1 : Number(callCenterCount) + 1;
editor
.chain()
.updateAttributes(Mind.name, {
callCenterCount: nextValue,
})
.focus()
.run();
}, [editor, callCenterCount]);
const setTemplate = useCallback(
(template) => {
editor
@ -91,6 +102,11 @@ export const MindBubbleMenu = ({ editor }) => {
/>
</Tooltip>
<Tooltip content="居中">
<Button size="small" type="tertiary" theme="borderless" icon={<IconAlignCenter />} onClick={setCenter} />
</Tooltip>
<Divider />
<Popover
zIndex={10000}
spacing={10}
@ -103,6 +119,7 @@ export const MindBubbleMenu = ({ editor }) => {
{TEMPLATES.map((item) => {
return (
<li
key={item.label}
className={cls(template === item.value && styles.active)}
onClick={() => setTemplate(item.value)}
>
@ -130,6 +147,7 @@ export const MindBubbleMenu = ({ editor }) => {
{THEMES.map((item) => {
return (
<li
key={item.label}
className={cls(theme === item.value && styles.active)}
style={item.style || {}}
onClick={() => setTheme(item.value)}

View File

@ -1,10 +1,11 @@
import { NodeViewWrapper } from '@tiptap/react';
import cls from 'classnames';
import { useCallback, useEffect, useRef } from 'react';
import { Spin, Button } from '@douyinfe/semi-ui';
import { IconMinus, IconPlus } from '@douyinfe/semi-icons';
import { Resizeable } from 'components/resizeable';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Spin, Button, Typography } from '@douyinfe/semi-ui';
import { IconMinus, IconPlus, IconAlignCenter } from '@douyinfe/semi-icons';
import deepEqual from 'deep-equal';
import { Resizeable } from 'components/resizeable';
import { Tooltip } from 'components/tooltip';
import { useToggle } from 'hooks/use-toggle';
import { MIN_ZOOM, MAX_ZOOM, ZOOM_STEP } from '../../menus/mind/constant';
import { clamp } from '../../utils/clamp';
@ -12,21 +13,54 @@ import { Mind } from '../../extensions/mind';
import { loadKityMinder } from './kityminder';
import styles from './index.module.scss';
const { Text } = Typography;
export const MindWrapper = ({ editor, node, updateAttributes }) => {
const $container = useRef();
const $mind = useRef<any>();
const isMindActive = editor.isActive(Mind.name);
const isEditable = editor.isEditable;
const { data, template, theme, zoom, width, height = 100 } = node.attrs;
const { data, template, theme, zoom, callCenterCount, width, height } = node.attrs;
const [loading, toggleLoading] = useToggle(true);
const [error, setError] = useState<Error | null>(null);
const content = useMemo(() => {
if (error) {
return (
<div style={{ width: '100%', height: '100%' }}>
<Text>{error.message || error}</Text>
</div>
);
}
if (loading) {
return <Spin spinning={loading} style={{ width: '100%', height: '100%' }}></Spin>;
}
return (
<div
ref={$container}
className={cls(styles.renderWrap, 'render-wrapper')}
tabIndex={0}
style={{ width: '100%', height: '100%' }}
></div>
);
}, [loading, error]);
const onResize = useCallback(
(size) => {
updateAttributes({ width: size.width, height: size.height });
setCenter();
},
[updateAttributes]
);
const setCenter = useCallback(() => {
const minder = $mind.current;
if (!minder) return;
minder.execCommand('camera');
}, []);
const setZoom = useCallback(
(type: 'minus' | 'plus') => {
return () => {
@ -50,30 +84,46 @@ export const MindWrapper = ({ editor, node, updateAttributes }) => {
updateAttributes({ data: minder.exportJson() });
}, [updateAttributes]);
// 初始化
// 加载依赖
useEffect(() => {
loadKityMinder()
.then(() => {
toggleLoading(false);
})
.catch((e) => {
setError(e);
});
}, []);
// 初始化渲染
useEffect(() => {
if (loading || !$container.current) return;
const onChange = () => {
saveData();
};
loadKityMinder().then((Editor) => {
toggleLoading(false);
try {
const Editor = window.kityminder.Editor;
const minder = new Editor($container.current).minder;
minder.importJson(data);
minder.execCommand('template', template);
minder.execCommand('theme', theme);
minder.execCommand('zoom', parseInt(zoom));
$mind.current = minder;
minder.on('contentChange', onChange);
toggleLoading(false);
} catch (e) {
//
setError(e);
}
});
return () => {
if ($mind.current) {
$mind.current.off('contentChange', onChange);
}
};
}, [toggleLoading]);
}, [loading]);
// 数据同步渲染
useEffect(() => {
@ -82,7 +132,9 @@ export const MindWrapper = ({ editor, node, updateAttributes }) => {
const currentData = minder.exportJson();
const isEqual = deepEqual(currentData, data);
if (isEqual) return;
minder.importData(data);
// TODO: 也许刷新更好些
minder.importJson(data);
}, [data]);
// 布局
@ -118,21 +170,15 @@ export const MindWrapper = ({ editor, node, updateAttributes }) => {
}
}, [isEditable]);
const content = loading ? (
<Spin spinning={loading} style={{ width: '100%', height: '100%' }}></Spin>
) : (
<div
ref={$container}
className={cls(styles.renderWrap, 'render-wrapper')}
tabIndex={0}
style={{ width: '100%', height: '100%' }}
></div>
);
// 居中
useEffect(() => {
setCenter();
}, [callCenterCount]);
return (
<NodeViewWrapper className={cls(styles.wrap, isMindActive && styles.isActive)}>
{isEditable ? (
<Resizeable width={width} height={height} onChange={onResize}>
<Resizeable width={width} height={height} onChangeEnd={onResize}>
{content}
</Resizeable>
) : (
@ -141,6 +187,7 @@ export const MindWrapper = ({ editor, node, updateAttributes }) => {
{!isEditable && (
<div className={styles.mindHandlerWrap}>
<Tooltip content="缩小">
<Button
size="small"
theme="borderless"
@ -148,6 +195,8 @@ export const MindWrapper = ({ editor, node, updateAttributes }) => {
icon={<IconMinus style={{ fontSize: 14 }} />}
onClick={setZoom('minus')}
/>
</Tooltip>
<Tooltip content="放大">
<Button
size="small"
theme="borderless"
@ -155,6 +204,16 @@ export const MindWrapper = ({ editor, node, updateAttributes }) => {
icon={<IconPlus style={{ fontSize: 14 }} />}
onClick={setZoom('plus')}
/>
</Tooltip>
<Tooltip content="居中">
<Button
size="small"
theme="borderless"
type="tertiary"
icon={<IconAlignCenter style={{ fontSize: 14 }} />}
onClick={setCenter}
/>
</Tooltip>
</div>
)}
</NodeViewWrapper>

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,11 @@
export const loadKityMinder = async (): Promise<any> => {
if (typeof window !== 'undefined') {
if (window.kityminder) {
if (window.kityminder.Editor) return;
}
}
await import('kity');
await import('./kity-core/kityminder');
await import('./kity-editor/expose-editor');
const Editor = (window as any).kityminder.Editor;
return Editor;
};

View File

@ -26,8 +26,7 @@ define(function(require, exports, module) {
this._modules = {};
this._rendererClasses = {};
var i, name, type, module, moduleDeals,
dealCommands, dealEvents, dealRenderers;
var i, name, type, module, moduleDeals, dealCommands, dealEvents, dealRenderers;
var me = this;
for (i = 0; i < modulesToLoad.length; i++) {
@ -37,7 +36,7 @@ define(function(require, exports, module) {
// 执行模块初始化,抛出后续处理对象
if (typeof(modulesPool[name]) == 'function') {
if (typeof modulesPool[name] == 'function') {
moduleDeals = modulesPool[name].call(me);
} else {
moduleDeals = modulesPool[name];
@ -98,7 +97,6 @@ define(function(require, exports, module) {
dealRenderers = moduleDeals.renderers;
if (dealRenderers) {
for (type in dealRenderers) {
this._rendererClasses[type] = this._rendererClasses[type] || [];
@ -118,7 +116,7 @@ define(function(require, exports, module) {
},
_garbage: function () {
this.clearSelect();
// this.clearSelect();
while (this._root.getChildren().length) {
this._root.removeChild(0);
@ -146,6 +144,6 @@ define(function(require, exports, module) {
if (!modules[key].reset) continue;
modules[key].reset.call(this);
}
}
},
});
});

View File

@ -16,15 +16,17 @@ define(function(require, exports, module) {
utils.extend(Minder, {
getTemplateList: function () {
return _templates;
}
},
});
kity.extendClass(Minder, (function() {
kity.extendClass(
Minder,
(function () {
var originGetTheme = Minder.prototype.getTheme;
return {
useTemplate: function (name, duration) {
this.setTemplate(name);
this.refresh(duration || 800);
this.refresh(duration || 500);
},
getTemplate: function () {
@ -43,12 +45,14 @@ define(function(require, exports, module) {
getTheme: function (node) {
var support = this.getTemplateSupport('getTheme') || originGetTheme;
return support.call(this, node);
}
},
};
})());
})()
);
kity.extendClass(MinderNode, (function() {
kity.extendClass(
MinderNode,
(function () {
var originGetLayout = MinderNode.prototype.getLayout;
var originGetConnect = MinderNode.prototype.getConnect;
return {
@ -60,9 +64,11 @@ define(function(require, exports, module) {
getConnect: function () {
var support = this.getMinder().getTemplateSupport('getConnect') || originGetConnect;
return support.call(this, this);
}
},
};
})());
})()
);
let timer = null;
Module.register('TemplateModule', {
/**
@ -75,18 +81,21 @@ define(function(require, exports, module) {
* @return 返回当前的模板名称
*/
commands: {
'template': kity.createClass('TemplateCommand', {
template: kity.createClass('TemplateCommand', {
base: Command,
execute: function (minder, name) {
minder.useTemplate(name);
clearTimeout(timer);
timer = setTimeout(() => {
minder.execCommand('camera');
}, 550);
},
queryValue: function (minder) {
return minder.getTemplate() || 'default';
}
})
}
},
}),
},
});
});

View File

@ -43,19 +43,21 @@ define(function(require, exports, module) {
},
moveTo: function (position, duration) {
if (duration) {
var dragger = this;
if (this._moveTimeline) this._moveTimeline.stop();
this._moveTimeline = this._minder.getRenderContainer().animate(new kity.Animator(
this.getMovement(),
position,
function(target, value) {
this._moveTimeline = this._minder
.getRenderContainer()
.animate(
new kity.Animator(this.getMovement(), position, function (target, value) {
dragger.moveTo(value);
}
), duration, 'easeOutCubic').timeline();
}),
duration,
'easeOutCubic'
)
.timeline();
this._moveTimeline.on('finish', function () {
dragger._moveTimeline = null;
@ -77,7 +79,7 @@ define(function(require, exports, module) {
var minder = this._minder;
var c = minder._lastClientSize || {
width: minder.getRenderTarget().clientWidth,
height: minder.getRenderTarget().clientHeight
height: minder.getRenderTarget().clientHeight,
};
var m = this.getMovement();
var box = new kity.Box(0, 0, c.width, c.height);
@ -94,7 +96,6 @@ define(function(require, exports, module) {
function dragEnd(e) {
if (!lastPosition) return;
lastPosition = null;
e.stopPropagation();
@ -103,8 +104,7 @@ define(function(require, exports, module) {
if (isTempDrag) {
dragger.setEnabled(false);
isTempDrag = false;
if (dragger._minder.getStatus() == 'hand')
dragger._minder.rollbackStatus();
if (dragger._minder.getStatus() == 'hand') dragger._minder.rollbackStatus();
}
var paper = dragger._minder.getPaper();
paper.setStyle('cursor', dragger._minder.getStatus() == 'hand' ? '-webkit-grab' : 'default');
@ -112,7 +112,9 @@ define(function(require, exports, module) {
dragger._minder.fire('viewchanged');
}
this._minder.on('normal.mousedown normal.touchstart ' +
this._minder
.on(
'normal.mousedown normal.touchstart ' +
'inputready.mousedown inputready.touchstart ' +
'readonly.mousedown readonly.touchstart',
function (e) {
@ -124,9 +126,11 @@ define(function(require, exports, module) {
lastPosition = e.getPosition('view');
isTempDrag = true;
}
})
}
)
.on('normal.mousemove normal.touchmove ' +
.on(
'normal.mousemove normal.touchmove ' +
'readonly.mousemove readonly.touchmove ' +
'inputready.mousemove inputready.touchmove',
function (e) {
@ -140,7 +144,8 @@ define(function(require, exports, module) {
var paper = dragger._minder.getPaper();
paper.setStyle('cursor', '-webkit-grabbing');
}
})
}
)
.on('hand.beforemousedown hand.beforetouchstart', function (e) {
// 已经被用户打开拖放模式
@ -172,11 +177,10 @@ define(function(require, exports, module) {
this._minder.on('contextmenu', function (e) {
e.preventDefault();
});
}
},
});
Module.register('View', function () {
var km = this;
/**
@ -189,19 +193,17 @@ define(function(require, exports, module) {
var ToggleHandCommand = kity.createClass('ToggleHandCommand', {
base: Command,
execute: function (minder) {
if (minder.getStatus() != 'hand') {
minder.setStatus('hand', true);
} else {
minder.rollbackStatus();
}
this.setContentChanged(false);
},
queryState: function (minder) {
return minder.getStatus() == 'hand' ? 1 : 0;
},
enableReadOnly: true
enableReadOnly: true,
});
/**
@ -215,19 +217,31 @@ define(function(require, exports, module) {
var CameraCommand = kity.createClass('CameraCommand', {
base: Command,
execute: function (km, focusNode) {
const dragger = km._viewDragger;
const duration = km.getOption('viewAnimationDuration');
let dx = 0;
let dy = 0;
focusNode = focusNode || km.getRoot();
if (!focusNode || focusNode.type === 'root') {
// 默认居中
const parentNode = km.getPaper().node;
const shapeNode = km.getRoot().rc.container.node;
const { width: pw, height: ph, x: px, y: py } = parentNode.getBoundingClientRect();
const { width: sw, height: sh, x, y } = shapeNode.getBBox();
dx = pw / 2 - x - sw / 2;
dy = ph / 2 - y - sh / 2;
dragger.moveTo(new kity.Point(dx, dy), duration);
} else {
var viewport = km.getPaper().getViewPort();
var offset = focusNode.getRenderContainer().getRenderBox('view');
var dx = viewport.center.x - offset.x - offset.width / 2,
dx = viewport.center.x - offset.x - offset.width / 2;
dy = viewport.center.y - offset.y;
var dragger = km._viewDragger;
var duration = km.getOption('viewAnimationDuration');
dragger.move(new kity.Point(dx, dy), duration);
}
this.setContentChanged(false);
},
enableReadOnly: true
enableReadOnly: true,
});
/**
@ -265,7 +279,7 @@ define(function(require, exports, module) {
}
},
enableReadOnly: true
enableReadOnly: true,
});
return {
@ -273,33 +287,29 @@ define(function(require, exports, module) {
this._viewDragger = new ViewDragger(this);
},
commands: {
'hand': ToggleHandCommand,
'camera': CameraCommand,
'move': MoveCommand
hand: ToggleHandCommand,
camera: CameraCommand,
move: MoveCommand,
},
events: {
statuschange: function(e) {
'statuschange': function (e) {
this._viewDragger.setEnabled(e.currentStatus == 'hand');
},
mousewheel: function(e) {
'mousewheel': function (e) {
var dx, dy;
e = e.originEvent;
if (e.ctrlKey || e.shiftKey) return;
if ('wheelDeltaX' in e) {
dx = e.wheelDeltaX || 0;
dy = e.wheelDeltaY || 0;
} else {
dx = 0;
dy = e.wheelDelta;
}
this._viewDragger.move({
x: dx / 2.5,
y: dy / 2.5
y: dy / 2.5,
});
var me = this;
@ -322,17 +332,16 @@ define(function(require, exports, module) {
this.execCommand('camera', null, 0);
this._lastClientSize = {
width: this.getRenderTarget().clientWidth,
height: this.getRenderTarget().clientHeight
height: this.getRenderTarget().clientHeight,
};
},
resize: function(e) {
'resize': function (e) {
var a = {
width: this.getRenderTarget().clientWidth,
height: this.getRenderTarget().clientHeight
height: this.getRenderTarget().clientHeight,
},
b = this._lastClientSize;
this._viewDragger.move(
new kity.Point((a.width - b.width) / 2 | 0, (a.height - b.height) / 2 | 0));
this._viewDragger.move(new kity.Point(((a.width - b.width) / 2) | 0, ((a.height - b.height) / 2) | 0));
this._lastClientSize = a;
},
'selectionchange layoutallfinish': function (e) {
@ -367,16 +376,15 @@ define(function(require, exports, module) {
return;
}
var view = dragger.getView();
var focus = selected.getLayoutBox();
var space = 50;
var dx = 0, dy = 0;
var dx = 0,
dy = 0;
if (focus.right > view.right) {
dx += view.right - focus.right - space;
}
else if (focus.left < view.left) {
} else if (focus.left < view.left) {
dx += view.left - focus.left + space;
}
@ -388,10 +396,8 @@ define(function(require, exports, module) {
}
if (dx || dy) dragger.move(new kity.Point(dx, dy), 100);
}
}
},
},
};
});
});

View File

@ -30,6 +30,6 @@
"event/*": ["event/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"include": ["next-env.d.ts", "global.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}