# msger JavaScript API

The **msger** JavaScript API provides window control, data persistence, and file system access for applications running inside msger.

## Table of Contents

- [Installation](#installation)
- [Window Control](#window-control)
- [Data Persistence](#data-persistence)
- [File System Access](#file-system-access)
- [Browser Compatibility](#browser-compatibility)

## Installation

### TypeScript Definitions

```bash
npm install @bobfrankston/msgerdefs
```

```typescript
import type { MsgerAPI } from '@bobfrankston/msgerdefs';
import { isMsger, getMsgerAPI } from '@bobfrankston/msgerdefs';
```

## Window Control

Control the msger window from JavaScript.

### toggleFullscreen()

Toggle fullscreen mode on/off.

```javascript
msger.toggleFullscreen();
```

**Keyboard Shortcuts:**
- F11: Toggle fullscreen (native window level)
- Esc: Exit fullscreen or dismiss window

### setFullscreen(enabled)

Set fullscreen state explicitly.

```javascript
msger.setFullscreen(true);   // Enter fullscreen
msger.setFullscreen(false);  // Exit fullscreen
```

### minimize()

Minimize the window to taskbar.

```javascript
msger.minimize();
```

### maximize()

Toggle between maximized and restored window state.

```javascript
msger.maximize();  // Maximize or restore
```

### setSize(width, height)

Set window dimensions in pixels.

```javascript
msger.setSize(800, 600);
msger.setSize(1920, 1080);
```

### setPosition(x, y)

Move window to specific screen coordinates.

```javascript
msger.setPosition(100, 100);  // Top-left corner
msger.setPosition(0, 0);      // Screen origin
```

### setAlwaysOnTop(enabled)

Keep window above other windows.

```javascript
msger.setAlwaysOnTop(true);   // Stay on top
msger.setAlwaysOnTop(false);  // Normal behavior
```

### setTitle(title)

Change window title.

```javascript
msger.setTitle('My Application');
msger.setTitle(`Status: ${status}`);
```

### close(result?)

Close the window with optional result data.

```javascript
// Close with default dismissed result
msger.close();

// Close with custom result
msger.close({
    button: 'OK',
    value: 'user input',
    form: { name: 'Bob', email: 'bob@example.com' }
});
```

## Data Persistence

Save and load data using localStorage (with `msger_` prefix).

### saveData(key, value)

Store data persistently. Value is automatically JSON.stringify'd.

```javascript
// Save simple values
msger.saveData('username', 'bob');
msger.saveData('count', 42);

// Save objects
msger.saveData('userPrefs', {
    theme: 'dark',
    fontSize: 14,
    notifications: true
});

// Save arrays
msger.saveData('recentFiles', ['/path/to/file1.txt', '/path/to/file2.txt']);
```

**Returns:** `true` on success, `false` on failure

### loadData(key, defaultValue?)

Load data from storage with optional default.

```javascript
// Load with default
const username = msger.loadData('username', 'guest');
const prefs = msger.loadData('userPrefs', {theme: 'light'});

// Load without default (returns undefined if not found)
const data = msger.loadData('optionalData');
```

**Returns:** Stored value (parsed from JSON) or `defaultValue`

### removeData(key)

Delete a specific key from storage.

```javascript
msger.removeData('tempData');
msger.removeData('oldSettings');
```

**Returns:** `true` on success, `false` on failure

### clearData()

Clear all msger-prefixed data from localStorage.

```javascript
msger.clearData();  // Removes all msger_* keys
```

**Returns:** `true` on success, `false` on failure

**Note:** Only removes keys with `msger_` prefix, preserving other localStorage data.

## File System Access

**Status:** Coming soon

### File Dialogs (Safe - Always Available)

```javascript
// Select single file
const file = await msger.fs.selectFile({
    title: 'Open File',
    filters: [{name: 'Text', extensions: ['txt', 'md']}]
});
if (file) {
    console.log(file.name, file.path, file.content);
}

// Select multiple files
const files = await msger.fs.selectFiles({
    title: 'Open Files'
});

// Save file dialog
const path = await msger.fs.saveFileAs(
    'File content here',
    'default.txt',
    {filters: [{name: 'Text', extensions: ['txt']}]}
);

// Select folder
const folder = await msger.fs.selectFolder({
    title: 'Select Output Folder'
});
```

### Direct File Access (Requires `allowFs: true`)

```javascript
// Read file
const content = await msger.fs.read('/path/to/file.txt');

// Write file
await msger.fs.write('/path/to/file.txt', 'Hello World');

// List directory
const files = await msger.fs.list('/path/to/dir');
files.forEach(file => {
    console.log(file.name, file.isDir, file.size);
});

// Check existence
const exists = await msger.fs.exists('/path/to/file.txt');

// Delete file
await msger.fs.delete('/path/to/file.txt');
```

**Note:** Direct file access requires launching msger with `--allowFs` flag for security.

## Browser Compatibility

Use `getMsgerAPI()` for cross-platform code that works in both msger and browsers:

```typescript
import { getMsgerAPI, isMsger } from '@bobfrankston/msgerdefs';

const msger = getMsgerAPI();

// Data persistence works in both!
msger.saveData('userPrefs', {theme: 'dark'});
const prefs = msger.loadData('userPrefs', {theme: 'light'});

// Window control - only works in msger (no-op in browser)
if (isMsger()) {
    msger.setTitle('My App');
    msger.toggleFullscreen();
}

// File system - only available in msger
if (msger.fs) {
    const file = await msger.fs.selectFile();
}
```

### Browser Behavior

| Feature | msger | Browser |
|---------|-------|---------|
| Data persistence | localStorage with `msger_` prefix | localStorage with `msger_` prefix |
| Window control | Full support | No-op (except `setTitle` → `document.title`) |
| File system | Full support (with `allowFs` flag) | Not available (`fs` is `undefined`) |

### Detection

```javascript
import { isMsger } from '@bobfrankston/msgerdefs';

if (isMsger()) {
    console.log('Running in msger!');
    // Use msger-specific features
} else {
    console.log('Running in browser');
    // Use browser fallbacks
}
```

## Examples

### Persistent Settings

```javascript
// Save user preferences
function saveSettings(settings) {
    msger.saveData('settings', settings);
}

// Load with defaults
function loadSettings() {
    return msger.loadData('settings', {
        theme: 'light',
        fontSize: 14,
        autoSave: true
    });
}

// Apply settings on startup
const settings = loadSettings();
if (settings.theme === 'dark') {
    document.body.classList.add('dark-theme');
}
```

### Fullscreen Presentation Mode

```javascript
function enterPresentationMode() {
    msger.setFullscreen(true);
    msger.setAlwaysOnTop(true);
    msger.saveData('wasPresenting', true);
}

function exitPresentationMode() {
    msger.setFullscreen(false);
    msger.setAlwaysOnTop(false);
    msger.removeData('wasPresenting');
}

// Restore presentation mode on reload
if (msger.loadData('wasPresenting', false)) {
    enterPresentationMode();
}
```

### Window Size Presets

```javascript
const windowSizes = {
    small: [600, 400],
    medium: [800, 600],
    large: [1200, 800],
    hd: [1920, 1080]
};

function setWindowSize(preset) {
    const [width, height] = windowSizes[preset];
    msger.setSize(width, height);
    msger.saveData('windowSize', preset);
}

// Restore last size on startup
const lastSize = msger.loadData('windowSize', 'medium');
setWindowSize(lastSize);
```

## Command Line Integration

```bash
# Launch with fullscreen
msger -url "file:///app/index.html" --fullscreen

# Launch with specific size and position
msger -url "https://example.com" -size 1024,768 -pos 100,100

# Launch always on top
msger -url "file:///app/monitor.html" --ontop --detach

# Launch with file system access (future)
msger -url "file:///app/editor.html" --allowFs
```

## See Also

- [README.md](README.md) - Main msger documentation
- [msgerdefs](msgerdefs/) - TypeScript definitions package
- [FULLSCREEN-FEATURE.md](FULLSCREEN-FEATURE.md) - Fullscreen implementation details
