# Creators

### [Custom Element Types](/nexo-maker-docs/main.js/api/custom-element-types.md)

Custom Creators are **Modular components** that provide UI for creating new elements. They appear as buttons in the project browser and show forms/modals for collecting initial data.

**Key Differences from Editors:**

* Use `module.exports =` (NOT `export default function`)
* Arrow function syntax
* Inline styles only (no CSS files)
* Use `onNext(data)` to enable/disable creation

***

### Registration (main.js)

#### `api.nexomaker.registerModularCreator(creatorId, componentPath, metadata)`

```javascript
module.exports.init = async () => {
  api.nexomaker.registerModularCreator(
    'create_armor',                              // Must start with 'create_'
    __dirname + '/creators/ArmorCreator.jsx',    // String concatenation, NOT path.join
    {
      label: 'Armor',
      icon: 'Shield',
      category: 'item',
      compatibility: ['nexo', 'itemsadder', 'oraxen', 'craftengine']
    }
  );
};
```

**Parameters**

| Parameter                | Type       | Required | Description                                            |
| ------------------------ | ---------- | -------- | ------------------------------------------------------ |
| `creatorId`              | `string`   | Yes      | Unique ID (must start with `'create_'`)                |
| `componentPath`          | `string`   | Yes      | Path to .jsx file (use `__dirname + '/path/file.jsx'`) |
| `metadata.label`         | `string`   | No       | Button text                                            |
| `metadata.icon`          | `string`   | No       | Icon name (e.g., 'Shield')                             |
| `metadata.category`      | `string`   | No       | Category grouping                                      |
| `metadata.compatibility` | `string[]` | No       | Compatible plugin IDs                                  |

***

### Component Structure (.jsx file)

#### Basic Template

```javascript
/**
 * NO IMPORTS!
 * Use module.exports (NOT export default)
 */

module.exports = ({ useState, useEffect, onNext, projectId }) => {
  const [name, setName] = useState('');
  
  // Call onNext(data) to enable "Next" button, onNext(null) to disable
  useEffect(() => {
    if (name.trim()) {
      onNext({
        id: name.toLowerCase().replace(/\s+/g, '_'),
        type: 'armor',
        display: name
      });
    } else {
      onNext(null);  // Disable Next button
    }
  }, [name]);
  
  return (
    <div style={{ padding: '30px' }}>
      <h2>Create Armor</h2>
      <input 
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter name..."
        style={{
          padding: '10px',
          border: '1px solid var(--col-outliner-default)',
          borderRadius: 'var(--radius-sm)',
          backgroundColor: 'var(--col-input-background)',
          color: 'var(--col-text-primary)'
        }}
      />
    </div>
  );
};
```

#### Props Available

| Prop        | Type     | Description                                        |
| ----------- | -------- | -------------------------------------------------- |
| `useState`  | Hook     | State hook (passed as prop, NOT imported)          |
| `useEffect` | Hook     | Effect hook (passed as prop, NOT imported)         |
| `useMemo`   | Hook     | Memo hook (passed as prop)                         |
| `useRef`    | Hook     | Ref hook (passed as prop)                          |
| `onNext`    | Function | `(data \| null) => void` - Enable/disable creation |
| `projectId` | string   | Current project ID                                 |

***

### Full Example (from apitest)

**File:** `creators/ArmorCreator.jsx`

```javascript
module.exports = ({ useState, useEffect, onNext, projectId }) => {
  const [armorName, setArmorName] = useState('');
  const [armorType, setArmorType] = useState('chestplate');

  useEffect(() => {
    if (armorName.trim()) {
      const armorData = {
        id: armorName.toLowerCase().replace(/\s+/g, '_'),
        type: 'armor',
        subtype: 'armor',
        display: armorName,
        armor_type: armorType,
        material: 'DIAMOND',
        defense: 6,
        toughness: 2
      };
      onNext(armorData);
    } else {
      onNext(null);
    }
  }, [armorName, armorType, onNext]);

  return (
    <div style={{ padding: '30px', display: 'flex', flexDirection: 'column', gap: '20px' }}>
      <div style={{ fontSize: '24px', fontWeight: '600', color: 'var(--col-text-primary)' }}>
        🛡️ Create Armor
      </div>
      
      <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
        <label style={{ fontSize: '14px', fontWeight: '500', color: 'var(--col-text-secondary)' }}>
          Armor Name:
        </label>
        <input
          type="text"
          value={armorName}
          onChange={(e) => setArmorName(e.target.value)}
          placeholder="Enter armor name..."
          autoFocus
          style={{
            padding: '10px 12px',
            fontSize: '15px',
            border: '1px solid var(--col-outliner-default)',
            borderRadius: 'var(--radius-sm)',
            backgroundColor: 'var(--col-input-background)',
            color: 'var(--col-text-primary)'
          }}
        />
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
        <label style={{ fontSize: '14px', fontWeight: '500', color: 'var(--col-text-secondary)' }}>
          Armor Type:
        </label>
        <select
          value={armorType}
          onChange={(e) => setArmorType(e.target.value)}
          style={{
            padding: '10px 12px',
            fontSize: '15px',
            border: '1px solid var(--col-outliner-default)',
            borderRadius: 'var(--radius-sm)',
            backgroundColor: 'var(--col-input-background)',
            color: 'var(--col-text-primary)',
            cursor: 'pointer'
          }}
        >
          <option value="helmet">Helmet</option>
          <option value="chestplate">Chestplate</option>
          <option value="leggings">Leggings</option>
          <option value="boots">Boots</option>
        </select>
      </div>
    </div>
  );
};
```

***

### How It Works

1. User clicks creator button → Modal opens with your component
2. User fills form → Component calls `onNext(data)` in useEffect
3. User clicks "Next" → NexoMaker creates `Data/{id}/item.yml` with the data
4. Item opens in appropriate editor

#### Data Object Requirements

```javascript
onNext({
  id: 'item_id',          // Required: Used for file/folder name
  type: 'armor',          // Required: Element type (must be registered)
  display: 'My Item',     // Optional: Display name
  // ... any other YAML fields
});
```

***

### Common Patterns

#### With Validation

```javascript
module.exports = ({ useState, useEffect, onNext }) => {
  const [name, setName] = useState('');
  const [error, setError] = useState('');
  
  useEffect(() => {
    if (!name.trim()) {
      setError('Name required');
      onNext(null);
    } else if (name.length < 3) {
      setError('Name too short');
      onNext(null);
    } else {
      setError('');
      onNext({ id: name.toLowerCase().replace(/\s+/g, '_'), type: 'custom', display: name });
    }
  }, [name]);
  
  return (
    <div style={{ padding: '30px' }}>
      <input value={name} onChange={(e) => setName(e.target.value)} />
      {error && <p style={{ color: 'red' }}>{error}</p>}
    </div>
  );
};
```

#### Multi-Step Wizard

```javascript
module.exports = ({ useState, useEffect, onNext }) => {
  const [step, setStep] = useState(1);
  const [data, setData] = useState({ name: '', category: '' });
  
  useEffect(() => {
    if (step === 2 && data.name && data.category) {
      onNext({ id: data.name.toLowerCase().replace(/\s+/g, '_'), type: 'custom', ...data });
    } else {
      onNext(null);
    }
  }, [step, data]);
  
  return (
    <div style={{ padding: '30px' }}>
      {step === 1 && (
        <>
          <input value={data.name} onChange={(e) => setData({ ...data, name: e.target.value })} />
          <button onClick={() => setStep(2)}>Next →</button>
        </>
      )}
      {step === 2 && (
        <>
          <select value={data.category} onChange={(e) => setData({ ...data, category: e.target.value })}>
            <option value="equipment">Equipment</option>
            <option value="consumable">Consumable</option>
          </select>
          <button onClick={() => setStep(1)}>← Back</button>
        </>
      )}
    </div>
  );
};
```

***

### Styling

**Use inline styles only** - CSS files are NOT automatically loaded for creators.

#### Available CSS Variables

```javascript
style={{
  backgroundColor: 'var(--col-background)',
  color: 'var(--col-text-primary)',
  border: '1px solid var(--col-outliner-default)',
  borderRadius: 'var(--radius-sm)'
}}
```

Common variables:

* `--col-background`
* `--col-text-primary`
* `--col-text-secondary`
* `--col-input-background`
* `--col-outliner-default`
* `--radius-sm`, `--radius-md`, `--radius-lg`

***

### Common Issues

#### "module is not defined"

**Solution:** Use `module.exports =` (NOT `export default`)

#### "Next" Button Always Disabled

**Solution:** Call `onNext(data)` with valid data object

#### Creator Button Not Showing

**Solution:** Creator ID must start with `'create_'`

#### Wrong Plugin Shows Creator

**Solution:** Add plugin to `compatibility` array

#### Path Not Found

**Solution:** Use `__dirname + '/path/file.jsx'` (NOT `path.join()`)

***

### Quick Reference

| Aspect            | Creators              | Editors                               |
| ----------------- | --------------------- | ------------------------------------- |
| **Export**        | `module.exports =`    | `export default function`             |
| **Syntax**        | Arrow function        | Function declaration                  |
| **Special Props** | `onNext`, `projectId` | `itemData`, `setContent`, `useWindow` |
| **CSS**           | Inline styles only    | Separate `.css` file                  |
| **Purpose**       | Create new items      | Edit existing items                   |

***

### Related APIs

* Custom Element Types
* Custom Editors


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nexo-maker.gitbook.io/nexo-maker-docs/modular/creators.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
