Files
windmill/frontend/src/lib/components/SimpleEditor.svelte
T
fda7b3f086 feat(ai-sessions): replace the context panel with an assistant settings modal (#10919)
* feat(ai-chat): make reusable skills ai_skill resources you select per workspace

* chore: pin the ee ref to the skill telemetry counters

* fix: address review findings on skill authoring, import and migration

* fix: enforce skill selection in read_skill and stop imports clobbering resources

* feat: carry format_extension from the hub into synced resource types

* fix: let an edit set or clear a resource type's format_extension

* fix: regenerate the sqlx cache and close the review round findings

* fix: close the round-2 findings on folder ACLs, cached sync and truncation

* refactor: make the skills migration non-destructive and use design-system inputs

* feat(ai-sessions): add a context panel listing what the chat can use

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmdCVM1ZvTcpatv78jN8Ed

* fix: track the prompt rebuild signal and trim the review round's nits

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmdCVM1ZvTcpatv78jN8Ed

* fix: keep the panel from perturbing an in-flight turn

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmdCVM1ZvTcpatv78jN8Ed

* fix: count a folder by its readable children

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NmdCVM1ZvTcpatv78jN8Ed

* feat(ai-sessions): replace the context panel with an assistant settings modal

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* feat(ai-sessions): page-based MCP editing and fuzzy tool search

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* feat(ai-sessions): tool detail page and a shared list row

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* feat(ai-sessions): add a files & folders section to the assistant settings

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* chore: point the ee ref at the merged ee branch

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: keep hidden sections from answering keys and swallowing a failed save

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: restore the staged-fork write guard and narrow the round-2 findings

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: restore the workspace-race guards and extend them to MCP

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: keep an in-flight settings read from overwriting typed instructions

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* docs: describe the tool row as the one line it renders

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: keep the prompt entries on the home composer, which has no settings modal

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: create the editor with the gutter its caller asked for

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* test: restore the attachment status label guard dropped in the merge

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: surface a refused mcp selection write instead of painting the switch

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: refuse instruction writes to a staged fork's parent, and read the target's role

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: pin the instructions role and field to the target workspace

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ld1m9NAGLdPPrNBiu5PSQK

* fix: retry a deferred instructions reload, and use Button for the row label

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGnKFvaX61wiMU1CzQp6XG

* fix: leave the arrows to a control that answered them, and say when a role read failed

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGnKFvaX61wiMU1CzQp6XG

* chore: update ee-repo-ref to a2776856c50e80c9dbcf6e689a66ce86567c03fa

This commit updates the EE repository reference after PR #765 was merged in windmill-ee-private.

Previous ee-repo-ref: dd7466e749753568a23c91ba5e165020769206b8

New ee-repo-ref: a2776856c50e80c9dbcf6e689a66ce86567c03fa

Automated by sync-ee-ref workflow.

* fix: withhold the page navigator from a parked section

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WGnKFvaX61wiMU1CzQp6XG

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Guilhem Lemouel <guilhemlemouel@gmail.com>
Co-authored-by: windmill-internal-app[bot] <windmill-internal-app[bot]@users.noreply.github.com>
2026-09-04 10:53:02 +02:00

825 lines
24 KiB
Svelte

<script module>
let cssClassesLoaded = $state(false)
let tailwindClassesLoaded = $state(false)
import '@codingame/monaco-vscode-standalone-languages'
import '@codingame/monaco-vscode-standalone-json-language-features'
import '@codingame/monaco-vscode-standalone-css-language-features'
import '@codingame/monaco-vscode-standalone-typescript-language-features'
import '@codingame/monaco-vscode-standalone-html-language-features'
import { javascriptDefaults } from '@codingame/monaco-vscode-standalone-typescript-language-features'
</script>
<script lang="ts">
import { registerPendingEditor } from './pendingEditorFlush'
import { BROWSER } from 'esm-env'
import { editorConfig, updateOptions } from '$lib/editorUtils'
import { editorFontSize } from '$lib/editorFontSize.svelte'
import { createHash } from '$lib/editorLangUtils'
// import {
// editor as meditor,
// KeyCode,
// KeyMod,
// Uri as mUri,
// languages,
// type IRange,
// type IDisposable
// } from 'monaco-editor'
import { allClasses } from './apps/editor/componentsPanel/cssUtils'
import { createEventDispatcher, onDestroy, onMount, tick, untrack } from 'svelte'
import libStdContent from '$lib/es6.d.ts.txt?raw'
import domContent from '$lib/dom.d.ts.txt?raw'
import {
initializeVscode,
keepModelAroundToAvoidDisposalOfWorkers,
MONACO_Y_PADDING
} from './vscode'
import EditorTheme from './EditorTheme.svelte'
import { vimMode, relativeLineNumbers } from '$lib/stores'
import { initVim } from './monaco_keybindings'
import FakeMonacoPlaceHolder from './FakeMonacoPlaceHolder.svelte'
import { editorPositionMap } from '$lib/utils'
import { langToExt } from '$lib/editorLangUtils'
import {
editor as meditor,
KeyCode,
KeyMod,
Uri as mUri,
languages,
type IRange,
type IDisposable,
type IPosition
} from 'monaco-editor'
import { setMonacoJavascriptOptions, setMonacoJsonOptions } from './monacoLanguagesOptions'
import { twMerge } from 'tailwind-merge'
// import { createConfiguredEditor } from 'vscode/monaco'
// import type { IStandaloneCodeEditor } from 'vscode/vscode/vs/editor/standalone/browser/standaloneCodeEditor'
/** Trailing debounce window (ms) on Monaco's onDidChangeModelContent. */
const CHANGE_TIMEOUT = 200
/** Gap between the line numbers and the first character. Zero puts them flush,
* so a two-digit line reads as one token with the code. */
const LINE_DECORATIONS_WIDTH = 6
let changeTimeoutId: number | undefined = undefined
// Monaco fires onDidChangeModelContent synchronously from within `setValue`, so without
// this an authoritative overwrite reads as a user edit on the `input` event.
let applyingCode = false
let divEl: HTMLDivElement | null = null
let editor = $state<meditor.IStandaloneCodeEditor | null>(null)
let model: meditor.ITextModel
let pasteListenerCleanup: (() => void) | undefined = undefined
let statusDiv = $state<Element | null>(null)
let width = $state(0)
let initialized = $state(false)
let placeholderVisible = $state(false)
// Monaco's content origin. The placeholder is a plain overlay on the editor container, so
// without these it sits over the line-number gutter and off the line-1 baseline.
let contentLeft = $state(0)
let contentLineHeight = $state(0)
let mounted = $state(false)
let valueAfterDispose: string | undefined = undefined
let {
lang,
code = $bindable(),
hash = createHash(),
cmdEnterAction,
formatAction,
automaticLayout = true,
extraLib = '',
placeholder = '',
disableSuggestions = false,
disableLinting = false,
hideLineNumbers = false,
shouldBindKey = true,
autoHeight = false,
fixedOverflowWidgets = true,
small = false,
domLib = false,
autofocus = false,
allowVim = false,
tailwindClasses = [],
class: className = '',
loadAsync = false,
key,
disabled = false,
readOnly = false,
minHeight = 1000,
renderLineHighlight = 'none',
suggestion,
leadingChangeSync = false,
lineNumbersMinChars = 3
}: {
lang: string
code?: string
hash?: string
cmdEnterAction?: () => void
formatAction?: () => void
automaticLayout?: boolean
extraLib?: string
placeholder?: string
disableSuggestions?: boolean
disableLinting?: boolean
hideLineNumbers?: boolean
shouldBindKey?: boolean
autoHeight?: boolean
fixedOverflowWidgets?: boolean
small?: boolean
domLib?: boolean
autofocus?: boolean
allowVim?: boolean
tailwindClasses?: string[]
class?: string
loadAsync?: boolean
initialCursorPos?: IPosition
key?: string
disabled?: boolean
/** Read-only Monaco mode: not editable, but still scrollable/selectable
* (unlike `disabled`, which makes the editor non-interactive). */
readOnly?: boolean
minHeight?: number
renderLineHighlight?: 'all' | 'line' | 'gutter' | 'none'
suggestion?: string
/** Materialize `code` on the first change of a burst instead of only after
* the trailing debounce. Set it when a control's enabled state derives from
* `code`; leave it off where each extra sync costs work downstream (an app
* code input feeding an autoRefresh runnable re-runs a job per sync). */
leadingChangeSync?: boolean
/** Width of the line-number gutter, in characters. Same name, and same
* default, as `Editor`, so the two render line numbers alike. */
lineNumbersMinChars?: number
} = $props()
let yPadding = MONACO_Y_PADDING
const dispatch = createEventDispatcher()
const uri = `file:///${untrack(() => hash)}.${langToExt(untrack(() => lang))}`
/** Materialise the debounced buffer into `code` now. A consumer that must act on
* what is on screen — persisting a draft before navigating away — cannot wait out
* CHANGE_TIMEOUT. Mirrors `Editor.flushPendingChanges`. */
export function flushPendingChanges(): void {
// Same guards as onDestroy: only a pending keystroke debounce is ours to flush.
// `getCode()` is '' until Monaco finishes initialising, and a caller draining every
// mounted editor reaches ones that have not — flushing those writes the blank out.
if (!editor || changeTimeoutId === undefined) return
cancelPendingChanges()
updateCode()
}
export function getCode(): string {
if (valueAfterDispose != undefined) {
return valueAfterDispose
}
return editor?.getValue() ?? ''
}
export function insertAtCursor(code: string): void {
if (editor) {
editor.trigger('keyboard', 'type', { text: code })
}
}
export function setCode(ncode: string, formatCode?: boolean): void {
if (ncode != code) {
code = ncode
}
applyingCode = true
try {
editor?.setValue(ncode)
} finally {
applyingCode = false
}
// setValue emits a change event of its own; drop the burst it opens so an edit
// made right after an authoritative overwrite still counts as a leading change.
cancelPendingChanges()
if (formatCode) {
format()
}
}
function cancelPendingChanges(): void {
if (changeTimeoutId !== undefined) {
clearTimeout(changeTimeoutId)
changeTimeoutId = undefined
}
}
export function formatCode(): void {
format()
}
function updateCode() {
const ncode = getCode()
if (code == ncode) {
return
}
code = ncode
dispatch('change', { code: ncode })
}
function updatePlaceholderVisibility(value: string) {
if (!value) {
placeholderVisible = true
return
}
placeholderVisible = value.trim() === ''
}
export function format() {
if (editor) {
updateCode()
editor.getAction('editor.action.formatDocument')?.run()
if (formatAction) {
formatAction()
updateCode()
}
}
}
export function focus() {
editor?.focus()
}
export function getSelectedLines(): string | undefined {
if (editor) {
const selection = editor.getSelection()
if (selection) {
const range: IRange = {
startLineNumber: selection.startLineNumber,
startColumn: 1,
endLineNumber: selection.endLineNumber + 1,
endColumn: 1
}
return editor.getModel()?.getValueInRange(range)
}
}
}
export function onDidChangeCursorSelection(f: (e: meditor.ICursorSelectionChangedEvent) => void) {
if (editor) {
return editor.onDidChangeCursorSelection(f)
}
}
export function show(): void {
divEl?.classList.remove('hidden')
}
export function hide(): void {
divEl?.classList.add('hidden')
}
let vimDisposable: IDisposable | undefined = undefined
$effect(() => {
if (allowVim && editor !== null && $vimMode && statusDiv) {
untrack(() => onVimMode())
}
})
$effect(() => {
if (!$vimMode && vimDisposable) {
untrack(() => onVimDisable())
}
})
$effect(() => {
editor?.updateOptions({
lineNumbers: $relativeLineNumbers ? 'relative' : 'on'
})
})
$effect(() => {
editor?.updateOptions({ readOnly })
})
function onVimDisable() {
vimDisposable?.dispose()
}
function onVimMode() {
if (editor && statusDiv) {
vimDisposable = initVim(editor, statusDiv, () => {
console.log('vim save not possible for simple editor')
})
}
}
function updateModelAndOptions() {
const model = editor?.getModel()
if (model) {
// Switch language if it changed
if (model.getLanguageId() !== lang) {
const currentCode = model.getValue()
const uri = `file:///${hash}.${langToExt(lang)}`
// The old model goes first: `langToExt` maps anything it does not know to
// `unknown`, so the new uri is usually the one this model already holds,
// and creating over an occupied uri throws ("model already exists").
editor?.setModel(null)
model.dispose()
editor?.setModel(meditor.createModel(currentCode, lang, mUri.parse(uri)))
}
// Update editor options for suggestions, validation decorations, and line numbers
editor?.updateOptions({
quickSuggestions: disableSuggestions
? { other: false, comments: false, strings: false }
: { other: true, comments: true, strings: true },
suggestOnTriggerCharacters: !disableSuggestions,
wordBasedSuggestions: disableSuggestions ? 'off' : 'matchingDocuments',
parameterHints: { enabled: !disableSuggestions },
suggest: {
showIcons: !disableSuggestions,
showSnippets: !disableSuggestions,
showKeywords: !disableSuggestions,
showWords: !disableSuggestions,
snippetsPreventQuickSuggestions: disableSuggestions
},
lineNumbers: hideLineNumbers ? 'off' : 'on',
lineDecorationsWidth: hideLineNumbers ? 0 : LINE_DECORATIONS_WIDTH,
lineNumbersMinChars: hideLineNumbers ? 0 : lineNumbersMinChars,
// Hide validation squiggles and decorations
renderValidationDecorations: disableLinting ? 'off' : 'on',
// Hide the validation margin indicators
hideCursorInOverviewRuler: disableLinting,
overviewRulerBorder: !disableLinting,
overviewRulerLanes: disableLinting ? 0 : 3
})
}
}
$effect(() => {
if (editor !== null && (lang || disableLinting || disableSuggestions || hideLineNumbers)) {
untrack(() => updateModelAndOptions())
}
})
let fontSize = $derived(small ? editorFontSize.small : editorFontSize.regular)
$effect(() => {
const next = fontSize
if (editor) {
editor.updateOptions({ fontSize: next })
}
})
async function loadMonaco() {
setMonacoJsonOptions()
setMonacoJavascriptOptions()
await initializeVscode()
initialized = true
try {
model = meditor.createModel(code ?? '', lang, mUri.parse(uri))
} catch (err) {
console.log('model already existed', err)
const nmodel = meditor.getModel(mUri.parse(uri))
if (!nmodel) {
throw err
}
model = nmodel
}
model.updateOptions(updateOptions)
// let widgets: HTMLElement | undefined =
// document.getElementById('monaco-widgets-root') ?? undefined
if (!divEl) {
return
}
try {
editor = meditor.create(divEl as HTMLDivElement, {
...editorConfig(
code ?? '',
lang,
automaticLayout,
fixedOverflowWidgets,
$relativeLineNumbers
),
model,
...(yPadding !== undefined ? { padding: { bottom: yPadding, top: yPadding } } : {}),
readOnly,
renderLineHighlight,
// Same conditional as `updateModelAndOptions`: created correct rather than
// created wide and narrowed a tick later, which a caller hiding the gutter
// would see as a flash of indent.
lineDecorationsWidth: hideLineNumbers ? 0 : LINE_DECORATIONS_WIDTH,
lineNumbersMinChars: hideLineNumbers ? 0 : lineNumbersMinChars,
fontSize: fontSize,
quickSuggestions: disableSuggestions
? { other: false, comments: false, strings: false }
: { other: true, comments: true, strings: true },
suggestOnTriggerCharacters: !disableSuggestions,
wordBasedSuggestions: disableSuggestions ? 'off' : 'matchingDocuments',
parameterHints: { enabled: !disableSuggestions },
suggest: {
showIcons: !disableSuggestions,
showSnippets: !disableSuggestions,
showKeywords: !disableSuggestions,
showWords: !disableSuggestions,
snippetsPreventQuickSuggestions: disableSuggestions
}
})
if (key && editorPositionMap?.[key]) {
editor.setPosition(editorPositionMap[key])
editor.revealPositionInCenterIfOutsideViewport(editorPositionMap[key])
}
} catch (e) {
console.error('Error loading monaco:', e)
return
}
keepModelAroundToAvoidDisposalOfWorkers()
// In VSCode webview (iframe), clipboard operations need special handling
// because the webview has restricted clipboard API access
if (window.parent !== window) {
editor.addCommand(KeyMod.CtrlCmd | KeyCode.KeyC, function () {
document.execCommand('copy')
})
editor.addCommand(KeyMod.CtrlCmd | KeyCode.KeyX, function () {
document.execCommand('cut')
})
// Paste is intercepted via a keydown listener scoped to THIS editor's
// DOM node. `editor.addCommand` registers a *global* keybinding in the
// shared standalone services, so with multiple SimpleEditor instances
// the last-registered handler wins and paste lands in the wrong editor.
// The native `paste` event can't be used either: in the VSCode webview
// `clipboardData` is empty, so the only way to read the clipboard is to
// focus a real <input> and run `document.execCommand('paste')`.
const pasteTarget = divEl
const onPasteKeydown = (e: KeyboardEvent) => {
const isPaste = (e.ctrlKey || e.metaKey) && !e.altKey && (e.key === 'v' || e.key === 'V')
if (!isPaste) return
if (!editor || !editor.hasTextFocus()) return
e.preventDefault()
e.stopPropagation()
inputEl?.focus()
document.execCommand('paste')
}
pasteTarget?.addEventListener('keydown', onPasteKeydown, true)
pasteListenerCleanup = () => pasteTarget?.removeEventListener('keydown', onPasteKeydown, true)
}
editor.onDidChangeModelContent(() => {
// A paste is a single change, so under a trailing-only sync `code` stays
// stale for CHANGE_TIMEOUT after it: a consumer gating a control on `code`
// (FlowYamlEditor disables "Apply changes" until it differs from a snapshot)
// then swallows a click made in that window. Schedule before firing so a
// re-entrant change from a consumer does not count as leading too.
const leading = leadingChangeSync && changeTimeoutId === undefined
cancelPendingChanges()
changeTimeoutId = setTimeout(() => {
changeTimeoutId = undefined
updateCode()
}, CHANGE_TIMEOUT)
// `change` trails the buffer by CHANGE_TIMEOUT, too late for a consumer that has to
// know the moment the buffer stopped being the one it wrote. `input` says only that,
// carrying no value: read `getCode()` for what is on screen.
if (!applyingCode) {
dispatch('input')
}
if (leading) {
updateCode()
}
})
editor.onDidChangeCursorPosition((event) => {
if (key) editorPositionMap[key] = event.position
})
editor.onDidFocusEditorText(() => {
if (!editor) return
dispatch('focus')
loadExtraLib()
editor.addCommand(KeyMod.CtrlCmd | KeyCode.KeyS, function () {
updateCode()
shouldBindKey && format && format()
// See Editor.svelte — re-broadcast the swallowed shortcut for
// page-level draft-flush handlers, after `tick()` so they see
// the value `updateCode()` just materialized.
void tick().then(() => window.dispatchEvent(new CustomEvent('wm-monaco-save-shortcut')))
})
editor.addCommand(KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.Digit7, function () {
// CMD + slash (toggle comment) on some EU keyboards
editor?.trigger('keyboard', 'editor.action.commentLine', {})
})
})
if (autoHeight) {
const updateHeight = () => {
if (!editor) return
const contentHeight = Math.min(minHeight, editor.getContentHeight())
if (divEl) {
divEl.style.height = `${contentHeight}px`
}
try {
editor.layout({ width, height: contentHeight })
} finally {
}
}
editor.onDidContentSizeChange(updateHeight)
updateHeight()
}
editor.onDidFocusEditorText(() => {
if (!editor) return
editor.addCommand(KeyMod.CtrlCmd | KeyCode.KeyS, function () {
updateCode()
shouldBindKey && format && format()
// See Editor.svelte — re-broadcast the swallowed shortcut for
// page-level draft-flush handlers, after `tick()` so they see
// the value `updateCode()` just materialized.
void tick().then(() => window.dispatchEvent(new CustomEvent('wm-monaco-save-shortcut')))
})
editor.addCommand(KeyMod.CtrlCmd | KeyCode.Enter, function () {
updateCode()
shouldBindKey && cmdEnterAction && cmdEnterAction()
})
dispatch('focus')
})
editor.onDidBlurEditorText(() => {
dispatch('blur')
updateCode()
})
if (lang === 'css' && !cssClassesLoaded) {
cssClassesLoaded = true
addCSSClassCompletions()
}
if (lang === 'tailwindcss' && !tailwindClassesLoaded) {
languages.register({ id: 'tailwindcss' })
tailwindClassesLoaded = true
addTailwindClassCompletions()
}
if (placeholder) {
const syncPlaceholderOrigin = () => {
if (!editor) return
contentLeft = editor.getLayoutInfo().contentLeft
contentLineHeight = editor.getOption(meditor.EditorOption.lineHeight)
}
syncPlaceholderOrigin()
editor.onDidLayoutChange(syncPlaceholderOrigin)
editor.onDidChangeModelContent(() => {
if (!editor) return
const value = editor.getValue()
updatePlaceholderVisibility(value)
})
}
}
function addCSSClassCompletions() {
languages.registerCompletionItemProvider('css', {
provideCompletionItems: function (model, position, context, token) {
const word = model.getWordUntilPosition(position)
const range = {
startLineNumber: position.lineNumber,
startColumn: word.startColumn,
endLineNumber: position.lineNumber,
endColumn: word.endColumn
}
if (word && word.word) {
const currentWord = word.word
const suggestions = allClasses
.filter((className) => className.includes(currentWord))
.map((className) => ({
label: className,
kind: languages.CompletionItemKind.Class,
insertText: className,
documentation: 'Custom CSS class',
range: range
}))
return { suggestions }
}
return { suggestions: [] }
}
})
}
function addTailwindClassCompletions() {
// Define a custom word definition for Tailwind classes
languages.setMonarchTokensProvider('tailwindcss', {
tokenizer: {
root: [[/[a-zA-Z0-9-]+/, 'tailwind-class']]
}
})
languages.registerCompletionItemProvider('tailwindcss', {
triggerCharacters: ['-'],
provideCompletionItems: function (model, position, context, token) {
const wordUntilPosition = model.getWordUntilPosition(position)
const lineContent = model.getLineContent(position.lineNumber)
// Get the text from the start of the line to the cursor
const textUntilPosition = lineContent.substring(0, position.column - 1)
// Find the last space before the cursor
const lastSpaceIndex = textUntilPosition.lastIndexOf(' ')
const startColumn = lastSpaceIndex === -1 ? 1 : lastSpaceIndex + 2
const range = {
startLineNumber: position.lineNumber,
startColumn: startColumn,
endLineNumber: position.lineNumber,
endColumn: position.column
}
const currentWord = wordUntilPosition.word
const suggestions = tailwindClasses
.filter((className) => className.includes(currentWord))
.map((className) => ({
label: className,
kind: languages.CompletionItemKind.Class,
insertText: className,
documentation: 'Tailwind CSS class',
range: range,
preselect: true
}))
return { suggestions }
}
})
}
let previousExtraLib: string | undefined = undefined
function loadExtraLib() {
if (lang == 'javascript') {
const stdLib = { content: libStdContent, filePath: 'es6.d.ts' }
const libs = [stdLib]
if (domLib) {
const domDTS = { content: domContent, filePath: 'dom.d.ts' }
libs.push(domDTS)
}
if (extraLib != '') {
libs.push({
content: extraLib,
filePath: 'windmill.d.ts'
})
if (previousExtraLib == extraLib) {
return
}
previousExtraLib = extraLib
}
javascriptDefaults.setExtraLibs(libs)
}
}
onMount(async () => {
if (BROWSER) {
if (loadAsync) {
setTimeout(async () => {
await loadMonaco()
mounted = true
if (autofocus) setTimeout(() => focus(), 0)
}, 0)
} else {
await loadMonaco()
mounted = true
if (autofocus) setTimeout(() => focus(), 0)
}
}
})
$effect(() => {
if (mounted && extraLib && initialized) {
untrack(() => loadExtraLib())
}
})
onMount(() => registerPendingEditor({ flushPendingChanges: () => flushPendingChanges() }))
onDestroy(() => {
try {
// Same guards as Editor: only a pending keystroke debounce is ours to flush.
if (editor && changeTimeoutId !== undefined) {
updateCode()
}
cancelPendingChanges()
valueAfterDispose = getCode()
pasteListenerCleanup?.()
vimDisposable?.dispose()
model && model.dispose()
editor && editor.dispose()
} catch (err) {}
})
export function setCursorToEnd(): void {
if (editor) {
const lastLine = editor.getModel()?.getLineCount() ?? 1
const lastColumn = editor.getModel()?.getLineMaxColumn(lastLine) ?? 1
editor.setPosition({ lineNumber: lastLine, column: lastColumn })
editor.focus()
}
}
updatePlaceholderVisibility(code ?? '')
// Hidden input used as the paste sink in the VSCode webview: focusing it and
// running `document.execCommand('paste')` fills `pasteValue`, which is then
// inserted into this editor's model below. This is an inline equivalent of
// `registerWebviewPaste` in $lib/editorUtils (used by Editor/TemplateEditor/
// DiffEditor) — kept inline here because it relies on Svelte bindings; keep
// the two implementations in sync.
let inputEl = $state<HTMLInputElement | null>(null)
let pasteValue = $state('')
$effect(() => {
if (inputEl && pasteValue) {
untrack(() => {
const selection = editor?.getSelection()
if (editor && selection) {
editor.executeEdits('paste', [
{
range: selection,
text: pasteValue,
forceMoveMarkers: true
}
])
editor.focus()
}
pasteValue = ''
})
}
})
</script>
{#if parent.window !== window}
<input
style="height: 0; width: 0; opacity: 0; position: absolute; top: 0; left: 0; z-index: -1;"
type="text"
aria-hidden="true"
tabindex="-1"
bind:this={inputEl}
bind:value={pasteValue}
/>
{/if}
<EditorTheme />
{#if !editor || suggestion}
<FakeMonacoPlaceHolder
code={suggestion || code}
autoheight
lineNumbersWidth={hideLineNumbers ? 0 : (23 * fontSize) / 14}
lineNumbersOffset={fontSize == 14 ? -8 : -11}
{fontSize}
showNumbers={!hideLineNumbers}
/>
{/if}
<div
bind:this={divEl}
class={twMerge(
'relative editor simple-editor',
className,
suggestion ? 'absolute opacity-0 pointer-events-none' : '',
!editor ? 'hidden' : '',
disabled ? 'disabled' : '',
!allowVim ? 'nonmain-editor' : ''
)}
bind:clientWidth={width}
>
{#if placeholder}
<div
id="placeholder"
class="absolute text-tertiary pointer-events-none font-mono z-10 {placeholderVisible
? ''
: 'hidden'}"
style="left: {contentLeft}px; top: {yPadding}px; font-size: {fontSize}px; line-height: {contentLineHeight}px;"
>
{@html placeholder}
</div>
{/if}
</div>
{#if allowVim && vimMode}
<div class="fixed bottom-0 z-30" bind:this={statusDiv}></div>
{/if}
<style lang="postcss">
.editor {
@apply rounded-md p-0;
}
.small-editor {
/* stylelint-disable-next-line unit-allowed-list */
height: 26vh;
}
.few-lines-editor {
/* stylelint-disable-next-line unit-allowed-list */
height: 100px;
}
</style>