stateMarker

stateMarker

Add data attributes to track drag state

The stateMarker plugin adds data attributes that track drag state. These attributes enable CSS styling based on drag status and provide hooks for debugging and analytics.

stateMarker(); // Adds data-neodrag-state and data-neodrag-count attributes

Attributes added:

  • data-neodrag="" - Marks element as draggable
  • data-neodrag-state="idle|dragging" - Current drag state
  • data-neodrag-count="0" - Number of completed drags

Note: StateMarker is included by default and is non-cancelable, so it always runs regardless of other plugin cancellations.

Basic Usage

<script>
  import { stateMarker } from '@neodrag/svelte';
</script>

<div {@attach draggable([stateMarker()])}>
  Drag me - watch the data attributes change
</div>

Reading State Attributes

<script>
  import { stateMarker, events } from '@neodrag/svelte';

  let dragElement;
  let currentState = $state('idle');
  let dragCount = $state(0);

  function updateStateInfo() {
    if (dragElement) {
      currentState =
        dragElement.getAttribute('data-neodrag-state') || 'idle';
      dragCount = parseInt(
        dragElement.getAttribute('data-neodrag-count') || '0',
      );
    }
  }

  const plugins = [
    stateMarker(),
    events({
      onDragStart: updateStateInfo,
      onDrag: updateStateInfo,
      onDragEnd: updateStateInfo,
    }),
  ];
</script>

<div bind:this={dragElement} {@attach draggable(plugins)}>
  State: {currentState}
  <br />
  Drag Count: {dragCount}
</div>

Monitoring State Changes

<script>
  import { stateMarker, events } from '@neodrag/svelte';

  let notifications = $state([]);

  function addNotification(message) {
    notifications = [
      ...notifications,
      {
        id: Date.now(),
        message,
        timestamp: new Date().toLocaleTimeString(),
      },
    ];

    // Remove after 3 seconds
    setTimeout(() => {
      notifications = notifications.filter(
        (n) => n.id !== notifications[0]?.id,
      );
    }, 3000);
  }

  const plugins = [
    stateMarker(),
    events({
      onDragStart: () => addNotification('Drag started'),
      onDragEnd: (data) => {
        const count = data.rootNode.getAttribute(
          'data-neodrag-count',
        );
        addNotification(`Drag ended (Total: ${count})`);
      },
    }),
  ];
</script>

<div {@attach draggable(plugins)}>Drag me for notifications</div>

<div class="notifications">
  {#each notifications as notification (notification.id)}
    <div>{notification.timestamp}: {notification.message}</div>
  {/each}
</div>

Analytics Integration

<script>
  import { stateMarker, events } from '@neodrag/svelte';

  function trackDragAnalytics(eventName, data) {
    // Send to analytics service
    analytics.track(eventName, {
      elementId: data.rootNode.id,
      dragCount: data.rootNode.getAttribute('data-neodrag-count'),
      position: data.offset,
      timestamp: Date.now(),
    });
  }

  const analyticsPlugins = [
    stateMarker(),
    events({
      onDragStart: (data) => trackDragAnalytics('drag_started', data),
      onDragEnd: (data) => trackDragAnalytics('drag_completed', data),
    }),
  ];
</script>

<div {@attach draggable(analyticsPlugins)}>
  Analytics-tracked element
</div>

Debug Inspector

<script>
  import { stateMarker, events } from '@neodrag/svelte';

  let debugInfo = $state({
    state: 'idle',
    count: 0,
    isDragging: false,
    lastEventTime: null,
  });

  function updateDebugInfo(eventType, data) {
    debugInfo = {
      state: data.rootNode.getAttribute('data-neodrag-state'),
      count: parseInt(
        data.rootNode.getAttribute('data-neodrag-count') || '0',
      ),
      isDragging: eventType === 'drag' || eventType === 'dragStart',
      lastEventTime: new Date().toLocaleTimeString(),
    };
  }

  const debugPlugins = [
    stateMarker(),
    events({
      onDragStart: (data) => updateDebugInfo('dragStart', data),
      onDrag: (data) => updateDebugInfo('drag', data),
      onDragEnd: (data) => updateDebugInfo('dragEnd', data),
    }),
  ];
</script>

<div {@attach draggable(debugPlugins)}>Drag me to see debug info</div>

<div class="debug-panel">
  <h3>Debug Information</h3>
  <p>State: {debugInfo.state}</p>
  <p>Total Drags: {debugInfo.count}</p>
  <p>Currently Dragging: {debugInfo.isDragging ? 'Yes' : 'No'}</p>
  <p>Last Event: {debugInfo.lastEventTime || 'None'}</p>
</div>

How It Works

The stateMarker plugin manages data attributes through the drag lifecycle:

  1. Setup phase:

    • Adds data-neodrag="" to mark element
    • Sets data-neodrag-state="idle"
    • Initializes data-neodrag-count="0"
  2. Start phase:

    • Updates data-neodrag-state="dragging"
  3. End phase:

    • Resets data-neodrag-state="idle"
    • Increments data-neodrag-count
  4. Non-cancelable:

    • Always runs regardless of other plugin cancellations
    • Ensures consistent state tracking
// Simplified internal implementation
setup(ctx) {
  setNodeDataset(ctx.rootNode, 'neodrag', '');
  setNodeDataset(ctx.rootNode, 'neodrag-state', 'idle');
  setNodeDataset(ctx.rootNode, 'neodrag-count', '0');
},

start(ctx) {
  setNodeDataset(ctx.rootNode, 'neodrag-state', 'dragging');
},

end(ctx, state) {
  setNodeDataset(ctx.rootNode, 'neodrag-state', 'idle');
  setNodeDataset(ctx.rootNode, 'neodrag-count', ++state.count);
}

API Reference

function stateMarker(): Plugin;

Parameters: None

Data attributes added:

  • data-neodrag="" - Marks element as draggable
  • data-neodrag-state="idle|dragging" - Current drag state
  • data-neodrag-count="0" - Number of completed drags

Behavior:

  • Non-cancelable - always runs
  • Updates attributes automatically during drag lifecycle
  • Increments count only on successful drag completion
  • Provides hooks for CSS styling and JavaScript integration

Returns: A plugin object for use with draggable.