Selecto.js Documentation

repository·master·Indexed 24 days ago

https://github.com/daybrush/selecto

Selecto.js is a component that allows you to select elements in a drag area using mouse or touch interactions. It is highly configurable and provides official integration packages for various frontend frameworks, including react-selecto, ngx-selecto (Angular), vue-selecto, vue3-selecto, preact-selecto, svelte-selecto, and lit-selecto.

Tokens
9.2K
Snippets
20
Records
53
Agent score
80%

What's inside Selecto.js

  1. Configure selection behaviors

    master

    Selecto provides several options to control how selection is triggered and how it interacts with elements:

    • Prevent selection from inside and disable click selection:
      • selectFromInside: false
      • selectByClick: false
    • Include targets regardless of hitTest when selecting from inside:
      • selectFromInside: true
      • selectByClick: true
    • Finish selection immediately (selectStart and selectEnd occur at the same time) without dragging when selecting from inside:
      • selectFromInside: false
      • selectByClick: true
      • preventDragFromInside: true
      • clickBySelectEnd: false
    • Trigger selectEnd (click) after stopping drag and mouse/touch:
      • selectFromInside: false
      • selectByClick: true
      • clickBySelectEnd: true
  2. Achieve accurate selection for rotated or distorted objects

    master

    By default, Selecto uses getBoundingClientRect, which may not be accurate for rotated or distorted elements. To achieve high accuracy, provide a custom function to the getElementRect option. This function should return the four corners of the element.

    Example using getElementInfo from moveable:

    import Selecto from "selecto";
    import { getElementInfo } from "moveable"; // (13kb function) if you use react, use react-moveable
    
    const selecto = new Selecto({
        ...,
        // (target: HTMLElement | SVGElement ) => { pos1: number[], pos2: number[], pos3: number[], pos4: number[] }
        // pos1: left top
        // pos2: right top
        // pos3: left bottom
        // pos4: right bottom
        getElementRect: getElementInfo,
    });
  3. Understand Selecto event data structures

    master

    Selecto emits several events that provide detailed information about the selection process.

    Selection Events

    Selection events (selectStart, select, selectEnd) provide information about which elements are being manipulated.

    • SelectedTargets: The core data for selection changes.
      • beforeSelected: Elements that were selected before the current change.
      • selected: The current list of selected elements.
      • added: Elements newly added to the selection.
      • removed: Elements removed from the selection.
    • OnSelectEvent: Extends SelectedTargets with:
      • inputEvent: The original input event.
      • data: Shared data from dragStart through selectEnd.
      • isDragStartEnd: True if the drag ended immediately at the start.
      • isTrusted: Whether the interaction was a user-initiated drag.
    • OnSelectEnd: Specific to the end of a selection action, adding:
      • isClick: True if the action was a click.
      • isDouble: True if it was a double click.
      • afterAdded / afterRemoved: Elements after the selection logic has finalized.
  4. Handle selection events with selectStart, select, and selectEnd

    master

    Selecto provides several events to manage the selection lifecycle. You can listen to these using the .on() method.

    • selectStart: Triggered when the selection (drag) begins.
    • select: Triggered in real-time as the selection area changes during a drag.
    • selectEnd: Triggered when the selection (drag or click) ends. This event provides detailed information about what was added and removed from the selection.

    Example of managing CSS classes based on selection state:

    selecto.on("selectStart", e => {
      e.added.forEach(el => {
        el.classList.add("selected");
      });
      e.removed.forEach(el => {
        el.classList.remove("selected");
      });
    }).on("selectEnd", e => {
      e.afterAdded.forEach(el => {
        el.classList.add("selected");
      });
      e.afterRemoved.forEach(el => {
        el.classList.remove("selected");
      });
    });
    import Selecto from "selecto";
    
    const selecto = new Selecto({
      container: document.body,
      selectByClick: true,
      selectFromInside: false,
    });
    
    selecto.on("selectStart", e => {
      e.added.forEach(el => {
        el.classList.add("selected");
      });
      e.removed.forEach(el => {
        el.classList.remove("selected");
      });
    }).on("selectEnd", e => {
      e.afterAdded.forEach(el => {
        el.classList.add("selected");
      });
      e.afterRemoved.forEach(el => {
        el.classList.remove("selected");
      });
    });
  5. Use ngx-selecto in Angular

    master

    The ngx-selecto component provides an Angular wrapper for the selecto library. It allows you to implement selection functionality within an Angular application using component inputs and outputs.

    To use it, add the <ngx-selecto> selector to your template. You can configure the selection behavior via inputs that correspond to SelectoOptions and listen to selection events via Angular EventEmitter outputs that correspond to selecto events.

    Note that the component manages the VanillaSelecto instance internally, running it outside of the Angular zone for performance, and re-entering the zone when emitting events.

  6. Initialize Selecto

    master

    To use Selecto, create a new instance of the Selecto class. You can pass a Partial<SelectoOptions> object to configure its behavior. The instance manages a selection area and emits events when targets are selected, added, or removed.

    Common configuration options include:

    • container: The element that acts as the selection area.
    • selectableTargets: A list of elements, selectors, or functions that return elements to be selectable.
    • selectByClick: Whether to select elements on a single click.
    • selectFromInside: Whether to allow starting a selection from inside a selectable element.
    • className: A custom class name for the selection rectangle.
    import Selecto from "selecto";
    
    const selecto = new Selecto({
      container: document.body,
      selectByClick: true,
      selectFromInside: false,
    });
  7. Basic usage of Selecto

    master

    Initialize a new Selecto instance by providing a configuration object. You can listen to the select event to handle elements being added to or removed from the current selection.

    import Selecto from "selecto";
    
    const selecto = new Selecto({
        // The container to add a selection element
        container: document.body,
        // Selecto's root container (No transformed container. (default: null)
        rootContainer: null,
        // The area to drag selection element (default: container)
        dragContainer: Element,
        // Targets to select. You can register a queryselector or an Element.
        selectableTargets: [".target", document.querySelector(".target2")],
        // Whether to select by click (default: true)
        selectByClick: true,
        // Whether to select from the target inside (default: true)
        selectFromInside: true,
        // After the select, whether to select the next target with the selected target (deselected if the target is selected again).
        continueSelect: false,
        // Determines which key to continue selecting the next target via keydown and keyup.
        toggleContinueSelect: "shift",
        // The container for keydown and keyup events
        keyContainer: window,
        // The rate at which the target overlaps the drag area to be selected. (default: 100)
        hitRate: 100,
    });
    
    selecto.on("select", e => {
        e.added.forEach(el => {
            el.classList.add("selected");
        });
        e.removed.forEach(el => {
            el.classList.remove("selected");
        });
    });
  8. Configure Croffle for Selecto Storybook

    master

    This configuration file defines how the croffle build tool transforms and bundles Selecto's Storybook stories across different frameworks (React, Vue, Svelte, Angular, Lit). It uses croissant for high-level transformations and waffle for framework-specific bundling logic.

    Key transformations include:

    • Selecto Component Transformation: Automatically injects the container property into the Selecto options object during the build process.
    • Framework-specific adaptations: Handles module prefixing, template attribute renaming (e.g., for Lit), and keydown event handling (e.g., useKeycon) for various environments.
    • Prop Injection: Injects preview props into components to facilitate Storybook usage.
    const config = [
        {
            targets: "stories/**/+([0-9A-Za-z])-*/React*App.tsx",
            croissant: () => {
                const croissant = new ReactCroissant();
                croissant.addSirup(PreviewPropsSirup);
                // ...
                return croissant;
            },
            waffle: [
                // Framework-specific waffle configurations (Vanilla, Vue, Svelte, Angular, Lit)
            ],
        },
    ];
    
    module.exports = config;