PHP code example of rafaelogic / writr

1. Go to this page and download the library: Download rafaelogic/writr library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rafaelogic / writr example snippets


// In your Controller
public function store(Request $request)
{
    $validated = $request->validate([
        'title' => 'ture
    $contentData = json_decode($validated['content'], true);
    if (!isset($contentData['blocks']) || empty($contentData['blocks'])) {
        return back()->withErrors(['content' => 'Content cannot be empty.']);
    }
    
    Document::create($validated);
    
    return redirect()->route('documents.index')
        ->with('success', 'Document saved successfully!');
}

// config/writr.php
'editor' => [
    'placeholder' => 'Start writing your story...',
    'autofocus' => false,
    'readonly' => false,
    'min_height' => 300,
    'max_height' => null,
    'spellcheck' => true,
],

'tools' => [
    'header' => [
        'enabled' => true,
        'config' => [
            'levels' => [1, 2, 3, 4, 5, 6],
            'defaultLevel' => 2,
            'allowAnchor' => true,
        ],
    ],
    'image' => [
        'enabled' => true,
        'config' => [
            'endpoints' => [
                'byFile' => route('writr.upload.image'),
                'byUrl' => route('writr.upload.url'),
            ],
            'additionalRequestData' => [
                '_token' => csrf_token(),
            ],
            'field' => 'image',
            'types' => 'image/*',
            'captionPlaceholder' => 'Enter caption...',
        ],
    ],
    'table' => [
        'enabled' => true,
        'config' => [
            'rows' => 2,
            'cols' => 3,
            'withHeadings' => true,
        ],
    ],
    // ... more tools
],

'features' => [
    'drag_drop' => true,
    'undo_redo' => true,
    'dark_mode' => [
        'enabled' => true,
        'default' => 'auto', // 'light', 'dark', 'auto'
        'storage_key' => 'writr-theme',
    ],
    'live_preview' => true,
    'table_of_contents' => [
        'enabled' => true,
        'levels' => [1, 2, 3, 4, 5, 6],
        'position' => 'right', // 'left', 'right', 'top'
    ],
    'word_count' => [
        'enabled' => true,
        'position' => 'bottom', // 'top', 'bottom'
        'show_characters' => true,
        'show_words' => true,
        'show_reading_time' => true,
    ],
    'auto_save' => [
        'enabled' => false,
        'interval' => 30000, // 30 seconds
        'endpoint' => null,
        'debounce' => 1000,
    ],
],

// config/writr.php
'uploads' => [
    'disk' => 'public',
    'path' => 'writr/uploads',
    'max_file_size' => 10 * 1024 * 1024, // 10MB
    'allowed_extensions' => [
        'images' => ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'],
        'documents' => ['pdf', 'doc', 'docx', 'txt', 'rtf'],
        'archives' => ['zip', 'rar', '7z'],
    ],
    'image_optimization' => [
        'enabled' => true,
        'quality' => 85,
        'max_width' => 1920,
        'max_height' => 1080,
    ],
],

// routes/web.php
Route::post('/custom-upload', [CustomUploadController::class, 'handle'])
    ->name('custom.upload')
    ->middleware(['auth', 'throttle:60,1']);

// CustomUploadController.php
public function handle(Request $request)
{
    $request->validate([
        'image' => ',
        'file' => [
            'url' => Storage::url($path),
            'name' => $file->getClientOriginalName(),
            'size' => $file->getSize(),
            'caption' => '',
        ]
    ]);
}

use Rafaelogic\Writr\Services\WritrService;

class DocumentController extends Controller
{
    public function __construct(
        private WritrService $writr
    ) {}
    
    public function show(Document $document)
    {
        $content = json_decode($document->content, true);
        
        // Convert to HTML for display
        $html = $this->writr->toHtml($content);
        
        // Convert to Markdown
        $markdown = $this->writr->toMarkdown($content);
        
        // Extract plain text (for search, etc.)
        $plainText = $this->writr->toText($content);
        
        // Get word count and reading time
        $stats = $this->writr->getContentStats($content);
        // Returns: ['words' => 245, 'characters' => 1428, 'reading_time' => 1.2]
        
        // Generate table of contents
        $toc = $this->writr->generateToc($content);
        
        return view('documents.show', [
            'document' => $document,
            'html' => $html,
            'stats' => $stats,
            'toc' => $toc,
        ]);
    }
}

// Custom validation rule
$request->validate([
    'content' => [
        ' $data = json_decode($value, true);
            
            // Validate structure
            if (!isset($data['blocks']) || !is_array($data['blocks'])) {
                $fail('Invalid content structure.');
            }
            
            // Validate content is not empty
            if (empty($data['blocks'])) {
                $fail('Content cannot be empty.');
            }
            
            // Validate each block
            foreach ($data['blocks'] as $block) {
                if (!isset($block['type']) || !isset($block['data'])) {
                    $fail('Invalid block structure.');
                }
            }
        }
    ]
]);

// Make content searchable
class Document extends Model
{
    protected $casts = [
        'content' => 'array',
    ];
    
    // Accessor for search indexing
    public function getSearchableContentAttribute()
    {
        return app(WritrService::class)->toText($this->content);
    }
    
    // Scope for searching
    public function scopeSearch($query, $term)
    {
        return $query->whereRaw(
            "JSON_UNQUOTE(JSON_EXTRACT(content, '$.blocks[*].data.text')) LIKE ?",
            ["%{$term}%"]
        );
    }
}

// config/writr.php
'theme' => [
    'css_variables' => [
        '--writr-primary-color' => '#your-color',
        '--writr-bg-color' => '#your-bg-color',
    ],
],

// config/writr.php - Production settings
'performance' => [
    'lazy_load_tools' => true,
    'cache_assets' => true,
    'minify_output' => true,
    'debounce_delay' => 300,
    'memory_monitoring' => env('APP_ENV') === 'local',
],

// Image optimization
'uploads' => [
    'image_optimization' => [
        'enabled' => true,
        'quality' => 85,
        'progressive' => true,
        'strip_metadata' => true,
    ],
],
bash
# Publish configuration file (recommended for customization)
php artisan vendor:publish --tag=writr-config

# Publish all Blade views (rarely needed)
php artisan vendor:publish --tag=writr-views

# Publish compiled assets (CSS/JS) to public directory
php artisan vendor:publish --tag=writr-assets

# Publish all package files
php artisan vendor:publish --provider="Rafaelogic\Writr\WritrServiceProvider"
bash
php artisan vendor:publish --tag=writr-config