All files / src/providers RefactoringProvider.ts

0% Statements 0/70
0% Branches 0/21
0% Functions 0/15
0% Lines 0/64

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
// src/providers/RefactoringProvider.ts
import * as vscode from 'vscode';
import type { CacheManager } from '../cache/CacheManager';
 
// ─── Rename Provider ──────────────────────────────────────────────────────
 
/**
 * Provides workspace-wide rename support for:
 * - Route names  (route('old.name') → route('new.name'))
 * - View names   (view('old.view') → view('new.view'))
 * - Translation keys (__('old.key') → __('new.key'))
 *
 * All replacements are batched into a single WorkspaceEdit, so the
 * developer can undo the entire operation with one Ctrl+Z.
 */
export class LaravelRenameProvider implements vscode.RenameProvider {
  constructor(
    private readonly cache: CacheManager,
    private readonly workspaceRoot: string
  ) {}
 
  // ─── Prepare Rename ───────────────────────────────────────────────────
 
  async prepareRename(
    document: vscode.TextDocument,
    position: vscode.Position
  ): Promise<vscode.Range | { range: vscode.Range; placeholder: string } | undefined> {
    const wordRange = document.getWordRangeAtPosition(position, /['"][^'"]+['"]/);
    if (!wordRange) {
      throw new Error('Laravel Maestro: Place cursor inside a quoted string to rename it.');
    }
 
    const word = document.getText(wordRange).replace(/['"]/g, '');
    const index = this.cache.getIndex();
 
    // Verify this is a known renameable symbol
    if (
      index.routes.has(word) ||
      index.views.has(word) ||
      index.translations.has(`en.${word}`) ||
      Array.from(index.translations.values()).some((t) => t.key === word)
    ) {
      return { range: wordRange, placeholder: word };
    }
 
    throw new Error(`Laravel Maestro: "${word}" is not a known route, view, or translation key.`);
  }
 
  // ─── Rename ───────────────────────────────────────────────────────────
 
  async provideRenameEdits(
    document: vscode.TextDocument,
    position: vscode.Position,
    newName: string
  ): Promise<vscode.WorkspaceEdit | undefined> {
    const wordRange = document.getWordRangeAtPosition(position, /['"][^'"]+['"]/);
    if (!wordRange) { return undefined; }
 
    const oldName = document.getText(wordRange).replace(/['"]/g, '');
    const index = this.cache.getIndex();
 
    const edit = new vscode.WorkspaceEdit();
    let replacements = 0;
 
    // Determine what kind of symbol we're renaming
    const isRoute = index.routes.has(oldName);
    const isView = index.views.has(oldName);
    const isTranslation = Array.from(index.translations.values()).some((t) => t.key === oldName);
 
    if (!isRoute && !isView && !isTranslation) { return undefined; }
 
    // Find all PHP / Blade files in the workspace
    const phpFiles = await vscode.workspace.findFiles(
      new vscode.RelativePattern(this.workspaceRoot, '**/*.{php,blade.php}'),
      '{vendor/**,node_modules/**}'
    );
 
    // Build regex for the string usage (matches both quote styles)
    const escapedOld = oldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const pattern = new RegExp(`(['"])${escapedOld}\\1`, 'g');
 
    for (const fileUri of phpFiles) {
      const fileDoc = await vscode.workspace.openTextDocument(fileUri);
      const fileText = fileDoc.getText();
 
      let match: RegExpExecArray | null;
      while ((match = pattern.exec(fileText)) !== null) {
        const quoteChar = match[1];
        const startPos = fileDoc.positionAt(match.index);
        const endPos = fileDoc.positionAt(match.index + match[0].length);
        const range = new vscode.Range(startPos, endPos);
 
        edit.replace(fileUri, range, `${quoteChar}${newName}${quoteChar}`);
        replacements++;
      }
      pattern.lastIndex = 0; // reset regex state for next file
    }
 
    if (replacements === 0) {
      vscode.window.showWarningMessage(
        `[Laravel Maestro] No usages of "${oldName}" found.`
      );
      return undefined;
    }
 
    vscode.window.showInformationMessage(
      `[Laravel Maestro] Renamed "${oldName}" → "${newName}" in ${replacements} location(s).`
    );
 
    return edit;
  }
}
 
// ─── Route List Panel ─────────────────────────────────────────────────────
 
export class RouteListPanel {
  private static currentPanel: RouteListPanel | undefined;
  private readonly panel: vscode.WebviewPanel;
  private readonly disposables: vscode.Disposable[] = [];
 
  static show(cache: CacheManager, _extensionUri: vscode.Uri): void {
    if (RouteListPanel.currentPanel) {
      RouteListPanel.currentPanel.panel.reveal(vscode.ViewColumn.One);
      RouteListPanel.currentPanel.update(cache);
      return;
    }
 
    const panel = vscode.window.createWebviewPanel(
      'laravelRouteList',
      '🛣 Laravel Routes',
      vscode.ViewColumn.One,
      {
        enableScripts: true,
        retainContextWhenHidden: true,
      }
    );
 
    RouteListPanel.currentPanel = new RouteListPanel(panel, cache);
  }
 
  private constructor(panel: vscode.WebviewPanel, cache: CacheManager) {
    this.panel = panel;
    this.panel.onDidDispose(() => this.dispose(), null, this.disposables);
    this.update(cache);
  }
 
  update(cache: CacheManager): void {
    const index = cache.getIndex();
    const routes = Array.from(index.routes.values());
    this.panel.webview.html = this.buildHtml(routes);
  }
 
  private buildHtml(routes: import('../types').RouteDefinition[]): string {
    const rows = routes
      .map((r) => {
        const methods = r.methods
          .map((m) => `<span class="method method-${m.toLowerCase()}">${m}</span>`)
          .join('');
        const params = r.parameters.map((p) => `{${p.name}}`).join(', ');
        return `
          <tr>
            <td>${methods}</td>
            <td><code>/${r.uri}</code></td>
            <td><strong>${r.name || '<em>anonymous</em>'}</strong></td>
            <td><code>${r.action}</code></td>
            <td>${r.middleware.join(', ')}</td>
            <td>${params}</td>
          </tr>`;
      })
      .join('\n');
 
    return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Laravel Routes</title>
  <style>
    body { font-family: var(--vscode-font-family); padding: 1rem; color: var(--vscode-foreground); background: var(--vscode-editor-background); }
    h1 { font-size: 1.4rem; margin-bottom: 1rem; }
    table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
    th { text-align: left; padding: 0.5rem 0.75rem; border-bottom: 2px solid var(--vscode-panel-border); background: var(--vscode-editorGroupHeader-tabsBackground); }
    td { padding: 0.4rem 0.75rem; border-bottom: 1px solid var(--vscode-panel-border); vertical-align: middle; }
    tr:hover td { background: var(--vscode-list-hoverBackground); }
    code { font-family: var(--vscode-editor-font-family); font-size: 0.82rem; background: var(--vscode-textBlockQuote-background); padding: 0.1em 0.3em; border-radius: 3px; }
    .method { display: inline-block; padding: 1px 6px; border-radius: 3px; font-size: 0.75rem; font-weight: bold; margin-right: 2px; }
    .method-get    { background: #2d6a2d; color: #9fefaf; }
    .method-post   { background: #2a4a8a; color: #9fc3ef; }
    .method-put    { background: #7a5a10; color: #efcf7f; }
    .method-patch  { background: #6a4a1a; color: #efbf8f; }
    .method-delete { background: #7a1a1a; color: #ef9f9f; }
    input[type=search] { width: 100%; padding: 0.4rem 0.75rem; margin-bottom: 1rem; background: var(--vscode-input-background); color: var(--vscode-input-foreground); border: 1px solid var(--vscode-input-border); border-radius: 4px; font-size: 0.9rem; }
    .count { color: var(--vscode-descriptionForeground); font-size: 0.85rem; margin-bottom: 0.5rem; }
  </style>
</head>
<body>
  <h1>🛣 Route List (${routes.length} routes)</h1>
  <input type="search" id="filter" placeholder="Filter by name, URI, or action…" oninput="filterRoutes(this.value)">
  <div class="count" id="count">${routes.length} routes</div>
  <table id="routeTable">
    <thead>
      <tr>
        <th>Methods</th>
        <th>URI</th>
        <th>Name</th>
        <th>Action</th>
        <th>Middleware</th>
        <th>Params</th>
      </tr>
    </thead>
    <tbody id="routeBody">${rows}</tbody>
  </table>
  <script>
    function filterRoutes(q) {
      const lower = q.toLowerCase();
      const rows = document.querySelectorAll('#routeBody tr');
      let visible = 0;
      rows.forEach(row => {
        const text = row.textContent.toLowerCase();
        const show = text.includes(lower);
        row.style.display = show ? '' : 'none';
        if (show) visible++;
      });
      document.getElementById('count').textContent = visible + ' routes';
    }
  </script>
</body>
</html>`;
  }
 
  dispose(): void {
    RouteListPanel.currentPanel = undefined;
    this.panel.dispose();
    for (const d of this.disposables) { d.dispose(); }
  }
}