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

Torchlight Laravel Laravel Package

torchlight/torchlight-laravel

Torchlight syntax highlighting for Laravel Blade/Markdown using the Torchlight API. VS Code-compatible highlighting with themes, line highlighting and diffing, no JavaScript required. Includes caching, config publishing, and optional Blade components.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require torchlight/torchlight-laravel
    
  2. Publish the config:
    php artisan torchlight:install
    
  3. Configure .env:
    TORCHLIGHT_TOKEN=your_api_token_from_torchlight.dev
    TORCHLIGHT_THEME=material-theme-palenight
    TORCHLIGHT_CACHE_DRIVER=file  # or redis, database, etc.
    
  4. First use case: Highlight a code block in Blade:
    @torchlight('php', '<?php echo "Hello, Torchlight!";')
    

Key Starting Points

  • Facade: Use Torchlight::highlight() for programmatic highlighting.
  • Blade Component: @torchlight('language', 'code') for inline usage.
  • Cache: Highlighted blocks are cached by default (configurable TTL).

Implementation Patterns

Core Workflows

1. Blade Integration (Most Common)

  • Inline Highlighting:
    @torchlight('javascript', 'console.log("Hello");')
    
  • Dynamic Code:
    @torchlight('php', $dynamicCodeVariable)
    
  • With Custom Attributes:
    @torchlight(['language' => 'python', 'class' => 'custom-class'], 'print("Hi")')
    

2. Programmatic Highlighting

  • Facade Method:
    $highlighted = Torchlight::highlight('css', '.selector { color: red; }');
    
  • Async Processing (for long blocks):
    $block = Torchlight::highlight('javascript', $largeCode);
    $block->setCacheTTL(3600); // Override cache TTL
    

3. Livewire Integration

  • Auto-registers middleware for Livewire 2/3. Use in components:
    public function render()
    {
        return view('livewire.component', [
            'highlighted' => Torchlight::highlight('html', '<div>...</div>'),
        ]);
    }
    

4. Post-Processing

  • Global Post-Processors (e.g., wrap in a container):
    Torchlight::addPostProcessor(function ($html) {
        return '<div class="code-container">' . $html . '</div>';
    });
    
  • Per-Block Post-Processors:
    $block = Torchlight::highlight('php', '<?php ...');
    $block->addPostProcessor(fn($html) => str_replace(' ', '&nbsp;', $html));
    

5. File/Partial Highlighting

  • Highlight an entire file:
    $highlighted = Torchlight::highlightFile('path/to/file.php');
    
  • Use snippet directories (configured in torchlight.php) for reusable code blocks.

Advanced Patterns

Dynamic Themes

  • Toggle themes per request:
    Torchlight::setTheme('dark' ? 'material-theme-darker' : 'material-theme-palenight');
    
  • Multi-theme Support:
    Torchlight::setThemeUsing(function () {
        return request()->user()->prefers_dark_mode ? 'dark-theme' : 'light-theme';
    });
    

Custom Cache Strategies

  • Override Cache Driver:
    Torchlight::setCacheDriver('redis');
    
  • Cache Tags (for invalidation):
    $block = Torchlight::highlight('js', '...')->setCacheTags(['user-guides']);
    cache()->forget('torchlight:tags:user-guides');
    

Macros for Blocks

  • Extend Block functionality:
    \Torchlight\Block::macro('addLineNumbers', function () {
        $this->addPostProcessor(function ($html) {
            return '<ol>' . str_replace('<div class="line">', '<li><div class="line">', $html) . '</ol>';
        });
        return $this;
    });
    
  • Usage:
    @torchlight(['language' => 'php'], '<?php ...')->addLineNumbers()
    

API Options

  • Pass custom API options:
    Torchlight::highlight('python', '...', [
        'showLineNumbers' => true,
        'tabSize' => 4,
    ]);
    

Gotchas and Tips

Pitfalls

  1. API Token Leaks:

    • Never commit .env with TORCHLIGHT_TOKEN. Use Laravel’s .env.example to document required vars.
    • Fix: Use env() in config or a secure secrets manager.
  2. Cache Invalidation:

    • Cached blocks persist until TTL expires. Manually clear with:
      Torchlight::clearCache();
      
    • Tip: Use cache tags for granular invalidation (e.g., per-user guides).
  3. Large Code Blocks:

    • API has payload size limits (~100KB). For larger files:
      • Split into chunks and highlight separately.
      • Use highlightFile() with chunked reading.
  4. Blade Component Registration:

    • If @torchlight directive doesn’t work:
      • Ensure 'blade_components' => true in torchlight.php.
      • Fix: Re-run php artisan torchlight:install or manually register the component in AppServiceProvider.
  5. Livewire Version Conflicts:

    • Livewire 1: Not supported (see changelog v0.5.3).
    • Fix: Upgrade to Livewire 2/3 or use manual middleware registration.
  6. Tabs vs. Spaces:

    • Torchlight converts tabs to spaces by default (tab_width in config).
    • Disable conversion:
      'tab_width' => false,
      
    • Tip: Set tab_width: 4 for consistent indentation.
  7. Post-Processor Timing:

    • Post-processors run after rendering but before sending to browser.
    • Gotcha: They don’t run during view compilation (e.g., php artisan view:cache).

Debugging Tips

  1. API Requests:

    • Enable HTTP logging in config/torchlight.php:
      'debug' => env('TORCHLIGHT_DEBUG', false),
      
    • Check Laravel logs for failed requests (e.g., rate limits, invalid tokens).
  2. Cache Issues:

    • Clear cache manually:
      php artisan cache:clear
      php artisan view:clear
      
    • Verify cache driver is writable (e.g., storage/framework/cache for file driver).
  3. Language Detection:

    • Torchlight auto-detects language if not specified. Force a language for consistency:
      @torchlight(['language' => 'php'], '<?php ...')
      
  4. Blade Parsing Errors:

    • Ensure the @torchlight directive is properly closed. Use:
      @torchlight(['language' => 'js'], 'code')->withAttributes(['class' => 'compact'])
      

Extension Points

  1. Custom Themes:

  2. Snippet Directories:

    • Configure in torchlight.php:
      'snippet_directories' => [
          resource_path('views/snippets'),
          base_path('snippets'),
      ],
      
    • Use Case: Store reusable code blocks (e.g., API response examples) in files and highlight via:
      @torchlightSnippet('api-response.json')
      
  3. Macros for Blocks:

    • Extend Block to add domain-specific logic:
      \Torchlight\Block::macro('highlightAsDiff', function ($oldCode, $newCode) {
          $this->addPostProcessor(function ($html) use ($oldCode, $newCode) {
              return Torchlight::highlight('diff', "{$oldCode}\n\n{$newCode}");
          });
      });
      
  4. Middleware for Livewire:

    • Manually register middleware for custom Livewire setups:
      Torchlight::registerLivewireMiddleware();
      
  5. Environment-Specific Config:

    • Override config per environment:
      Torchlight::setConfigUsing(function () {
          return config('torchlight', []) + [
              'theme' => env('APP_ENV') === 'production' ? 'minimal' : 'palenight',
          ];
      });
      

Performance Optimizations

  1. Cache TTL:
    • Short-lived content (e.g., user-generated code
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport