CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-tauri-apps--api

TypeScript/JavaScript API bindings for Tauri applications providing comprehensive desktop app functionality

Pending
Overview
Eval results
Files

window-management.mddocs/

Window & Webview Management

Comprehensive control over application windows and webviews, including creation, positioning, styling, and advanced features like effects and drag operations.

Capabilities

Window Control

Main window management class providing complete control over window properties and behavior.

/**
 * Main window management class
 */
class Window {
  constructor(window: WindowHandle, label: string, listeners: Map<string, EventCallback<any>>);
  
  /**
   * Get window by label
   * @param label - Window identifier
   * @returns Window instance or null if not found
   */
  static getByLabel(label: string): Promise<Window | null>;
  
  /**
   * Get current window instance
   * @returns Current window
   */
  static getCurrent(): Window;
  
  /**
   * Get all window instances
   * @returns Array of all windows
   */
  static getAll(): Promise<Window[]>;
  
  // Event handling
  listen<T>(event: EventName, handler: EventCallback<T>, options?: EventOptions): Promise<UnlistenFn>;
  once<T>(event: EventName, handler: EventCallback<T>, options?: EventOptions): Promise<UnlistenFn>;
  emit<T>(event: string, payload?: T): Promise<void>;
  emitTo<T>(target: EventTarget | string, event: string, payload?: T): Promise<void>;
  
  // Position and size
  outerPosition(): Promise<PhysicalPosition>;
  innerPosition(): Promise<PhysicalPosition>;
  outerSize(): Promise<PhysicalSize>;
  innerSize(): Promise<PhysicalSize>;
  setPosition(position: LogicalPosition | PhysicalPosition): Promise<void>;
  setSize(size: LogicalSize | PhysicalSize): Promise<void>;
  
  // Window state
  isFullscreen(): Promise<boolean>;
  isMinimized(): Promise<boolean>;
  isMaximized(): Promise<boolean>;
  isVisible(): Promise<boolean>;
  isFocused(): Promise<boolean>;
  isDecorated(): Promise<boolean>;
  isResizable(): Promise<boolean>;
  isMaximizable(): Promise<boolean>;
  isMinimizable(): Promise<boolean>;
  isClosable(): Promise<boolean>;
  
  // Window control
  show(): Promise<void>;
  hide(): Promise<void>;
  close(): Promise<void>;
  minimize(): Promise<void>;
  unminimize(): Promise<void>;
  maximize(): Promise<void>;
  unmaximize(): Promise<void>;
  toggleMaximize(): Promise<void>;
  setFocus(): Promise<void>;
  
  // Appearance
  setTitle(title: string): Promise<void>;
  setIcon(icon: Image | string): Promise<void>;
  setDecorated(decorated: boolean): Promise<void>;
  setAlwaysOnTop(alwaysOnTop: boolean): Promise<void>;
  setResizable(resizable: boolean): Promise<void>;
  setMaximizable(maximizable: boolean): Promise<void>;
  setMinimizable(minimizable: boolean): Promise<void>;
  setClosable(closable: boolean): Promise<void>;
  
  // Advanced features
  startDragging(): Promise<void>;
  requestUserAttention(requestType?: UserAttentionType): Promise<void>;
  setProgressBar(state: ProgressBarState): Promise<void>;
  setBadgeLabel(label?: string): Promise<void>;
  setOverlayIcon(icon: Image | string | null, description?: string): Promise<void>;
  setCursorIcon(icon: CursorIcon): Promise<void>;
  setTitleBarStyle(style: TitleBarStyle): Promise<void>;
  setFullscreen(fullscreen: boolean): Promise<void>;
  setEffects(effects: Effects): Promise<void>;
  clearEffects(): Promise<void>;
  
  // Event listeners
  onResized(handler: EventCallback<PhysicalSize>): Promise<UnlistenFn>;
  onMoved(handler: EventCallback<PhysicalPosition>): Promise<UnlistenFn>;
  onCloseRequested(handler: EventCallback<CloseRequestedEvent>): Promise<UnlistenFn>;
  onFocusChanged(handler: EventCallback<boolean>): Promise<UnlistenFn>;
  onScaleChanged(handler: EventCallback<ScaleFactorChanged>): Promise<UnlistenFn>;
  onThemeChanged(handler: EventCallback<Theme>): Promise<UnlistenFn>;
}

/**
 * Convenience functions for current window
 */
function getCurrentWindow(): Window;
function getAllWindows(): Promise<Window[]>;

Webview Control

Webview management for embedding web content with full control over navigation and behavior.

/**
 * Webview management class
 */
class Webview {
  constructor(webview: WebviewHandle, label: string, listeners: Map<string, EventCallback<any>>);
  
  /**
   * Get webview by label
   * @param label - Webview identifier
   * @returns Webview instance or null if not found
   */
  static getByLabel(label: string): Promise<Webview | null>;
  
  /**
   * Get current webview instance
   * @returns Current webview
   */
  static getCurrent(): Webview;
  
  /**
   * Get all webview instances
   * @returns Array of all webviews
   */
  static getAll(): Promise<Webview[]>;
  
  // Event handling
  listen<T>(event: EventName, handler: EventCallback<T>, options?: EventOptions): Promise<UnlistenFn>;
  once<T>(event: EventName, handler: EventCallback<T>, options?: EventOptions): Promise<UnlistenFn>;
  emit<T>(event: string, payload?: T): Promise<void>;
  emitTo<T>(target: EventTarget | string, event: string, payload?: T): Promise<void>;
  
  // Position and size
  position(): Promise<PhysicalPosition>;
  size(): Promise<PhysicalSize>;
  setPosition(position: LogicalPosition | PhysicalPosition): Promise<void>;
  setSize(size: LogicalSize | PhysicalSize): Promise<void>;
  
  // Webview control
  close(): Promise<void>;
  setFocus(): Promise<void>;
  reparent(window: Window): Promise<void>;
  print(): Promise<void>;
  
  // Navigation and content
  setUrl(url: string): Promise<void>;
  reload(): Promise<void>;
  goBack(): Promise<void>;
  goForward(): Promise<void>;
  canGoBack(): Promise<boolean>;
  canGoForward(): Promise<boolean>;
  
  // Zoom and appearance
  setZoom(factor: number): Promise<void>;
  getZoom(): Promise<number>;
  setBackgroundColor(color: Color): Promise<void>;
  
  // Developer tools
  openDevTools(): Promise<void>;
  closeDevTools(): Promise<void>;
  isDevToolsOpen(): Promise<boolean>;
}

/**
 * Convenience functions for current webview
 */
function getCurrentWebview(): Webview;
function getAllWebviews(): Promise<Webview[]>;

Combined WebviewWindow

Unified class combining window and webview functionality for most common use cases.

/**
 * Combined window and webview functionality
 */
class WebviewWindow {
  /**
   * Create a new webview window
   * @param label - Unique identifier for the window
   * @param options - Window and webview configuration
   */
  constructor(label: string, options?: WebviewWindowOptions);
  
  /**
   * Set the background color of the webview
   * @param color - RGBA color specification
   */
  setBackgroundColor(color: Color): Promise<void>;
  
  // Inherits all methods from both Window and Webview classes
}

/**
 * Convenience functions for current webview window
 */
function getCurrentWebviewWindow(): WebviewWindow;
function getAllWebviewWindows(): Promise<WebviewWindow[]>;

Position and Size Types

Device-independent positioning and sizing utilities.

/**
 * Logical size in device-independent pixels
 */
class LogicalSize {
  constructor(width: number, height: number);
  toPhysical(scaleFactor: number): PhysicalSize;
}

/**
 * Physical size in actual screen pixels
 */
class PhysicalSize {
  constructor(width: number, height: number);
  toLogical(scaleFactor: number): LogicalSize;
}

/**
 * Union wrapper for logical or physical size
 */
class Size {
  static logical(width: number, height: number): Size;
  static physical(width: number, height: number): Size;
}

/**
 * Logical position in device-independent pixels
 */
class LogicalPosition {
  constructor(x: number, y: number);
  toPhysical(scaleFactor: number): PhysicalPosition;
}

/**
 * Physical position in actual screen pixels
 */
class PhysicalPosition {
  constructor(x: number, y: number);
  toLogical(scaleFactor: number): LogicalPosition;
}

/**
 * Union wrapper for logical or physical position
 */
class Position {
  static logical(x: number, y: number): Position;
  static physical(x: number, y: number): Position;
}

Window Configuration

Comprehensive configuration options for window creation and management.

interface WebviewWindowOptions {
  // Window properties
  width?: number;
  height?: number;
  minWidth?: number;
  minHeight?: number;
  maxWidth?: number;
  maxHeight?: number;
  x?: number;
  y?: number;
  center?: boolean;
  
  // Window behavior
  resizable?: boolean;
  maximizable?: boolean;
  minimizable?: boolean;
  closable?: boolean;
  title?: string;
  titleBarStyle?: TitleBarStyle;
  fullscreen?: boolean;
  focus?: boolean;
  alwaysOnTop?: boolean;
  alwaysOnBottom?: boolean;
  visible?: boolean;
  transparent?: boolean;
  decorations?: boolean;
  shadow?: boolean;
  
  // Webview properties
  url?: string;
  html?: string;
  userAgent?: string;
  acceptFirstMouse?: boolean;
  backgroundColor?: Color;
  
  // Advanced
  theme?: Theme;
  windowClassId?: string;
  incognito?: boolean;
  proxyUrl?: string;
}

interface WindowOptions {
  // Similar to WebviewWindowOptions but without webview-specific properties
}

interface WebviewOptions {
  // Webview-specific configuration
  x?: number;
  y?: number;
  width?: number;
  height?: number;
  url?: string;
  html?: string;
  initialization?: string;
  userAgent?: string;
  acceptFirstMouse?: boolean;
  autoplay?: boolean;
  backgroundColor?: Color;
  transparent?: boolean;
  zoom?: number;
}

type TitleBarStyle = 'visible' | 'transparent' | 'overlay';
type Theme = 'light' | 'dark' | 'auto';
type UserAttentionType = 'critical' | 'informational';

interface Color {
  r: number;
  g: number;
  b: number;
  a: number;
}

interface ProgressBarState {
  status?: ProgressBarStatus;
  progress?: number;
}

enum ProgressBarStatus {
  None = 'none',
  Normal = 'normal',
  Indeterminate = 'indeterminate',
  Paused = 'paused',
  Error = 'error'
}

type CursorIcon =
  | 'default'
  | 'crosshair'
  | 'hand'
  | 'arrow'
  | 'move'
  | 'text'
  | 'wait'
  | 'help'
  | 'progress'
  | 'notAllowed'
  | 'contextMenu'
  | 'cell'
  | 'verticalText'
  | 'alias'
  | 'copy'
  | 'noDrop'
  | 'grab'
  | 'grabbing'
  | 'allScroll'
  | 'zoomIn'
  | 'zoomOut'
  | 'eResize'
  | 'nResize'
  | 'neResize'
  | 'nwResize'
  | 'sResize'
  | 'seResize'
  | 'swResize'
  | 'wResize'
  | 'ewResize'
  | 'nsResize'
  | 'neswResize'
  | 'nwseResize'
  | 'colResize'
  | 'rowResize';

interface ScaleFactorChanged {
  scaleFactor: number;
  size: PhysicalSize;
}

class CloseRequestedEvent {
  event: EventName;
  id: number;
  preventDefault(): void;
  isPreventDefault(): boolean;
}

Monitor Information

System monitor detection and information.

/**
 * Monitor information interface
 */
interface Monitor {
  name: string | null;
  position: PhysicalPosition;
  size: PhysicalSize;
  scaleFactor: number;
}

/**
 * Get the monitor containing the current window
 * @returns Monitor information or null if not found
 */
function currentMonitor(): Promise<Monitor | null>;

/**
 * Get the primary monitor
 * @returns Primary monitor information or null if not found
 */
function primaryMonitor(): Promise<Monitor | null>;

/**
 * Get monitor at specific screen coordinates
 * @param x - Screen X coordinate
 * @param y - Screen Y coordinate
 * @returns Monitor at the given point or null if not found
 */
function monitorFromPoint(x: number, y: number): Promise<Monitor | null>;

/**
 * Get all available monitors
 * @returns Array of all available monitors
 */
function availableMonitors(): Promise<Monitor[]>;

/**
 * Get current cursor position
 * @returns Cursor position in physical coordinates
 */
function cursorPosition(): Promise<PhysicalPosition>;

Visual Effects

Advanced window visual effects and styling (primarily macOS).

/**
 * Window visual effects configuration
 */
interface Effects {
  effect: Effect;
  state?: EffectState;
  radius?: number;
}

enum Effect {
  AppearanceBased = 'appearanceBased',
  Light = 'light',
  Dark = 'dark',
  MediumLight = 'mediumLight',
  UltraDark = 'ultraDark',
  Titlebar = 'titlebar',
  Selection = 'selection',
  Menu = 'menu',
  Popover = 'popover',
  Sidebar = 'sidebar',
  HeaderView = 'headerView',
  Sheet = 'sheet',
  WindowBackground = 'windowBackground',
  HudWindow = 'hudWindow',
  FullScreenUI = 'fullScreenUI',
  Tooltip = 'tooltip',
  ContentBackground = 'contentBackground',
  UnderWindowBackground = 'underWindowBackground',
  UnderPageBackground = 'underPageBackground'
}

enum EffectState {
  FollowsWindowActiveState = 'followsWindowActiveState',
  Active = 'active',
  Inactive = 'inactive'
}

Close Event Handling

Handle window close requests with prevention capability.

/**
 * Window close request event
 */
class CloseRequestedEvent {
  /**
   * Prevent the window from closing
   */
  preventDefault(): void;
  
  /**
   * Check if the default close behavior was prevented
   * @returns true if preventDefault() was called
   */
  isDefaultPrevented(): boolean;
}

Usage Examples

Basic Window Management

import { getCurrentWindow } from '@tauri-apps/api/window';

const window = getCurrentWindow();

// Set window properties
await window.setTitle('My Application');
await window.setSize({ width: 800, height: 600 });
await window.center();

// Window state management
if (await window.isMinimized()) {
  await window.unminimize();
}

await window.setAlwaysOnTop(true);
await window.setResizable(false);

Creating New Windows

import { WebviewWindow } from '@tauri-apps/api/webviewWindow';

const newWindow = new WebviewWindow('settings', {
  title: 'Settings',
  width: 600,
  height: 400,
  center: true,
  resizable: false,
  url: '/settings.html'
});

// Wait for window to be ready
newWindow.once('tauri://created', () => {
  console.log('Settings window created');
});

newWindow.once('tauri://error', (error) => {
  console.error('Failed to create window:', error);
});

Handling Window Events

import { getCurrentWindow } from '@tauri-apps/api/window';

const window = getCurrentWindow();

// Handle window close request
await window.listen('tauri://close-requested', (event) => {
  // event is CloseRequestedEvent
  if (hasUnsavedChanges()) {
    event.preventDefault();
    showSaveDialog();
  }
});

// Handle resize events
await window.listen('tauri://resize', (event) => {
  console.log('Window resized:', event.payload);
});

// Handle focus events
await window.listen('tauri://focus', () => {
  console.log('Window focused');
});

Multi-Monitor Support

import { availableMonitors, currentMonitor } from '@tauri-apps/api/window';

// Get all monitors
const monitors = await availableMonitors();
console.log(`Found ${monitors.length} monitors`);

// Get current monitor
const current = await currentMonitor();
if (current) {
  console.log(`Current monitor: ${current.name}, Scale: ${current.scaleFactor}`);
}

// Position window on specific monitor
const targetMonitor = monitors[1]; // Second monitor
if (targetMonitor) {
  await window.setPosition({
    x: targetMonitor.position.x + 100,
    y: targetMonitor.position.y + 100
  });
}

Progressive Enhancement for Web vs Desktop

import { isTauri } from '@tauri-apps/api/core';
import { getCurrentWindow } from '@tauri-apps/api/window';

if (isTauri()) {
  // Desktop-specific functionality
  const window = getCurrentWindow();
  
  // Add desktop window controls
  document.getElementById('minimize-btn')?.addEventListener('click', () => {
    window.minimize();
  });
  
  document.getElementById('maximize-btn')?.addEventListener('click', () => {
    window.toggleMaximize();
  });
  
  document.getElementById('close-btn')?.addEventListener('click', () => {
    window.close();
  });
} else {
  // Web fallback - hide desktop controls
  document.querySelector('.window-controls')?.remove();
}

Install with Tessl CLI

npx tessl i tessl/npm-tauri-apps--api

docs

app-lifecycle.md

core-ipc.md

events.md

index.md

menu-system.md

system-integration.md

testing.md

utilities.md

window-management.md

tile.json