mirror of
https://github.com/supabase/supabase.git
synced 2026-10-10 03:45:06 +03:00
Post-merge fixes for the TanStack Start migration (#46424) — things that broke on the TanStack build as master evolved under the migration branches. Kept on their own branch off master rather than piling onto the E2E-matrix PR (#47119); all land on master and cascade up to S6 + the big PR. Common theme: a master PR changed something the Next pipeline handles via `next/font` / `pages/_app.tsx` / `next.config.ts`, but the hand-rolled TanStack equivalent (`routes/__root.tsx`, `styles/fonts.css`, `vercel.ts`) wasn't updated to match — invisible on the Next deploy, broken only on TanStack. --- ## 1. Monaco loader path (#47182) #47182 re-nested the served Monaco assets from a flat `public/monaco-editor/` layout into `public/monaco-editor/vs/` and updated `pages/_app.tsx`, but `routes/__root.tsx` still pointed `loader.config` at the old path, so `loader.js` 404'd and **no Monaco editor mounted anywhere in the TanStack build**. Now mirrors the Next config (`${origin}${BASE_PATH}/monaco-editor/vs`, window-guarded for SSR). Was failing the whole `tanstack` E2E shard on #47119. ## 2. Inter + Manrope fonts (#47306) #47306 renamed Tailwind's sans var `--font-custom` → `--font-sans` and added `--font-heading` (Manrope), set via `next/font` on Next. `fonts.css` still only set the now-ignored `--font-custom`, so the body fell back to the theme's system chain (`Circular, custom-font, Helvetica…`) at weight 450 — that's the "Inter weights look wrong". Manrope was missing entirely. - Wire `--font-sans` (Inter) + `--font-heading` (Manrope) to match `next/font`. - **Vendor all three families** (Inter, Manrope, Source Code Pro) via `@font-face` so nothing depends on the Google Fonts CDN — matches `next/font` self-hosting, and (see below) `font-src` doesn't allow `fonts.gstatic.com` anyway. Verified in-browser: computed `body` → `Inter`, headings → `Manrope`, all loading from local `/assets/*.woff2`. ## 3. Security headers / CSP (next.config.ts `headers()`) The Next build sets X-Frame-Options / X-Content-Type-Options / HSTS / **Content-Security-Policy** / Referrer-Policy via `next.config.ts`. The TanStack build never carried these over — `vercel.ts` only set cache-control, so **the deployed TanStack dashboard shipped with no CSP at all**. The TanStack deploy serves a static shell (no server to attach headers), so they go in the Vercel config: - `security-headers.ts` — shared source of truth, reuses `getCSP()`, env-gated exactly like next.config. - `vercel.ts` — apply to every response (all base-path prefixes): full `getCSP()` + HSTS on platform. - `scripts/serve.js` — the non-platform set (`frame-ancestors 'none'`) for the self-hosted server. **Tested the policy in a real browser** (temporarily enforced it on the TanStack build via /test-supabase-local): everything passed except one real gap — `font-src` was missing `data:`, so GraphiQL's bundled Monaco codicon font and Stripe's payment-element fonts (both data: URIs) were blocked (37 violations on a cold load). Added `data:` to `font-src` in `csp.ts` → violations drop to zero, SQL editor Monaco renders clean. That gap affects the Next build too. --- ## 4. `node:path` import crashing `/project/[ref]/merge` Found by a full-site click-through of the TanStack build (all product areas, ongoing — see below). `useEdgeFunctionsDiff.ts` + `EdgeFunctionsDiffPanel.tsx` did `import { basename } from 'path'` in client code. Webpack (Next) polyfills `path` in the browser; Vite externalizes it, so the whole `/merge` route crashed with "Module \"path\" has been externalized for browser compatibility". Replaced the two `basename` call sites with a string helper. Verified in-browser: `/merge` renders. ## 5. URL shape — Next-style search-param semantics + shim fixes The dashboard produced malformed URLs vs the Next build (strange query params, trailing slashes, `##` hashes). Root cause + audit verified empirically against `@tanstack/react-router@1.170.10`; all fixed with unit tests and browser-verified: - **`createRouter` used TanStack's default JSON search codec** — `?flag=true` became `?flag=%22true%22` via links, repeated `?filter=…&filter=…` collapsed into a JSON array (breaking multi-filter/sort table-editor URLs and the account-page round-trip, which double-encoded), and search values arrived as numbers/booleans where the app expects strings. New `lib/router-search-params.ts` (Next-style: strings in, strings out, repeated keys → string[]) wired into the router. - **Link shim** (`compat/next/link.tsx`): `URL.hash` includes the leading `#` while TanStack's `hash` prop adds its own → every `href="…#section"` navigated to `##section` (hash-scroll broke); `Object.fromEntries(searchParams)` dropped repeated query params. Both fixed. - **Trailing slash injected before the query** on every `?`-only relative navigation (`/auth/providers/?provider=…`): fixed in the compat router (prefix current pathname) and via a custom nuqs adapter (`lib/nuqs-tanstack-adapter.tsx`) replacing the stock tanstack-router adapter, whose `navigate({ to: '?…' })` writes hit the same TanStack behavior (123 files use nuqs). - **Pathname-less `router.push({ query })` leaked path params** — Next re-consumes `ref`/`id` from `query` into the path pattern; the shim didn't, yielding `/editor/17597?schema=public&ref=<ref>&id=17597&filter=…` from table-editor filter/sort, linter panels, and advisor shortcuts. The shim now defaults the pathname to the current route pattern and backfills omitted params. - **Redirects dropped query + hash** (Next's `redirects()` preserves them): `__root.tsx` `matchRedirect` and `routes/index.tsx` now carry incoming params/hash through (consumed rule params excluded, destination's own params win). `/?next=new-project&projectName=zzz` → `/new/new-project?projectName=zzz`; `/sql/quickstarts?template=x#frag` → `/sql/examples?template=x#frag`. Browser-verified post-fix: advisors `?preset=WARN`, providers `?provider=Google`, `?schema=auth` — all clean (no `/?`, no leaks); repeated `filter` params survive hydration; `=true` unquoted; single `#`. ## 6. TanStack `navigate` corrupting query values (Logs Explorer SQL newline loss) TanStack router-core treats a query string embedded in `navigate({ to })` as part of the *path*: `decodePath` percent-decodes it and `sanitizePathSegment` strips control characters, silently deleting every `%0A`. Logs Explorer's SQL (`s` param) lost its newlines on Run/reload — `order by timestamp desc` / `limit 5` glued into `desclimit 5`, which then failed the LIMIT lint. Pre-existing on the TanStack build (the stock nuqs adapter had the same shape); Next unaffected. Fixed by never embedding query strings in `to`: the nuqs adapter and the compat `router.push`/`replace`/`prefetch` (plus the `next/navigation` shim) now pass search as an object through the app codec (`splitInternalUrl` hoisted to `lib/internal-url.ts`). Guard test drives a real `createRouter` with multi-line SQL through both producers. Browser-verified: newlines survive the full Run → reload → re-Run cycle. ## 7. Integration overview markdown never loaded (all integrations) `MarkdownContent` used a template-literal dynamic import (``import(`@/static-data/integrations/${id}/overview.md`)``) — webpack builds a context module for that, Vite can't analyze it, so every integration detail page threw `Failed to resolve module specifier` and rendered no overview text. Fixed with an explicit lazy registry of literal imports (`static-data/integrations/overviews.ts`, drift-guarded by a test) plus an `mdRawLoader()` Vite plugin mirroring next.config's turbopack raw-loader rule. Both runtimes keep working; md stays out of the main bundle. ## 8. GraphiQL editor never mounted (`exports is not defined`) Our `umdAmdShortCircuit()` Vite plugin (which disarms Monaco's global AMD loader for deps like papaparse) rewrote `typeof define === 'function' && define.amd` to `false` inside `monaco-editor`'s bundled copy of marked — whose UMD relies on its own *local* `define` shim — so the whole optimized monaco chunk failed to evaluate and GraphiQL's editor pane stayed blank. The check now only short-circuits when `define` is the global AMD loader. Browser-verified: all four GraphiQL Monaco panes mount, queries execute. (Known follow-up: GraphiQL's Monaco workers fall back to the main thread under Vite — functional, worker wiring is Next-specific `setup-workers/webpack`.) ## 9. `@sentry/nextjs` bundling Next internals — built TanStack bundle crashed (caught by E2E) The E2E suite against the **built** TanStack bundle (not the dev server) found lazy chunks like `table-editor-*.js` dead on arrival: `@sentry/nextjs` (imported by ~25 client files) drags in `next/dist/shared/lib/constants`, whose module scope evaluates `process?.features?.typescript` — optional chaining doesn't guard an undeclared `process` in the browser, so the whole chunk failed at load with `ReferenceError: process is not defined`. Dev shims `process`, which is why weeks of dev-server testing never saw it. Fixed by aliasing `@sentry/nextjs` → `compat/sentry-nextjs.ts` (re-exports `@sentry/react`, same deduped 10.59.0, plus explicit stand-ins for the three Next-only APIs) in the Vite build only. Verified: fresh build has zero Next-internals markers in any chunk; table editor loads clean; full E2E suite run against the built bundle. Note for the stack: `alaister/tanstack-start` / the E2E-matrix branch already carried a different fix for the same crash (a `next/constants` shim) that never made it to master — the cherry-pick onto those branches keeps **both** (the shim covers any other transitive importer; the alias keeps Next internals out of the client bundle entirely). **Follow-up found while fixing:** Sentry is never *initialized* in the TanStack runtime — `instrumentation-client.ts` / `sentry.server.config.ts` are Next-convention files nothing imports under TanStack, so `captureException` calls are silent no-ops. Needs an `@sentry/react` init (+ `tanstackRouterBrowserTracingIntegration`) wired into the TanStack client entry as its own PR. ## 10. GraphiQL Monaco workers + edge-function Deno typings (Vite-only gaps) - **GraphiQL's Monaco workers ran on the main thread** under Vite ("Could not create web worker(s)…" — `setup-workers/webpack`'s `new URL(...)` form isn't rewritten by Vite). A `graphiqlViteWorkers()` plugin resolves the import to graphiql's own `setup-workers/vite` variant for client builds (SSR untouched, Next untouched); the setup-workers chain is `optimizeDeps.exclude`d because the Rolldown optimizer can't load `?worker` ids. - **Edge-function editors silently lost their Deno typings** — `AIEditor` loaded `public/deno/*.d.ts` via `/* @vite-ignore */` imports that always failed at runtime under Vite. The `.md` raw loader is generalized into `rawTextLoader` (exact-path allowlist for the two typings files, served as virtual string modules so the dep scanner never parses `.d.ts` syntax), and the imports are now static-analyzable literals that both bundlers handle (turbopack's raw-loader rules match them on the Next side). ## Split out for reviewability App-level fixes that reproduce on the Next build too (DOM-nesting hydration errors, the ghost deleted-snippet nav, the recurring pg-meta `migrations` 400) moved to their own PR: #47667. Sentry initialization for the TanStack runtime (captures were silent no-ops) is #47666, stacked on this PR. ## Full-site test campaign Drove every dashboard product area on the local TanStack build (Playwright, human-style) hunting migration regressions: redirects/404/catch-alls, org, account, project home/branches/merge, table editor CRUD, SQL editor (Monaco/run/save/templates/AI), all database pages, all auth pages, storage CRUD, edge functions + realtime, logs/observability, advisors, settings, integrations hub incl. nested routes, global UI (palette/connect/switchers/theme/fonts), and a cross-cutting sweep (document titles, back/forward chain, hard-refresh hydration on deep URLs, trailing-slash active state). Every failure found is fixed above and re-verified in-browser; remaining console quirks were cross-checked against the deployed Next build and are pre-existing (tracked separately). ## To test Most fixes are already browser-verified + covered by unit tests and the self-hosted E2E suite; the last two landed after the final browser pass and still need an in-browser check: 1. **GraphiQL Monaco workers** — restart the dev server (clear `apps/studio/node_modules/.vite` once first — the optimizer cache may hold a stale prebundle of the worker chain). Open `/project/<ref>/integrations/graphiql/graphiql` with the console open: the `Could not create web worker(s). Falling back to loading web worker code in main thread` warning must be gone, and DevTools → Sources → Threads shows the three workers (json, editor, graphql). Autocomplete in the query editor stays responsive. 2. **Edge-function Deno typings** — `/project/<ref>/functions/new`: no "Failed to load … typings" console error, and typing `Deno.` in the editor offers typed completions (e.g. `Deno.env`). Spot-checks for the rest (all previously verified): - `/project/<ref>/merge` renders (no "Module path" crash). - Multi-line SQL in Logs Explorer survives Run → reload (no `desclimit` gluing, no LIMIT-lint false failure); `s` param keeps `%0A`. - `/auth/providers` → open a provider → `?provider=…` with no trailing slash before `?`; table-editor filter/sort URLs carry no leaked `ref`/`id` params; `/?next=new-project&projectName=x` lands on `/new/new-project?projectName=x`. - Integration detail pages (cron/queues/vault/data_api) show their overview prose; GraphiQL query editor mounts. - Built bundle (`MODE=test vite build` + `start:tanstack`): table editor loads with no `process is not defined`. - `curl -sI` any page on a platform deploy: `X-Content-Type-Options: nosniff` (was the invalid `no-sniff`). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Centralized integration overview markdown loading with registry-based lookup. * Improved Monaco loading/asset path handling for smoother editor startup. * **Bug Fixes** * Next-style navigation/search handling now preserves pathname, hash, repeated query keys, and special characters (including newlines). * Redirects now reliably carry over query and hash with correct precedence. * **Security/Configuration** * Updated CSP font sourcing and unified security headers delivery across environments; conditional HSTS behavior. * Refreshed font CSS variables and font-face definitions to match the theme. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- ### Review feedback: non-prod favicon (Joshen) The TanStack `__root.tsx` hardcoded the prod favicon; local + hosted staging now use the white staging favicon (`/favicon/staging`), matching what `pages/_app.tsx` passes to `MetaFaviconsPagesRouter` for non-prod. Rather than pull the pages-router component into the TanStack head, it reuses the same synchronous `NEXT_PUBLIC_ENVIRONMENT` signal the file already uses for `IS_DEV_TOOLBAR_ENABLED` (the `head()` route option isn't a React component, so it can't run `_app`'s async CLI check — but the env signal covers the reported local/staging case). --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
445 lines
15 KiB
TypeScript
445 lines
15 KiB
TypeScript
import { Monaco, OnMount } from '@monaco-editor/react'
|
|
import { AnimatePresence, motion } from 'framer-motion'
|
|
import type { editor as monacoEditor } from 'monaco-editor'
|
|
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
import { toast } from 'sonner'
|
|
import { KeyboardShortcut } from 'ui'
|
|
import { useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
|
|
|
|
import { CodeEditor, type ValidLanguages } from '../CodeEditor/CodeEditor'
|
|
import { DiffEditor } from '../DiffEditor'
|
|
import ResizableAIWidget from './ResizableAIWidget'
|
|
import { getEditorSelectionParts } from './utils'
|
|
import { SIDEBAR_KEYS } from '@/components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
|
|
import { constructHeaders } from '@/data/fetchers'
|
|
import { useLatest } from '@/hooks/misc/useLatest'
|
|
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
|
|
import { useIsShortcutEnabled } from '@/state/shortcuts/useIsShortcutEnabled'
|
|
import { useSidebarManagerSnapshot } from '@/state/sidebar-manager-state'
|
|
|
|
interface AIEditorProps {
|
|
id?: string
|
|
language: ValidLanguages
|
|
value?: string
|
|
defaultValue?: string
|
|
aiEndpoint?: string
|
|
aiMetadata?: {
|
|
projectRef?: string
|
|
connectionString?: string | null
|
|
orgSlug?: string
|
|
language?: string
|
|
}
|
|
initialPrompt?: string
|
|
readOnly?: boolean
|
|
autoFocus?: boolean
|
|
className?: string
|
|
options?: monacoEditor.IStandaloneEditorConstructionOptions
|
|
onChange?: (value: string) => void
|
|
onClose?: () => void
|
|
closeShortcutEnabled?: boolean
|
|
openAIAssistantShortcutEnabled?: boolean
|
|
executeQuery?: () => void
|
|
onMount?: (editor: monacoEditor.IStandaloneCodeEditor, monaco: Monaco) => void
|
|
}
|
|
|
|
// [Joshen] This has overlap with components/interfaces/SQLEditor/MonacoEditor
|
|
// Can we try to de-dupe accordingly? Perhaps the SQL Editor could use this AIEditor
|
|
// We have a tendency to create multiple versions of the monaco editor like RLSCodeEditor
|
|
// so hoping to prevent that from snowballing
|
|
export const AIEditor = ({
|
|
language = 'javascript',
|
|
value,
|
|
defaultValue = '',
|
|
aiEndpoint,
|
|
aiMetadata,
|
|
initialPrompt,
|
|
readOnly = false,
|
|
autoFocus = false,
|
|
className = '',
|
|
options = {},
|
|
onChange,
|
|
onClose,
|
|
closeShortcutEnabled = true,
|
|
openAIAssistantShortcutEnabled = true,
|
|
executeQuery,
|
|
onMount,
|
|
}: AIEditorProps) => {
|
|
const { toggleSidebar } = useSidebarManagerSnapshot()
|
|
const editorRef = useRef<monacoEditor.IStandaloneCodeEditor | null>(null)
|
|
const diffEditorRef = useRef<monacoEditor.IStandaloneDiffEditor | null>(null)
|
|
const monacoRef = useRef<Monaco | null>(null)
|
|
const closeActionDisposableRef = useRef<{ dispose: () => void } | null>(null)
|
|
|
|
const isCommandMenuHotkeyEnabled = useIsShortcutEnabled(SHORTCUT_IDS.COMMAND_MENU_OPEN)
|
|
const setCommandMenuOpen = useSetCommandMenuOpen()
|
|
|
|
const executeQueryRef = useLatest(executeQuery)
|
|
const commandMenuHotkeyEnabledRef = useLatest(isCommandMenuHotkeyEnabled)
|
|
const setCommandMenuOpenRef = useLatest(setCommandMenuOpen)
|
|
|
|
const [currentValue, setCurrentValue] = useState(value || defaultValue)
|
|
const [isDiffMode, setIsDiffMode] = useState(false)
|
|
const [isDiffEditorMounted, setIsDiffEditorMounted] = useState(false)
|
|
const [diffValue, setDiffValue] = useState({ original: '', modified: '' })
|
|
const [promptState, setPromptState] = useState({
|
|
isOpen: Boolean(initialPrompt),
|
|
selection: '',
|
|
beforeSelection: '',
|
|
afterSelection: '',
|
|
startLineNumber: 0,
|
|
endLineNumber: 0,
|
|
})
|
|
const [promptInput, setPromptInput] = useState(initialPrompt || '')
|
|
|
|
const [isCompletionLoading, setIsCompletionLoading] = useState(false)
|
|
|
|
const complete = useCallback(
|
|
async (
|
|
_prompt: string,
|
|
options?: {
|
|
headers?: Record<string, string>
|
|
body?: { completionMetadata?: any }
|
|
}
|
|
) => {
|
|
try {
|
|
if (!aiEndpoint) throw new Error('AI endpoint is not configured')
|
|
setIsCompletionLoading(true)
|
|
|
|
const response = await fetch(aiEndpoint, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
...(options?.headers ?? {}),
|
|
},
|
|
body: JSON.stringify({
|
|
...(aiMetadata ?? {}),
|
|
...(options?.body ?? {}),
|
|
}),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text()
|
|
throw new Error(errorText || 'Failed to generate completion')
|
|
}
|
|
|
|
const text: string = await response.json()
|
|
|
|
const meta = options?.body?.completionMetadata ?? {}
|
|
const beforeSelection: string = meta.textBeforeCursor ?? ''
|
|
const afterSelection: string = meta.textAfterCursor ?? ''
|
|
const selection: string = meta.selection ?? ''
|
|
|
|
const original = beforeSelection + selection + afterSelection
|
|
const modified = beforeSelection + text + afterSelection
|
|
|
|
setDiffValue({ original, modified })
|
|
setIsDiffMode(true)
|
|
} catch (error: any) {
|
|
toast.error(`Failed to generate: ${error?.message ?? 'Unknown error'}`)
|
|
} finally {
|
|
setIsCompletionLoading(false)
|
|
}
|
|
},
|
|
[aiEndpoint, aiMetadata]
|
|
)
|
|
|
|
const handleReset = useCallback(() => {
|
|
setIsDiffMode(false)
|
|
setPromptState((prev) => ({ ...prev, isOpen: false }))
|
|
setPromptInput('')
|
|
editorRef.current?.focus()
|
|
}, [])
|
|
|
|
const handleAcceptDiff = useCallback(() => {
|
|
if (diffValue.modified) {
|
|
const newValue = diffValue.modified
|
|
setCurrentValue(newValue)
|
|
onChange?.(newValue)
|
|
handleReset()
|
|
}
|
|
}, [diffValue.modified, onChange, handleReset])
|
|
|
|
const handleRejectDiff = () => {
|
|
handleReset()
|
|
}
|
|
|
|
const refreshCloseAction = useCallback(() => {
|
|
closeActionDisposableRef.current?.dispose()
|
|
closeActionDisposableRef.current = null
|
|
|
|
const editor = editorRef.current
|
|
const monaco = monacoRef.current
|
|
|
|
if (!editor || !monaco || !onClose || !closeShortcutEnabled) return
|
|
|
|
const action = editor.addAction({
|
|
id: 'close-editor',
|
|
label: 'Close editor',
|
|
keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.KeyE],
|
|
contextMenuGroupId: 'operation',
|
|
contextMenuOrder: 0,
|
|
run: onClose,
|
|
})
|
|
|
|
closeActionDisposableRef.current = action ?? null
|
|
}, [closeShortcutEnabled, onClose])
|
|
|
|
const handleEditorOnMount: OnMount = (
|
|
editor: monacoEditor.IStandaloneCodeEditor,
|
|
monaco: Monaco
|
|
) => {
|
|
editorRef.current = editor
|
|
monacoRef.current = monaco
|
|
onMount?.(editor, monaco)
|
|
// Set prompt state to open if promptInput exists
|
|
if (promptInput) {
|
|
const model = editor.getModel()
|
|
if (model) {
|
|
const lineCount = model.getLineCount()
|
|
setPromptState({
|
|
isOpen: true,
|
|
selection: model.getValue(),
|
|
beforeSelection: '',
|
|
afterSelection: '',
|
|
startLineNumber: 1,
|
|
endLineNumber: lineCount,
|
|
})
|
|
}
|
|
}
|
|
|
|
// [Joshen] Opting to ignore "Cannot find module" errors here as users are getting
|
|
// confused with the error highlighting when importing external modules
|
|
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
|
|
diagnosticCodesToIgnore: [2792],
|
|
})
|
|
|
|
if (language === 'javascript' || language === 'typescript') {
|
|
// The Deno libs load as raw text — via the raw-loader rules in
|
|
// next.config.ts (Next/turbopack) and the `rawTextLoader` plugin in
|
|
// vite.config.ts (TanStack/Vite) — and are registered as Monaco extra
|
|
// libs. The specifiers must stay string literals so both bundlers can
|
|
// statically analyze and code-split them; the `as string` cast keeps
|
|
// tsc from resolving the `.d.ts` files as declaration files (TS2846 /
|
|
// "not a module") while erasing to a plain literal for the bundlers.
|
|
const denoTypeLibs: Record<string, Promise<{ default: string }>> = {
|
|
'edge-runtime': import('@/public/deno/edge-runtime.d.ts' as string),
|
|
'lib.deno': import('@/public/deno/lib.deno.d.ts' as string),
|
|
}
|
|
for (const [lib, loading] of Object.entries(denoTypeLibs)) {
|
|
loading
|
|
.then((module) => {
|
|
monaco.languages.typescript.typescriptDefaults.addExtraLib(module.default)
|
|
})
|
|
.catch((error) => {
|
|
console.error(`Failed to load Deno ${lib} typings:`, error)
|
|
})
|
|
}
|
|
}
|
|
|
|
refreshCloseAction()
|
|
|
|
// Add AI Assistant toggle keybinding (Cmd+I)
|
|
if (openAIAssistantShortcutEnabled) {
|
|
editor.addAction({
|
|
id: 'toggle-ai-assistant',
|
|
label: 'Toggle AI Assistant',
|
|
keybindings: [monaco.KeyMod.CtrlCmd + monaco.KeyCode.KeyI],
|
|
run: () => {
|
|
toggleSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
|
|
},
|
|
})
|
|
}
|
|
|
|
editor.addAction({
|
|
id: 'generate-ai',
|
|
label: 'Generate with AI',
|
|
keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyK],
|
|
run: () => {
|
|
const selectionParts = getEditorSelectionParts(editor)
|
|
if (!selectionParts) return
|
|
setPromptState({ isOpen: true, ...selectionParts })
|
|
},
|
|
})
|
|
|
|
// Monaco claims Cmd+K as a chord prefix, which swallows the global command
|
|
// menu shortcut while the editor is focused. Intercept it here and open the
|
|
// command menu directly so it works the same inside and outside the editor.
|
|
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyK, () => {
|
|
if (commandMenuHotkeyEnabledRef.current) {
|
|
setCommandMenuOpenRef.current(true)
|
|
}
|
|
})
|
|
}
|
|
|
|
const handlePrompt = async (
|
|
prompt: string,
|
|
context: {
|
|
beforeSelection: string
|
|
selection: string
|
|
afterSelection: string
|
|
}
|
|
) => {
|
|
try {
|
|
setPromptState((prev) => ({
|
|
...prev,
|
|
selection: context.selection,
|
|
beforeSelection: context.beforeSelection,
|
|
afterSelection: context.afterSelection,
|
|
}))
|
|
|
|
const headerData = await constructHeaders()
|
|
const authorizationHeader = headerData.get('Authorization')
|
|
|
|
await complete(prompt, {
|
|
...(authorizationHeader ? { headers: { Authorization: authorizationHeader } } : undefined),
|
|
body: {
|
|
...aiMetadata,
|
|
completionMetadata: {
|
|
textBeforeCursor: context.beforeSelection,
|
|
textAfterCursor: context.afterSelection,
|
|
language,
|
|
prompt,
|
|
selection: context.selection,
|
|
},
|
|
},
|
|
})
|
|
} catch (error) {
|
|
setPromptState((prev) => ({ ...prev, isOpen: false }))
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
setCurrentValue(value || defaultValue)
|
|
}, [value, defaultValue])
|
|
|
|
useEffect(() => {
|
|
if (initialPrompt) {
|
|
setPromptInput(initialPrompt)
|
|
setPromptState({
|
|
isOpen: Boolean(initialPrompt),
|
|
selection: '',
|
|
beforeSelection: '',
|
|
afterSelection: '',
|
|
startLineNumber: 0,
|
|
endLineNumber: 0,
|
|
})
|
|
}
|
|
}, [initialPrompt])
|
|
|
|
useEffect(() => {
|
|
if (!isDiffMode) {
|
|
setIsDiffEditorMounted(false)
|
|
}
|
|
}, [isDiffMode])
|
|
|
|
useEffect(() => {
|
|
const handleKeyboard = (event: KeyboardEvent) => {
|
|
if (event.key === 'Escape') {
|
|
handleReset()
|
|
} else if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && isDiffMode) {
|
|
event.preventDefault()
|
|
handleAcceptDiff()
|
|
}
|
|
}
|
|
|
|
window.addEventListener('keydown', handleKeyboard)
|
|
return () => window.removeEventListener('keydown', handleKeyboard)
|
|
}, [isDiffMode, handleAcceptDiff, handleReset])
|
|
|
|
return (
|
|
<div className="flex-1 overflow-hidden flex flex-col h-full relative">
|
|
{isDiffMode ? (
|
|
<div className="w-full h-full">
|
|
<DiffEditor
|
|
language={language}
|
|
original={diffValue.original}
|
|
modified={diffValue.modified}
|
|
onMount={(editor: monacoEditor.IStandaloneDiffEditor) => {
|
|
diffEditorRef.current = editor
|
|
setIsDiffEditorMounted(true)
|
|
}}
|
|
/>
|
|
{isDiffEditorMounted && (
|
|
<ResizableAIWidget
|
|
editor={diffEditorRef.current!}
|
|
id="ask-ai-diff"
|
|
value={promptInput}
|
|
onChange={setPromptInput}
|
|
onSubmit={(prompt: string) => {
|
|
handlePrompt(prompt, {
|
|
beforeSelection: promptState.beforeSelection,
|
|
selection: promptState.selection || diffValue.modified,
|
|
afterSelection: promptState.afterSelection,
|
|
})
|
|
}}
|
|
onAccept={handleAcceptDiff}
|
|
onReject={handleRejectDiff}
|
|
onCancel={handleReset}
|
|
isDiffVisible={true}
|
|
isLoading={isCompletionLoading}
|
|
startLineNumber={Math.max(0, promptState.startLineNumber)}
|
|
endLineNumber={promptState.endLineNumber}
|
|
/>
|
|
)}
|
|
</div>
|
|
) : (
|
|
<div className="w-full h-full relative">
|
|
<CodeEditor
|
|
language={language}
|
|
autofocus={autoFocus}
|
|
className={className}
|
|
isReadOnly={readOnly}
|
|
options={options}
|
|
value={currentValue}
|
|
onInputChange={(value) => {
|
|
const newValue = value || ''
|
|
setCurrentValue(newValue)
|
|
onChange?.(newValue)
|
|
}}
|
|
onMount={handleEditorOnMount}
|
|
actions={{ runQuery: { enabled: true, callback: () => executeQueryRef.current?.() } }}
|
|
/>
|
|
{promptState.isOpen && editorRef.current && (
|
|
<ResizableAIWidget
|
|
editor={editorRef.current}
|
|
id="ask-ai"
|
|
value={promptInput}
|
|
onChange={setPromptInput}
|
|
onSubmit={(prompt: string) => {
|
|
handlePrompt(prompt, {
|
|
beforeSelection: promptState.beforeSelection,
|
|
selection: promptState.selection,
|
|
afterSelection: promptState.afterSelection,
|
|
})
|
|
}}
|
|
onCancel={handleReset}
|
|
isDiffVisible={false}
|
|
isLoading={isCompletionLoading}
|
|
startLineNumber={Math.max(0, promptState.startLineNumber)}
|
|
endLineNumber={promptState.endLineNumber}
|
|
/>
|
|
)}
|
|
<AnimatePresence>
|
|
{!promptState.isOpen && !currentValue && aiEndpoint && (
|
|
<motion.p
|
|
initial={{ y: 5, opacity: 0 }}
|
|
animate={{ y: 0, opacity: 1 }}
|
|
exit={{ y: 5, opacity: 0 }}
|
|
className="text-foreground-lighter absolute bottom-4 left-4 z-10 font-mono text-xs flex items-center gap-1"
|
|
>
|
|
Hit{' '}
|
|
<KeyboardShortcut
|
|
keys={['Meta', 'Shift', 'k']}
|
|
variant="inline"
|
|
className="text-xs text-foreground-lighter"
|
|
/>{' '}
|
|
to edit with the Assistant
|
|
</motion.p>
|
|
)}
|
|
</AnimatePresence>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)
|
|
}
|