# Salla Twilight Bundles Starter Kit

This starter kit provides a foundation for building custom Twilight components for Salla's e-commerce platform. It includes a pre-configured build setup and development environment to help you get started quickly.

## Getting Started

1. Clone this repository
2. Remove the example components in `src/components/` using:
   ```
   tw-delete-component
   ```
3. Create your own components using the component generator:
   ```
   tw-create-component <component-name>
   ```
4. Run `pnpm install` to install dependencies
5. Run `pnpm run dev` to start the development server
6. Run `pnpm run build` to build your components for production
7. Run `pnpm tw-preview` to publish a shareable preview of your bundle (see [Public Preview](#public-preview))

## Project Structure

```
src/
  components/
    your-component-name/
      index.ts        # Main component file
      styles.ts       # Component styles (optional)
      types.ts        # Component types (optional)
```

## Built-in Plugins

This starter kit includes three Vite plugins that handle the build process:

### 1. Transform Plugin (`sallaTransformPlugin`)
- Transforms component files to ensure proper naming and registration
- Matches components in `src/components/*/index.ts`
- To disable: Remove from `vite.config.ts` plugins array

### 2. Build Plugin (`sallaBuildPlugin`)
- Handles component bundling and output
- Creates individual files for each component in `dist/`
- Configures external dependencies (lit libraries)
- To customize: Remove from plugins array and configure your own build settings:
  ```typescript
  {
    build: {
      lib: {
        entry: {/* your entries */},
        formats: ['es'],
        fileName: (format, entryName) => `${entryName}.js`
      },
      rollupOptions: {
        external: [/^lit/],
        output: {/* your output config */}
      }
    }
  }
  ```

### 3. Demo Plugin (`sallaDemoPlugin`)
- Provides a development environment for testing components
- Creates a demo page with your components
- Configures hot module reloading
- To disable: Remove from plugins array and set up your own dev server

### Demo Plugin Options

The `sallaDemoPlugin` accepts the following configuration options:

```typescript
{
  // Optional: Show only specific components
  components?: string[];

  // Optional: Customize the demo grid layout
  grid?: {
    // CSS grid-template-columns value
    columns?: string;     // default: 'repeat(auto-fill, minmax(300px, 1fr))'
    
    // Gap between components
    gap?: string;        // default: '1rem'
    
    // Responsive breakpoint
    minWidth?: string;   // default: '300px'
  };

  // Optional: Add custom CSS
  css?: string;

  // Optional: Add custom JavaScript
  js?: string;
}
```

#### Example Configuration

```typescript
// vite.config.ts
export default defineConfig({
  plugins: [
    // ... other plugins
    sallaDemoPlugin({
      // Show only specific components
      components: ['product-card', 'scroll-top'],
      
      // Customize grid layout
      grid: {
        columns: 'repeat(3, 1fr)',
        gap: '1.5rem',
        minWidth: '768px'
      },

      // Add custom styles
      css: `
        .component-card {
          box-shadow: 0 2px 4px rgba(0,0,0,0.1);
          transition: transform 0.2s;
        }
        .component-card:hover {
          transform: translateY(-2px);
        }
      `,

      // Add custom JavaScript
      js: `
        console.log('Demo page loaded!');
        // Add your custom JavaScript here
      `
    })
  ]
});
```

## Component Management

### Creating New Components

This starter kit includes a component generator to help you create new components quickly. To use it, run:

```bash
tw-create-component <component-name>
```

Or run without arguments for interactive mode:

```bash
tw-create-component
```

The generator will:
1. Prompt you for a component name (in kebab-case format)
2. Validate that the name is in kebab-case and doesn't already exist
3. Create a new component folder with an `index.ts` file
4. Add the component definition to `twilight-bundle.json`

### Deleting Components

To remove a component, use:

```bash
tw-delete-component <component-name>
```

Or run without arguments to see a list of available components:

```bash
tw-delete-component
```

This will:
1. Show a list of available components to select from
2. Ask for confirmation before deletion
3. Remove the component folder from `src/components/`
4. Remove the component definition from `twilight-bundle.json`

## Component Requirements

Each component should:
1. Be a class that extends `LitElement`
2. Export the class as default
3. Be placed in its own directory under `src/components/`
4. Have an `index.ts` as the entry point

Example:
```typescript
import { css, html, LitElement } from 'lit';
import { property } from 'lit/decorators.js';

export default class MyComponent extends LitElement {
  @property({ type: Object })
  config?: {
      title: string;
      // ... Add more properties as needed
  };
  

  static styles = css`/* your styles */`;

  render() {
    return html`<div>Hello ${this.config?.title || 'World'}!</div>`;
  }
}
```

## Templates

A template is a saved arrangement of your components with their field values, stored as `templates/<name>.json` and registered in the `templates` array of `twilight-bundle.json`. The starter kit ships with one example template (`templates/starter-template.json`).

To create or update templates, use the demo page that opens with `pnpm run dev`:

1. Adjust your components' settings in the demo sidebar — values are the same ones stored in each component's `fields` in `twilight-bundle.json`
2. Save the current state as a template from the templates panel
3. The dev server writes `templates/<name>.json` (component list + field values) and updates `twilight-bundle.json` for you

You can also edit the template JSON files directly — each file contains the component objects with the `value` of every field.

## Public Preview

Every saved template can get a shareable preview page — no npm publish, no public repo, and no hosting needed. Build, then publish a preview snapshot:

```bash
pnpm build
pnpm tw-preview
```

`tw-preview` uploads the bundle's templates and built components to Salla's preview service and prints a URL like:

```
https://salla.design/preview/s/<preview-id>/<template-name>
```

- Everything the build produced is included: component scripts, their shared chunks, and any media under `dist/assets/` (images, fonts, video — up to 50MB per file). References like `/assets/logo.svg` are automatically repointed at the preview's own copies.
- Media is hosted on Salla's real CDN (`cdn.assets.salla.network`), the same infrastructure published bundle releases use — not a temporary or preview-only store.
- The first publish authenticates with your Salla partner account — just be logged in via `salla login` (CI can set `TW_PREVIEW_TOKEN` instead).
- The preview id and its write key are saved to `.salla-preview.json` (auto-gitignored) — keep that file private. Re-running `tw-preview` after changes updates the **same URL** in place, no login needed.
- The URL is unguessable, so it's safe to share with clients even for private bundles.

### CDN upload timing

A brand-new or just-changed asset is uploaded to the CDN as part of the same publish, and `tw-preview` re-checks with the preview service right after to pick up the direct CDN link once the upload is confirmed — usually resolving within the same run. On the rare occasion that confirmation hasn't landed yet, the reference falls back to a redirect that still works (it resolves to the same file) until you run `tw-preview` once more.

Bundles that *are* published to npm under the `@salla.sa` scope also get automatic previews at `https://salla.design/preview/<package-name>/<template-name>` (pin a version with `?version=x.y.z`).

## Building for Production

Run `pnpm run build` to create production-ready bundles in the `dist/` directory. Each component will have its own file named after the component (e.g., `my-component.js`).

## Development

Run `pnpm run dev` to start the development server. This will:
1. Create a demo page with all your components
2. Enable hot module reloading
3. Provide a development environment for testing

## License

MIT
