Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Commonmark Alert Laravel Package

pomodocs/commonmark-alert

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require pomodocs/commonmark-alert
    

    Register the extension in your Laravel app (e.g., in config/commonmark.php):

    'extensions' => [
        // ... other extensions
        \Pomodocs\CommonMark\Alert\AlertExtension::class,
    ],
    
  2. First Use Case Use the alert block in Markdown to render styled alerts (e.g., in a blog post or documentation):

    ::: alert
    This is an alert message!
    :::
    

    Outputs a styled blockquote with a warning icon (default) or customizable variants (success, danger, info).

  3. Where to Look First

    • Extension Class: AlertExtension – Defines block parsing logic.
    • Block Syntax: Markdown Examples – Test different alert types (alert, success, warning, etc.).
    • Configuration: Check if the package supports customizing icons/colors via config (e.g., config/commonmark-alert.php).
    • Renderer Logic: AlertRenderer – Now merges attributes instead of overwriting them (v0.8+).

Implementation Patterns

Workflow Integration

  1. Markdown Processing Pipeline

    • Use the package in Laravel’s Markdown rendering (e.g., with commonmark or spatie/laravel-markdown):
      use Pomodocs\CommonMark\Alert\AlertExtension;
      $markdown = file_get_contents('post.md');
      $html = \CommonMark\CommonMarkConverter::create()
          ->getEnvironment()
          ->addExtension(new AlertExtension())
          ->convert($markdown);
      
    • Cache processed Markdown (e.g., with spatie/laravel-caching) to avoid reprocessing.
  2. Dynamic Alert Types

    • Support multiple alert variants in a single template:
      ::: success
      Operation completed successfully!
      :::
      ::: danger
      Failed to save changes.
      :::
      
    • Extend the extension to add custom types (e.g., tip, note) by overriding the getAlertTypes() method.
  3. Blade Integration

    • Render alerts in Blade views by processing Markdown strings:
      @markdown(file_get_contents('docs/alerts.md'))
      
    • Use with Laravel Livewire/Alpine for interactive alerts (e.g., toggle visibility).
  4. API Responses

    • Return formatted alerts in API responses (e.g., for admin notifications):
      return response()->json([
          'message' => 'User created',
          'alert' => '<div class="alert success">...</div>', // Pre-rendered HTML
      ]);
      

Custom Attributes in Alerts (v0.8+)

  • Leverage the improved AlertRenderer to merge custom attributes without overwriting existing ones:
    ::: alert{data-custom="value" class="custom-class"}
    This alert has merged attributes!
    :::
    
  • This allows for finer-grained styling or data attributes without breaking default behavior.

Gotchas and Tips

Pitfalls

  1. Block Parsing Conflicts

    • If alerts don’t render, ensure the extension is registered after other block-level extensions (e.g., tables, code blocks) in CommonMarkConverter.
    • Debug with:
      $environment->getBlockParserRegistry()->getBlockParsers();
      
      to verify the AlertBlockParser is last in the chain.
  2. Nested Alerts

    • The package doesn’t support nested alerts (e.g., alerts inside lists). Workaround: Use HTML <div> wrappers or flatten structure.
  3. Customization Limits

    • Default styles are hardcoded (e.g., Bootstrap classes). Override via CSS or extend the extension to accept a style parameter:
      ::: alert{style="custom"}
      Custom-styled alert.
      :::
      
    • v0.8 Note: Attribute merging now allows combining custom classes with default styles without conflicts.
  4. Performance

    • Avoid processing large Markdown files repeatedly. Cache the CommonMarkConverter instance:
      $converter = app()->makeWith(\CommonMark\CommonMarkConverter::class, [
          'environment' => fn() => tap(new \CommonMark\Environment\Environment(), fn($env) =>
              $env->addExtension(new AlertExtension())
          ),
      ]);
      

Debugging Tips

  • Enable CommonMark Debugging:
    $environment->addRenderer(\CommonMark\Node\Block\Paragraph::class, function ($node) {
        return '<pre>' . print_r($node->getData(), true) . '</pre>';
    });
    
  • Check for Syntax Errors:
    • Invalid alert blocks (e.g., ::: alert) may silently fail. Validate with:
      try {
          $html = $converter->convert($markdown);
      } catch (\CommonMark\CommonMarkException $e) {
          report($e);
      }
      
  • Inspect Rendered Attributes:
    • Use browser dev tools to verify merged attributes in the output HTML (e.g., data-custom and default classes coexisting).

Extension Points

  1. Add Custom Alert Types Extend AlertExtension to support new types (e.g., example):

    protected function getAlertTypes(): array {
        return array_merge(parent::getAlertTypes(), ['example']);
    }
    

    Then use in Markdown:

    ::: example
    Usage: `php artisan migrate`
    :::
    
  2. Modify Renderer Logic (v0.8+) Override the AlertRenderer to customize attribute merging or HTML structure:

    $environment->addRenderer(\Pomodocs\CommonMark\Alert\AlertBlock::class, function ($node) {
        $type = $node->getData('type') ?? 'alert';
        $attributes = $node->getData('attributes', []);
        return sprintf(
            '<div class="alert %s %s">%s</div>',
            $type,
            $attributes['class'] ?? '',
            $node->getLiteral()
        );
    });
    
  3. Integrate with Tailwind CSS Replace Bootstrap classes with Tailwind:

    // In your CSS or extension
    .alert { @apply p-4 mb-4 text-sm text-gray-700 bg-gray-100 rounded-lg }
    .alert.success { @apply bg-green-100 border border-green-400 text-green-700 }
    
    • Use merged attributes to combine custom classes:
      ::: alert{class="border-red-500"}
      Custom border alert.
      :::
      
  4. Localization Support translated alert labels (e.g., warningadvertencia):

    $environment->addRenderer(\Pomodocs\CommonMark\Alert\AlertBlock::class, function ($node) use ($translator) {
        $type = $translator->get('alert.types.' . ($node->getData('type') ?? 'alert'));
        $attributes = $node->getData('attributes', []);
        return sprintf('<div class="alert %s" %s>%s</div>',
            $type,
            $this->renderAttributes($attributes),
            $node->getLiteral()
        );
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle