Загрузка данных


import classNames from 'classnames';
import { Button } from 'exchange-elements/v2';
import { useEffect, useLayoutEffect, useRef, useState } from 'react';

import { GearIcon, LockIcon, LockOpenIcon, TrashIcon } from '@src/components/Icon';

import styles from './index.module.scss';

import type { Drawing } from '@core/Drawings';
import type { PointerEvent as ReactPointerEvent, SyntheticEvent } from 'react';
import type { Observable } from 'rxjs';

interface FloatingDrawingToolbarProps {
  selectedDrawing$: Observable<Drawing | null>;
  getInitialContainer: () => HTMLElement | null;
  onToggleLock: () => void;
  onOpenSettings: () => void;
  onDelete: () => void;
}

interface Position {
  x: number;
  y: number;
}

interface DragState {
  pointerId: number;
  startX: number;
  startY: number;
  initialX: number;
  initialY: number;
}

const TOOLBAR_TOP_OFFSET = 12;

export function FloatingDrawingToolbar({
  selectedDrawing$,
  getInitialContainer,
  onToggleLock,
  onOpenSettings,
  onDelete,
}: FloatingDrawingToolbarProps) {
  const toolbarRef = useRef<HTMLDivElement | null>(null);
  const dragStateRef = useRef<DragState | null>(null);
  const positionRef = useRef<Position | null>(null);
  const hasManualPositionRef = useRef(false);

  const [selectedDrawing, setSelectedDrawing] = useState<Drawing | null>(null);
  const [isLocked, setIsLocked] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const [position, setPosition] = useState<Position | null>(null);

  useEffect(() => {
    const subscription = selectedDrawing$.subscribe(setSelectedDrawing);

    return () => {
      subscription.unsubscribe();
    };
  }, [selectedDrawing$]);

  useEffect(() => {
    if (!selectedDrawing) {
      setIsLocked(false);

      return;
    }

    const subscription = selectedDrawing.subscribeIsLocked(setIsLocked);

    return () => {
      subscription.unsubscribe();
    };
  }, [selectedDrawing]);

  useLayoutEffect(() => {
    if (!selectedDrawing || hasManualPositionRef.current) {
      return;
    }

    let frameId: number;

    const setInitialPosition = (): void => {
      const toolbar = toolbarRef.current;
      const container = toolbar?.parentElement;
      const initialContainer = getInitialContainer();

      if (!toolbar || !container || !initialContainer) {
        frameId = requestAnimationFrame(setInitialPosition);

        return;
      }

      updatePosition(
        getInitialPosition(
          initialContainer,
          toolbar,
          container,
        ),
      );
    };

    frameId = requestAnimationFrame(setInitialPosition);

    return () => {
      cancelAnimationFrame(frameId);
    };
  }, [getInitialContainer, selectedDrawing]);

  const updatePosition = (nextPosition: Position): void => {
    positionRef.current = nextPosition;
    setPosition(nextPosition);
  };

  const handleDragStart = (event: ReactPointerEvent<HTMLButtonElement>): void => {
    const currentPosition = positionRef.current;

    if (event.button !== 0 || !currentPosition) {
      return;
    }

    event.preventDefault();
    event.currentTarget.setPointerCapture(event.pointerId);

    hasManualPositionRef.current = true;

    dragStateRef.current = {
      pointerId: event.pointerId,
      startX: event.clientX,
      startY: event.clientY,
      initialX: currentPosition.x,
      initialY: currentPosition.y,
    };

    setIsDragging(true);
  };

  const handleDrag = (event: ReactPointerEvent<HTMLButtonElement>): void => {
    const dragState = dragStateRef.current;
    const toolbar = toolbarRef.current;
    const container = toolbar?.parentElement;

    if (
      !dragState ||
      dragState.pointerId !== event.pointerId ||
      !toolbar ||
      !container
    ) {
      return;
    }

    event.preventDefault();

    updatePosition(
      clampPosition(
        dragState.initialX + event.clientX - dragState.startX,
        dragState.initialY + event.clientY - dragState.startY,
        toolbar,
        container,
      ),
    );
  };

  const handleDragEnd = (event: ReactPointerEvent<HTMLButtonElement>): void => {
    if (dragStateRef.current?.pointerId !== event.pointerId) {
      return;
    }

    if (event.currentTarget.hasPointerCapture(event.pointerId)) {
      event.currentTarget.releasePointerCapture(event.pointerId);
    }

    dragStateRef.current = null;
    setIsDragging(false);
  };

  const stopPropagation = (event: SyntheticEvent): void => {
    event.stopPropagation();
  };

  if (!selectedDrawing) {
    return null;
  }

  return (
    <div
      ref={toolbarRef}
      className={styles.toolbar}
      style={{
        visibility: position ? 'visible' : 'hidden',
        transform: `translate3d(${position?.x ?? 0}px, ${position?.y ?? 0}px, 0)`,
      }}
      onClick={stopPropagation}
      onContextMenu={stopPropagation}
      onDoubleClick={stopPropagation}
      onPointerCancel={stopPropagation}
      onPointerDown={stopPropagation}
      onPointerMove={stopPropagation}
      onPointerUp={stopPropagation}
    >
      <button
        type="button"
        className={classNames(styles.toolbar_handle, {
          [styles.dragging]: isDragging,
        })}
        onPointerCancel={handleDragEnd}
        onPointerDown={handleDragStart}
        onPointerMove={handleDrag}
        onPointerUp={handleDragEnd}
      >
        <span />
        <span />
        <span />
        <span />
        <span />
        <span />
      </button>

      {selectedDrawing.hasSettings() && (
        <Button
          size="sm"
          className={styles.button}
          onClick={onOpenSettings}
          label={<GearIcon />}
        />
      )}

      <Button
        size="sm"
        className={classNames(styles.button, {
          [styles.pressed]: isLocked,
        })}
        onClick={onToggleLock}
        label={isLocked ? <LockIcon /> : <LockOpenIcon />}
      />

      <Button
        size="sm"
        className={styles.button}
        onClick={onDelete}
        label={<TrashIcon />}
      />
    </div>
  );

  function updatePosition(nextPosition: Position): void {
    positionRef.current = nextPosition;
    setPosition(nextPosition);
  }
}

function getInitialPosition(
  initialContainer: HTMLElement,
  toolbar: HTMLElement,
  container: HTMLElement,
): Position {
  const initialContainerRect = initialContainer.getBoundingClientRect();
  const containerRect = container.getBoundingClientRect();

  const x =
    initialContainerRect.left -
    containerRect.left +
    (initialContainerRect.width - toolbar.offsetWidth) / 2;

  const y =
    initialContainerRect.top -
    containerRect.top +
    TOOLBAR_TOP_OFFSET;

  return clampPosition(x, y, toolbar, container);
}

function clampPosition(
  x: number,
  y: number,
  toolbar: HTMLElement,
  container: HTMLElement,
): Position {
  return {
    x: Math.max(
      0,
      Math.min(
        Math.round(x),
        container.clientWidth - toolbar.offsetWidth,
      ),
    ),
    y: Math.max(
      0,
      Math.min(
        Math.round(y),
        container.clientHeight - toolbar.offsetHeight,
      ),
    ),
  };
}



import {
  CHART_DRAWING_TOOLBAR_CONTAINER,
  CHART_MODAL_CONTAINER_CLASSNAME,
  CHART_PANE_OVERLAY_CONTAINER,
  CHART_ROOT_CLASSNAME,
} from '@src/constants';

import styles from './styles.module.scss';

interface CreateContainersOptions {
  parentContainer: HTMLElement;
  showBottomPanel?: boolean;
  showMenuButton?: boolean;
}

enum ZIndex {
  Chart = '0',
  Base = '10',
  Floating = '20',
  Modal = '1000',
}

const ContainerLayoutConfig = {
  headerHeight: 36,
  footerHeight: 32,
  toolbarWidth: 42,
  verticalGap: 8,
};

/**
 * Утилита для создания DOM контейнеров
 */
export class ContainerManager {
  private static injectFont(): void {
    const existingLink = document.querySelector(
      'link[href*="fonts.googleapis.com"]',
    );

    if (existingLink) {
      return;
    }

    const link = document.createElement('link');

    link.rel = 'stylesheet';
    link.href =
      'https://fonts.googleapis.com/css2?family=Inter:opsz,wght@14..32,100..900&display=swap';

    document.head.appendChild(link);
  }

  /**
   * Создание контейнеров для графика и UI компонентов
   */
  static createContainers({
    parentContainer,
    showBottomPanel,
    showMenuButton,
  }: CreateContainersOptions) {
    this.injectFont();

    const {
      headerHeight,
      footerHeight,
      toolbarWidth,
      verticalGap,
    } = ContainerLayoutConfig;

    parentContainer.innerHTML = '';
    parentContainer.classList.add(CHART_ROOT_CLASSNAME);
    parentContainer.style.height = '100%';
    parentContainer.style.width = '100%';
    parentContainer.style.padding = 'var(--space-1000)';
    parentContainer.style.backgroundColor = 'var(--neutral-0)';
    parentContainer.style.borderRadius = 'var(--space-0500)';
    parentContainer.style.display = 'grid';
    parentContainer.style.rowGap = `${verticalGap}px`;
    parentContainer.style.gridTemplateRows = showBottomPanel
      ? `${headerHeight}px minmax(0, 1fr) ${footerHeight}px`
      : `${headerHeight}px minmax(0, 1fr)`;

    const headerContainer = document.createElement('div');

    headerContainer.style.width = '100%';
    headerContainer.style.height = `${headerHeight}px`;
    headerContainer.style.overflow = 'auto hidden';
    headerContainer.className = styles.scrollableBox;

    const footerContainer = document.createElement('div');

    footerContainer.style.width = '100%';
    footerContainer.style.height = `${footerHeight}px`;

    const chartContainer = document.createElement('div');

    chartContainer.style.position = 'relative';
    chartContainer.style.height = '100%';
    chartContainer.style.width = '100%';
    chartContainer.style.minWidth = '0';
    chartContainer.style.minHeight = '0';
    chartContainer.style.display = 'grid';
    chartContainer.style.columnGap = 'var(--space-0500)';
    chartContainer.style.gridTemplateColumns = 'minmax(0, 1fr)';

    const chartAreaContainer = document.createElement('div');

    chartAreaContainer.style.position = 'relative';
    chartAreaContainer.style.height = '100%';
    chartAreaContainer.style.minHeight = '0';
    chartAreaContainer.style.minWidth = '0';
    chartAreaContainer.style.cursor = 'crosshair';

    const toolBarContainer = document.createElement('div');

    toolBarContainer.style.height = '100%';
    toolBarContainer.style.minHeight = '0';
    toolBarContainer.style.overflow = 'hidden';

    const controlBarContainer = document.createElement('div');

    controlBarContainer.style.position = 'absolute';
    controlBarContainer.style.left = '50%';
    controlBarContainer.style.transform = 'translateX(-50%)';
    controlBarContainer.style.bottom = 'var(--space-2000)';
    controlBarContainer.style.zIndex = ZIndex.Base;

    const drawingToolbarContainer = document.createElement('div');

    drawingToolbarContainer.classList.add(
      CHART_DRAWING_TOOLBAR_CONTAINER,
    );
    drawingToolbarContainer.style.position = 'absolute';
    drawingToolbarContainer.style.inset = '0';
    drawingToolbarContainer.style.zIndex = ZIndex.Floating;
    drawingToolbarContainer.style.pointerEvents = 'none';
    drawingToolbarContainer.style.overflow = 'hidden';

    const modalContainer = document.createElement('div');

    modalContainer.classList.add(CHART_MODAL_CONTAINER_CLASSNAME);
    modalContainer.style.position = 'absolute';
    modalContainer.style.inset = '0';
    modalContainer.style.zIndex = ZIndex.Modal;
    modalContainer.hidden = true;

    chartAreaContainer.append(
      controlBarContainer,
      drawingToolbarContainer,
    );

    chartContainer.append(chartAreaContainer, modalContainer);
    parentContainer.append(headerContainer, chartContainer);

    if (showBottomPanel) {
      parentContainer.append(footerContainer);
    }

    const toggleToolbar = () => {
      const mounted = toolBarContainer.isConnected;

      if (mounted) {
        toolBarContainer.remove();
        chartContainer.style.gridTemplateColumns = 'minmax(0, 1fr)';

        return false;
      }

      chartContainer.insertBefore(
        toolBarContainer,
        chartAreaContainer,
      );
      chartContainer.style.gridTemplateColumns =
        `${toolbarWidth}px minmax(0, 1fr)`;

      return true;
    };

    chartContainer.insertBefore(
      toolBarContainer,
      chartAreaContainer,
    );
    chartContainer.style.gridTemplateColumns =
      `${toolbarWidth}px minmax(0, 1fr)`;

    if (!showMenuButton) {
      toggleToolbar();
    }

    return {
      headerContainer,
      footerContainer,

      chartContainer,
      chartAreaContainer,
      toolBarContainer,

      modalContainer,
      controlBarContainer,
      drawingToolbarContainer,

      toggleToolbar,
    };
  }

  /**
   * Очистка контейнеров
   */
  static clearContainers(parentContainer: HTMLElement): void {
    parentContainer.innerHTML = '';
  }

  static createPaneContainers() {
    const legendContainer = document.createElement('div');

    legendContainer.style.width = '80%';
    legendContainer.style.position = 'absolute';
    legendContainer.style.top = '0';
    legendContainer.style.left = '0';
    legendContainer.style.zIndex = ZIndex.Base;
    legendContainer.style.pointerEvents = 'none';

    const paneOverlayContainer = document.createElement('div');

    paneOverlayContainer.classList.add(
      CHART_PANE_OVERLAY_CONTAINER,
    );
    paneOverlayContainer.style.position = 'absolute';
    paneOverlayContainer.style.inset = '0';
    paneOverlayContainer.style.zIndex = ZIndex.Base;
    paneOverlayContainer.style.pointerEvents = 'none';

    return {
      legendContainer,
      paneOverlayContainer,
    };
  }
}