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

Highlight Laravel Package

tempest/highlight

Fast, extensible server-side syntax highlighting for PHP and other languages. Install via Composer and use the Highlighter to parse code into highlighted output for rendering in docs, blogs, or apps, with a focus on performance and customization.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tempest/highlight
    

    Add to composer.json if using Laravel’s autoloader.

  2. First Use Case: Highlight PHP, GraphQL, or Svelte code in a Blade template:

    use Tempest\Highlight\Highlighter;
    
    $highlighter = new Highlighter();
    $highlighted = $highlighter->parse($svelteCode, 'svelte'); // New in 2.25.0
    

    Render in Blade:

    <pre>{{ $highlighted }}</pre>
    
  3. Key Entry Points:

    • Highlighter::parse($code, $language): Core method (now supports svelte alongside graphql).
    • Highlighter::getLanguages(): List all supported languages (includes svelte).
    • Official Docs: Reference for languages/themes.

Implementation Patterns

Core Workflows

1. Blade Integration

Pattern: Use a Blade directive for reusable highlighting (now with Svelte support):

// app/Providers/AppServiceProvider.php
Blade::directive('highlight', function ($expression) {
    $highlighter = app(Highlighter::class);
    return "<?php echo {$highlighter}->parse({$expression}, 'svelte'); ?>"; // Updated for Svelte
});

Usage:

@highlight($svelteComponent)

2. API Responses

Pattern: Return highlighted Svelte components in JSON APIs:

return response()->json([
    'component' => $highlighter->parse($svelteCode, 'svelte'),
]);

3. Dynamic Language Detection

Pattern: Infer language from file extension (now includes .svelte):

$language = match (pathinfo($filePath, PATHINFO_EXTENSION)) {
    'svelte' => 'svelte',
    'graphql' => 'graphql',
    default => $defaultLanguage,
};
$highlighted = $highlighter->parse(file_get_contents($filePath), $language);

4. Theming for Svelte

Pattern: Apply themes to Svelte components:

$highlighter = new Highlighter(['theme' => 'catppuccin']);
$highlighted = $highlighter->parse($svelteCode, 'svelte');

5. Svelte-Specific Highlighting

Pattern: Highlight Svelte syntax (components, directives, stores):

$component = <<<SVELTE
<script>
  let count = 0;
  $: doubled = count * 2;
</script>

<button on:click={() => count++}>
  Clicked {count} {doubled > 10 ? 'times' : 'time'}
</button>
SVELTE;
$highlighted = $highlighter->parse($component, 'svelte');

Laravel-Specific Integrations

1. Service Provider Binding

Pattern: Bind Highlighter as a singleton (unchanged):

// config/services.php
'highlight' => Tempest\Highlight\Highlighter::class,

// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->singleton(Tempest\Highlight\Highlighter::class);
}

2. Form Request Validation

Pattern: Highlight Svelte code in validation errors:

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($validator->errors()->has('svelte_code')) {
            $highlighted = app(Highlighter::class)->parse(
                $validator->errors()->first('svelte_code'),
                'svelte'
            );
            // Log or display $highlighted
        }
    });
}

3. Nova Customization

Pattern: Highlight Svelte in Nova tooltips:

use Tempest\Highlight\Highlighter;

public function fields(Request $request)
{
    return [
        Text::make('Svelte Component')
            ->asHtml()
            ->content(fn () => app(Highlighter::class)->parse($this->component, 'svelte')),
    ];
}

4. Event Listeners

Pattern: Highlight Svelte in event payloads:

public function handle(SvelteComponentRendered $event)
{
    $highlightedCode = app(Highlighter::class)->parse(
        $event->code,
        'svelte'
    );
    // Log or notify with $highlightedCode
}

Gotchas and Tips

Pitfalls

1. Language Auto-Detection Failures

  • Issue: parse() may return unhighlighted code if the language isn’t registered (e.g., svelte must be explicit).
  • Fix: Always specify the language:
    $highlighted = $highlighter->parse($code, 'svelte'); // Not 'text/svelte'
    
  • Debug: Verify svelte is in supported languages:
    dd($highlighter->getLanguages()); // Should include 'svelte'
    

2. Blade Whitespace Conflicts

  • Issue: Highlighted output may break Blade whitespace control.
  • Fix: Use {{ !! }} or wrap in a component:
    <x-highlight :code="$svelteComponent" language="svelte" />
    

3. Performance with Large Svelte Components

  • Issue: Highlighting large Svelte files may cause timeouts.
  • Fix: Stream or chunk the code:
    $highlighter->parse(file($largeSvelteFile), 'svelte'); // Processes line-by-line
    

4. Svelte-Specific Syntax Quirks

  • Issue: Custom Svelte directives or stores may not highlight correctly.
  • Fix: Extend the Svelte language definition:
    $highlighter->addLanguage(new CustomSvelteLanguage());
    

5. Terminal Styles in Web Context

  • Issue: Terminal styles may render as text in browsers.
  • Fix: Use style: 'html' for web output:
    $highlighter->parse($svelteCode, 'svelte', ['style' => 'html']);
    

Debugging Tips

1. Inspect Svelte Tokens

Use debug() to inspect Svelte parsing:

$tokens = $highlighter->tokenize($svelteCode, 'svelte');
dd($tokens); // Analyze token structure (e.g., components, directives, stores)

2. Benchmarking

Compare performance with PHPBench:

$highlighter->parse($benchmarkComponent, 'svelte'); // Measure execution time

3. Theme Debugging for Svelte

Override theme variables for Svelte:

$highlighter->setThemeVariables([
    'svelte_tag' => '#FF0000', // Force red for Svelte tags
    'svelte_directive' => '#00FF00',
]);

4. CI/CD Integration

Add a test to verify Svelte highlighting:

public function testSvelteHighlighting()
{
    $highlighted = $this->app->make(Highlighter::class)->parse(
        '<script>let count = 0;</script><button>{count}</button>',
        'svelte'
    );
    $this->assertStringContainsString('<span class="svelte_tag">&lt;script&gt;</span>', $highlighted);
}

Extension Points

1. Custom Svelte Renderers

Extend \Tempest\Highlight\Renderer\Renderer for Svelte-specific output (e.g., Markdown):

class SvelteMarkdownRenderer extends Renderer
{
    protected function renderToken(Token $token): string
    {
        return match ($token->type) {
            'svelte_tag' => '```svelte\n' . $token->value . '\n```',
            'svelte_directive' => '!' . $token->value,
            default => $token->value,
        };
    }
}

Register with:

$highlighter->addRenderer('svelte-mark
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