# Widget Embedding

> Embed Nyx astronomical components in your website or application

Nyx provides embeddable widgets that you can easily integrate into your own
websites and applications. This guide covers all available widgets and how to
use them.

## Table of Contents

1. [Overview](#overview)
2. [Quick Start](#quick-start)
3. [Available Widgets](#available-widgets)
4. [Widget Configuration](#widget-configuration)
5. [JavaScript API](#javascript-api)
6. [Styling and Theming](#styling-and-theming)
7. [Advanced Integration](#advanced-integration)
8. [Examples](#examples)

---

## Overview

Nyx widgets are self-contained components that display astronomical data and
visualizations. They can be embedded using:

- **iframe**: Simple HTML embed, no coding required
- **Web Components**: Custom HTML elements with JavaScript
- **React/Vue/Angular**: Framework-specific components
- **JavaScript API**: Full programmatic control

### Supported Widgets

| Widget         | Description                       |
| -------------- | --------------------------------- |
| Star Map       | Interactive sky chart             |
| Planet Tracker | Current planet positions          |
| Moon Phase     | Current moon phase display        |
| ISS Tracker    | Real-time ISS position            |
| Event Calendar | Upcoming astronomical events      |
| Tonight's Sky  | What's visible tonight            |
| Object Info    | Detailed object information panel |

---

## Quick Start

### Embed with iframe

The simplest way to embed a widget:

```html
<!-- Star Map Widget -->
<iframe
  src="https://widgets.nyx.oshun.io/star-map?lat=40.7128&lon=-74.0060"
  width="800"
  height="600"
  frameborder="0"
  allowfullscreen
>
</iframe>

<!-- Moon Phase Widget -->
<iframe
  src="https://widgets.nyx.oshun.io/moon-phase"
  width="200"
  height="200"
  frameborder="0"
>
</iframe>
```

### Embed with JavaScript

For more control, use the JavaScript SDK:

```html
<div id="star-map"></div>

<script src="https://cdn.nyx.oshun.io/widgets/v1/nyx-widgets.min.js"></script>
<script>
  NyxWidgets.starMap('#star-map', {
    apiKey: 'YOUR_API_KEY',
    latitude: 40.7128,
    longitude: -74.006,
    width: 800,
    height: 600,
  });
</script>
```

---

## Available Widgets

### Star Map Widget

Interactive sky chart showing stars, constellations, and celestial objects.

**iframe URL:**

```
https://widgets.nyx.oshun.io/star-map
```

**Parameters:**

| Parameter        | Type    | Default | Description              |
| ---------------- | ------- | ------- | ------------------------ |
| `lat`            | float   | 0       | Observer latitude        |
| `lon`            | float   | 0       | Observer longitude       |
| `fov`            | float   | 90      | Field of view (degrees)  |
| `ra`             | float   | -       | Center right ascension   |
| `dec`            | float   | -       | Center declination       |
| `time`           | string  | now     | ISO 8601 date/time       |
| `constellations` | boolean | true    | Show constellation lines |
| `grid`           | boolean | false   | Show coordinate grid     |
| `labels`         | boolean | true    | Show object labels       |
| `magLimit`       | float   | 6       | Limiting magnitude       |
| `theme`          | string  | dark    | Color theme (dark/light) |

**JavaScript:**

```javascript
NyxWidgets.starMap('#container', {
  latitude: 40.7128,
  longitude: -74.006,
  fieldOfView: 90,
  showConstellations: true,
  showGrid: false,
  showLabels: true,
  limitingMagnitude: 6.5,
  theme: 'dark',
  interactive: true,
  onObjectClick: (object) => {
    console.log('Clicked:', object.name);
  },
});
```

---

### Planet Tracker Widget

Displays current positions of solar system planets.

**iframe URL:**

```
https://widgets.nyx.oshun.io/planet-tracker
```

**Parameters:**

| Parameter  | Type    | Default | Description                      |
| ---------- | ------- | ------- | -------------------------------- |
| `lat`      | float   | 0       | Observer latitude                |
| `lon`      | float   | 0       | Observer longitude               |
| `planets`  | string  | all     | Comma-separated planet list      |
| `style`    | string  | table   | Display style (table/cards/list) |
| `showRise` | boolean | true    | Show rise/set times              |
| `theme`    | string  | dark    | Color theme                      |

**Example:**

```html
<iframe
  src="https://widgets.nyx.oshun.io/planet-tracker?lat=40.7128&lon=-74.0060&planets=mars,jupiter,saturn&style=cards"
  width="400"
  height="300"
>
</iframe>
```

**JavaScript:**

```javascript
NyxWidgets.planetTracker('#container', {
  latitude: 40.7128,
  longitude: -74.006,
  planets: ['mars', 'jupiter', 'saturn'],
  displayStyle: 'cards',
  showRiseSetTimes: true,
  autoRefresh: 60000, // Update every minute
});
```

---

### Moon Phase Widget

Displays current moon phase with illumination percentage.

**iframe URL:**

```
https://widgets.nyx.oshun.io/moon-phase
```

**Parameters:**

| Parameter  | Type    | Default | Description                |
| ---------- | ------- | ------- | -------------------------- |
| `date`     | string  | now     | Date to display (ISO 8601) |
| `size`     | string  | medium  | Size (small/medium/large)  |
| `showName` | boolean | true    | Show phase name            |
| `showAge`  | boolean | true    | Show moon age (days)       |
| `showNext` | boolean | true    | Show next phase date       |
| `theme`    | string  | dark    | Color theme                |

**Sizes:**

- `small`: 100×100 px
- `medium`: 200×200 px
- `large`: 300×300 px

**Example:**

```html
<iframe
  src="https://widgets.nyx.oshun.io/moon-phase?size=medium&showNext=true"
  width="200"
  height="250"
>
</iframe>
```

**JavaScript:**

```javascript
NyxWidgets.moonPhase('#container', {
  size: 'medium',
  showPhaseName: true,
  showMoonAge: true,
  showNextPhase: true,
  animate: true, // Smooth illumination animation
});
```

---

### ISS Tracker Widget

Real-time International Space Station tracking.

**iframe URL:**

```
https://widgets.nyx.oshun.io/iss-tracker
```

**Parameters:**

| Parameter    | Type    | Default | Description              |
| ------------ | ------- | ------- | ------------------------ |
| `lat`        | float   | 0       | Observer latitude        |
| `lon`        | float   | 0       | Observer longitude       |
| `view`       | string  | map     | View type (map/sky/data) |
| `showPath`   | boolean | true    | Show orbital path        |
| `showPasses` | boolean | true    | Show upcoming passes     |
| `passCount`  | int     | 3       | Number of passes to show |

**Example:**

```html
<iframe
  src="https://widgets.nyx.oshun.io/iss-tracker?lat=40.7128&lon=-74.0060&view=map&showPasses=true"
  width="600"
  height="400"
>
</iframe>
```

**JavaScript:**

```javascript
NyxWidgets.issTracker('#container', {
  latitude: 40.7128,
  longitude: -74.006,
  view: 'map',
  showOrbitalPath: true,
  showUpcomingPasses: true,
  passCount: 5,
  onPassAlert: (pass) => {
    console.log('ISS pass starting!', pass);
  },
});
```

---

### Event Calendar Widget

Displays upcoming astronomical events.

**iframe URL:**

```
https://widgets.nyx.oshun.io/event-calendar
```

**Parameters:**

| Parameter    | Type   | Default | Description                   |
| ------------ | ------ | ------- | ----------------------------- |
| `days`       | int    | 30      | Days to show (1-365)          |
| `types`      | string | all     | Event types (comma-separated) |
| `lat`        | float  | -       | Filter by visibility          |
| `lon`        | float  | -       | Filter by visibility          |
| `view`       | string | list    | View type (list/calendar)     |
| `importance` | string | all     | Filter by importance          |

**Example:**

```html
<iframe
  src="https://widgets.nyx.oshun.io/event-calendar?days=30&types=eclipse,meteor_shower&view=list"
  width="400"
  height="500"
>
</iframe>
```

**JavaScript:**

```javascript
NyxWidgets.eventCalendar('#container', {
  days: 30,
  eventTypes: ['eclipse', 'meteor_shower', 'conjunction'],
  view: 'list',
  showImportance: true,
  onEventClick: (event) => {
    console.log('Event:', event.name);
  },
});
```

---

### Tonight's Sky Widget

Shows what's visible from your location tonight.

**iframe URL:**

```
https://widgets.nyx.oshun.io/tonights-sky
```

**Parameters:**

| Parameter    | Type   | Default  | Description        |
| ------------ | ------ | -------- | ------------------ |
| `lat`        | float  | required | Observer latitude  |
| `lon`        | float  | required | Observer longitude |
| `categories` | string | all      | Object categories  |
| `magLimit`   | float  | 6        | Limiting magnitude |
| `style`      | string | compact  | Display style      |

**Example:**

```html
<iframe
  src="https://widgets.nyx.oshun.io/tonights-sky?lat=40.7128&lon=-74.0060&categories=planets,messier"
  width="350"
  height="600"
>
</iframe>
```

---

### Object Info Widget

Detailed information panel for a specific object.

**iframe URL:**

```
https://widgets.nyx.oshun.io/object-info
```

**Parameters:**

| Parameter | Type    | Required | Description             |
| --------- | ------- | -------- | ----------------------- |
| `object`  | string  | Yes      | Object ID (e.g., "M42") |
| `lat`     | float   | No       | Observer latitude       |
| `lon`     | float   | No       | Observer longitude      |
| `compact` | boolean | No       | Compact view            |

**Example:**

```html
<iframe
  src="https://widgets.nyx.oshun.io/object-info?object=M42&lat=40.7128&lon=-74.0060"
  width="300"
  height="400"
>
</iframe>
```

---

## Widget Configuration

### API Key

For full functionality and higher rate limits, include your API key:

**iframe:**

```html
<iframe
  src="https://widgets.nyx.oshun.io/star-map?apiKey=YOUR_KEY&..."
></iframe>
```

**JavaScript:**

```javascript
NyxWidgets.configure({
  apiKey: 'YOUR_API_KEY',
});
```

### Global Configuration

Set defaults for all widgets:

```javascript
NyxWidgets.configure({
  apiKey: 'YOUR_API_KEY',
  theme: 'dark',
  locale: 'en-US',
  units: 'metric',
  defaultLocation: {
    latitude: 40.7128,
    longitude: -74.006,
  },
  analytics: false,
});
```

---

## JavaScript API

### Loading the SDK

```html
<!-- Production -->
<script src="https://cdn.nyx.oshun.io/widgets/v1/nyx-widgets.min.js"></script>

<!-- With integrity check -->
<script
  src="https://cdn.nyx.oshun.io/widgets/v1/nyx-widgets.min.js"
  integrity="sha384-..."
  crossorigin="anonymous"
></script>
```

### Creating Widgets

```javascript
// Using CSS selector
const starMap = NyxWidgets.starMap('#container', options);

// Using DOM element
const element = document.getElementById('container');
const starMap = NyxWidgets.starMap(element, options);
```

### Widget Methods

All widgets support these methods:

```javascript
const widget = NyxWidgets.starMap('#container', options);

// Update options
widget.setOptions({
  latitude: 51.5074,
  longitude: -0.1278,
});

// Get current state
const state = widget.getState();

// Refresh data
widget.refresh();

// Destroy widget
widget.destroy();

// Event handling
widget.on('ready', () => console.log('Widget loaded'));
widget.on('error', (err) => console.error(err));
widget.off('ready', handler);
```

### Events

| Event        | Description                          |
| ------------ | ------------------------------------ |
| `ready`      | Widget fully loaded                  |
| `error`      | Error occurred                       |
| `click`      | Object clicked (returns object data) |
| `hover`      | Mouse over object                    |
| `viewChange` | View position changed                |
| `timeChange` | Time setting changed                 |
| `dataUpdate` | New data received                    |

```javascript
widget.on('click', (data) => {
  console.log('Clicked object:', data.name);
  console.log('Coordinates:', data.ra, data.dec);
});
```

---

## Styling and Theming

### Built-in Themes

| Theme      | Description                           |
| ---------- | ------------------------------------- |
| `dark`     | Dark background, light text (default) |
| `light`    | Light background, dark text           |
| `space`    | Deep space black                      |
| `sepia`    | Vintage sepia tones                   |
| `contrast` | High contrast accessibility theme     |

### Custom CSS

Override styles with CSS variables:

```css
.nyx-widget {
  --nyx-bg-primary: #1a1a2e;
  --nyx-bg-secondary: #16213e;
  --nyx-text-primary: #ffffff;
  --nyx-text-secondary: #a0a0a0;
  --nyx-accent: #0f4c75;
  --nyx-highlight: #3282b8;
  --nyx-star-color: #ffffff;
  --nyx-constellation-color: #4a90a4;
  --nyx-grid-color: #2a2a4a;
  --nyx-border-radius: 8px;
  --nyx-font-family: 'Inter', sans-serif;
}
```

### Responsive Sizing

```css
.nyx-widget-container {
  width: 100%;
  max-width: 800px;
  aspect-ratio: 16 / 9;
}

@media (max-width: 600px) {
  .nyx-widget-container {
    aspect-ratio: 4 / 3;
  }
}
```

---

## Advanced Integration

### React Component

```jsx
import { useEffect, useRef } from 'react';
import NyxWidgets from '@nyx/widgets';

function StarMapWidget({ latitude, longitude }) {
  const containerRef = useRef(null);
  const widgetRef = useRef(null);

  useEffect(() => {
    widgetRef.current = NyxWidgets.starMap(containerRef.current, {
      latitude,
      longitude,
      interactive: true,
    });

    return () => {
      widgetRef.current?.destroy();
    };
  }, []);

  useEffect(() => {
    widgetRef.current?.setOptions({ latitude, longitude });
  }, [latitude, longitude]);

  return <div ref={containerRef} style={{ width: '100%', height: '400px' }} />;
}

export default StarMapWidget;
```

### Vue Component

```vue
<template>
  <div ref="container" class="star-map-widget"></div>
</template>

<script>
import NyxWidgets from '@nyx/widgets';

export default {
  props: {
    latitude: { type: Number, required: true },
    longitude: { type: Number, required: true },
  },
  mounted() {
    this.widget = NyxWidgets.starMap(this.$refs.container, {
      latitude: this.latitude,
      longitude: this.longitude,
    });
  },
  watch: {
    latitude(val) {
      this.widget.setOptions({ latitude: val });
    },
    longitude(val) {
      this.widget.setOptions({ longitude: val });
    },
  },
  beforeDestroy() {
    this.widget?.destroy();
  },
};
</script>
```

### Web Components

Use native web components:

```html
<script src="https://cdn.nyx.oshun.io/widgets/v1/nyx-elements.min.js"></script>

<nyx-star-map latitude="40.7128" longitude="-74.0060" theme="dark" interactive>
</nyx-star-map>

<nyx-moon-phase size="medium"></nyx-moon-phase>

<nyx-iss-tracker latitude="40.7128" longitude="-74.0060" show-passes>
</nyx-iss-tracker>
```

---

## Examples

### Astronomy Blog Sidebar

```html
<div class="sidebar">
  <h3>Tonight's Moon</h3>
  <iframe
    src="https://widgets.nyx.oshun.io/moon-phase?size=small"
    width="120"
    height="150"
    frameborder="0"
  >
  </iframe>

  <h3>Upcoming Events</h3>
  <iframe
    src="https://widgets.nyx.oshun.io/event-calendar?days=7&view=compact"
    width="280"
    height="300"
    frameborder="0"
  >
  </iframe>
</div>
```

### Interactive Star Chart Page

```html
<!DOCTYPE html>
<html>
  <head>
    <title>Interactive Star Map</title>
    <style>
      #star-map {
        width: 100%;
        height: 80vh;
      }
      .controls {
        padding: 10px;
        background: #1a1a2e;
      }
    </style>
  </head>
  <body>
    <div class="controls">
      <label>
        Latitude: <input type="number" id="lat" value="40.7128" step="0.1" />
      </label>
      <label>
        Longitude: <input type="number" id="lon" value="-74.0060" step="0.1" />
      </label>
      <button onclick="updateLocation()">Update</button>
    </div>

    <div id="star-map"></div>

    <script src="https://cdn.nyx.oshun.io/widgets/v1/nyx-widgets.min.js"></script>
    <script>
      NyxWidgets.configure({ apiKey: 'YOUR_API_KEY' });

      const starMap = NyxWidgets.starMap('#star-map', {
        latitude: 40.7128,
        longitude: -74.006,
        interactive: true,
        showConstellations: true,
        onObjectClick: (obj) => {
          alert(`${obj.name}\nMagnitude: ${obj.magnitude}`);
        },
      });

      function updateLocation() {
        const lat = parseFloat(document.getElementById('lat').value);
        const lon = parseFloat(document.getElementById('lon').value);
        starMap.setOptions({ latitude: lat, longitude: lon });
      }
    </script>
  </body>
</html>
```

### Observatory Dashboard

```html
<div class="dashboard">
  <div class="panel">
    <nyx-star-map latitude="40.7128" longitude="-74.0060"></nyx-star-map>
  </div>

  <div class="panel">
    <nyx-planet-tracker
      latitude="40.7128"
      longitude="-74.0060"
    ></nyx-planet-tracker>
  </div>

  <div class="panel">
    <nyx-moon-phase size="large"></nyx-moon-phase>
  </div>

  <div class="panel">
    <nyx-iss-tracker latitude="40.7128" longitude="-74.0060"></nyx-iss-tracker>
  </div>

  <div class="panel">
    <nyx-event-calendar days="30"></nyx-event-calendar>
  </div>
</div>
```

---

## Troubleshooting

### Widget Not Loading

1. Check browser console for errors
2. Verify API key is correct
3. Ensure CDN script is loading
4. Check for Content Security Policy issues

### Iframe Issues

```html
<!-- Allow fullscreen and other features -->
<iframe
  src="..."
  allow="fullscreen; geolocation"
  sandbox="allow-scripts allow-same-origin"
>
</iframe>
```

### CORS Errors

Widgets hosted on `widgets.nyx.oshun.io` have CORS enabled for all origins. If
using a custom domain, configure CORS headers appropriately.

---

## Next: [Authentication](./authentication.md)
