@emacapt/widget-svelte
TypeScript icon, indicating that this package has built-in type declarations

0.0.21 • Public • Published

@emacapt/widget-svelte

@emacapt/widget-svelte is a customizable, accessible, and easy-to-use form widget for Svelte applications. It provides a pop-up modal form with various field types, customizable styling, and built-in validation.

Features

  • 🎨 Customizable styling
  • 📱 Responsive design with mobile-friendly layout
  • ♿ Accessibility-ready with proper ARIA attributes
  • 🔒 Supports both server-side (SvelteKit) and client-side API calls
  • 🔢 Various input types: text, email, number, checkbox, select
  • ✅ Built-in and custom validation support
  • 🌈 Easy theming with primary color selection

Installation

Install the package using npm:

npm install @emacapt/widget-svelte

Usage

There are two ways to use the EmacaptWidget: with a server-side endpoint (recommended for security) or with direct API calls. You must choose one of these methods.

Server-Side Usage (Recommended for Security)

Use @emacapt/widget-svelte with a SvelteKit server route:

  1. Create a server route (e.g., src/routes/api/submit-form/+server.ts):
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';

export const POST: RequestHandler = async ({ request, fetch }) => {
  const formData = await request.json();

  try {
    const headers = new Headers();

    headers.append('Content-Type', 'application/json');
    headers.append('X-Project-Api-Key', process.env.API_KEY ?? '');

    const response = await fetch('https://api.emacapt.com/clients', {
      method: 'POST',
      headers,
      body: JSON.stringify(formData)
    });

    if (!response.ok) {
      throw new Error('API request failed');
    }

    const data = await response.json();
    return json(data);
  } catch (error) {
    console.error('Error submitting form:', error);
    return json({ error: 'An error occurred while submitting the form' }, { status: 500 });
  }
};
  1. Use the widget in your Svelte component:
<script lang="ts">
  import { EmacaptWidget } from '@emacapt/widget-svelte';
  import type { TextOptions } from '@emacapt/widget-svelte';

  const customTextOptions: Partial<TextOptions> = {
    openFormButton: 'Contact Us',
    submit: 'Send Message',
    success: 'Thank you for your message!'
  };

  function handleSuccess(event: CustomEvent) {
    console.log('Form submitted successfully:', event.detail);
  }

  function handleError(event: CustomEvent) {
    console.error('Error submitting form:', event.detail);
  }
</script>

<EmacaptWidget
  serverEndpoint="/api/submit-form"
  primaryColor="indigo"
  textOptions={customTextOptions}
  on:success={handleSuccess}
  on:error={handleError}
/>

Client-Side Usage (Less Secure)

For scenarios where server-side processing is not possible, you can use the widget with direct API calls. However, this method is less secure as it exposes your API key to the client.

<script lang="ts">
  import { EmacaptWidget} from '@emacapt/widget-svelte';
  import type { Field  } from '@emacapt/widget-svelte';

  // ... rest of the component logic
</script>

<EmacaptWidget
  apiKey="your-api-key-here"
  apiUrl="https://api.emacapt.com/submit-form"
  primaryColor="indigo"
  textOptions={customTextOptions}
  on:success={handleSuccess}
  on:error={handleError}
/>

Configuration Options

Props

You must provide either serverEndpoint or both apiKey and apiUrl:

  • serverEndpoint (string, recommended): The endpoint for your server-side API route.
  • apiKey (string, less secure): Your API key for direct API calls.
  • apiUrl (string, less secure): The URL to submit the form data to.

Other props:

  • fields (Field[]): An array of field configurations.
  • primaryColor (string, optional): The primary color theme ('blue', 'indigo', 'green', or 'red'). Default is 'blue' or put your own color value as hex string, e.g "#0066ff".
  • textColor (string, optional): The color of the text in the form. Default is 'white'.
  • textOptions (Partial, optional): Customized text for various parts of the widget.

Field Configuration

Fields are typically configured using the createField helper function and preset validations. However, you can also manually create fields and provide custom validation functions if needed.

import { createField, validations } from '@emacapt/widget-svelte';

const customTextOptions: Partial<TextOptions> = {
  openFormButton: 'Contact Us',
  submit: 'Send',
  submitting: 'Sending...',
  success: 'Thank you!',
  error: 'Oops! Something went wrong.',
  requiredField: 'This field is required',
  invalidEmail: 'Please enter a valid email',
  selectPlaceholder: 'Choose an option',
  modalTitle: 'Get in Touch',
  modalSubheading: "We'd love to hear from you!",
  closeButtonAriaLabel: 'Close form'
};

const fields: Field[] = [
  createField({
    name: 'email',
    label: 'Email Address',
    type: 'email',
    required: true,
    validation: validations.email
  }),
  createField({
    name: 'name',
    label: 'Full Name',
    type: 'text',
    required: true
  }),
  createField({
    name: 'age',
    label: 'Age',
    type: 'number',
    required: true,
    validation: (value: number) => {
      return value >= 18 ? null : 'You must be 18 or older';
    }
  })
  // ... other fields
];

<EmacaptWidget
  apiKey="your-api-key-here"
  apiUrl="https://api.emacapt.com/submit-form"
  fields={fields}
  primaryColor="indigo"
  textOptions={customTextOptions}
  on:success={handleSuccess}
  on:error={handleError}
/>

Text Customization

Customize the widget's text by passing a textOptions object:

const customTextOptions: Partial<TextOptions> = {
  openFormButton: 'Contact Us',
  submit: 'Send',
  submitting: 'Sending...',
  success: 'Thank you!',
  error: 'Oops! Something went wrong.',
  requiredField: 'This field is required',
  invalidEmail: 'Please enter a valid email',
  selectPlaceholder: 'Choose an option',
  modalTitle: 'Get in Touch',
  modalSubheading: "We'd love to hear from you!",
  closeButtonAriaLabel: 'Close form'
};

Accessibility

@emacapt/widget-svelte is designed with accessibility in mind, including proper ARIA attributes and keyboard navigation support. However, always test your implementation to ensure it meets your specific accessibility requirements.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Readme

Keywords

none

Package Sidebar

Install

npm i @emacapt/widget-svelte

Weekly Downloads

4

Version

0.0.21

License

MIT

Unpacked Size

38.3 kB

Total Files

11

Last publish

Collaborators

  • jackie_j