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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@nldoc/validation

v2.0.1

Published

Validation hooks and components for NLdoc TipTap integration

Readme

@nldoc/validation

Validation hooks and components for integrating NLdoc validation with TipTap editors.

Installation

npm install @nldoc/validation @nldoc/api @nldoc/types

Features

  • Validation Hooks: React hooks for validating TipTap document content via the NLdoc API
  • Validation Context: Provider pattern for sharing validation state across components
  • UI Components: Headless UI components for displaying validation results
  • Positioning & Stacking: Sophisticated layout system for non-overlapping validation indicators
  • Bundling: Groups related validation findings from the same block-level element
  • TypeScript: Full TypeScript support with comprehensive type definitions

Quick Start

Using ValidationProvider (Recommended)

The simplest way to add validation is with ValidationProvider. It automatically tracks editor updates, validates content with debouncing, and applies findings to the editor—no manual state management required.

import { ValidationProvider, useValidationContext } from '@nldoc/validation'
import { NLDocStarterKit } from '@nldoc/tiptap-extensions'
import { useEditor, EditorContent } from '@tiptap/react'

function ValidationStatus() {
  const { findings, isValidating } = useValidationContext()
  return <div>{isValidating ? 'Validating...' : `${findings.length} issues`}</div>
}

function MyEditor() {
  const editor = useEditor({
    extensions: [NLDocStarterKit],
  })

  return (
    <ValidationProvider editor={editor} options={{ debounceDelay: 500 }}>
      <EditorContent editor={editor} />
      <ValidationStatus />
    </ValidationProvider>
  )
}

That's it! ValidationProvider handles:

  • ✅ Tracking editor updates (while filtering out validation transactions)
  • ✅ Debouncing validation requests
  • ✅ Applying findings back to the editor automatically
  • ✅ Preventing infinite validation loops

Using the useValidation Hook (Advanced)

For more control, use the useValidation hook directly and manage state yourself:

import { useValidation } from '@nldoc/validation'
import { useEditor } from '@tiptap/react'
import { useState } from 'react'

function MyEditor() {
  const [editorJSON, setEditorJSON] = useState(null)

  const editor = useEditor({
    /* ...your extensions */
    onUpdate: ({ editor }) => setEditorJSON(editor.getJSON())
  })

  const { findings, isValidating, error } = useValidation(editorJSON, {
    debounceDelay: 500,
    debounceMaxWait: 5000,
  })

  return (
    <div>
      <EditorContent editor={editor} />
      {isValidating && <p>Validating...</p>}
      {findings.length > 0 && <p>{findings.length} issues found</p>}
    </div>
  )
}

API Reference

Hooks

useValidation(editorJSON, options)

Main validation hook that converts TipTap JSON to validation format and fetches validation findings.

Parameters:

  • editorJSON: JSONContent | null - The TipTap editor JSON content
  • options?: ValidationHookOptions - Configuration options

Returns: Validation

  • findings: ValidationFinding[] - Array of validation findings
  • isValidating: boolean - Whether validation is in progress
  • error: Error | null - Error if validation failed

Options:

  • debounceDelay?: number - Delay in ms before starting validation (default: 500)
  • debounceMaxWait?: number - Maximum wait time in ms before forcing validation (default: 5000)
  • includeAssets?: boolean - Whether to include image assets in validation (default: false)

useValidationContext()

Access validation state from context. Must be used within a ValidationProvider.

Returns: Validation

useTiptapValidation(editorJSON, options)

Low-level hook that converts TipTap JSON to validation format with debouncing.

Components

<ValidationProvider>

Provider component that manages validation state and applies findings to the editor.

Automatically tracks editor updates and validates content with debouncing. Excludes validation transactions to prevent infinite loops.

Props:

  • editor: Editor | null - The TipTap editor instance
  • editorJSON?: JSONContent | null - (Optional) Manual editor JSON. If not provided, ValidationProvider tracks updates automatically
  • options?: ValidationHookOptions - Validation configuration
  • autoApplyFindings?: boolean - Whether to automatically apply findings (default: true)
  • onApplyFindings?: (editor, findings) => void - Custom callback to apply findings

Example (Automatic):

<ValidationProvider editor={editor}>
  <EditorContent editor={editor} />
</ValidationProvider>

Example (Manual Control):

const [editorJSON, setEditorJSON] = useState(null)

<ValidationProvider editor={editor} editorJSON={editorJSON}>
  <EditorContent editor={editor} />
</ValidationProvider>

<ValidationResult>

Headless component for displaying individual validation results. Highly customizable via render props.

Props:

  • findings: ValidationFinding[] - Array of findings to display
  • isBundle?: boolean - Whether this is a bundle of findings
  • variant?: 'default' | 'stack' - Display variant
  • onResolve?: (ids: string[]) => void - Callback when user resolves findings
  • onRetrigger?: () => void - Callback to retrigger validation
  • renderIcon?: (type, props) => ReactNode - Custom icon renderer
  • renderMessage?: (finding, count, isBundle) => ReactNode - Custom message renderer
  • renderResolution?: (ids, onResolved) => ReactNode - Custom resolution renderer
  • className?: string - CSS class for styling
  • styles?: object - Style overrides for specific elements

<ValidationResultSummary>

Main component that orchestrates the layout of all validation results with sophisticated positioning, stacking, and bundling.

Props:

  • findings: ValidationFinding[] - All validation findings
  • isAnimating?: boolean - Whether editor is animating (delays layout updates)
  • positioningConfig?: PositioningConfig - Configuration for position calculations
  • buildFindingBlockMap?: (findings) => Map<string, string> - Custom function to map findings to parent blocks
  • validationResultProps?: Partial<ValidationResultProps> - Props to pass to ValidationResult components
  • resizeDebounceDelay?: number - Debounce delay for window resize (default: 100ms)

Utilities

Positioning

import {
  makePositionedFindings,
  calculateDesiredYLocation,
} from '@nldoc/validation'

const positionedFindings = makePositionedFindings(findings, {
  editorSelector: '#my-editor', // Default: '#tiptap'
})

Bundling

import { computeBundles, BUNDLEABLE_RULES } from '@nldoc/validation'

// Rules that support bundling:
// - 'no-underline'
// - 'style-bold-in-header'
// - 'style-italic-in-header'

const bundles = computeBundles(positionedFindings, findingBlockMap)

Stacking

import {
  createInitialStacksFromItems,
  mergeOverlappingStacksWithBundles,
  positionStacksWithBundles,
} from '@nldoc/validation'

const initialStacks = createInitialStacksFromItems(items)
const mergedStacks = mergeOverlappingStacksWithBundles(
  initialStacks,
  itemHeights,
  expandedStackIds
)
const positioned = positionStacksWithBundles(mergedStacks, stackRefs)

Advanced Usage

Custom Validation Result Display

import { ValidationResult } from '@nldoc/validation'

function MyValidationResult({ findings }) {
  return (
    <ValidationResult
      findings={findings}
      renderIcon={(type) => {
        const icons = {
          error: <ErrorIcon />,
          warning: <WarningIcon />,
          suggestion: <InfoIcon />,
        }
        return icons[type]
      }}
      renderMessage={(finding, count) => (
        <div>
          <h4>{finding.rule}</h4>
          <p>{finding.message}</p>
          {count > 1 && <span>{count} occurrences</span>}
        </div>
      )}
      renderResolution={(ids, onResolved) => (
        <button onClick={() => {
          // Custom resolution logic
          resolveFindings(ids)
          onResolved()
        }}>
          Fix Issue
        </button>
      )}
    />
  )
}

Complete Example with TipTap

import { ValidationProvider, useValidationContext } from '@nldoc/validation'
import { NLDocStarterKit } from '@nldoc/tiptap-extensions'
import { useEditor, EditorContent } from '@tiptap/react'

function ValidationSidebar() {
  const { findings, isValidating, error } = useValidationContext()

  if (isValidating) return <div>Validating...</div>
  if (error) return <div>Error: {error.message}</div>

  return (
    <aside>
      <h3>Accessibility Issues</h3>
      {findings.length === 0 ? (
        <p>No issues found!</p>
      ) : (
        <ul>
          {findings.map((finding, i) => (
            <li key={i}>
              [{finding.severity}] {finding.rule}
            </li>
          ))}
        </ul>
      )}
    </aside>
  )
}

function MyEditor() {
  const editor = useEditor({
    extensions: [
      NLDocStarterKit.configure({
        // Configure your extensions
      }),
    ],
    content: '<p>Start typing...</p>',
  })

  return (
    <ValidationProvider
      editor={editor}
      options={{
        debounceDelay: 500,
        debounceMaxWait: 5000,
        includeAssets: false,
      }}
    >
      <div style={{ display: 'flex' }}>
        <EditorContent editor={editor} />
        <ValidationSidebar />
      </div>
    </ValidationProvider>
  )
}

Key Points:

  • No manual state management needed
  • ValidationProvider automatically tracks updates
  • Findings are automatically applied to the editor
  • Validation transactions are filtered to prevent loops
  • Use useValidationContext() anywhere within the provider to access validation state

TypeScript

All exports are fully typed. Key types:

import type {
  Validation,
  ValidationHookOptions,
  ValidationResultProps,
  ValidationResultSummaryProps,
  PositionedFinding,
  Bundle,
  Stack,
  StackableItem,
  PositioningConfig,
} from '@nldoc/validation'

Related Packages

  • @nldoc/tiptap-extensions - Custom TipTap extensions including ValidationFindingsExtension
  • @nldoc/api - API client for NLdoc services
  • @nldoc/types - Shared TypeScript types

License

EUPL-1.2