@cyber-harbour/ui 1.0.18 → 1.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cyber-harbour/ui",
3
- "version": "1.0.18",
3
+ "version": "1.0.20",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
@@ -27,6 +27,8 @@
27
27
  "license": "ISC",
28
28
  "description": "",
29
29
  "dependencies": {
30
+ "react-force-graph-2d": "^1.27.1",
31
+ "react-tiny-popover": "^8.1.6",
30
32
  "styled-components": "^6.1.18"
31
33
  },
32
34
  "devDependencies": {
@@ -0,0 +1,122 @@
1
+ import { ButtonSize, getButtonSizeStyles } from '../../Theme';
2
+ import { useRef } from 'react';
3
+ import { Popover, PopoverAlign, PopoverPosition } from 'react-tiny-popover';
4
+ import { styled, useTheme } from 'styled-components';
5
+ import { ChevronDownIcon, ChevronUpIcon } from '../IconComponents';
6
+
7
+ interface ContextMenuProps {
8
+ isOpen: boolean;
9
+ onClick: () => void;
10
+ onClickOutside: (e: MouseEvent) => void;
11
+ size?: ButtonSize;
12
+ disabled?: boolean;
13
+ fullWidth?: boolean;
14
+ className?: string;
15
+ children?: any;
16
+ anchor?: any;
17
+ positions?: PopoverPosition[] | PopoverPosition;
18
+ align?: PopoverAlign;
19
+ }
20
+
21
+ export const ContextMenu = ({
22
+ isOpen,
23
+ onClickOutside,
24
+ onClick,
25
+ anchor,
26
+ size = 'medium',
27
+ disabled,
28
+ fullWidth,
29
+ className,
30
+ positions = ['bottom'],
31
+ align = 'start',
32
+ children,
33
+ }: ContextMenuProps) => {
34
+ const buttonRef = useRef<HTMLButtonElement | null>(null);
35
+
36
+ const theme = useTheme();
37
+
38
+ return (
39
+ <Popover
40
+ padding={theme.contextMenu.padding}
41
+ isOpen={isOpen}
42
+ positions={positions}
43
+ align={align}
44
+ onClickOutside={onClickOutside}
45
+ content={children}
46
+ >
47
+ <StyledButton
48
+ ref={buttonRef}
49
+ onClick={onClick}
50
+ $disabled={disabled}
51
+ $fullWidth={fullWidth}
52
+ $size={size}
53
+ className={className}
54
+ >
55
+ <div>{anchor}</div>
56
+ {isOpen ? (
57
+ <ChevronUpIcon width={theme.contextMenu.icon.size} height={theme.contextMenu.icon.size} />
58
+ ) : (
59
+ <ChevronDownIcon width={theme.contextMenu.icon.size} height={theme.contextMenu.icon.size} />
60
+ )}
61
+ </StyledButton>
62
+ </Popover>
63
+ );
64
+ };
65
+
66
+ // Створюємо стилізований компонент, що використовує уніфіковану палітру
67
+ const StyledButton = styled.button<{
68
+ $size: ButtonSize;
69
+ $disabled?: boolean;
70
+ $fullWidth?: boolean;
71
+ }>`
72
+ ${({ $size, $disabled, $fullWidth, theme }) => {
73
+ const sizes = getButtonSizeStyles(theme, $size);
74
+ return `
75
+ background: ${theme.contextMenu.button.default.background};
76
+ color: ${theme.contextMenu.button.default.text};
77
+ border-color: ${theme.contextMenu.button.default.border};
78
+ box-shadow: ${theme.contextMenu.button.default.boxShadow};
79
+ font-size: ${sizes.fontSize};
80
+ gap: ${sizes.gap};
81
+ padding-block: ${sizes.paddingBlock};
82
+ padding-inline: ${sizes.paddingInline};
83
+ border-radius: ${sizes.borderRadius};
84
+ border-width: ${sizes.borderWidth};
85
+ border-style: solid;
86
+ width: ${$fullWidth ? '100%' : 'auto'};
87
+ cursor: ${$disabled ? 'not-allowed' : 'pointer'};
88
+ font-weight: 500;
89
+ display: inline-flex;
90
+ align-items: center;
91
+ justify-content: center;
92
+ text-decoration: none;
93
+ transition: all 0.2s ease;
94
+ outline: none;
95
+ flex-direction: row;
96
+
97
+ &:hover {
98
+ background: ${theme.contextMenu.button.hover.background};
99
+ color: ${theme.contextMenu.button.hover.text};
100
+ border-color: ${theme.contextMenu.button.hover.border};
101
+ box-shadow: ${theme.contextMenu.button.hover.boxShadow};
102
+ }
103
+
104
+ &:active {
105
+ background: ${theme.contextMenu.button.active.background};
106
+ color: ${theme.contextMenu.button.active.text};
107
+ border-color: ${theme.contextMenu.button.active.border};
108
+ box-shadow: ${theme.contextMenu.button.active.boxShadow};
109
+ }
110
+
111
+ &:disabled {
112
+ background: ${theme.contextMenu.button.disabled.background};
113
+ color: ${theme.contextMenu.button.disabled.text};
114
+ border-color: ${theme.contextMenu.button.disabled.border};
115
+ box-shadow: ${theme.contextMenu.button.disabled.boxShadow};
116
+ }
117
+
118
+ `;
119
+ }}
120
+ `;
121
+
122
+ const StyledContainer = styled.div``;
@@ -0,0 +1,13 @@
1
+ import { styled } from 'styled-components';
2
+
3
+ interface StyledProps {}
4
+
5
+ export const ContextMenuDelimiter = styled.div<StyledProps>(
6
+ ({ theme }) => `
7
+ margin-inline: ${theme.contextMenu.delimeter.marginInline};
8
+ margin-block: ${theme.contextMenu.delimeter.marginBlock};
9
+ border-top-width: ${theme.contextMenu.delimeter.thickness};
10
+ border-top-style: ${theme.contextMenu.delimeter.style};
11
+ border-top-color: ${theme.contextMenu.delimeter.color};
12
+ `
13
+ );
@@ -0,0 +1,3 @@
1
+ export * from './ContextMenu';
2
+ export * from './ContextMenuDelimiter';
3
+ export * from './useContextMenuControl';
@@ -0,0 +1,21 @@
1
+ import { useState } from 'react';
2
+
3
+ export const useContextMenuControl = () => {
4
+ const [isOpen, setIsOpen] = useState(false);
5
+
6
+ const toggleMenu = () => {
7
+ setIsOpen((prev) => !prev);
8
+ };
9
+ const closeMenu = () => {
10
+ setIsOpen(false);
11
+ };
12
+ const openMenu = () => {
13
+ setIsOpen(true);
14
+ };
15
+ return {
16
+ isOpen,
17
+ toggleMenu,
18
+ closeMenu,
19
+ openMenu,
20
+ };
21
+ };
@@ -0,0 +1,15 @@
1
+ import { SVGProps } from 'react';
2
+
3
+ interface InfoCircleIconProps extends SVGProps<SVGSVGElement> {
4
+ fill?: string;
5
+ }
6
+
7
+ export const BallsMenu = ({ fill = 'currentColor', ...props }: InfoCircleIconProps) => {
8
+ return (
9
+ <svg viewBox="0 0 16 3" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
10
+ <ellipse cx="1.56746" cy="1.5" rx="1.53633" ry="1.5" fill={fill} />
11
+ <ellipse cx="7.71278" cy="1.5" rx="1.53633" ry="1.5" fill={fill} />
12
+ <ellipse cx="13.8581" cy="1.5" rx="1.53633" ry="1.5" fill={fill} />
13
+ </svg>
14
+ );
15
+ };
@@ -0,0 +1,13 @@
1
+ import { SVGProps } from 'react';
2
+
3
+ interface InfoCircleIconProps extends SVGProps<SVGSVGElement> {
4
+ fill?: string;
5
+ }
6
+
7
+ export const CheckIcon = ({ fill = 'currentColor', ...props }: InfoCircleIconProps) => {
8
+ return (
9
+ <svg viewBox="0 0 16 12" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
10
+ <path d="M14.4983 1L5.34428 11L1.18338 6.45455" stroke={fill} stroke-width="1.5" stroke-linejoin="round" />;
11
+ </svg>
12
+ );
13
+ };
@@ -0,0 +1,18 @@
1
+ import { SVGProps } from 'react';
2
+
3
+ interface ChevronRightIconProps extends SVGProps<SVGSVGElement> {
4
+ fill?: string;
5
+ }
6
+
7
+ export const ChevronDownIcon = ({ fill = 'currentColor', ...props }: ChevronRightIconProps) => {
8
+ return (
9
+ <svg viewBox="0 0 18 17" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
10
+ <path
11
+ fill-rule="evenodd"
12
+ clip-rule="evenodd"
13
+ d="M17.4517 5.77798L16.4067 6.79197L10.8447 12.1899C10.0753 12.9367 8.82791 12.9367 8.05853 12.1899L2.49647 6.79197L1.45166 5.77798L3.54128 3.75L4.58609 4.76399L9.45161 9.48599L14.3172 4.76399L15.362 3.75L17.4517 5.77798Z"
14
+ fill={fill}
15
+ />
16
+ </svg>
17
+ );
18
+ };
@@ -0,0 +1,18 @@
1
+ import { SVGProps } from 'react';
2
+
3
+ interface ChevronRightIconProps extends SVGProps<SVGSVGElement> {
4
+ fill?: string;
5
+ }
6
+
7
+ export const ChevronUpIcon = ({ fill = 'currentColor', ...props }: ChevronRightIconProps) => {
8
+ return (
9
+ <svg viewBox="0 0 17 17" fill="none" xmlns="http://www.w3.org/2000/svg" {...props}>
10
+ <path
11
+ fill-rule="evenodd"
12
+ clip-rule="evenodd"
13
+ d="M0.20166 10.722L1.24661 9.70803L6.80863 4.31012C7.57801 3.56329 8.82541 3.56329 9.59479 4.31012L15.1569 9.70803L16.2017 10.722L14.112 12.75L13.0672 11.736L8.20171 7.01401L3.33611 11.736L2.29136 12.75L0.20166 10.722Z"
14
+ fill={fill}
15
+ />
16
+ </svg>
17
+ );
18
+ };
@@ -32,3 +32,7 @@ export { StatisticIcon } from './StatisticIcon';
32
32
  export { SunIcon } from './SunIcon';
33
33
  export { UpRightArrowCircleIcon } from './UpRightArrowCircleIcon';
34
34
  export { VectorIcon } from './VectorIcon';
35
+ export { BallsMenu } from './BallsMenu';
36
+ export { CheckIcon } from './Check';
37
+ export { ChevronDownIcon } from './ChevronDown';
38
+ export { ChevronUpIcon } from './ChevronUp';
@@ -2,7 +2,7 @@ import { ReactNode } from 'react';
2
2
  import { styled } from 'styled-components';
3
3
 
4
4
  export interface ListMenuSectionProps {
5
- items: ReactNode | ReactNode[];
5
+ items: any;
6
6
  title?: string;
7
7
  }
8
8
  export const ListMenuSection = ({ title, items }: ListMenuSectionProps) => {
@@ -16,7 +16,7 @@ const VISIBLE_GROUPE = 5;
16
16
  const STEP = 1;
17
17
  const ELLIPSIS = '...';
18
18
 
19
- export const Pagination: FC<PaginationProps> = ({ total_items, limit, offset, onChangePage }) => {
19
+ export const Pagination = ({ total_items, limit, offset, onChangePage }: PaginationProps) => {
20
20
  const currentPage = useMemo(() => (offset ? offset / limit + 1 : 1), [limit, offset]);
21
21
  const pages = Math.ceil(total_items / limit);
22
22
  const paginationItems: (number | string)[] = useMemo(() => {
@@ -1,4 +1,4 @@
1
- import { FC, ReactNode, useMemo, CSSProperties } from 'react';
1
+ import { ReactNode, useMemo, CSSProperties } from 'react';
2
2
  import { styled } from 'styled-components';
3
3
  import { Row } from './Row';
4
4
  import { Cell, HeadCell } from './Cell';
@@ -24,12 +24,12 @@ export type RenderHeaderCellProps<T = string> = {
24
24
  interface TableProps {
25
25
  columns: ColumnTable[];
26
26
  rowCount: number;
27
- renderCell: (props: RenderCellProps<any>) => ReactNode;
28
- renderHeaderCell: (props: RenderHeaderCellProps<any>) => ReactNode;
27
+ renderCell: (props: RenderCellProps<any>) => any;
28
+ renderHeaderCell: (props: RenderHeaderCellProps<any>) => any;
29
29
  rowIds?: string[];
30
30
  }
31
31
 
32
- export const Table: FC<TableProps> = ({ columns, rowCount, renderCell, renderHeaderCell, rowIds }) => {
32
+ export const Table = ({ columns, rowCount, renderCell, renderHeaderCell, rowIds }: TableProps) => {
33
33
  const cellCount = columns.length;
34
34
 
35
35
  const data = useMemo(() => {
@@ -49,7 +49,7 @@ export const Table: FC<TableProps> = ({ columns, rowCount, renderCell, renderHea
49
49
 
50
50
  return (
51
51
  <StyledTable>
52
- <thead>
52
+ <StyledHead>
53
53
  <Row>
54
54
  {columns.map(({ id, title, width }) => (
55
55
  <HeadCell
@@ -62,7 +62,7 @@ export const Table: FC<TableProps> = ({ columns, rowCount, renderCell, renderHea
62
62
  </HeadCell>
63
63
  ))}
64
64
  </Row>
65
- </thead>
65
+ </StyledHead>
66
66
  <tbody>
67
67
  {data.map((cells, rowIndex) => (
68
68
  <Row key={`row-${rowIndex}`} id={rowIds ? rowIds[rowIndex] : `row-${rowIndex}`}>
@@ -83,3 +83,12 @@ const StyledTable = styled.table`
83
83
  border-spacing: 0;
84
84
  table-layout: fixed;
85
85
  `;
86
+
87
+ const StyledHead = styled.thead(
88
+ ({ theme }) => `
89
+ background-color: ${theme.colors.background};
90
+ position: sticky;
91
+ top: 0;
92
+ z-index: 1;
93
+ `
94
+ );
package/src/Core/index.ts CHANGED
@@ -6,3 +6,4 @@ export * from './ListMenu';
6
6
  export * from './Header';
7
7
  export * from './Table';
8
8
  export * from './Pagination';
9
+ export * from './ContextMenu';
@@ -0,0 +1,186 @@
1
+ import ForceGraph2D, { ForceGraphMethods } from 'react-force-graph-2d';
2
+ import { Graph2DProps } from './types';
3
+ import { useEffect, useRef, MutableRefObject } from 'react';
4
+
5
+ export const Graph2D = ({
6
+ graphData,
7
+ width,
8
+ height,
9
+ linkTarget,
10
+ linkSource,
11
+ config = {
12
+ nodeSizeFactor: 2, // Множник для розміру вузла
13
+ fontSize: 14, // Базовий розмір шрифту
14
+ nodeSizeBase: 5, // Базовий розмір вузла (перед застосуванням множника)
15
+ textPaddingFactor: 0.95, // Скільки разів текст може бути ширший за розмір вузла
16
+ },
17
+ onNodeClick,
18
+ onLinkClick,
19
+ }: Graph2DProps) => {
20
+ // Максимальний рівень зуму
21
+ const MAX_ZOOM = 4;
22
+ // Максимальний розмір шрифту при максимальному зумі
23
+ const MAX_FONT_SIZE = 8;
24
+
25
+ // Функція для реверсивного масштабування тексту
26
+ // При максимальному зумі текст має розмір MAX_FONT_SIZE
27
+ // При зменшенні зуму текст також зменшується
28
+ const calculateFontSize = (scale: number): number => {
29
+ // Обмежуємо масштаб до MAX_ZOOM
30
+ const limitedScale = Math.min(scale, MAX_ZOOM);
31
+
32
+ // Обчислюємо коефіцієнт масштабування: при максимальному зумі = 1, при мінімальному - менше
33
+ const fontSizeRatio = limitedScale / MAX_ZOOM;
34
+
35
+ // Розраховуємо розмір шрифту в діапазоні від (MAX_FONT_SIZE / MAX_ZOOM) до MAX_FONT_SIZE
36
+ return Math.max(MAX_FONT_SIZE * fontSizeRatio, MAX_FONT_SIZE / MAX_ZOOM);
37
+ };
38
+
39
+ const fgRef = useRef<ForceGraphMethods>(null) as MutableRefObject<ForceGraphMethods | undefined>;
40
+
41
+ useEffect(() => {
42
+ fgRef.current?.d3Force('link')?.distance(() => {
43
+ return 100; // Set a constant distance of 100 for all links
44
+ // Or use a function for dynamic distance based on link properties:
45
+ // return link.value * 50;
46
+ });
47
+ }, [graphData]);
48
+
49
+ return (
50
+ <ForceGraph2D
51
+ ref={fgRef}
52
+ width={width}
53
+ height={height}
54
+ graphData={graphData}
55
+ linkTarget={linkTarget}
56
+ linkSource={linkSource}
57
+ onNodeClick={onNodeClick}
58
+ onLinkClick={onLinkClick}
59
+ nodeLabel={(node: any) => `${node.label}`} // Показуємо повний текст у тултіпі
60
+ linkLabel={(link: any) => link.label}
61
+ nodeAutoColorBy="label"
62
+ linkDirectionalArrowLength={3.5}
63
+ linkDirectionalArrowRelPos={1}
64
+ linkCurvature={0}
65
+ // Обмеження максимального зуму
66
+ maxZoom={MAX_ZOOM}
67
+ linkCanvasObjectMode={() => 'after'}
68
+ linkCanvasObject={(link: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
69
+ // Отримуємо позиції початку і кінця зв'язку
70
+ const { source, target, label } = link;
71
+ if (!label) return; // Пропускаємо, якщо немає мітки
72
+
73
+ // Координати початку і кінця зв'язку
74
+ const start = { x: source.x, y: source.y };
75
+ const end = { x: target.x, y: target.y };
76
+
77
+ // Знаходимо середину лінії для розміщення тексту
78
+ const middleX = start.x + (end.x - start.x) / 2;
79
+ const middleY = start.y + (end.y - start.y) / 2;
80
+
81
+ // Використовуємо реверсивне масштабування для тексту
82
+ const scaledFontSize = calculateFontSize(globalScale);
83
+ ctx.font = `${scaledFontSize}px Sans-Serif`;
84
+ ctx.fillStyle = '#666'; // Колір тексту
85
+ ctx.textAlign = 'center';
86
+ ctx.textBaseline = 'middle';
87
+
88
+ // Визначення кута нахилу лінії для повороту тексту
89
+ const angle = Math.atan2(end.y - start.y, end.x - start.x);
90
+
91
+ // Збереження поточного стану контексту
92
+ ctx.save();
93
+
94
+ // Переміщення до центру лінії та поворот тексту
95
+ ctx.translate(middleX, middleY);
96
+
97
+ // Якщо кут близький до вертикального або перевернутий, коригуємо його
98
+ if (Math.abs(angle) > Math.PI / 2) {
99
+ ctx.rotate(angle + Math.PI);
100
+ ctx.textAlign = 'center';
101
+ } else {
102
+ ctx.rotate(angle);
103
+ ctx.textAlign = 'center';
104
+ }
105
+
106
+ // Рисуємо фон для тексту для кращої читаємості
107
+ const textWidth = ctx.measureText(label).width;
108
+ const padding = 2;
109
+ ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
110
+ ctx.fillRect(
111
+ -textWidth / 2 - padding,
112
+ -scaledFontSize / 2 - padding,
113
+ textWidth + padding * 2,
114
+ scaledFontSize + padding * 2
115
+ );
116
+
117
+ // Малюємо текст
118
+ ctx.fillStyle = '#666';
119
+ ctx.fillText(label, 0, 0);
120
+
121
+ // Відновлення стану контексту
122
+ ctx.restore();
123
+ }}
124
+ nodeCanvasObject={(node: any, ctx: CanvasRenderingContext2D, globalScale: number) => {
125
+ // Отримуємо дані вузла та конфігурацію
126
+ const { x, y, color, label } = node;
127
+
128
+ // Розраховуємо розмір вузла
129
+ const nodeSize = config.nodeSizeBase * config.nodeSizeFactor;
130
+
131
+ // Малюємо коло
132
+ ctx.beginPath();
133
+ ctx.arc(x, y, nodeSize, 0, 2 * Math.PI);
134
+ ctx.fillStyle = color;
135
+ ctx.fill();
136
+
137
+ // Зберігаємо стан контексту перед поворотом
138
+ ctx.save();
139
+ // Переміщуємось до позиції вузла
140
+ ctx.translate(x, y);
141
+
142
+ // Функція для обрізання тексту з трикрапкою (аналог text-overflow: ellipsis)
143
+ const truncateText = (text: string, maxWidth: number): string => {
144
+ if (!text) return '';
145
+
146
+ // Вимірюємо ширину тексту
147
+ const textWidth = ctx.measureText(text).width;
148
+
149
+ // Якщо текст коротший за максимальну ширину, повертаємо як є
150
+ if (textWidth <= maxWidth) return text;
151
+
152
+ // Інакше обрізаємо текст і додаємо трикрапку
153
+ let truncated = text;
154
+ const ellipsis = '...';
155
+
156
+ // Поступово скорочуємо текст, поки він не поміститься
157
+ while (ctx.measureText(truncated + ellipsis).width > maxWidth && truncated.length > 0) {
158
+ truncated = truncated.slice(0, -1);
159
+ }
160
+
161
+ return truncated + ellipsis;
162
+ };
163
+
164
+ // Використовуємо реверсивне масштабування для тексту вузлів
165
+ const scaledFontSize = calculateFontSize(globalScale);
166
+ ctx.font = `${scaledFontSize}px Sans-Serif`;
167
+ ctx.textAlign = 'center';
168
+ ctx.textBaseline = 'middle';
169
+ ctx.fillStyle = 'black';
170
+
171
+ // Розрахунок максимальної ширини тексту на основі розміру вузла
172
+ // Ширина тексту = діаметр вузла * коефіцієнт розширення
173
+ // Використовуємо globalScale для визначення пропорцій тексту
174
+ const maxWidth = (nodeSize * config.textPaddingFactor) / globalScale;
175
+
176
+ // Малюємо тип вузла з обрізанням (з меншою шириною)
177
+ ctx.font = `${scaledFontSize * 0.8}px Sans-Serif`;
178
+ const truncatedLabel = truncateText(label, maxWidth);
179
+ ctx.fillText(truncatedLabel, 0, 0);
180
+
181
+ // Відновлюємо стан контексту
182
+ ctx.restore();
183
+ }}
184
+ />
185
+ );
186
+ };
@@ -0,0 +1,2 @@
1
+ export * from './Graph2D';
2
+ export * from './types';