Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

11.9 KB
Raw Blame
import { LayerColorLabel, LayerItem, isFolderLikeLayer } from '../types/editor';

export interface LayerColorLabelPreset {
  id: LayerColorLabel;
  name: string;
  swatchHex: string;
  rowTint: string;
  rowTintHover: string;
}

export const LAYER_COLOR_LABEL_PRESETS: readonly LayerColorLabelPreset[] = [
  {
    id: 'none',
    name: 'None',
    swatchHex: 'transparent',
    rowTint: 'transparent',
    rowTintHover: 'transparent',
  },
  {
    id: 'red',
    name: 'Red',
    swatchHex: '#e05555',
    rowTint: 'rgba(224, 85, 85, 0.11)',
    rowTintHover: 'rgba(224, 85, 85, 0.17)',
  },
  {
    id: 'orange',
    name: 'Orange',
    swatchHex: '#e58a3c',
    rowTint: 'rgba(229, 138, 60, 0.11)',
    rowTintHover: 'rgba(229, 138, 60, 0.17)',
  },
  {
    id: 'yellow',
    name: 'Yellow',
    swatchHex: '#dfbe3a',
    rowTint: 'rgba(223, 190, 58, 0.11)',
    rowTintHover: 'rgba(223, 190, 58, 0.17)',
  },
  {
    id: 'green',
    name: 'Green',
    swatchHex: '#4cae6b',
    rowTint: 'rgba(76, 174, 107, 0.11)',
    rowTintHover: 'rgba(76, 174, 107, 0.17)',
  },
  {
    id: 'cyan',
    name: 'Cyan',
    swatchHex: '#38b2ac',
    rowTint: 'rgba(56, 178, 172, 0.11)',
    rowTintHover: 'rgba(56, 178, 172, 0.17)',
  },
  {
    id: 'blue',
    name: 'Blue',
    swatchHex: '#4a90e2',
    rowTint: 'rgba(74, 144, 226, 0.12)',
    rowTintHover: 'rgba(74, 144, 226, 0.18)',
  },
  {
    id: 'purple',
    name: 'Purple',
    swatchHex: '#9b6be8',
    rowTint: 'rgba(155, 107, 232, 0.12)',
    rowTintHover: 'rgba(155, 107, 232, 0.18)',
  },
  {
    id: 'gray',
    name: 'Gray',
    swatchHex: '#8c929c',
    rowTint: 'rgba(140, 146, 156, 0.12)',
    rowTintHover: 'rgba(140, 146, 156, 0.18)',
  },
] as const;

export const LAYER_COLOR_LABEL_MAP = new Map<LayerColorLabel, LayerColorLabelPreset>(
  LAYER_COLOR_LABEL_PRESETS.map((p) => [p.id, p])
);

const VALID_COLOR_LABELS = new Set<string>(LAYER_COLOR_LABEL_PRESETS.map((p) => p.id));

export function isValidLayerColorLabel(value: unknown): value is LayerColorLabel {
  return typeof value === 'string' && VALID_COLOR_LABELS.has(value);
}

export function normalizeLayerColorLabel(value: unknown): LayerColorLabel | undefined {
  if (!isValidLayerColorLabel(value) || value === 'none') return undefined;
  return value;
}

export function getLayerColorLabelPreset(
  label: LayerColorLabel | undefined
): LayerColorLabelPreset | null {
  if (!label || label === 'none') return null;
  return LAYER_COLOR_LABEL_MAP.get(label) ?? null;
}

export type PsdSheetColor =
  | 'none'
  | 'red'
  | 'orange'
  | 'yellow'
  | 'green'
  | 'blue'
  | 'violet'
  | 'gray';

export function toPsdLayerColor(label?: LayerColorLabel): PsdSheetColor | undefined {
  if (!label || label === 'none') return undefined;
  switch (label) {
    case 'red':
    case 'orange':
    case 'yellow':
    case 'green':
    case 'blue':
    case 'gray':
      return label;
    case 'purple':
      return 'violet';
    case 'cyan':
      return 'blue';
  }
}

export function fromPsdLayerColor(psdColor?: string): LayerColorLabel | undefined {
  if (!psdColor || psdColor === 'none') return undefined;
  switch (psdColor) {
    case 'red':
    case 'orange':
    case 'yellow':
    case 'green':
    case 'blue':
    case 'gray':
      return psdColor;
    case 'violet':
      return 'purple';
    default:
      return undefined;
  }
}

export type LayerKindFilter =
  | 'all'
  | 'raster'
  | 'folder'
  | 'text'
  | 'adjustment'
  | 'tone'
  | 'masked'
  | 'reference'
  | 'locked'
  | 'hidden';

export interface LayerFilterCriteria {
  query: string;
  colorLabel: LayerColorLabel | 'all';
  kind: LayerKindFilter;
}

export const DEFAULT_LAYER_FILTER_CRITERIA: LayerFilterCriteria = {
  query: '',
  colorLabel: 'all',
  kind: 'all',
};

export interface LayerFilterResult {
  isActive: boolean;
  visibleLayerIds: Set<string>;
  directMatchIds: Set<string>;
  ancestorOnlyIds: Set<string>;
  matchCount: number;
}

export function isLayerFilterActive(criteria: LayerFilterCriteria): boolean {
  return (
    criteria.query.trim().length > 0 ||
    criteria.colorLabel !== 'all' ||
    criteria.kind !== 'all'
  );
}

export function matchesLayerFilter(layer: LayerItem, criteria: LayerFilterCriteria): boolean {
  const trimmed = criteria.query.trim().toLowerCase();
  if (trimmed.length > 0 && !layer.name.toLowerCase().includes(trimmed)) {
    return false;
  }

  if (criteria.colorLabel !== 'all') {
    const effectiveLabel: LayerColorLabel =
      layer.colorLabel && layer.colorLabel !== 'none' ? layer.colorLabel : 'none';
    if (effectiveLabel !== criteria.colorLabel) {
      return false;
    }
  }

  switch (criteria.kind) {
    case 'all':
      return true;
    case 'raster':
      return layer.type === 'raster';
    case 'folder':
      return isFolderLikeLayer(layer);
    case 'text':
      return layer.type === 'text' || layer.type === 'balloon';
    case 'adjustment':
      return layer.type === 'adjustment';
    case 'tone':
      return Boolean(layer.toneEnabled || layer.isToneLayer);
    case 'masked':
      return Boolean(
        layer.maskCanvas || layer.maskEnabled !== undefined || layer.maskThumbnailUrl
      );
    case 'reference':
      return Boolean(layer.isReference);
    case 'locked':
      return Boolean(layer.locked || layer.alphaLocked);
    case 'hidden':
      return !layer.visible;
  }
}

/**
 * Evaluates search + color label + kind/state filtering across a nested layer tree,
 * keeping ancestor folders visible as structural context whenever a descendant matches.
 */
export function filterLayerTree(
  layers: readonly LayerItem[],
  criteria: LayerFilterCriteria
): LayerFilterResult {
  if (!isLayerFilterActive(criteria)) {
    const allIds = new Set(layers.map((l) => l.id));
    return {
      isActive: false,
      visibleLayerIds: allIds,
      directMatchIds: allIds,
      ancestorOnlyIds: new Set<string>(),
      matchCount: layers.length,
    };
  }

  const byId = new Map(layers.map((l) => [l.id, l]));
  const directMatchIds = new Set<string>();
  const visibleLayerIds = new Set<string>();
  const ancestorOnlyIds = new Set<string>();

  for (const layer of layers) {
    if (matchesLayerFilter(layer, criteria)) {
      directMatchIds.add(layer.id);
      visibleLayerIds.add(layer.id);
    }
  }

  for (const matchedId of directMatchIds) {
    const seen = new Set<string>([matchedId]);
    let parentId = byId.get(matchedId)?.parentId ?? null;
    while (parentId && !seen.has(parentId)) {
      seen.add(parentId);
      const parent = byId.get(parentId);
      if (!parent) break;
      visibleLayerIds.add(parent.id);
      if (!directMatchIds.has(parent.id)) {
        ancestorOnlyIds.add(parent.id);
      }
      parentId = parent.parentId;
    }
  }

  return {
    isActive: true,
    visibleLayerIds,
    directMatchIds,
    ancestorOnlyIds,
    matchCount: directMatchIds.size,
  };
}

/**
 * Pure batch update for assigning a LayerColorLabel to one layer or a multi-selected group.
 */
export function computeBatchColorLabel(
  layers: LayerItem[],
  selectedIds: string[],
  targetId: string,
  colorLabel: LayerColorLabel
): LayerItem[] {
  const normalized = normalizeLayerColorLabel(colorLabel);
  const isMulti = selectedIds.length > 1 && selectedIds.includes(targetId);
  const targetSet = isMulti ? new Set(selectedIds) : new Set([targetId]);

  let changed = false;
  const next = layers.map((l) => {
    if (!targetSet.has(l.id)) return l;
    const current = normalizeLayerColorLabel(l.colorLabel);
    if (current === normalized) return l;
    changed = true;
    return { ...l, colorLabel: normalized };
  });

  return changed ? next : layers;
}

export interface SoloLayerState {
  layerId: string;
  previousVisibility: Record<string, boolean>;
}

export interface ComputeSoloResult {
  nextLayers: LayerItem[];
  nextSolo: SoloLayerState | null;
  action: 'solo' | 'switch-solo' | 'restore' | 'show-all' | 'noop';
}

function collectAncestorFolderIds(
  byId: Map<string, LayerItem>,
  layerId: string
): Set<string> {
  const ancestors = new Set<string>();
  const seen = new Set<string>([layerId]);
  let parentId = byId.get(layerId)?.parentId ?? null;
  while (parentId && !seen.has(parentId)) {
    seen.add(parentId);
    const parent = byId.get(parentId);
    if (!parent) break;
    ancestors.add(parent.id);
    parentId = parent.parentId;
  }
  return ancestors;
}

function collectDescendantIds(layers: readonly LayerItem[], folderId: string): Set<string> {
  const descendants = new Set<string>();
  const collect = (parentId: string) => {
    for (const l of layers) {
      if (l.parentId === parentId && !descendants.has(l.id)) {
        descendants.add(l.id);
        if (isFolderLikeLayer(l)) {
          collect(l.id);
        }
      }
    }
  };
  collect(folderId);
  return descendants;
}

/**
 * Pure state transition for Alt+Click Solo/Isolate Layer:
 * - First Alt+Click: snapshots all layer visibilities and hides everything except `targetId`
 *   (plus ancestor folders so nested layers stay renderable, and preserves descendants' visibility if soloing a folder).
 * - Alt+Click on the same soloed layer: restores exact pre-solo visibility for every layer.
 * - Alt+Click on a different layer while soloed: switches solo target while preserving the original restore snapshot.
 * - Alt+Click when all other layers are already manually hidden (no active snapshot): reveals all layers.
 */
export function computeSoloToggle(
  layers: LayerItem[],
  targetId: string,
  currentSolo: SoloLayerState | null
): ComputeSoloResult {
  const byId = new Map(layers.map((l) => [l.id, l]));
  const target = byId.get(targetId);
  if (!target) {
    return { nextLayers: layers, nextSolo: currentSolo, action: 'noop' };
  }

  // Clicking Alt+Eye on the currently soloed layer restores pre-solo visibility
  if (currentSolo && currentSolo.layerId === targetId) {
    return computeRestoreSolo(layers, currentSolo);
  }

  const ancestors = collectAncestorFolderIds(byId, targetId);
  const descendants = isFolderLikeLayer(target)
    ? collectDescendantIds(layers, targetId)
    : new Set<string>();

  const baselineVisibility: Record<string, boolean> = currentSolo
    ? currentSolo.previousVisibility
    : Object.fromEntries(layers.map((l) => [l.id, l.visible]));

  // If not currently in solo mode and everything outside target/ancestors/descendants is already hidden,
  // Alt+Click reveals all layers cleanly (Photoshop / CSP convention).
  if (!currentSolo) {
    const outsideLayers = layers.filter(
      (l) => l.id !== targetId && !ancestors.has(l.id) && !descendants.has(l.id)
    );
    const allOutsideAlreadyHidden =
      outsideLayers.length > 0 && outsideLayers.every((l) => !l.visible);
    const targetAndAncestorsVisible =
      target.visible && Array.from(ancestors).every((aid) => Boolean(byId.get(aid)?.visible));

    if (allOutsideAlreadyHidden && targetAndAncestorsVisible) {
      const nextLayers = layers.map((l) => (l.visible ? l : { ...l, visible: true }));
      return { nextLayers, nextSolo: null, action: 'show-all' };
    }
  }

  const nextLayers = layers.map((l) => {
    let desiredVisible: boolean;
    if (l.id === targetId || ancestors.has(l.id)) {
      desiredVisible = true;
    } else if (descendants.has(l.id)) {
      desiredVisible = baselineVisibility[l.id] ?? l.visible;
    } else {
      desiredVisible = false;
    }
    return l.visible === desiredVisible ? l : { ...l, visible: desiredVisible };
  });

  return {
    nextLayers,
    nextSolo: {
      layerId: targetId,
      previousVisibility: baselineVisibility,
    },
    action: currentSolo ? 'switch-solo' : 'solo',
  };
}

export function computeRestoreSolo(
  layers: LayerItem[],
  currentSolo: SoloLayerState | null
): ComputeSoloResult {
  if (!currentSolo) {
    return { nextLayers: layers, nextSolo: null, action: 'noop' };
  }
  const nextLayers = layers.map((l) => {
    const restored = currentSolo.previousVisibility[l.id];
    if (restored === undefined || l.visible === restored) return l;
    return { ...l, visible: restored };
  });
  return {
    nextLayers,
    nextSolo: null,
    action: 'restore',
  };
}