npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@emacapt/widget-svelte

v0.0.7

Published

@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.

Downloads

437

Readme

@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 response = await fetch('https://api.emacapt.com/submit-form', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Project-Api-Key': process.env.EMACAPT_API_KEY
      },
      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, createField, validations } from '@emacapt/widget-svelte';
  import type { Field, TextOptions } from '@emacapt/widget-svelte';

  const fields: Field[] = [
    createField({
      name: 'email',
      label: 'Email Address',
      type: 'email',
      required: true,
      validation: validations.email
    })
    // ... other fields
  ];

  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"
  {fields}
  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, createField, validations } from '@emacapt/widget-svelte';
  import type { Field, TextOptions } from '@emacapt/widget-svelte';

  const fields: Field[] = [
    createField({
      name: 'email',
      label: 'Email Address',
      type: 'email',
      required: true,
      validation: validations.email
    })
    // ... other fields
  ];

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

<EmacaptWidget
  apiKey="your-api-key-here"
  apiUrl="https://api.emacapt.com/submit-form"
  {fields}
  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'.
  • 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 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: validations.min(18)
  })
  // ... other fields
];

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.