Skip to content

Commit

Permalink
feat: update graphin
Browse files Browse the repository at this point in the history
  • Loading branch information
pomelo-nwu committed Nov 15, 2023
1 parent 14d0b5f commit 66be154
Show file tree
Hide file tree
Showing 13 changed files with 341 additions and 96 deletions.
17 changes: 0 additions & 17 deletions packages/graphin/.umirc.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/graphin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"postpublish": "tnpm sync @antv/graphin"
},
"dependencies": {
"@antv/g6": "5.0.0-beta.5",
"@antv/g6": "5.0.0-beta.27",
"lodash-es": "^4.17.21"
},
"peerDependencies": {
Expand Down
20 changes: 16 additions & 4 deletions packages/graphin/src/ExtendGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,32 @@ import { Extensions, Graph as G6Graph, extend } from '@antv/g6';

const handler = (data, options = {}, graphCore) => {
const { combos } = data;
console.log('node graphin....', data);

const nodes = (data.nodes || []).map(item => {
const { id, data } = item;
const { id, data, type, ...others } = item;

return {
id: id,
data: data,
data: {
__type: type,
...data,
},
...others,
};
});

const edges = (data.edges || []).map((item, index) => {
const { source, target, id, data } = item;
const { source, target, id, type, data, ...others } = item;
return {
id: id || `edge-${index}`,
source,
target,
data,
data: {
__type: type,
...data,
},
...others,
};
});

Expand All @@ -43,6 +54,7 @@ export default extend(G6Graph, {
},
nodes: {
'sphere-node': Extensions.SphereNode,
'donut-node': Extensions.DonutNode,
},

layouts: {
Expand Down
13 changes: 2 additions & 11 deletions packages/graphin/src/Graphin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,6 @@ const Graphin: React.FunctionComponent<GraphinProps> = forwardRef((props, ref) =
console.log('%c GRAPHIN DATA CHANGE....', 'color:yellow', data);
console.time('GRAPHIN_CHANGE_DATA_COST');
//@ts-ignore
// if (dataRef.current.nodes !== data.nodes.length) {
// graph.updatePlugin({
// key: 'lod-controller',
// type: 'lod-controller',
// //@ts-ignore
// disableLod: data.nodes.length < LOD_NODE_NUM_THRESHOLD,
// });
// }
//@ts-ignore
graph && graph.changeData(data, 'mergeReplace', false);
//@ts-ignore
if (
Expand Down Expand Up @@ -116,7 +107,7 @@ const Graphin: React.FunctionComponent<GraphinProps> = forwardRef((props, ref) =
//@ts-ignore
edge,
// behaviors
modes = { default: [], lasso: [] },
modes = { default: ['zoom-canvas', 'drag-canvas'], lasso: [] },
} = options;
const ContainerDOM = document.getElementById(container);

Expand Down Expand Up @@ -152,7 +143,7 @@ const Graphin: React.FunctionComponent<GraphinProps> = forwardRef((props, ref) =
{
type: 'lod-controller',
//@ts-ignore
disableLod: data.nodes.length < LOD_NODE_NUM_THRESHOLD,
disableLod: true, //data.nodes.length < LOD_NODE_NUM_THRESHOLD,
},
],
nodeState: {
Expand Down
74 changes: 74 additions & 0 deletions packages/graphin/src/icon/loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @file Icon loader
*/

/**
* @description 获取图标字体资源的方式,离线方式需要将字体资源放到本地,供私有化部署使用
*/
type Mode = 'online' | 'offline';

export type FontJson = {
id: string;
name: string;
font_family: string;
css_prefix_text: string;
description: string;
glyphs: {
icon_id: string;
name: string;
font_class: string;
unicode: string;
unicode_decimal: number;
}[];
};

/**
* @description 加载 unicode json 资源
*/
export async function loadFontJson(id: string, mode: Mode = 'online', url?: string): Promise<FontJson> {
if (mode === 'online') {
const _url = url || `https://at.alicdn.com/t/a/${id}.json`;
const json: FontJson = await fetch(_url).then(res => res.json());
return json;
}
/**
* @description TODO offline
* @example 私有化部署示例
*
* import font from './path/to/font.json';
* return font;
*/
return { id: '', name: '', font_family: '', css_prefix_text: '', description: '', glyphs: [] };
}

/**
* @description 加载 unicode 字体
*/
export async function loadUnicodeFont(id: string, mode: Mode = 'online') {
if (mode === 'online') {
const fontList = [
{
fontUrl: `//at.alicdn.com/t/a/${id}.woff2`,
format: 'woff2',
},
{
fontUrl: `//at.alicdn.com/t/a/${id}.woff`,
format: 'woff',
},
{
fontUrl: `//at.alicdn.com/t/a/${id}.ttf`,
format: 'truetype',
},
];
const load = async (fontFamily: string, fontUrl: string) => {
const font = new FontFace(fontFamily, `url(${fontUrl})`);
await font.load();
//@ts-ignore
document.fonts.add(font);
};

await Promise.all(fontList.map(({ fontUrl }) => load('iconfont', fontUrl)));
} else {
// TODO: offline
}
}
24 changes: 24 additions & 0 deletions packages/graphin/src/icon/registerFontFamily.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export const registerFontFamily = iconLoader => {
/** 注册 font icon */
const iconFont = iconLoader();
const { glyphs, fontFamily } = iconFont;
const icons = glyphs.map(item => {
return {
name: item.name,
unicode: String.fromCodePoint(item.unicode_decimal),
};
});

return new Proxy(icons, {
get: (target, propKey: string) => {
const matchIcon = target.find(icon => {
return icon.name === propKey;
});
if (!matchIcon) {
console.error(`%c fontFamily:${fontFamily},does not found ${propKey} icon`);
return '';
}
return matchIcon?.unicode;
},
});
};
61 changes: 61 additions & 0 deletions packages/graphin/src/icon/registerIconFonts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// 资源地址:https://www.iconfont.cn/manage/index?spm=a313x.7781069.1998910419.20&manage_type=myprojects&projectId=3381398&keyword=&project_type=&page=

import { createFromIconfontCN } from '@ant-design/icons';
import { loadFontJson, loadUnicodeFont, type FontJson } from './loader';
import { registerFontFamily } from './registerFontFamily';

export const fontFamily = 'iconfont';

// --- 注册 font icon ---

let icons = registerFontFamily(() => ({ fontFamily, glyphs: [] }));
let glyphs: FontJson['glyphs'] = [];

async function loadFontsJson(ids: string[]) {
const fonts = await Promise.all(ids.map(id => loadFontJson(id)));
// 合并所有字体
const _glyphs = fonts.reduce((acc, curr) => {
acc.push(...curr.glyphs);
return acc;
}, [] as FontJson['glyphs']);

glyphs = _glyphs;
icons = registerFontFamily(() => ({
fontFamily,
glyphs: _glyphs.map(item => {
return {
...item,
name: item.font_class, //统一为font class
};
}),
}));
return icons;
}

// --- 注册 antd iconfont ---
const registeredIds = new Set<string>();
const builtInIconFontId = 'font_3381398_29c1c449r6f';
const getIconfontScriptUrl = (id: string) => `//at.alicdn.com/t/a/${id}.js`;

async function loadUnicodeFonts(ids: string[]) {
await Promise.all(ids.map(id => loadUnicodeFont(id)));
}

export async function registerIconFonts(ids: string[] = [builtInIconFontId]) {
const unregisteredIds = ids.filter(id => !registeredIds.has(id));

if (!unregisteredIds.length) return icons;

// register
createFromIconfontCN({
scriptUrl: unregisteredIds.map(getIconfontScriptUrl),
});

const [ICONS] = await Promise.all([loadFontsJson(unregisteredIds), loadUnicodeFonts(unregisteredIds)]);
unregisteredIds.forEach(id => registeredIds.add(id));
return ICONS;
}

export function getFontIcons() {
return icons;
}
27 changes: 2 additions & 25 deletions packages/graphin/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,8 @@ export const registerNode = () => {};
//@ts-ignore
export const registerEdge = () => {};

//@ts-ignore
export const registerFontFamily = iconLoader => {
/** 注册 font icon */
const iconFont = iconLoader();
const { glyphs, fontFamily } = iconFont;
const icons = glyphs.map(item => {
return {
name: item.name,
unicode: String.fromCodePoint(item.unicode_decimal),
};
});

return new Proxy(icons, {
get: (target, propKey: string) => {
const matchIcon = target.find(icon => {
return icon.name === propKey;
});
if (!matchIcon) {
console.error(`%c fontFamily:${fontFamily},does not found ${propKey} icon`);
return '';
}
return matchIcon?.unicode;
},
});
};
export { registerFontFamily } from './icon/registerFontFamily';
export { getFontIcons, registerIconFonts } from './icon/registerIconFonts';

export { default as Behaviors, registerBehavior, useBehaviorHook } from './behaviors';

Expand Down
64 changes: 51 additions & 13 deletions packages/graphin/src/styling/edge-style-transform.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,52 @@
const transGraphinStyle = style => {
const { keyshape = {}, halo = {}, icon = {}, label = {}, badges = [] } = style || {};
import { merge } from 'lodash-es';
import getEdgeStyleByTheme from '../theme/edge-style';
const { style: defaultStyle } = getEdgeStyleByTheme({
primaryEdgeColor: '#ddd',
edgeSize: 1,
mode: 'light',
});

const transGraphinStyle = (style, otherStyles) => {
const { keyshape, halo, label } = merge({}, defaultStyle, style || {}) as typeof defaultStyle;
const { background } = label;
//@ts-ignore  用户指定的优先级最高
const { poly, loop } = keyshape;
//@ts-ignore
const { isMultiple, type } = otherStyles;
//@ts-ignore
const { loopCfg, curveOffset } = otherStyles.keyShape || {};

return {
type: 'line-edge',
type: type || 'line-edge',
keyShape: {
opacity: 0.6, // 边主图形的透明度
stroke: 'grey', // 边主图形描边颜色
opacity: keyshape.strokeOpacity, // 边主图形的透明度
stroke: keyshape.stroke, // 边主图形描边颜色
lineAppendWidth: keyshape.lineAppendWidth,
lineWidth: keyshape.lineWidth,
endArrow: {
path: '',
},
...(curveOffset ? { curveOffset: (poly && poly.distance) || curveOffset } : {}),
...(loopCfg ? { loopCfg: loop || loopCfg } : {}),

// ...(curveOffset ? { curveOffset } : {}),
// ...(loopCfg ? { loopCfg } : {}),
},
// 边上的标签文本配置
labelShape: {
text: label.value,
position: label.position,
fill: label.fill,
fontSize: label.fontSize,
textAlign: label.textAlign,
autoRotate: true, // 边上的标签文本根据边的方向旋转
maxLines: '400%',
},
labelBackgroundShape: {
radius: background.radius,
fill: background.fill,
stroke: background.stroke,
opacity: background.opacity,
},
// 边的动画配置
// animates: {
Expand All @@ -29,18 +66,19 @@ const transGraphinStyle = style => {
};

export const edgeStyleTransform = edge => {
const { style, type, id, data, source, target } = edge;
const IS_GRAPHIN = (style && type === 'graphin-line') || !type;
// console.log('edge', edge);
const { id, source, target, data } = edge;
const { __type, style } = data;
const IS_GRAPHIN = (__type && __type === 'graphin-line') || !__type;

if (IS_GRAPHIN) {
const { isMultiple, keyShape, type } = data;
const displayData = transGraphinStyle(style, { isMultiple, keyShape, type });
console.log('edge', edge, IS_GRAPHIN, displayData);
return {
source,
target,
id: id || `${source}-${target}-${Math.random()}`,
data: {
...data,
...transGraphinStyle(style),
},
id: id,
data: displayData,
};
}
return edge;
Expand Down
Loading

0 comments on commit 66be154

Please sign in to comment.