tiptap: add center method in mind

pull/29/head
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 100644
View File

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

View File

@ -7,14 +7,15 @@ import styles from './style.module.scss';
interface IProps { interface IProps {
width: number; width: number;
height: 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; className?: string;
} }
const MIN_WIDTH = 50; const MIN_WIDTH = 50;
const MIN_HEIGHT = 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 $container = useRef<HTMLDivElement>(null);
const $topLeft = useRef<HTMLDivElement>(null); const $topLeft = useRef<HTMLDivElement>(null);
const $topRight = 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 }); Object.assign(event.target.dataset, { x, y });
onChange && onChange({ width, height }); 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, default: 100,
parseHTML: getDatasetAttribute('zoom'), parseHTML: getDatasetAttribute('zoom'),
}, },
callCenterCount: {
default: 0,
parseHTML: (element) => Number(getDatasetAttribute('callcentercount')(element)),
},
}; };
}, },

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -1,4 +1,4 @@
define(function(require, exports, module) { define(function (require, exports, module) {
var kity = require('./kity'); var kity = require('./kity');
var utils = require('./utils'); var utils = require('./utils');
var Minder = require('./minder'); var Minder = require('./minder');
@ -6,18 +6,18 @@ define(function(require, exports, module) {
/* 已注册的模块 */ /* 已注册的模块 */
var _modules = {}; var _modules = {};
exports.register = function(name, module) { exports.register = function (name, module) {
_modules[name] = module; _modules[name] = module;
}; };
/* 模块初始化 */ /* 模块初始化 */
Minder.registerInitHook(function() { Minder.registerInitHook(function () {
this._initModules(); this._initModules();
}); });
// 模块声明周期维护 // 模块声明周期维护
kity.extendClass(Minder, { kity.extendClass(Minder, {
_initModules: function() { _initModules: function () {
var modulesPool = _modules; var modulesPool = _modules;
var modulesToLoad = this._options.modules || utils.keys(modulesPool); var modulesToLoad = this._options.modules || utils.keys(modulesPool);
@ -26,8 +26,7 @@ define(function(require, exports, module) {
this._modules = {}; this._modules = {};
this._rendererClasses = {}; this._rendererClasses = {};
var i, name, type, module, moduleDeals, var i, name, type, module, moduleDeals, dealCommands, dealEvents, dealRenderers;
dealCommands, dealEvents, dealRenderers;
var me = this; var me = this;
for (i = 0; i < modulesToLoad.length; i++) { 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); moduleDeals = modulesPool[name].call(me);
} else { } else {
moduleDeals = modulesPool[name]; moduleDeals = modulesPool[name];
@ -98,7 +97,6 @@ define(function(require, exports, module) {
dealRenderers = moduleDeals.renderers; dealRenderers = moduleDeals.renderers;
if (dealRenderers) { if (dealRenderers) {
for (type in dealRenderers) { for (type in dealRenderers) {
this._rendererClasses[type] = this._rendererClasses[type] || []; this._rendererClasses[type] = this._rendererClasses[type] || [];
@ -117,15 +115,15 @@ define(function(require, exports, module) {
} }
}, },
_garbage: function() { _garbage: function () {
this.clearSelect(); // this.clearSelect();
while (this._root.getChildren().length) { while (this._root.getChildren().length) {
this._root.removeChild(0); this._root.removeChild(0);
} }
}, },
destroy: function() { destroy: function () {
var modules = this._modules; var modules = this._modules;
this._resetEvents(); this._resetEvents();
@ -137,7 +135,7 @@ define(function(require, exports, module) {
} }
}, },
reset: function() { reset: function () {
var modules = this._modules; var modules = this._modules;
this._garbage(); this._garbage();
@ -146,6 +144,6 @@ define(function(require, exports, module) {
if (!modules[key].reset) continue; if (!modules[key].reset) continue;
modules[key].reset.call(this); modules[key].reset.call(this);
} }
} },
}); });
}); });

View File

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

View File

@ -1,4 +1,4 @@
define(function(require, exports, module) { define(function (require, exports, module) {
var kity = require('../core/kity'); var kity = require('../core/kity');
var utils = require('../core/utils'); var utils = require('../core/utils');
@ -9,32 +9,32 @@ define(function(require, exports, module) {
var Renderer = require('../core/render'); var Renderer = require('../core/render');
var ViewDragger = kity.createClass('ViewDragger', { var ViewDragger = kity.createClass('ViewDragger', {
constructor: function(minder) { constructor: function (minder) {
this._minder = minder; this._minder = minder;
this._enabled = false; this._enabled = false;
this._bind(); this._bind();
var me = this; var me = this;
this._minder.getViewDragger = function() { this._minder.getViewDragger = function () {
return me; return me;
}; };
this.setEnabled(false); this.setEnabled(false);
}, },
isEnabled: function() { isEnabled: function () {
return this._enabled; return this._enabled;
}, },
setEnabled: function(value) { setEnabled: function (value) {
var paper = this._minder.getPaper(); var paper = this._minder.getPaper();
paper.setStyle('cursor', value ? 'pointer' : 'default'); paper.setStyle('cursor', value ? 'pointer' : 'default');
paper.setStyle('cursor', value ? '-webkit-grab' : 'default'); paper.setStyle('cursor', value ? '-webkit-grab' : 'default');
this._enabled = value; this._enabled = value;
}, },
timeline: function() { timeline: function () {
return this._moveTimeline; return this._moveTimeline;
}, },
move: function(offset, duration) { move: function (offset, duration) {
var minder = this._minder; var minder = this._minder;
var targetPosition = this.getMovement().offset(offset); var targetPosition = this.getMovement().offset(offset);
@ -42,22 +42,24 @@ define(function(require, exports, module) {
this.moveTo(targetPosition, duration); this.moveTo(targetPosition, duration);
}, },
moveTo: function(position, duration) { moveTo: function (position, duration) {
if (duration) { if (duration) {
var dragger = this; var dragger = this;
if (this._moveTimeline) this._moveTimeline.stop(); if (this._moveTimeline) this._moveTimeline.stop();
this._moveTimeline = this._minder.getRenderContainer().animate(new kity.Animator( this._moveTimeline = this._minder
this.getMovement(), .getRenderContainer()
position, .animate(
function(target, value) { new kity.Animator(this.getMovement(), position, function (target, value) {
dragger.moveTo(value); dragger.moveTo(value);
} }),
), duration, 'easeOutCubic').timeline(); duration,
'easeOutCubic'
)
.timeline();
this._moveTimeline.on('finish', function() { this._moveTimeline.on('finish', function () {
dragger._moveTimeline = null; dragger._moveTimeline = null;
}); });
@ -68,16 +70,16 @@ define(function(require, exports, module) {
this._minder.fire('viewchange'); this._minder.fire('viewchange');
}, },
getMovement: function() { getMovement: function () {
var translate = this._minder.getRenderContainer().transform.translate; var translate = this._minder.getRenderContainer().transform.translate;
return translate ? translate[0] : new kity.Point(); return translate ? translate[0] : new kity.Point();
}, },
getView: function() { getView: function () {
var minder = this._minder; var minder = this._minder;
var c = minder._lastClientSize || { var c = minder._lastClientSize || {
width: minder.getRenderTarget().clientWidth, width: minder.getRenderTarget().clientWidth,
height: minder.getRenderTarget().clientHeight height: minder.getRenderTarget().clientHeight,
}; };
var m = this.getMovement(); var m = this.getMovement();
var box = new kity.Box(0, 0, c.width, c.height); var box = new kity.Box(0, 0, c.width, c.height);
@ -85,7 +87,7 @@ define(function(require, exports, module) {
return viewMatrix.inverse().translate(-m.x, -m.y).transformBox(box); return viewMatrix.inverse().translate(-m.x, -m.y).transformBox(box);
}, },
_bind: function() { _bind: function () {
var dragger = this, var dragger = this,
isTempDrag = false, isTempDrag = false,
lastPosition = null, lastPosition = null,
@ -94,7 +96,6 @@ define(function(require, exports, module) {
function dragEnd(e) { function dragEnd(e) {
if (!lastPosition) return; if (!lastPosition) return;
lastPosition = null; lastPosition = null;
e.stopPropagation(); e.stopPropagation();
@ -103,8 +104,7 @@ define(function(require, exports, module) {
if (isTempDrag) { if (isTempDrag) {
dragger.setEnabled(false); dragger.setEnabled(false);
isTempDrag = false; isTempDrag = false;
if (dragger._minder.getStatus() == 'hand') if (dragger._minder.getStatus() == 'hand') dragger._minder.rollbackStatus();
dragger._minder.rollbackStatus();
} }
var paper = dragger._minder.getPaper(); var paper = dragger._minder.getPaper();
paper.setStyle('cursor', dragger._minder.getStatus() == 'hand' ? '-webkit-grab' : 'default'); paper.setStyle('cursor', dragger._minder.getStatus() == 'hand' ? '-webkit-grab' : 'default');
@ -112,10 +112,12 @@ define(function(require, exports, module) {
dragger._minder.fire('viewchanged'); dragger._minder.fire('viewchanged');
} }
this._minder.on('normal.mousedown normal.touchstart ' + this._minder
.on(
'normal.mousedown normal.touchstart ' +
'inputready.mousedown inputready.touchstart ' + 'inputready.mousedown inputready.touchstart ' +
'readonly.mousedown readonly.touchstart', 'readonly.mousedown readonly.touchstart',
function(e) { function (e) {
if (e.originEvent.button == 2) { if (e.originEvent.button == 2) {
e.originEvent.preventDefault(); // 阻止中键拉动 e.originEvent.preventDefault(); // 阻止中键拉动
} }
@ -124,12 +126,14 @@ define(function(require, exports, module) {
lastPosition = e.getPosition('view'); lastPosition = e.getPosition('view');
isTempDrag = true; isTempDrag = true;
} }
}) }
)
.on('normal.mousemove normal.touchmove ' + .on(
'normal.mousemove normal.touchmove ' +
'readonly.mousemove readonly.touchmove ' + 'readonly.mousemove readonly.touchmove ' +
'inputready.mousemove inputready.touchmove', 'inputready.mousemove inputready.touchmove',
function(e) { function (e) {
if (e.type == 'touchmove') { if (e.type == 'touchmove') {
e.preventDefault(); // 阻止浏览器的后退事件 e.preventDefault(); // 阻止浏览器的后退事件
} }
@ -140,9 +144,10 @@ define(function(require, exports, module) {
var paper = dragger._minder.getPaper(); var paper = dragger._minder.getPaper();
paper.setStyle('cursor', '-webkit-grabbing'); paper.setStyle('cursor', '-webkit-grabbing');
} }
}) }
)
.on('hand.beforemousedown hand.beforetouchstart', function(e) { .on('hand.beforemousedown hand.beforetouchstart', function (e) {
// 已经被用户打开拖放模式 // 已经被用户打开拖放模式
if (dragger.isEnabled()) { if (dragger.isEnabled()) {
lastPosition = e.getPosition('view'); lastPosition = e.getPosition('view');
@ -152,7 +157,7 @@ define(function(require, exports, module) {
} }
}) })
.on('hand.beforemousemove hand.beforetouchmove', function(e) { .on('hand.beforemousemove hand.beforetouchmove', function (e) {
if (lastPosition) { if (lastPosition) {
currentPosition = e.getPosition('view'); currentPosition = e.getPosition('view');
@ -169,14 +174,13 @@ define(function(require, exports, module) {
.on('mouseup touchend', dragEnd); .on('mouseup touchend', dragEnd);
window.addEventListener('mouseup', dragEnd); window.addEventListener('mouseup', dragEnd);
this._minder.on('contextmenu', function(e) { this._minder.on('contextmenu', function (e) {
e.preventDefault(); e.preventDefault();
}); });
} },
}); });
Module.register('View', function() { Module.register('View', function () {
var km = this; var km = this;
/** /**
@ -188,20 +192,18 @@ define(function(require, exports, module) {
*/ */
var ToggleHandCommand = kity.createClass('ToggleHandCommand', { var ToggleHandCommand = kity.createClass('ToggleHandCommand', {
base: Command, base: Command,
execute: function(minder) { execute: function (minder) {
if (minder.getStatus() != 'hand') { if (minder.getStatus() != 'hand') {
minder.setStatus('hand', true); minder.setStatus('hand', true);
} else { } else {
minder.rollbackStatus(); minder.rollbackStatus();
} }
this.setContentChanged(false); this.setContentChanged(false);
}, },
queryState: function(minder) { queryState: function (minder) {
return minder.getStatus() == 'hand' ? 1 : 0; return minder.getStatus() == 'hand' ? 1 : 0;
}, },
enableReadOnly: true enableReadOnly: true,
}); });
/** /**
@ -214,20 +216,32 @@ define(function(require, exports, module) {
*/ */
var CameraCommand = kity.createClass('CameraCommand', { var CameraCommand = kity.createClass('CameraCommand', {
base: Command, base: Command,
execute: function(km, focusNode) { 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 viewport = km.getPaper().getViewPort();
var offset = focusNode.getRenderContainer().getRenderBox('view'); 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; dy = viewport.center.y - offset.y;
var dragger = km._viewDragger;
var duration = km.getOption('viewAnimationDuration');
dragger.move(new kity.Point(dx, dy), duration); dragger.move(new kity.Point(dx, dy), duration);
}
this.setContentChanged(false); this.setContentChanged(false);
}, },
enableReadOnly: true enableReadOnly: true,
}); });
/** /**
@ -245,7 +259,7 @@ define(function(require, exports, module) {
var MoveCommand = kity.createClass('MoveCommand', { var MoveCommand = kity.createClass('MoveCommand', {
base: Command, base: Command,
execute: function(km, dir) { execute: function (km, dir) {
var dragger = km._viewDragger; var dragger = km._viewDragger;
var size = km._lastClientSize; var size = km._lastClientSize;
var duration = km.getOption('viewAnimationDuration'); var duration = km.getOption('viewAnimationDuration');
@ -265,77 +279,72 @@ define(function(require, exports, module) {
} }
}, },
enableReadOnly: true enableReadOnly: true,
}); });
return { return {
init: function() { init: function () {
this._viewDragger = new ViewDragger(this); this._viewDragger = new ViewDragger(this);
}, },
commands: { commands: {
'hand': ToggleHandCommand, hand: ToggleHandCommand,
'camera': CameraCommand, camera: CameraCommand,
'move': MoveCommand move: MoveCommand,
}, },
events: { events: {
statuschange: function(e) { 'statuschange': function (e) {
this._viewDragger.setEnabled(e.currentStatus == 'hand'); this._viewDragger.setEnabled(e.currentStatus == 'hand');
}, },
mousewheel: function(e) { 'mousewheel': function (e) {
var dx, dy; var dx, dy;
e = e.originEvent; e = e.originEvent;
if (e.ctrlKey || e.shiftKey) return; if (e.ctrlKey || e.shiftKey) return;
if ('wheelDeltaX' in e) { if ('wheelDeltaX' in e) {
dx = e.wheelDeltaX || 0; dx = e.wheelDeltaX || 0;
dy = e.wheelDeltaY || 0; dy = e.wheelDeltaY || 0;
} else { } else {
dx = 0; dx = 0;
dy = e.wheelDelta; dy = e.wheelDelta;
} }
this._viewDragger.move({ this._viewDragger.move({
x: dx / 2.5, x: dx / 2.5,
y: dy / 2.5 y: dy / 2.5,
}); });
var me = this; var me = this;
clearTimeout(this._mousewheeltimer); clearTimeout(this._mousewheeltimer);
this._mousewheeltimer = setTimeout(function() { this._mousewheeltimer = setTimeout(function () {
me.fire('viewchanged'); me.fire('viewchanged');
}, 100); }, 100);
e.preventDefault(); e.preventDefault();
}, },
'normal.dblclick readonly.dblclick': function(e) { 'normal.dblclick readonly.dblclick': function (e) {
if (e.kityEvent.targetShape instanceof kity.Paper) { if (e.kityEvent.targetShape instanceof kity.Paper) {
this.execCommand('camera', this.getRoot(), 800); this.execCommand('camera', this.getRoot(), 800);
} }
}, },
'paperrender finishInitHook': function() { 'paperrender finishInitHook': function () {
if (!this.getRenderTarget()) { if (!this.getRenderTarget()) {
return; return;
} }
this.execCommand('camera', null, 0); this.execCommand('camera', null, 0);
this._lastClientSize = { this._lastClientSize = {
width: this.getRenderTarget().clientWidth, width: this.getRenderTarget().clientWidth,
height: this.getRenderTarget().clientHeight height: this.getRenderTarget().clientHeight,
}; };
}, },
resize: function(e) { 'resize': function (e) {
var a = { var a = {
width: this.getRenderTarget().clientWidth, width: this.getRenderTarget().clientWidth,
height: this.getRenderTarget().clientHeight height: this.getRenderTarget().clientHeight,
}, },
b = this._lastClientSize; b = this._lastClientSize;
this._viewDragger.move( this._viewDragger.move(new kity.Point(((a.width - b.width) / 2) | 0, ((a.height - b.height) / 2) | 0));
new kity.Point((a.width - b.width) / 2 | 0, (a.height - b.height) / 2 | 0));
this._lastClientSize = a; this._lastClientSize = a;
}, },
'selectionchange layoutallfinish': function(e) { 'selectionchange layoutallfinish': function (e) {
var selected = this.getSelectedNode(); var selected = this.getSelectedNode();
var minder = this; var minder = this;
@ -359,24 +368,23 @@ define(function(require, exports, module) {
* *
* fixed bug : 初始化的时候中心节点位置不固定有的时候在左上角有的时候在中心 * fixed bug : 初始化的时候中心节点位置不固定有的时候在左上角有的时候在中心
* */ * */
if (timeline){ if (timeline) {
timeline.on('finish', function() { timeline.on('finish', function () {
minder.fire('selectionchange'); minder.fire('selectionchange');
}); });
return; return;
} }
var view = dragger.getView(); var view = dragger.getView();
var focus = selected.getLayoutBox(); var focus = selected.getLayoutBox();
var space = 50; var space = 50;
var dx = 0, dy = 0; var dx = 0,
dy = 0;
if (focus.right > view.right) { if (focus.right > view.right) {
dx += view.right - focus.right - space; dx += view.right - focus.right - space;
} } else if (focus.left < view.left) {
else if (focus.left < view.left) {
dx += view.left - focus.left + space; 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); if (dx || dy) dragger.move(new kity.Point(dx, dy), 100);
},
},
}
}
}; };
}); });
}); });

View File

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