@koslibs/components 1.1.0 → 1.2.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @koslibs/components
2
2
 
3
+ ## 1.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#3](https://github.com/koslibs/components/pull/3) [`a618f52`](https://github.com/koslibs/components/commit/a618f526010adc6203a708e73fac3906b555ac78) Thanks [@holypower777](https://github.com/holypower777)! - Перенесён Popover из GullEye с отдельным импортом `@koslibs/components/Popover`,
8
+ стилями, Docs и Playground. Сохранены управляемая видимость, позиционирование,
9
+ ограничение размеров и способы закрытия. Портал и позиционирование адаптированы
10
+ для самостоятельного использования в React 18 и 19.
11
+
12
+ Popover управляет позицией и размерами и рендерит children напрямую. Оформление
13
+ и прокрутка содержимого задаются вызывающим компонентом; colors и contentClassName
14
+ не входят в API. Прежнее оформление Storybook-примеров сохранено в их содержимом.
15
+ Тень задаёт сам Popover через CSS-переменную --popover-shadow.
16
+ Offset по умолчанию равен `[0, 0]`, без смещения и зазора между якорем и содержимым.
17
+
18
+ Документация каждого компонента собрана в его папке docs: stories, страницы Docs
19
+ и стили примеров. Папки документации исключены из JS-сборки и деклараций npm-пакета.
20
+
3
21
  ## 1.1.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -39,9 +39,11 @@ src/components/Button/
39
39
  index.ts
40
40
  button.tsx
41
41
  button.module.css
42
- button.stories.tsx
43
- button.docs.tsx
44
42
  CHANGELOG.md
43
+ docs/
44
+ button.stories.tsx
45
+ button.docs.tsx
46
+ examples.module.css
45
47
  ```
46
48
 
47
49
  1. Перенесите компонент в `src/components/<Name>`; имя папки — PascalCase, например `Button`.
@@ -59,7 +61,9 @@ src/components/Button/
59
61
  }
60
62
  ```
61
63
 
62
- 4. Добавьте Docs, Playground и `CHANGELOG.md` по [примеру документации](https://github.com/koslibs/components/blob/main/docs/component-changelogs.md).
64
+ 4. Добавьте Docs и Playground в папку компонента `docs`, а `CHANGELOG.md` оставьте
65
+ рядом с реализацией, по [примеру документации](https://github.com/koslibs/components/blob/main/docs/component-changelogs.md).
66
+ Папки `src/**/docs` исключены из npm-сборки. Общие блоки Storybook находятся в `src/docs`.
63
67
  5. Добавьте тесты поведения. `npm run test:unit` запускает unit-тесты через
64
68
  `koslibs-builder lib:test`; `npm test` также проверяет отдельные импорты.
65
69
  6. Выполните сборку и проверьте реальные пути JS, деклараций и CSS в `dist`.
@@ -0,0 +1,4 @@
1
+ import type { PopoverProps } from '../../types.js';
2
+ export declare const PopoverSurface: import("react").ForwardRefExoticComponent<Omit<PopoverProps, "open" | "getPortalContainer" | "anchorElement"> & {
3
+ anchorElement: HTMLElement;
4
+ } & import("react").RefAttributes<HTMLDivElement>>;
@@ -0,0 +1,106 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import classnames from "classnames";
3
+ import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
4
+ import { createSizeModifier } from "../../create-size-modifier.js";
5
+ import { usePopoverPosition } from "../../use-popover-position.js";
6
+ import index_module from "../../index.module.js";
7
+ const DEFAULT_OFFSET = [
8
+ 0,
9
+ 0
10
+ ];
11
+ const PopoverSurface = /*#__PURE__*/ forwardRef(({ anchorElement, position = 'bottom-start', offset = DEFAULT_OFFSET, useAnchorWidth = false, preventFlip = false, fallbackPlacements, preventOverflow = true, availableHeight = true, viewportPadding = 8, onClose, outsideClick = true, escapeKeyDown = true, className, style, children, dataTestId, ...restProps }, ref)=>{
12
+ const [popperElement, setPopperElement] = useState(null);
13
+ useImperativeHandle(ref, ()=>popperElement, [
14
+ popperElement
15
+ ]);
16
+ const padding = Math.max(0, viewportPadding);
17
+ const modifiers = useMemo(()=>[
18
+ {
19
+ name: 'offset',
20
+ options: {
21
+ offset
22
+ }
23
+ },
24
+ {
25
+ name: 'flip',
26
+ enabled: !preventFlip,
27
+ options: {
28
+ fallbackPlacements,
29
+ boundary: [],
30
+ padding
31
+ }
32
+ },
33
+ {
34
+ name: 'preventOverflow',
35
+ enabled: preventOverflow,
36
+ options: {
37
+ boundary: [],
38
+ padding
39
+ }
40
+ },
41
+ createSizeModifier({
42
+ availableHeight,
43
+ useAnchorWidth,
44
+ viewportPadding: padding
45
+ })
46
+ ], [
47
+ offset,
48
+ preventFlip,
49
+ fallbackPlacements,
50
+ preventOverflow,
51
+ availableHeight,
52
+ useAnchorWidth,
53
+ padding
54
+ ]);
55
+ const { styles: popperStyles, attributes, update } = usePopoverPosition(anchorElement, popperElement, position, modifiers);
56
+ useEffect(()=>{
57
+ if (update) update();
58
+ }, [
59
+ children,
60
+ style,
61
+ update
62
+ ]);
63
+ useEffect(()=>{
64
+ if (!onClose) return;
65
+ const ownerDocument = anchorElement.ownerDocument;
66
+ const handlePointerDown = (event)=>{
67
+ if (event.defaultPrevented) return;
68
+ const path = event.composedPath();
69
+ if (path.includes(anchorElement) || popperElement && path.includes(popperElement)) return;
70
+ onClose();
71
+ };
72
+ const handleKeyDown = (event)=>{
73
+ if ('Escape' !== event.key || event.defaultPrevented) return;
74
+ event.preventDefault();
75
+ event.stopPropagation();
76
+ onClose();
77
+ };
78
+ if (outsideClick) ownerDocument.addEventListener('pointerdown', handlePointerDown);
79
+ if (escapeKeyDown) ownerDocument.addEventListener('keydown', handleKeyDown);
80
+ return ()=>{
81
+ ownerDocument.removeEventListener('pointerdown', handlePointerDown);
82
+ ownerDocument.removeEventListener('keydown', handleKeyDown);
83
+ };
84
+ }, [
85
+ anchorElement,
86
+ popperElement,
87
+ onClose,
88
+ outsideClick,
89
+ escapeKeyDown
90
+ ]);
91
+ return /*#__PURE__*/ jsx("div", {
92
+ ...restProps,
93
+ ...attributes,
94
+ ref: setPopperElement,
95
+ className: classnames(index_module.component, className),
96
+ style: {
97
+ ...style,
98
+ ...popperStyles,
99
+ visibility: popperStyles?.transform ? style?.visibility : 'hidden'
100
+ },
101
+ "data-test-id": dataTestId,
102
+ children: children
103
+ });
104
+ });
105
+ PopoverSurface.displayName = 'PopoverSurface';
106
+ export { PopoverSurface };
@@ -0,0 +1,8 @@
1
+ import { type Modifier } from '@popperjs/core';
2
+ type Options = {
3
+ availableHeight: boolean;
4
+ useAnchorWidth: boolean;
5
+ viewportPadding: number;
6
+ };
7
+ export declare const createSizeModifier: (options: Options) => Modifier<"availableSize", Options>;
8
+ export {};
@@ -0,0 +1,26 @@
1
+ import { detectOverflow } from "@popperjs/core";
2
+ const createSizeModifier = (options)=>({
3
+ name: 'availableSize',
4
+ enabled: true,
5
+ phase: 'beforeWrite',
6
+ requires: [
7
+ 'computeStyles'
8
+ ],
9
+ options,
10
+ fn ({ state }) {
11
+ const { availableHeight, useAnchorWidth, viewportPadding } = options;
12
+ const documentElement = state.elements.popper.ownerDocument.documentElement;
13
+ const overflow = detectOverflow(state, {
14
+ boundary: [],
15
+ padding: viewportPadding
16
+ });
17
+ const side = state.placement.split('-')[0];
18
+ const height = 'top' === side || 'bottom' === side ? state.rects.popper.height - overflow[side] : documentElement.clientHeight - 2 * viewportPadding;
19
+ Object.assign(state.styles.popper, {
20
+ '--popover-viewport-padding': `${viewportPadding}px`,
21
+ '--popover-available-height': availableHeight ? `${Math.max(0, height)}px` : 'none'
22
+ });
23
+ if (useAnchorWidth) state.styles.popper.width = `${state.rects.reference.width}px`;
24
+ }
25
+ });
26
+ export { createSizeModifier };
@@ -0,0 +1,2 @@
1
+ export { Popover } from './popover.js';
2
+ export type { PopoverProps, PopoverPosition } from './types.js';
@@ -0,0 +1 @@
1
+ export { Popover } from "./popover.js";
@@ -0,0 +1,5 @@
1
+ import "./index_module.css";
2
+ const index_module = {
3
+ component: "component-wBbNPp"
4
+ };
5
+ export default index_module;
@@ -0,0 +1,15 @@
1
+ @import "./vars.css";
2
+
3
+ .component-wBbNPp {
4
+ box-sizing: border-box;
5
+ z-index: var(--popover-z-index);
6
+ max-width: calc(100vw - var(--popover-viewport-padding, 8px) * 2);
7
+ min-width: 0;
8
+ min-height: 0;
9
+ max-height: var(--popover-available-height, none);
10
+ box-shadow: var(--popover-shadow);
11
+ flex-direction: column;
12
+ display: flex;
13
+ position: fixed;
14
+ }
15
+
@@ -0,0 +1,21 @@
1
+ export type { PopoverProps, PopoverPosition } from './types.js';
2
+ export declare const Popover: import("react").ForwardRefExoticComponent<Omit<import("react").HTMLAttributes<HTMLDivElement>, "className" | "style" | "children"> & {
3
+ children?: import("react").ReactNode;
4
+ className?: string;
5
+ style?: import("react").CSSProperties;
6
+ open: boolean;
7
+ anchorElement: HTMLElement | null;
8
+ position?: import("./types.js").PopoverPosition;
9
+ offset?: [number, number];
10
+ useAnchorWidth?: boolean;
11
+ preventFlip?: boolean;
12
+ fallbackPlacements?: import("./types.js").PopoverPosition[];
13
+ preventOverflow?: boolean;
14
+ availableHeight?: boolean;
15
+ viewportPadding?: number;
16
+ onClose?: VoidFunction;
17
+ outsideClick?: boolean;
18
+ escapeKeyDown?: boolean;
19
+ getPortalContainer?: () => Element | null;
20
+ dataTestId?: string;
21
+ } & import("react").RefAttributes<HTMLDivElement>>;
@@ -0,0 +1,15 @@
1
+ import { jsx } from "react/jsx-runtime";
2
+ import { forwardRef } from "react";
3
+ import { createPortal } from "react-dom";
4
+ import { PopoverSurface } from "./components/popover-surface/index.js";
5
+ const Popover = /*#__PURE__*/ forwardRef(({ open, anchorElement, getPortalContainer, ...restProps }, ref)=>{
6
+ if (!open || !anchorElement) return null;
7
+ const container = getPortalContainer ? getPortalContainer() : anchorElement.ownerDocument.body;
8
+ return container ? /*#__PURE__*/ createPortal(/*#__PURE__*/ jsx(PopoverSurface, {
9
+ ...restProps,
10
+ anchorElement: anchorElement,
11
+ ref: ref
12
+ }), container) : null;
13
+ });
14
+ Popover.displayName = 'Popover';
15
+ export { Popover };
@@ -0,0 +1,86 @@
1
+ import type { Placement } from '@popperjs/core';
2
+ import type { CSSProperties, HTMLAttributes, ReactNode } from 'react';
3
+ export type PopoverPosition = Exclude<Placement, 'auto' | 'auto-start' | 'auto-end'>;
4
+ export type PopoverProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'className' | 'style'> & {
5
+ /** Содержимое поповера. Оформление и прокрутка задаются вызывающим компонентом. */
6
+ children?: ReactNode;
7
+ /**
8
+ * Дополнительный класс внешнего контейнера.
9
+ */
10
+ className?: string;
11
+ /**
12
+ * Стили внешнего контейнера, включая ширину.
13
+ */
14
+ style?: CSSProperties;
15
+ /**
16
+ * Видимость поповера.
17
+ */
18
+ open: boolean;
19
+ /**
20
+ * Элемент, относительно которого открывается поповер.
21
+ */
22
+ anchorElement: HTMLElement | null;
23
+ /**
24
+ * Предпочтительная позиция относительно элемента.
25
+ * @default 'bottom-start'
26
+ */
27
+ position?: PopoverPosition;
28
+ /**
29
+ * Смещение вдоль элемента и расстояние от него, в пикселях.
30
+ * @default [0, 0]
31
+ */
32
+ offset?: [number, number];
33
+ /**
34
+ * Использовать ширину элемента, относительно которого открыт поповер.
35
+ * @default false
36
+ */
37
+ useAnchorWidth?: boolean;
38
+ /**
39
+ * Запретить смену стороны при недостатке места.
40
+ * @default false
41
+ */
42
+ preventFlip?: boolean;
43
+ /**
44
+ * Позиции, которые проверяются при недостатке места.
45
+ */
46
+ fallbackPlacements?: PopoverPosition[];
47
+ /**
48
+ * Удерживать поповер в пределах видимой области.
49
+ * @default true
50
+ */
51
+ preventOverflow?: boolean;
52
+ /**
53
+ * Ограничивать высоту доступным местом.
54
+ * Для прокрутки задайте содержимому min-height: 0 и overflow: auto.
55
+ * @default true
56
+ */
57
+ availableHeight?: boolean;
58
+ /**
59
+ * Минимальный отступ от границ видимой области, в пикселях.
60
+ * @default 8
61
+ */
62
+ viewportPadding?: number;
63
+ /**
64
+ * Обработчик запроса закрытия. Обновите open в вызывающем компоненте.
65
+ */
66
+ onClose?: VoidFunction;
67
+ /**
68
+ * Разрешить закрытие по нажатию вне поповера и его элемента.
69
+ * @default true
70
+ */
71
+ outsideClick?: boolean;
72
+ /**
73
+ * Разрешить закрытие по Escape.
74
+ * @default true
75
+ */
76
+ escapeKeyDown?: boolean;
77
+ /**
78
+ * Контейнер портала. По умолчанию — body документа anchorElement.
79
+ * Если функция возвращает null, поповер не рендерится.
80
+ */
81
+ getPortalContainer?: () => Element | null;
82
+ /**
83
+ * Идентификатор для автоматизированных тестов.
84
+ */
85
+ dataTestId?: string;
86
+ };
File without changes
@@ -0,0 +1,8 @@
1
+ import { type Modifier } from '@popperjs/core';
2
+ import { type CSSProperties } from 'react';
3
+ import type { PopoverPosition } from './types.js';
4
+ export declare function usePopoverPosition(anchorElement: HTMLElement, popperElement: HTMLDivElement | null, position: PopoverPosition, modifiers: Partial<Modifier<string, object>>[]): {
5
+ update: () => Promise<Partial<import("@popperjs/core").State>> | undefined;
6
+ styles: CSSProperties;
7
+ attributes: Record<string, string | boolean>;
8
+ };
@@ -0,0 +1,78 @@
1
+ import { createPopper } from "@popperjs/core";
2
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ const initialState = {
4
+ styles: {
5
+ position: 'fixed',
6
+ left: 0,
7
+ top: 0,
8
+ visibility: 'hidden'
9
+ },
10
+ attributes: {}
11
+ };
12
+ function usePopoverPosition(anchorElement, popperElement, position, modifiers) {
13
+ const [state, setState] = useState(initialState);
14
+ const instanceRef = useRef(null);
15
+ const updateState = useMemo(()=>({
16
+ name: 'reactStyles',
17
+ enabled: true,
18
+ phase: 'write',
19
+ requires: [
20
+ 'computeStyles'
21
+ ],
22
+ fn: ({ state: popperState })=>{
23
+ setState({
24
+ styles: {
25
+ ...popperState.styles.popper
26
+ },
27
+ attributes: {
28
+ ...popperState.attributes.popper
29
+ }
30
+ });
31
+ }
32
+ }), []);
33
+ useEffect(()=>{
34
+ if (!popperElement) return;
35
+ let active = true;
36
+ setState(initialState);
37
+ const instance = createPopper(anchorElement, popperElement, {
38
+ placement: position,
39
+ strategy: 'fixed',
40
+ modifiers: [
41
+ ...modifiers,
42
+ {
43
+ ...updateState,
44
+ fn: (args)=>{
45
+ if (active) updateState.fn(args);
46
+ }
47
+ },
48
+ {
49
+ name: 'applyStyles',
50
+ enabled: false
51
+ }
52
+ ]
53
+ });
54
+ instanceRef.current = instance;
55
+ const ResizeObserverClass = anchorElement.ownerDocument.defaultView?.ResizeObserver;
56
+ const observer = ResizeObserverClass ? new ResizeObserverClass(()=>void instance.update()) : void 0;
57
+ observer?.observe(anchorElement);
58
+ observer?.observe(popperElement);
59
+ return ()=>{
60
+ active = false;
61
+ observer?.disconnect();
62
+ instance.destroy();
63
+ instanceRef.current = null;
64
+ };
65
+ }, [
66
+ anchorElement,
67
+ popperElement,
68
+ position,
69
+ modifiers,
70
+ updateState
71
+ ]);
72
+ const update = useCallback(()=>instanceRef.current?.update(), []);
73
+ return {
74
+ ...state,
75
+ update
76
+ };
77
+ }
78
+ export { usePopoverPosition };
@@ -0,0 +1,5 @@
1
+ :root {
2
+ --popover-z-index: 1100;
3
+ --popover-shadow: 0 8px 24px #00000029;
4
+ }
5
+
package/dist/index.d.ts CHANGED
@@ -4,3 +4,5 @@ export { Spinner } from './components/Spinner/index.js';
4
4
  export type { SpinnerProps } from './components/Spinner/index.js';
5
5
  export { Typography, TypographyText, TypographyTitle, Text, Title } from './components/Typography/index.js';
6
6
  export type { TextProps, TitleProps, TypographyColor, TypographyWeight, } from './components/Typography/index.js';
7
+ export { Popover } from './components/Popover/index.js';
8
+ export type { PopoverProps, PopoverPosition } from './components/Popover/index.js';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { Button } from "./components/Button/index.js";
2
2
  export { Spinner } from "./components/Spinner/index.js";
3
3
  export { Text, Title, Typography, TypographyText, TypographyTitle } from "./components/Typography/index.js";
4
+ export { Popover } from "./components/Popover/index.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@koslibs/components",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Shared React components for koslibs projects",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -80,6 +80,7 @@
80
80
  "react-dom": "^18.3.1 || ^19.0.0"
81
81
  },
82
82
  "dependencies": {
83
+ "@popperjs/core": "2.11.8",
83
84
  "classnames": "2.5.1"
84
85
  }
85
86
  }