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. 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**:
   ```bash
   composer require torchlight/torchlight-laravel
  1. Publish the config:
    php artisan torchlight:install
    
  2. Configure .env:
    TORCHLIGHT_TOKEN=your_api_token_from_torchlight.dev
    TORCHLIGHT_THEME=material-theme-palenight
    TORCHLIGHT_CACHE_DRIVER=file  # or redis, database, etc.
    
  3. First use case: Highlight code in a Blade view:
    @torchlight('php', '<?php echo "Hello, Torchlight!";')
    

Where to Look First

  • Facade: Torchlight facade for direct API calls (e.g., Torchlight::highlight()).
  • Blade Directives: @torchlight for inline highlighting or @torchlightBlock for reusable blocks.
  • Config File: config/torchlight.php for customizing themes, cache, and API options.
  • Documentation: Focus on the Torchlight API docs for language/feature support.

Implementation Patterns

Core Workflows

1. Inline Code Highlighting

  • Blade Directive:
    @torchlight('javascript', 'console.log("Hello");')
    
  • Facade Method:
    $highlighted = Torchlight::highlight('python', 'print("Hello")');
    echo $highlighted;
    

2. Reusable Code Blocks

  • Named Blocks (cached):
    @torchlightBlock('my-python-code', 'python', 'def hello(): ...')
    
  • Dynamic Blocks (non-cached):
    @torchlightBlock('dynamic-' . $id, 'javascript', $code)
    

3. File-Based Highlighting

  • Highlight entire files (e.g., for docs):
    $highlighted = Torchlight::file('path/to/Controller.php');
    

4. Theming & Dark Mode

  • Multi-theme support (configurable per request):
    Torchlight::highlight('php', $code, ['theme' => 'dracula']);
    
  • Environment-based themes:
    $theme = app()->environment('local') ? 'dark+' : 'light+';
    Torchlight::setConfig(['theme' => $theme]);
    

5. Livewire Integration

  • Dynamic updates without full page reloads:
    use Torchlight\Livewire\HandlesTorchlight;
    
    class MyComponent extends Component {
        use HandlesTorchlight;
    
        public function highlightCode() {
            $this->highlight('javascript', $this->codeInput);
        }
    }
    

6. Post-Processing

  • Modify output before rendering (e.g., add line numbers):
    Torchlight::addPostProcessor(function ($html, $block) {
        return '<div class="line-numbers">' . $html . '</div>';
    });
    
  • Per-block processors:
    Torchlight::highlight('php', $code, [
        'postProcessors' => [fn($html) => str_replace(' ', '&nbsp;', $html)]
    ]);
    

7. Caching Strategies

  • Global cache: Configure cache.driver and cache.ttl in torchlight.php.
  • Manual cache control:
    Torchlight::clearCache(); // Clear all cached blocks
    Torchlight::clearBlock('my-python-code'); // Clear specific block
    

Integration Tips

Blade Components

  • Customize the component by extending the default:
    // app/View/Components/TorchlightComponent.php
    use Torchlight\Blade\TorchlightComponent as BaseComponent;
    
    class TorchlightComponent extends BaseComponent {
        public function class($class) {
            $this->attributes['class'] = $class;
            return $this;
        }
    }
    
  • Register globally in AppServiceProvider:
    Blade::component('torchlight', \App\View\Components\TorchlightComponent::class);
    

API Options

  • Pass custom options to the Torchlight API:
    Torchlight::highlight('php', $code, [
        'options' => [
            'showLineNumbers' => true,
            'tabWidth' => 4,
        ]
    ]);
    

Snippet Directories

  • Custom snippet paths for reusable code:
    Torchlight::setSnippetDirectories([
        resource_path('snippets/php'),
        resource_path('snippets/javascript'),
    ]);
    

Livewire + Alpine.js

  • Dynamic updates with Alpine.js:
    <div x-data="{ code: 'console.log(\'Hello\')' }">
        @torchlight('javascript', $code)
        <button @click="code = 'alert(\'Updated!\')'">Update</button>
    </div>
    

Gotchas and Tips

Pitfalls

  1. API Token Leaks

    • Risk: Hardcoding TORCHLIGHT_TOKEN in .env may expose it in logs or Git history.
    • Fix: Use Laravel’s environment variables and validate the token in AppServiceProvider:
      if (empty(config('torchlight.token'))) {
          throw new \RuntimeException('Torchlight API token not configured.');
      }
      
  2. Cache Invalidation

    • Issue: Cached blocks may serve stale content if the underlying code changes.
    • Fix: Use versioned block IDs or clear cache manually:
      Torchlight::clearBlock('my-code-' . md5($code));
      
  3. Tab Replacement

    • Problem: Tabs are converted to spaces by default, which may break indentation-sensitive languages (e.g., YAML).
    • Fix: Disable tab replacement:
      Torchlight::highlight('yaml', $code, ['tabWidth' => false]);
      
  4. Livewire Version Conflicts

    • Issue: Livewire V1/V2/V3 have different middleware requirements.
    • Fix: Ensure compatibility by checking the Livewire version in AppServiceProvider:
      if (version_compare(\Livewire\Livewire::VERSION, '2.0', '<')) {
          Torchlight::registerLivewireMiddleware();
      }
      
  5. Memory Leaks in Octane

    • Issue: Long-running Octane processes may accumulate cached blocks.
    • Fix: Use a short TTL or clear cache periodically:
      Torchlight::setConfig(['cache.ttl' => 3600]); // 1 hour
      
  6. Blade Component Registration

    • Problem: @torchlight directive may not work if Blade components are disabled.
    • Fix: Ensure blade_components is true in torchlight.php or register manually:
      Torchlight::registerBladeComponents();
      

Debugging

  1. API Requests

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

    • Verify cache keys with:
      Torchlight::getCacheKey('php', '<?php echo 1;');
      
    • Clear cache and retry to test live updates.
  3. Language Detection

    • Issue: Torchlight may misidentify languages (e.g., text/x-markdown vs. markdown).
    • Fix: Explicitly specify the language:
      @torchlight('text/x-markdown', '```php\n...')
      

Extension Points

  1. Macroable Blocks

    • Extend Block functionality:
      \Torchlight\Block::macro('addLineNumbers', function ($html) {
          return '<div class="line-numbers">' . $html . '</div>';
      });
      
    • Usage:
      $block = Torchlight::highlight('php', $code);
      echo $block->addLineNumbers();
      
  2. Custom Cache Drivers

    • Implement a custom cache store by extending Torchlight\Cache\CacheStore:
      class MyCacheStore implements \Torchlight\Cache\CacheStore {
          public function get($key) { ... }
          public function put($key, $value, $ttl) { ... }
          public function forget($key) { ... }
      }
      
    • Register in AppServiceProvider:
      Torchlight::setCacheStore(new My
      
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope