Weave 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. Highlight code blocks with VS Code-compatible themes and zero JavaScript. Includes caching, configurable themes and host, and Blade components/directives. Requires a Torchlight API token (free for personal/open source).

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.
    

First Use Case: Highlighting Code in Blade

Use the @torchlight directive in your Blade templates:

@torchlight('php', '<?php echo "Hello, Torchlight!";')

This will render a syntax-highlighted code block with the specified language (php).


Implementation Patterns

1. Blade Integration

  • Default Blade Component: The package auto-registers a Blade component (torchlight) if blade_components is true in config.
  • Custom Directives: Extend functionality by creating custom directives:
    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        Blade::directive('highlight', function ($expression) {
            return "<?php echo Torchlight::highlight($expression); ?>";
        });
    }
    
    Usage:
    @highlight('javascript', 'console.log("Custom directive!");')
    

2. Dynamic Themes

  • Theme Switching: Use middleware or user preferences to toggle themes:
    // app/Http/Middleware/SwitchTheme.php
    public function handle($request, Closure $next)
    {
        config(['torchlight.theme' => $request->user()->prefers_dark_mode ? 'dracula' : 'material-theme-palenight']);
        return $next($request);
    }
    

3. Caching Strategies

  • Per-Request Caching: Leverage Laravel’s cache drivers (e.g., Redis) for high-traffic sites:
    // config/torchlight.php
    'cache' => env('TORCHLIGHT_CACHE_DRIVER', 'redis'),
    'cache_ttl' => 60 * 60, // 1 hour
    
  • Cache Invalidation: Clear cache for specific blocks:
    Torchlight::clearCache('block_id_123');
    

4. Livewire Integration

  • Real-Time Updates: Use Torchlight with Livewire for dynamic code highlighting:
    // app/Http/Livewire/CodeEditor.php
    public function render()
    {
        return view('livewire.code-editor', [
            'highlightedCode' => Torchlight::highlight('javascript', $this->code),
        ]);
    }
    

5. Post-Processing

  • Modify Output: Hook into the rendered response:
    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        Torchlight::addPostProcessor(function ($html, $block) {
            return str_replace('<div class="line">', '<div class="line" data-block-id="'.$block->id.'">', $html);
        });
    }
    

6. File Processing

  • Highlight Entire Files: Process files from disk:
    $highlighted = Torchlight::highlightFile('path/to/file.php');
    
  • Custom Directories: Configure snippet directories:
    // config/torchlight.php
    'snippet_directories' => [storage_path('app/snippets')],
    

7. Macros for Blocks

  • Extend Block Functionality: Use macros to add custom methods:
    Torchlight\Block::macro('addLineNumbers', function () {
        $this->options['lineNumbers'] = true;
        return $this;
    });
    
    Usage:
    @torchlight('php')->addLineNumbers()
        <?php echo "Line numbers enabled!"; ?>
    @endtorchlight
    

Gotchas and Tips

Pitfalls

  1. API Rate Limiting:

    • Torchlight’s free tier has rate limits. Cache aggressively or use a fallback for failed requests:
      Torchlight::setFallbackResponse('<div class="fallback">Code highlighting unavailable.</div>');
      
    • Monitor API usage via TORCHLIGHT_API_REQUESTS env variable (if supported).
  2. Tab Replacement:

    • By default, tabs are converted to spaces. Disable this in config:
      'tab_width' => false,
      
    • Or override per block:
      Torchlight::highlight('javascript', $code, ['tab_width' => false]);
      
  3. Livewire Version Conflicts:

    • Ensure compatibility with your Livewire version (v2, v3, or Octane). Test in staging:
      php artisan torchlight:test-livewire
      
  4. Blade Component Registration:

    • If blade_components is false, manually register the component:
      Blade::component('torchlight', Torchlight\Blade::class);
      
  5. Cache Stale Data:

    • Clear cache when themes or tokens change:
      php artisan cache:clear
      php artisan torchlight:clear-cache
      

Debugging Tips

  1. Log API Responses:

    • Enable debug mode in config:
      'debug' => env('TORCHLIGHT_DEBUG', false),
      
    • Check logs for failed requests or malformed payloads.
  2. Validate Token:

    • Test your token with a direct API call:
      curl -X POST https://api.torchlight.dev/highlight \
           -H "Authorization: Bearer $TORCHLIGHT_TOKEN" \
           -d '{"code":"<?php echo 1; ?>","language":"php"}'
      
  3. Inspect Blocks:

    • Dump block IDs to debug rendering:
      dd(Torchlight::getBlocks());
      
  4. Check for Trailing Spaces:

    • If highlights appear broken, ensure no trailing spaces in code snippets (fixed in v0.5.9).

Extension Points

  1. Custom Themes:

    • Upload themes to Torchlight and reference them in config:
      'theme' => 'your-custom-theme-name',
      
  2. Language Detection:

    • Auto-detect languages using linguist or highlight.js:
      Torchlight::highlight($code, Torchlight\LanguageDetector::detect($code));
      
  3. Git Diff Highlighting:

    • Use Torchlight’s diff language mode:
      @torchlight('diff', '@@ -1 +1 @@
      -old code
      +new code')
      
  4. Dark/Light Mode:

    • Dynamically switch themes based on user preferences:
      $theme = $request->user()->prefers_dark_mode ? 'dracula' : 'material-theme-palenight';
      Torchlight::setTheme($theme);
      
  5. Custom Fallbacks:

    • Provide static HTML fallbacks for offline use:
      Torchlight::setFallbackResponse('<pre><code class="fallback">'.$code.'</code></pre>');
      

Performance Optimizations

  1. Cache Headers:

    • Set Cache-Control headers for static code blocks:
      Torchlight::setCacheHeaders(['public', 'max-age=31536000']);
      
  2. Batch Processing:

    • Process multiple blocks in a single request (if API supports it):
      Torchlight::highlightBatch([
          ['code' => $code1, 'language' => 'php'],
          ['code' => $code2, 'language' => 'javascript'],
      ]);
      
  3. Lazy Loading:

    • Load Torchlight JS/CSS only when needed (e.g., via Alpine.js):
      <div x-data="{ loadTorchlight: false }" @click="loadTorchlight = true">
          @if($loadTorchlight)
              @torchlight('javascript', 'console.log("Lazy loaded!");')
          @endif
      </div>
      

Security Considerations

  1. Sanitize Input:

    • Escape user-provided code to prevent XSS:
      $safeCode = htmlspecialchars($userInput, ENT_QUOTES, 'UTF-8');
      Torchlight::highlight('php', $safeCode);
      
  2. Token Storage:

    • Use Laravel’s env() or Vault for sensitive tokens:
      TORCHLIGHT_TOKEN=${VAULT_TORCHLIGHT_TOKEN}
      
  3. Rate Limiting:

    • Implement middleware to throttle requests:
      // app/Http/Middleware/ThrottleTorchlight.php
      public function handle($request, Closure $next)
      {
          if ($request->
      
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.
xiloryx/log-collector
a21ns1g4ts/filament-stripe
la-php/laravel-admin
artisan-build/community-prompts
vleroy/smart
ayles-software/laravel-australian-public-holidays
cboxdk/laravel-id-spatie
cboxdk/laravel-id-billing
cboxdk/laravel-id-billing-bridge
simple-as-fuck/php-performance-log
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk