Skip to content

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

7.7 KB
Raw Blame
/**
 * Prevents accidental page reloads and browser history navigation (`Ctrl+R`, `Cmd+R`,
 * `Ctrl+Shift+R`, `F5`, `BrowserRefresh`, `Alt+Left/Right`, right-click "Reload", and
 * browser/WebView unload when unsaved artwork exists) without blocking Ink Studio's own
 * shortcuts (such as `Ctrl+Shift+R` Perspective Ruler or custom shortcut recording).
 */

export interface ReloadKeyEventLike {
  key?: string;
  code?: string;
  ctrlKey?: boolean;
  metaKey?: boolean;
  shiftKey?: boolean;
  altKey?: boolean;
  repeat?: boolean;
}

export interface DirtyDocumentLike {
  isDirty?: boolean;
}

export interface InstallReloadGuardOptions {
  /** Target EventTarget (defaults to `window`). */
  target?: Window;
  /** Returns current open documents to check for unsaved changes. */
  getDocuments: () => ReadonlyArray<DirtyDocumentLike>;
  /** Returns true while app close is intentionally finalizing (never prompt/block shutdown). */
  isFinalizingClose: () => boolean;
  /** Optional check for an active in-progress stroke before history marks the document dirty. */
  isDrawingActive?: () => boolean;
  /**
   * Optional predicate returning true if the reload/nav keystroke should trigger a user-visible
   * notification (e.g. skip when bound to an Ink Studio command like `Ctrl+Shift+R` or while
   * recording a shortcut in Settings).
   */
  shouldNotifyBlockedKey?: (e: KeyboardEvent) => boolean;
  /** Optional callback invoked when an unbound reload shortcut is blocked. */
  onBlockedReloadShortcut?: () => void;
}

const NON_TEXT_INPUT_TYPES = new Set([
  'button',
  'checkbox',
  'color',
  'file',
  'hidden',
  'image',
  'radio',
  'range',
  'reset',
  'submit',
]);

let intentionalReloadAllowed = false;

/**
 * Marks an explicit, user-confirmed programmatic reload (e.g. ErrorBoundary "Reload Editor")
 * so `beforeunload` does not block crash recovery.
 */
export function markIntentionalReload(): void {
  intentionalReloadAllowed = true;
}

/** Test-only reset for `intentionalReloadAllowed`. */
export function _resetReloadGuardForTests(): void {
  intentionalReloadAllowed = false;
}

function detectIsMacPlatform(): boolean {
  if (typeof navigator === 'undefined') return false;
  const plat =
    (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform ||
    navigator.platform ||
    navigator.userAgent ||
    '';
  return /mac|iphone|ipad|ipod/i.test(plat);
}

/**
 * Returns true if the keyboard event triggers a browser/WebView reload or history navigation
 * (`Ctrl/Cmd+R`, `Ctrl/Cmd+Shift+R`, `F5`, `Ctrl/Shift/Alt+F5`, `BrowserRefresh`,
 * `BrowserBack`, `BrowserForward`, and `Alt+ArrowLeft`/`Alt+ArrowRight` on Windows/Linux),
 * matching both physical `code` (layout-independent for Cyrillic/IME/etc.) and logical `key`.
 */
export function isBrowserReloadOrNavShortcut(
  e: ReloadKeyEventLike,
  isMac: boolean = detectIsMacPlatform()
): boolean {
  const code = e.code || '';
  const key = e.key || '';
  const keyLower = key.toLowerCase();

  // F5 / Ctrl+F5 / Shift+F5 / Cmd+F5 / Alt+F5
  if (code === 'F5' || key === 'F5') {
    return true;
  }

  // Dedicated multimedia keyboard refresh / back / forward keys
  if (
    code === 'BrowserRefresh' ||
    key === 'BrowserRefresh' ||
    code === 'BrowserBack' ||
    key === 'BrowserBack' ||
    code === 'BrowserForward' ||
    key === 'BrowserForward'
  ) {
    return true;
  }

  // Ctrl+R / Cmd+R / Ctrl+Shift+R / Cmd+Shift+R (layout-independent via KeyR + key fallback)
  if ((e.ctrlKey || e.metaKey) && !e.altKey) {
    if (code === 'KeyR' || keyLower === 'r') {
      return true;
    }
  }

  // Alt+Left / Alt+Right browser history navigation on Windows/Linux (on macOS Option+Arrow is word jump)
  if (!isMac && e.altKey && !e.ctrlKey && !e.metaKey) {
    if (
      code === 'ArrowLeft' ||
      code === 'ArrowRight' ||
      key === 'ArrowLeft' ||
      key === 'ArrowRight'
    ) {
      return true;
    }
  }

  return false;
}

/**
 * Returns true if the browser/WebView default context menu (which exposes "Reload", "Back",
 * "Forward") should be blocked for this event target. Editable text inputs, textareas,
 * contentEditable regions, and active text selections retain their native Copy/Paste menu.
 */
export function shouldBlockDefaultContextMenu(
  target: EventTarget | null,
  selectionText?: string
): boolean {
  const selected =
    selectionText !== undefined
      ? selectionText
      : typeof window !== 'undefined'
        ? window.getSelection?.()?.toString() ?? ''
        : '';
  if (selected.length > 0) {
    return false;
  }

  if (!target || typeof target !== 'object') {
    return true;
  }

  const el = target as {
    tagName?: string;
    type?: string;
    isContentEditable?: boolean;
    closest?: (selector: string) => {
      tagName?: string;
      type?: string;
      isContentEditable?: boolean;
    } | null;
  };

  const editable =
    typeof el.closest === 'function'
      ? el.closest('input, textarea, [contenteditable="true"], [contenteditable=""]')
      : el;

  if (!editable) {
    return true;
  }

  if (editable.isContentEditable) {
    return false;
  }

  const tag = (editable.tagName || '').toUpperCase();
  if (tag === 'TEXTAREA') {
    return false;
  }
  if (tag === 'INPUT') {
    const inputType = (editable.type || 'text').toLowerCase();
    return NON_TEXT_INPUT_TYPES.has(inputType);
  }

  return true;
}

/**
 * Returns true when `beforeunload` should ask confirmation / prevent unload.
 */
export function shouldConfirmBeforeUnload(
  documents: ReadonlyArray<DirtyDocumentLike>,
  finalizingClose: boolean,
  isDrawingActive = false
): boolean {
  if (finalizingClose || intentionalReloadAllowed) {
    return false;
  }
  if (isDrawingActive) {
    return true;
  }
  return documents.some((d) => Boolean(d.isDirty));
}

/**
 * Installs capture-phase reload-key prevention, default context-menu suppression outside
 * text inputs, and `beforeunload` protection (active in BOTH Tauri desktop and Web).
 */
export function installReloadGuard(options: InstallReloadGuardOptions): () => void {
  const win = options.target ?? (typeof window !== 'undefined' ? window : undefined);
  if (!win) return () => {};

  let lastNotifyMs = 0;

  const handleKeyDownCapture = (e: KeyboardEvent) => {
    if (!isBrowserReloadOrNavShortcut(e)) return;

    // Prevent browser/WebView reload & history navigation while deliberately NOT stopping
    // propagation so Ink Studio commands (e.g. Ctrl+Shift+R Perspective Ruler) and Settings
    // shortcut recording still receive the event normally.
    e.preventDefault();

    if (
      !e.repeat &&
      options.onBlockedReloadShortcut &&
      (options.shouldNotifyBlockedKey ? options.shouldNotifyBlockedKey(e) : true)
    ) {
      const now = Date.now();
      if (now - lastNotifyMs >= 1500) {
        lastNotifyMs = now;
        options.onBlockedReloadShortcut();
      }
    }
  };

  const handleContextMenu = (e: MouseEvent) => {
    if (e.defaultPrevented) return;
    if (shouldBlockDefaultContextMenu(e.target)) {
      e.preventDefault();
    }
  };

  const handleBeforeUnload = (e: BeforeUnloadEvent) => {
    const docs = options.getDocuments();
    const drawingActive = options.isDrawingActive ? options.isDrawingActive() : false;
    if (shouldConfirmBeforeUnload(docs, options.isFinalizingClose(), drawingActive)) {
      e.preventDefault();
      e.returnValue = '';
    }
  };

  win.addEventListener('keydown', handleKeyDownCapture, true);
  win.addEventListener('contextmenu', handleContextMenu, false);
  win.addEventListener('beforeunload', handleBeforeUnload);

  return () => {
    win.removeEventListener('keydown', handleKeyDownCapture, true);
    win.removeEventListener('contextmenu', handleContextMenu, false);
    win.removeEventListener('beforeunload', handleBeforeUnload);
  };
}