All files / src/providers FilamentEnhancedProvider.ts

0% Statements 0/132
0% Branches 0/87
0% Functions 0/28
0% Lines 0/118

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
// src/providers/FilamentEnhancedProvider.ts
// Full Filament v4 support: resource generator, relation manager, inlay hints
import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import type { CacheManager } from '../cache/CacheManager';
import type { ModelDefinition } from '../types';
 
// ─── Filament Resource Generator ─────────────────────────────────────────
 
export class FilamentResourceGenerator {
  constructor(
    private readonly workspaceRoot: string,
    private readonly cache: CacheManager
  ) {}
 
  async generateResource(): Promise<void> {
    const index = this.cache.getIndex();
    const models = Array.from(index.models.values());
 
    let modelName: string | undefined;
    if (models.length > 0) {
      const picked = await vscode.window.showQuickPick(
        models.map((m) => ({ label: m.className, description: m.namespace, model: m })),
        { placeHolder: 'Select model for Filament resource' }
      );
      modelName = picked?.label;
    }
    if (!modelName) {
      modelName = await vscode.window.showInputBox({
        prompt: 'Model class name (e.g. Post)',
        placeHolder: 'Post',
        validateInput: (v) => v.trim() ? null : 'Required',
      });
    }
    if (!modelName) { return; }
 
    const model = models.find((m) => m.className === modelName);
    const options = await vscode.window.showQuickPick([
      { label: 'Simple Resource', value: 'simple' },
      { label: 'Full Resource (with pages)', value: 'full' },
    ], { placeHolder: 'Resource type' });
    if (!options) { return; }
 
    await this.writeResource(modelName, model, options.value === 'simple');
  }
 
  async generateRelationManager(): Promise<void> {
    const resourceName = await vscode.window.showInputBox({
      prompt: 'Parent resource (e.g. PostResource)',
      placeHolder: 'PostResource',
      validateInput: (v) => v.trim() ? null : 'Required',
    });
    if (!resourceName) { return; }
 
    const relationName = await vscode.window.showInputBox({
      prompt: 'Relationship name (e.g. comments)',
      placeHolder: 'comments',
      validateInput: (v) => v.trim() ? null : 'Required',
    });
    if (!relationName) { return; }
 
    const className = `${capitalize(relationName)}RelationManager`;
    const content = this.buildRelationManager(resourceName, relationName, className);
    const dir = path.join(this.workspaceRoot, 'app', 'Filament', 'Resources', `${resourceName}`, 'RelationManagers');
    const filePath = path.join(dir, `${className}.php`);
    await this.writeFile(filePath, content);
  }
 
  // ─── Resource Content ─────────────────────────────────────────────────
 
  private async writeResource(modelName: string, model: ModelDefinition | undefined, simple: boolean): Promise<void> {
    const resourceName = `${modelName}Resource`;
    const ns = 'App\\Filament\\Resources';
    const modelNs = model?.namespace ?? 'App\\Models';
 
    const formFields = this.inferFormFields(model);
    const tableColumns = this.inferTableColumns(model);
 
    const content = `<?php
 
namespace ${ns};
 
use ${modelNs}\\${modelName};
use App\\Filament\\Resources\\${resourceName}\\Pages;
use Filament\\Forms;
use Filament\\Forms\\Form;
use Filament\\Resources\\Resource;
use Filament\\Tables;
use Filament\\Tables\\Table;
use Illuminate\\Database\\Eloquent\\Builder;
use Illuminate\\Database\\Eloquent\\SoftDeletingScope;
 
class ${resourceName} extends Resource
{
    protected static ?string $model = ${modelName}::class;
 
    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
 
    protected static ?string $navigationGroup = null;
 
    protected static ?int $navigationSort = null;
 
    public static function form(Form $form): Form
    {
        return $form
            ->schema([
${formFields}            ]);
    }
 
    public static function table(Table $table): Table
    {
        return $table
            ->columns([
${tableColumns}            ])
            ->filters([
                Tables\\Filters\\TrashedFilter::make(),
            ])
            ->actions([
                Tables\\Actions\\ViewAction::make(),
                Tables\\Actions\\EditAction::make(),
                Tables\\Actions\\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\\Actions\\BulkActionGroup::make([
                    Tables\\Actions\\DeleteBulkAction::make(),
                    Tables\\Actions\\ForceDeleteBulkAction::make(),
                    Tables\\Actions\\RestoreBulkAction::make(),
                ]),
            ]);
    }
 
    public static function getRelations(): array
    {
        return [
            //
        ];
    }
 
    public static function getPages(): array
    {
        return [
            'index'  => Pages\\List${modelName}::route('/'),
            'create' => Pages\\Create${modelName}::route('/create'),
            'view'   => Pages\\View${modelName}::route('/{record}'),
            'edit'   => Pages\\Edit${modelName}::route('/{record}/edit'),
        ];
    }
 
    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }
}
`;
 
    const resourceDir = path.join(this.workspaceRoot, 'app', 'Filament', 'Resources');
    await this.writeFile(path.join(resourceDir, `${resourceName}.php`), content);
 
    if (!simple) {
      await this.writeResourcePages(modelName, ns);
    }
  }
 
  private inferFormFields(model: ModelDefinition | undefined): string {
    if (!model || model.columns.length === 0) {
      return `                Forms\\Components\\TextInput::make('name')->required(),\n`;
    }
    const excluded = new Set(['id', 'created_at', 'updated_at', 'deleted_at']);
    return model.columns
      .filter((c) => !excluded.has(c.name) && model.fillable.includes(c.name))
      .slice(0, 8)
      .map((col) => {
        const field = this.columnToFormField(col.name, col.type);
        return `                ${field},`;
      })
      .join('\n') + '\n';
  }
 
  private inferTableColumns(model: ModelDefinition | undefined): string {
    if (!model || model.columns.length === 0) {
      return `                Tables\\Columns\\TextColumn::make('id')->sortable(),\n`;
    }
    const show = ['id', 'name', 'title', 'email', 'status', 'created_at'];
    const cols = model.columns.filter((c) => show.includes(c.name) || model.columns.indexOf(c) < 5);
    return cols.slice(0, 6).map((col) => {
      const tc = col.name.includes('date') || col.name.includes('_at')
        ? `Tables\\Columns\\TextColumn::make('${col.name}')->dateTime()->sortable()`
        : `Tables\\Columns\\TextColumn::make('${col.name}')->searchable()->sortable()`;
      return `                ${tc},`;
    }).join('\n') + '\n';
  }
 
  private columnToFormField(name: string, type: string): string {
    const t = type.toLowerCase();
    if (t.includes('text') || name.includes('description') || name.includes('body') || name.includes('content')) {
      return `Forms\\Components\\Textarea::make('${name}')->columnSpanFull()`;
    }
    if (t.includes('bool')) {
      return `Forms\\Components\\Toggle::make('${name}')`;
    }
    if (t.includes('date') || t.includes('time')) {
      return `Forms\\Components\\DateTimePicker::make('${name}')`;
    }
    if (name.includes('email')) {
      return `Forms\\Components\\TextInput::make('${name}')->email()->required()`;
    }
    if (name.includes('password')) {
      return `Forms\\Components\\TextInput::make('${name}')->password()->required()`;
    }
    if (t.includes('int') || t.includes('decimal') || t.includes('float')) {
      return `Forms\\Components\\TextInput::make('${name}')->numeric()`;
    }
    if (name.includes('color') || name.includes('colour')) {
      return `Forms\\Components\\ColorPicker::make('${name}')`;
    }
    if (name.endsWith('_id')) {
      const rel = name.slice(0, -3);
      return `Forms\\Components\\Select::make('${name}')->relationship('${rel}', 'name')`;
    }
    return `Forms\\Components\\TextInput::make('${name}')->maxLength(255)`;
  }
 
  private async writeResourcePages(modelName: string, ns: string): Promise<void> {
    const pages = [
      { name: `List${modelName}`, content: this.buildListPage(modelName, ns) },
      { name: `Create${modelName}`, content: this.buildCreatePage(modelName, ns) },
      { name: `Edit${modelName}`, content: this.buildEditPage(modelName, ns) },
      { name: `View${modelName}`, content: this.buildViewPage(modelName, ns) },
    ];
    const pagesDir = path.join(
      this.workspaceRoot, 'app', 'Filament', 'Resources', `${modelName}Resource`, 'Pages'
    );
    for (const page of pages) {
      await this.writeFile(path.join(pagesDir, `${page.name}.php`), page.content);
    }
  }
 
  private buildListPage(model: string, ns: string): string {
    return `<?php\n\nnamespace ${ns}\\${model}Resource\\Pages;\n\nuse ${ns}\\${model}Resource;\nuse Filament\\Actions;\nuse Filament\\Resources\\Pages\\ListRecords;\n\nclass List${model} extends ListRecords\n{\n    protected static string $resource = ${model}Resource::class;\n\n    protected function getHeaderActions(): array\n    {\n        return [\n            Actions\\CreateAction::make(),\n        ];\n    }\n}\n`;
  }
 
  private buildCreatePage(model: string, ns: string): string {
    return `<?php\n\nnamespace ${ns}\\${model}Resource\\Pages;\n\nuse ${ns}\\${model}Resource;\nuse Filament\\Resources\\Pages\\CreateRecord;\n\nclass Create${model} extends CreateRecord\n{\n    protected static string $resource = ${model}Resource::class;\n}\n`;
  }
 
  private buildEditPage(model: string, ns: string): string {
    return `<?php\n\nnamespace ${ns}\\${model}Resource\\Pages;\n\nuse ${ns}\\${model}Resource;\nuse Filament\\Actions;\nuse Filament\\Resources\\Pages\\EditRecord;\n\nclass Edit${model} extends EditRecord\n{\n    protected static string $resource = ${model}Resource::class;\n\n    protected function getHeaderActions(): array\n    {\n        return [\n            Actions\\ViewAction::make(),\n            Actions\\DeleteAction::make(),\n            Actions\\ForceDeleteAction::make(),\n            Actions\\RestoreAction::make(),\n        ];\n    }\n}\n`;
  }
 
  private buildViewPage(model: string, ns: string): string {
    return `<?php\n\nnamespace ${ns}\\${model}Resource\\Pages;\n\nuse ${ns}\\${model}Resource;\nuse Filament\\Actions;\nuse Filament\\Resources\\Pages\\ViewRecord;\n\nclass View${model} extends ViewRecord\n{\n    protected static string $resource = ${model}Resource::class;\n\n    protected function getHeaderActions(): array\n    {\n        return [\n            Actions\\EditAction::make(),\n        ];\n    }\n}\n`;
  }
 
  private buildRelationManager(resourceName: string, relationName: string, className: string): string {
    return `<?php\n\nnamespace App\\Filament\\Resources\\${resourceName}\\RelationManagers;\n\nuse Filament\\Forms;\nuse Filament\\Forms\\Form;\nuse Filament\\Resources\\RelationManagers\\RelationManager;\nuse Filament\\Tables;\nuse Filament\\Tables\\Table;\n\nclass ${className} extends RelationManager\n{\n    protected static string $relationship = '${relationName}';\n\n    public function form(Form $form): Form\n    {\n        return $form\n            ->schema([\n                Forms\\Components\\TextInput::make('id')\n                    ->required()\n                    ->maxLength(255),\n            ]);\n    }\n\n    public function table(Table $table): Table\n    {\n        return $table\n            ->recordTitleAttribute('id')\n            ->columns([\n                Tables\\Columns\\TextColumn::make('id'),\n            ])\n            ->filters([])\n            ->headerActions([\n                Tables\\Actions\\CreateAction::make(),\n            ])\n            ->actions([\n                Tables\\Actions\\EditAction::make(),\n                Tables\\Actions\\DeleteAction::make(),\n            ])\n            ->bulkActions([\n                Tables\\Actions\\BulkActionGroup::make([\n                    Tables\\Actions\\DeleteBulkAction::make(),\n                ]),\n            ]);\n    }\n}\n`;
  }
 
  private async writeFile(filePath: string, content: string): Promise<void> {
    const dir = path.dirname(filePath);
    if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); }
    const uri = vscode.Uri.file(filePath);
    const edit = new vscode.WorkspaceEdit();
    edit.createFile(uri, { overwrite: true });
    edit.insert(uri, new vscode.Position(0, 0), content);
    await vscode.workspace.applyEdit(edit);
    const doc = await vscode.workspace.openTextDocument(uri);
    await vscode.window.showTextDocument(doc);
    vscode.window.showInformationMessage(`✅ Created: ${path.relative(this.workspaceRoot, filePath)}`);
  }
}
 
// ─── Filament Field Inlay Hints ───────────────────────────────────────────
 
export class FilamentInlayHintsProvider implements vscode.InlayHintsProvider {
  constructor(private readonly cache: CacheManager) {}
 
  provideInlayHints(
    document: vscode.TextDocument,
    range: vscode.Range
  ): vscode.InlayHint[] {
    if (!document.fileName.endsWith('.php')) { return []; }
    const text = document.getText(range);
    if (!text.includes('::make(') && !text.includes('FilamentResource')) { return []; }
 
    const hints: vscode.InlayHint[] = [];
    const index = this.cache.getIndex();
    const offset = document.offsetAt(range.start);
 
    // Detect which model this resource is for
    let resourceModel: ModelDefinition | undefined;
    const fullText = document.getText();
    const modelMatch = /protected\s+static\s+\?string\s+\$model\s*=\s*(\w+)::class/.exec(fullText);
    if (modelMatch) {
      const modelName = modelMatch[1];
      for (const [, m] of index.models) {
        if (m.className === modelName) { resourceModel = m; break; }
      }
    }
    if (!resourceModel) { return []; }
 
    // Hint column types next to ::make('field_name')
    const makePattern = /::make\s*\(\s*'([^']+)'/g;
    let match: RegExpExecArray | null;
    while ((match = makePattern.exec(text)) !== null) {
      const fieldName = match[1].split('.').pop() ?? match[1]; // handle 'relation.field'
      const col = resourceModel.columns.find((c) => c.name === fieldName);
      if (!col) { continue; }
 
      const hintPos = document.positionAt(offset + match.index + match[0].length);
      const hint = new vscode.InlayHint(
        hintPos,
        ` /* ${col.type}${col.nullable ? '?' : ''} */`,
        vscode.InlayHintKind.Type
      );
      hint.tooltip = new vscode.MarkdownString(
        `**${fieldName}:** \`${col.type}\`${col.nullable ? ' (nullable)' : ''}`
      );
      hints.push(hint);
    }
 
    return hints;
  }
}
 
function capitalize(s: string): string {
  return s.charAt(0).toUpperCase() + s.slice(1);
}