n8n-editor-ui
Version:
Workflow Editor UI for n8n
43,410 lines • 2 MB
JavaScript
;
(function () {
System.register(["./chunk-legacy-Re9CbdfL.js", "./vue.runtime.esm-bundler-legacy--Sn1h8On.js", "./_MapCache-legacy-DlYNX_X1.js", "./src-legacy-uZTNWMC0.js", "./preload-helper-legacy-CXRjoQ0T.js", "./_plugin-vue_export-helper-legacy-DZMI5HPp.js", "./truncate-legacy-BGje52Or.js", "./empty-legacy-CA9D6itE.js", "./useTelemetry-legacy-B3pzzkAE.js", "./useToast-legacy-C4Vu5mt9.js", "./constants-legacy-TKxWCqvM.js", "./merge-legacy-8xjIc_ts.js", "./assistant.store-legacy-Bo4ZVN6u.js", "./_baseOrderBy-legacy-CB2Dh5d_.js", "./useExternalHooks-legacy-8pg6K3ln.js", "./chatPanel.store-legacy-6e-l0_Mt.js", "./useRunWorkflow-legacy-BClq6Sr5.js", "./usePinnedData-legacy-CfMMmXZ8.js", "./useClipboard-legacy-DEPZr2pv.js", "./NDVEmptyState-legacy-jxrI30cG.js", "./externalSecrets.ee.store-legacy-7f0X4y9E.js", "./uniqBy-legacy-C7T-xRJq.js", "./RunDataHtml-legacy-BuMmN5Mb.js", "./schemaPreview.store-legacy-DaPvEjFt.js", "./FileSaver.min-legacy-D7uxxng5.js", "./vue-json-pretty-legacy-DXTjoBRT.js", "./useExecutionHelpers-legacy-DORjcnBO.js"], function (_export, _context) {
"use strict";
var __toESM, __commonJS, computed, toDisplayString, createElementBlock, createCommentVNode, unref, guardReactiveProps, ref, onBeforeUnmount, createVNode, defineAsyncComponent, defineComponent, createBlock, toRef, onMounted, Fragment, watch, renderSlot, withCtx, openBlock, withModifiers, renderList, createTextVNode, createSlots, vShow, resolveDirective, normalizeClass, createBaseVNode, withDirectives, Suspense, normalizeProps, I18nT, require_isObject, useI18n, computedAsync, require_isArray, i18n, N8nBlockUi_default, N8nCallout_default, ElPagination, N8nInfoTip_default, N8nSelect_default, N8nButton_default, N8nOption_default, InlineAskAssistantButton_default, N8nRadioButtons_default, N8nSpinner_default, N8nText_default, N8nIcon_default, N8nTabs_default, N8nTooltip_default, N8nLink_default, N8nIconButton_default, __vitePreload, __plugin_vue_export_helper_default, useRoute, useRouter, process$1, init_dist, escapeMappingString, searchInObject, useSourceControlStore, CREDENTIAL_EDIT_MODAL_KEY, useUIStore, parseAiContent, dataPinningEventBus, injectWorkflowState, useStorage, executionDataToJson, useAIAssistantHelpers, getGenericHints, useNDVStore, useNodeTypesStore, isPresent, useEnvironmentsStore, unwrapExpression, clearJsonKey, resolveParameter, usePostHog, hasTrimmedRunData, useWorkflowsStore, isPairedItemIntermediateNodesError, useTelemetry, isEmpty$1, useNodeHelpers, sanitizeHtml, useToast, jsonParse, MAX_DISPLAY_DATA_SIZE_SCHEMA_VIEW, base64DecodeUTF8, NODE_TYPES_EXCLUDED_FROM_OUTPUT_NAME_APPEND, DateTime, VIEWS, RUN_DATA_DEFAULT_PAGE_SIZE, NodeConnectionTypes, LOCAL_STORAGE_PIN_DATA_DISCOVERY_CANVAS_FLAG, LOCAL_STORAGE_PIN_DATA_DISCOVERY_NDV_FLAG, CODEMIRROR_TOOLTIP_CONTAINER_ELEMENT_ID, isCommunityPackageName, EXTENSION_OBJECTS, MAX_DISPLAY_DATA_SIZE, validateFieldType, Expression, ViewableMimeTypes, parseErrorMetadata, require_isEqual, CORE_NODES_CATEGORY, require__baseKeys, getConnectionTypes, NATIVE_METHODS, HTTP_REQUEST_NODE_TYPE, NDV_UI_OVERHAUL_EXPERIMENT, VALID_EMAIL_REGEX, DATA_PINNING_DOCS_URL, HTML_NODE_TYPE, getNodeOutputs, NEW_ASSISTANT_SESSION_MODAL, SPLIT_IN_BATCHES_NODE_TYPE, DATA_EDITING_DOCS_URL, require__getTag, require_isTypedArray, require_isBuffer, require_isArguments, require__isPrototype, require_isArrayLike, ndvEventBus, useAssistantStore, storeToRefs, useRootStore, useExternalHooks, useChatPanelStore, useRunWorkflow, useNodeType, usePinnedData, useClipboard, Cu, Ln, $d, NDVEmptyState_default, useExternalSecretsStore, require_uniqBy, RunDataHtml_default, useSchemaPreviewStore, require_FileSaver_min, P, useExecutionHelpers, __vite_style__, Text, TextLeaf$1, TextNode$1, RawTextCursor$1, PartialTextCursor$1, LineCursor$1, Line$1, extend$1, ZWJ$1, DefaultSplit$1, MapMode, ChangeDesc$1, ChangeSet, SectionIter$1, SelectionRange$1, EditorSelection, nextID$1, Facet$1, FacetProvider$1, initField$1, StateField$1, Prec_$1, Prec, PrecExtension$1, Compartment$1, CompartmentInstance$1, Configuration$1, languageData$1, allowMultipleSelections$1, lineSeparator$1, changeFilter$1, transactionFilter$1, transactionExtender$1, readOnly$1, Annotation, AnnotationType$1, StateEffectType$1, StateEffect$1, Transaction, none$3, CharCategory, nonASCIISingleCaseWordChar$1, wordChar$1, EditorState, RangeValue, Range$2, Chunk$1, RangeSet$1, RangeSetBuilder$1, LayerCursor$1, HeapCursor$1, SpanCursor$1, C, COUNT, SET, top, StyleModule, adoptedSet, StyleSet, base, shift, chrome$2, mac, ie$2, brokenModifierNames, i, code, DOMSelectionState$1, preventScrollSupported$1, scratchRange$1, DOMPos$1, noChildren$1, ContentView$1, ChildCursor$1, nav$1, doc$1, ie_edge$1, ie_upto10$1, ie_11up$1, ie$1, gecko$1, chrome$1, webkit$1, safari$1, ios$1, browser$1, MaxJoinLen$1, TextView$1, MarkView$1, WidgetView$1, WidgetBufferView$1, noAttrs$1, LineView$1, BlockWidgetView$1, WidgetType$1, BlockType$1, Decoration$1, MarkDecoration$1, LineDecoration$1, PointDecoration$1, ContentBuilder$1, NullWidget$1, Direction$1, LTR$1, RTL$1, LowTypes$1, ArabicTypes$1, Brackets$1, BracketStack$1, BidiRE$1, BidiSpan$1, types$1, movedOver$1, clickAddsSelectionRange$1, dragMovesSelection$1$1, mouseSelectionStyle$1, exceptionSink$1, updateListener$1, inputHandler$2, focusChangeEffect$1, perLineTextDirection$1, nativeSelectionHidden$1, scrollHandler, ScrollTarget$1, scrollIntoView$2, editable$1, nextPluginID$1, viewPlugin$1, ViewPlugin$1, PluginInstance$1, editorAttributes$1, contentAttributes$1, decorations$1, outerDecorations, atomicRanges$1, bidiIsolatedRanges$1, scrollMargins$1, styleModule$1, ChangedRange$1, ViewUpdate$1, DocView$1, BlockGapWidget$1, DecorationComparator$1$1, InputState$1, PendingKeys$1, EmacsyPendingKeys$1, modifierCodes$1, dragScrollMargin$1, MouseSelection$1, handlers$1, observers$1, brokenClipboardAPI$1, insideY$1, inside$1, BadMouseDetail$1, lastMouseDown$1, lastMouseDownCount$1, lastMouseDownTime$1, lastLinewiseCopy$1, isFocusChange$1, appliedFirefoxHack$1, wrappingWhiteSpace$1, HeightOracle$1, MeasuredHeights$1, BlockInfo$1, QueryType$2, Epsilon$1, HeightMap$1, HeightMapBlock$1, HeightMapText$1, HeightMapGap$1, HeightMapBranch$1, relevantWidgetHeight$1, NodeBuilder$1, DecorationComparator$2, LineGap$1, LineGapWidget$1, ViewState$1, Viewport$1, IdScaler$1, BigScaler$1, theme$1, darkTheme$1, baseThemeID$1, baseLightID$1, baseDarkID$1, lightDarkIDs$1, baseTheme$1$6, LineBreakPlaceholder$1, DOMReader$1, DOMPoint$1, DOMChange$1, observeOptions$1, useCharData$1, DOMObserver$1, EditorView, MaxBidiLine$1, BadMeasure$1, CachedOrder$1, currentPlatform$1, handleKeyEvents, keymap, Keymaps, storedPrefix, PrefixTimeout, RectangleMarker, LayerView, layerOrder, CanHidePrimary$1, selectionConfig, cursorLayer, selectionLayer, themeSpec$1, hideNativeSelection, setDropCursorPos$1, dropCursorPos$1, drawDropCursor$1, MatchDecorator, UnicodeRegexpSupport$1, Specials, Names, _supportsTabSize, specialCharConfig, _plugin, DefaultPlaceholder, SpecialCharWidget, TabWidget, lineDeco, activeLineHighlighter, Outside, TooltipViewManager, tooltipConfig, knownHeight, tooltipPlugin, baseTheme$4, noOffset, showTooltip, showHoverTooltip, HoverTooltipHost, showHoverTooltipHost, HoverPlugin, tooltipMargin, closeHoverTooltipEffect, panelConfig, panelPlugin, PanelGroup, showPanel, GutterMarker$1, gutterLineClass, defaults$1, activeGutters, unfixGutters, gutterView, UpdateContext, SingleGutterView, GutterElement, lineNumberMarkers, lineNumberConfig, NumberMarker, lineNumberGutter, activeLineGutterMarker, activeLineGutterHighlighter, DefaultBufferLength, nextPropID, Range$1, NodeProp, MountedTree, noProps, NodeType, NodeSet, CachedNode, CachedInnerNode, IterMode, Tree, FlatBufferCursor, TreeBuffer, BaseNode, TreeNode, BufferContext, BufferNode, StackIterator, TreeCursor, nodeSizeCache, NodeWeakMap, TreeFragment, Parser, StringInput, InnerParse, ActiveOverlay, stoppedInner, MixedParse, StructureCursor, FragmentCursor$1, nextTagID, Tag, nextModifierID, Modifier, ruleNodeProp, Rule, HighlightBuilder, t, comment, name, typeName, propertyName, literal, string, number, content, heading, keyword, operator, punctuation, bracket, meta, tags, classHighlighter, _a$1, languageDataProp$1, sublanguageProp$1, Language$1, LRLanguage, DocInput$1, currentContext$1, ParseContext$1, LanguageState$1, requestIdle$1, isInputPending$1, parseWorker$1, language$1, LanguageSupport, indentService, indentUnit, IndentContext, indentNodeProp, TreeIndentContext, flatIndent, DontIndentBeyond, foldService, foldNodeProp, foldEffect, unfoldEffect, foldState, foldCode, unfoldCode, foldAll, unfoldAll, defaultConfig, foldConfig, foldWidget, PreparedFoldWidget, foldGutterDefaults, FoldMarker, baseTheme$1$4, HighlightStyle, highlighterFacet, fallbackHighlighter, TreeHighlighter, treeHighlighter, defaultHighlightStyle$1, baseTheme$5, DefaultScanDist, DefaultBrackets, bracketMatchingConfig, matchingMark, nonmatchingMark, bracketMatchingUnique, bracketMatchingHandle, noTokens$1, typeArray$1, warned$1, byTag$1, defaultTable$1, marks, toggleComment, toggleLineComment, lineComment, lineUncomment, toggleBlockComment, toggleBlockCommentByLine, SearchMargin, fromHistory, isolateHistory, invertedEffects, historyConfig, historyField_, historyField, undo, redo, undoSelection, HistEvent, none$2, MaxSelectionsPerEvent, joinableUserEvent, HistoryState, cursorCharLeft, cursorCharRight, cursorGroupLeft, cursorGroupRight, segmenter, cursorLineUp, cursorLineDown, cursorPageUp, cursorPageDown, cursorLineBoundaryForward, cursorLineBoundaryBackward, cursorLineStart, cursorLineEnd, cursorMatchingBracket, selectCharLeft, selectCharRight, selectGroupLeft, selectGroupRight, selectLineUp, selectLineDown, selectPageUp, selectPageDown, selectLineBoundaryForward, selectLineBoundaryBackward, selectLineStart, selectLineEnd, cursorDocStart, cursorDocEnd, selectDocStart, selectDocEnd, selectAll, selectLine, deleteByChar, deleteCharBackward, deleteCharForward, deleteByGroup, deleteGroupBackward, deleteGroupForward, deleteToLineEnd, deleteToLineStart, splitLine, transposeChars, moveLineUp, moveLineDown, copyLineUp, copyLineDown, deleteLine, insertNewlineAndIndent, indentMore, indentLess, CompletionContext, Option, pickedCompletion, SourceCache, startCompletionEffect, closeCompletionEffect, FuzzyMatcher, StrictMatcher, completionConfig, CompletionTooltip, CompletionDialog, CompletionState, baseAttrs, none$1, ActiveSource, ActiveResult, setActiveEffect, setSelectedEffect, completionState, createTooltip, acceptCompletion, startCompletion, closeCompletion, RunningQuery, MaxUpdateCount, MinAbortTime, completionPlugin, windows, commitCharacters, baseTheme$3, FieldPos, FieldRange, Snippet, fieldMarker, fieldRange, ActiveSnippet, setActive, moveToField, snippetState, clearSnippet, nextSnippetField, prevSnippetField, defaultSnippetKeymap, snippetKeymap, addSnippetKeymap, snippetPointerHandler, defaults, closeBracketEffect, closedBracket, bracketState, definedClosing, android$1, inputHandler$1, deleteBracketPair, closeBracketsKeymap, completionKeymap, completionKeymapExt, Stack, StackContext, SimulatedStack, StackBufferCursor, CachedToken, nullToken, InputStream, TokenGroup, LocalTokenGroup, ExternalTokenizer, verbose, stackIDs, FragmentCursor, TokenCache, Parse, Dialect, id, ContextTracker, LRParser, TSExtends, noSemi, incdec, incdecPrefix, templateContent, InterpolationStart, templateEnd, insertSemi, spaces, newline, LineComment, BlockComment, Dialect_ts, space, braceR, braceL, semicolon, slash, star, plus, minus, dollar, backtick, backslash, trackNewline, insertSemicolon, noSemicolon, incdecToken, template, tsExtends, jsHighlight, spec_identifier, spec_word, spec_LessThan, parser$2, snippets, typescriptSnippets, cache, ScopeNodes, functionContext, gatherCompletions, Identifier, dontComplete, javascriptLanguage, jsxSublanguage, typescriptLanguage, jsxLanguage, tsxLanguage, kwCompletion, keywords, typescriptKeywords, android, autoCloseTags, prefixMatch, isPseudoParam, isAllowedInDotNotation, isCredentialsModalOpen, isInHttpNodePagination, hasActiveNode, isSplitInBatchesAbsent, stripExcessParens, getDefaultArgs, insertDefaultArgs, applyCompletion, applyBracketAccess, applyBracketAccessCompletion, hasRequiredArgs, sortCompletionsAlpha, renderSectionHeader, withSectionHeader, isCompletionSection, getDisplayType, shouldHighlightArgument, renderFunctionHeader, renderPropHeader, renderDescription, renderArg, renderArgList, renderArgs, renderExample, renderExamples, createInfoBoxRenderer, FIELDS_SECTION, RECOMMENDED_SECTION, RECOMMENDED_METHODS_SECTION, PREVIOUS_NODES_SECTION, PROPERTIES_SECTION, METHODS_SECTION, METADATA_SECTION, OTHER_METHODS_SECTION, OTHER_SECTION, ROOT_DOLLAR_COMPLETIONS, STRING_RECOMMENDED_OPTIONS, LUXON_RECOMMENDED_OPTIONS, OBJECT_RECOMMENDED_OPTIONS, ARRAY_RECOMMENDED_OPTIONS, ARRAY_NUMBER_ONLY_METHODS, LUXON_SECTIONS, STRING_SECTIONS, VARIABLE_SECTIONS, TARGET_NODE_PARAMETER_FACET, luxonInstanceDocs, luxonStaticDocs, import_uniqBy, natives, extensions, isInputData, isItem, isBinary, getDetail, toOptions, createCompletionOption, customObjectOptions, objectOptions, applySections, isUrl, stringOptions, booleanOptions, isWithinMargin, toTimestampUnit, numberOptions, dateOptions, luxonOptions, arrayOptions, variablesOptions, responseOptions, executionOptions, customDataOptions, nodeRefOptions, inputOptions, prevNodeOptions, itemOptions, binaryOptions, workflowOptions, secretOptions, secretProvidersOptions, luxonInstanceOptions, luxonStaticOptions, createLuxonAutocompleteOption, objectGlobalOptions, DATATYPE_REGEX, setDropCursorPos, dropCursorPos, drawDropCursor, expressionBracketSpacing, expressionCloseBracketsConfig, expressionCloseBrackets, basicNormalize, SearchCursor, empty, baseFlags, RegExpCursor, flattened, FlattenedDoc, MultilineRegExpCursor, dialogEffect, dialogField, gotoLine, baseTheme$1$1, defaultHighlightOptions, highlightConfig, matchDeco, mainMatchDeco, matchHighlighter, defaultTheme, selectWord, selectNextOccurrence, searchConfigFacet, SearchQuery, QueryType$1, StringQuery, RegExpQuery, setSearchQuery, togglePanel$1, searchState, SearchState, matchMark, selectedMatchMark, searchHighlighter, findNext, findPrevious, selectMatches, selectSelectionMatches, replaceNext, replaceAll, openSearchPanel, closeSearchPanel, SearchPanel, AnnounceMargin, Break, baseTheme$2, searchExtensions, createAddCursor, addCursorUp, addCursorDown, addCursorAtEachSelectionLine, SelectedDiagnostic, LintState, setDiagnosticsEffect, togglePanel, movePanelSelection, lintState, activeMark, openLintPanel, closeLintPanel, nextDiagnostic, previousDiagnostic, lintPlugin, lintConfig, DiagnosticWidget, PanelItem, LintPanel, baseTheme, LintGutterMarker, lintGutterExtension, lintGutterMarkers, setLintGutterTooltip, lintGutterTooltip, lintGutterTheme, lintExtensions, lintGutterConfig, languageFacet, SELECTED_AUTOCOMPLETE_OPTION_SELECTOR, onAutocompleteNavigate, editorKeymap, Text$1, TextLeaf, TextNode, RawTextCursor, PartialTextCursor, LineCursor, Line, extend, ZWJ, DefaultSplit, MapMode$1, ChangeDesc, ChangeSet$1, SectionIter, SelectionRange, EditorSelection$1, nextID, Facet, FacetProvider, initField, StateField, Prec_, Prec$1, PrecExtension, Compartment, CompartmentInstance, Configuration, languageData, allowMultipleSelections, lineSeparator, changeFilter, transactionFilter, transactionExtender, readOnly, Annotation$1, AnnotationType, StateEffectType, StateEffect, Transaction$1, none, CharCategory$1, nonASCIISingleCaseWordChar, wordChar, EditorState$1, RangeValue$1, Range, Chunk, RangeSet, RangeSetBuilder, LayerCursor, HeapCursor, SpanCursor, DOMSelectionState, preventScrollSupported, scratchRange, DOMPos, noChildren, ContentView, ChildCursor, nav, doc, ie_edge, ie_upto10, ie_11up, ie, gecko, chrome, webkit, safari, ios, browser, MaxJoinLen, TextView, MarkView, WidgetView, WidgetBufferView, noAttrs, LineView, BlockWidgetView, WidgetType, BlockType, Decoration, MarkDecoration, LineDecoration, PointDecoration, ContentBuilder, NullWidget, clickAddsSelectionRange, dragMovesSelection$1, mouseSelectionStyle, exceptionSink, updateListener, inputHandler, focusChangeEffect, perLineTextDirection, nativeSelectionHidden, ScrollTarget, scrollIntoView, editable, nextPluginID, viewPlugin, ViewPlugin, PluginInstance, editorAttributes, contentAttributes, decorations, atomicRanges, bidiIsolatedRanges, scrollMargins, styleModule, ChangedRange, ViewUpdate, Direction, LTR, RTL, LowTypes, ArabicTypes, Brackets, BracketStack, BidiRE, BidiSpan, types, movedOver, DocView, BlockGapWidget, DecorationComparator$1, InputState, PendingKeys, EmacsyPendingKeys, modifierCodes, dragScrollMargin, MouseSelection, handlers, observers, brokenClipboardAPI, insideY, inside, BadMouseDetail, lastMouseDown, lastMouseDownCount, lastMouseDownTime, lastLinewiseCopy, isFocusChange, appliedFirefoxHack, wrappingWhiteSpace, HeightOracle, MeasuredHeights, BlockInfo, QueryType, Epsilon, HeightMap, HeightMapBlock, HeightMapText, HeightMapGap, HeightMapBranch, relevantWidgetHeight, NodeBuilder, DecorationComparator, LineGap, LineGapWidget, ViewState, Viewport, IdScaler, BigScaler, theme, darkTheme, baseThemeID, baseLightID, baseDarkID, lightDarkIDs, baseTheme$1, LineBreakPlaceholder, DOMReader, DOMPoint, DOMChange, observeOptions, useCharData, DOMObserver, EditorView$1, MaxBidiLine, BadMeasure, CachedOrder, currentPlatform, CanHidePrimary, themeSpec, UnicodeRegexpSupport, GutterMarker, _a, languageDataProp, sublanguageProp, Language, LRLanguage$1, DocInput, currentContext, ParseContext, LanguageState, requestIdle, isInputPending, parseWorker, language, foldNodeProp$1, HighlightStyle$1, defaultHighlightStyle, noTokens, typeArray, warned, byTag, defaultTable, parser$1, expressionParser, parserWithMetaData, n8nLanguage$1, isResolvable, n8nParserWithNestedJsParser, n8nLanguage, n8nAutocompletion, BASE_STYLING, codeEditorSyntaxHighlighting, codeEditorTheme, jsonHighlighting, parser, jsonParseLinter, jsonLanguage, _hoisted_1$9, close_default, JsonEditor_vue_vue_type_script_setup_true_lang_default, fillHeight, JsonEditor_vue_vue_type_style_index_0_lang_module_default, cssModules$7, JsonEditor_default, DUMMY_PIN_DATA, SAMPLE_SUBWORKFLOW_TRIGGER_ID, SAMPLE_SUBWORKFLOW_WORKFLOW, SAMPLE_EVALUATION_WORKFLOW, NodeSettingsHint_vue_vue_type_script_setup_true_lang_default, settingsHint, settingItem, iconWrapper, icon$1, message, NodeSettingsHint_vue_vue_type_style_index_0_lang_module_default, cssModules$6, NodeSettingsHint_default, _hoisted_1$8, _hoisted_2$5, _hoisted_3$3, _hoisted_4$3, _hoisted_5$3, _hoisted_6$2, _hoisted_7$1, _hoisted_8$1, _hoisted_9$1, BinaryDataDisplayEmbed_vue_vue_type_script_setup_true_lang_default, BinaryDataDisplayEmbed_default, _hoisted_1$7, _hoisted_2$4, BinaryDataDisplay_vue_vue_type_script_setup_true_lang_default, BinaryDataDisplay_default, _hoisted_1$6, _hoisted_2$3, _hoisted_3$2, _hoisted_4$2, _hoisted_5$2, _hoisted_6$1, _hoisted_7, _hoisted_8, _hoisted_9, _hoisted_10, _hoisted_11, _hoisted_12, _hoisted_13, _hoisted_14, _hoisted_15, _hoisted_16, _hoisted_17, _hoisted_18, _hoisted_19, _hoisted_20, _hoisted_21, _hoisted_22, _hoisted_23, _hoisted_24, _hoisted_25, _hoisted_26, _hoisted_27, _hoisted_28, _hoisted_29, _hoisted_30, _hoisted_31, _hoisted_32, _hoisted_33, _hoisted_34, _hoisted_35, _hoisted_36, _hoisted_37, _hoisted_38, _hoisted_39, _hoisted_40, _hoisted_41, _hoisted_42, _hoisted_43, _hoisted_44, _hoisted_45, _hoisted_46, _hoisted_47, _hoisted_48, _hoisted_49, _hoisted_50, _hoisted_51, _hoisted_52, _hoisted_53, _hoisted_54, _hoisted_55, _hoisted_56, _hoisted_57, _hoisted_58, _hoisted_59, _hoisted_60, _hoisted_61, NodeErrorView_vue_vue_type_script_setup_true_lang_default, NodeErrorView_default, _hoisted_1$5, _hoisted_2$2, _hoisted_3$1, _hoisted_4$1, _hoisted_5$1, RunDataPinButton_vue_vue_type_script_setup_true_lang_default, pinDataButton, RunDataPinButton_vue_vue_type_style_index_0_lang_module_default, cssModules$5, RunDataPinButton_default, _hoisted_1$4, ViewSubExecution_vue_vue_type_script_setup_true_lang_default, relatedExecutionInfo, ViewSubExecution_vue_vue_type_style_index_0_lang_module_default, cssModules$4, ViewSubExecution_default, _hoisted_1$3, RunDataItemCount_vue_vue_type_script_setup_true_lang_default, itemsText, RunDataItemCount_vue_vue_type_style_index_0_lang_module_default, cssModules$3, RunDataItemCount_default, _hoisted_1$2, RunDataDisplayModeSelect_vue_vue_type_script_setup_true_lang_default, RunDataDisplayModeSelect_default, RunDataPaginationBar_vue_vue_type_script_setup_true_lang_default, pagination, pageSizeSelector, RunDataPaginationBar_vue_vue_type_style_index_0_lang_module_default, cssModules$2, RunDataPaginationBar_default, import_FileSaver_min$1, _hoisted_1$1, _hoisted_2$1, _hoisted_3, _hoisted_4, _hoisted_5, _hoisted_6, RunDataBinary_vue_vue_type_script_setup_true_lang_default, component, binaryIndex, binaryRow, binaryCell, binaryHeader, binaryButtonContainer, binaryValue, RunDataBinary_vue_vue_type_style_index_0_lang_module_default, cssModules$1, RunDataBinary_default, import_FileSaver_min, import_isEqual, import_isObject, _hoisted_1, _hoisted_2, RunData_vue_vue_type_script_setup_true_lang_default, infoIcon, center, container, pinnedDataCallout, header, compact, dataContainer, dataDisplay, inlineError, outputs, tabs, itemsCount, inputSelect, runSelector, runSelectorInner, runSelectorSelect, search, displayModes, showActionsOnHover, tooltipContain, spinner, editMode, editModeBody, editModeFooter, editModeFooterInfotip, editModeActions, stretchVertically, uiBlocker, uiBlockerNdvV2, hintCallout, schema, messageSection, singleIcon, multipleIcons, iconStack, icon, executingMessage, resetCollapseButton, title, dataSizeWarning, warningActions, RunData_vue_vue_type_style_index_0_lang_module_default, cssModules, RunData_default, require_isEmpty;
function textLength$1(text) {
let length = -1;
for (let line of text) length += line.length + 1;
return length;
}
function appendText$1(text, target, from = 0, to = 1e9) {
for (let pos = 0, i$1 = 0, first = true; i$1 < text.length && pos <= to; i$1++) {
let line = text[i$1],
end = pos + line.length;
if (end >= from) {
if (end > to) line = line.slice(0, to - pos);
if (pos < from) line = line.slice(from - pos);
if (first) {
target[target.length - 1] += line;
first = false;
} else target.push(line);
}
pos = end + 1;
}
return target;
}
function sliceText$1(text, from, to) {
return appendText$1(text, [""], from, to);
}
function clip$1(text, from, to) {
from = Math.max(0, Math.min(text.length, from));
return [from, Math.max(from, Math.min(text.length, to))];
}
function isExtendingChar$1(code$1) {
for (let i$1 = 1; i$1 < extend$1.length; i$1 += 2) if (extend$1[i$1] > code$1) return extend$1[i$1 - 1] <= code$1;
return false;
}
function isRegionalIndicator$1(code$1) {
return code$1 >= 127462 && code$1 <= 127487;
}
/**
Returns a next grapheme cluster break _after_ (not equal to)
`pos`, if `forward` is true, or before otherwise. Returns `pos`
itself if no further cluster break is available in the string.
Moves across surrogate pairs, extending characters (when
`includeExtending` is true), characters joined with zero-width
joiners, and flag emoji.
*/
function findClusterBreak(str, pos, forward = true, includeExtending = true) {
return (forward ? nextClusterBreak$1 : prevClusterBreak$1)(str, pos, includeExtending);
}
function nextClusterBreak$1(str, pos, includeExtending) {
if (pos == str.length) return pos;
if (pos && surrogateLow$1(str.charCodeAt(pos)) && surrogateHigh$1(str.charCodeAt(pos - 1))) pos--;
let prev = codePointAt(str, pos);
pos += codePointSize(prev);
while (pos < str.length) {
let next = codePointAt(str, pos);
if (prev == ZWJ$1 || next == ZWJ$1 || includeExtending && isExtendingChar$1(next)) {
pos += codePointSize(next);
prev = next;
} else if (isRegionalIndicator$1(next)) {
let countBefore = 0,
i$1 = pos - 2;
while (i$1 >= 0 && isRegionalIndicator$1(codePointAt(str, i$1))) {
countBefore++;
i$1 -= 2;
}
if (countBefore % 2 == 0) break;else pos += 2;
} else break;
}
return pos;
}
function prevClusterBreak$1(str, pos, includeExtending) {
while (pos > 0) {
let found = nextClusterBreak$1(str, pos - 2, includeExtending);
if (found < pos) return found;
pos--;
}
return 0;
}
function surrogateLow$1(ch) {
return ch >= 56320 && ch < 57344;
}
function surrogateHigh$1(ch) {
return ch >= 55296 && ch < 56320;
}
/**
Find the code point at the given position in a string (like the
[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
string method).
*/
function codePointAt(str, pos) {
let code0 = str.charCodeAt(pos);
if (!surrogateHigh$1(code0) || pos + 1 == str.length) return code0;
let code1 = str.charCodeAt(pos + 1);
if (!surrogateLow$1(code1)) return code0;
return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
}
/**
Given a Unicode codepoint, return the JavaScript string that
respresents it (like
[`String.fromCodePoint`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint)).
*/
function fromCodePoint(code$1) {
if (code$1 <= 65535) return String.fromCharCode(code$1);
code$1 -= 65536;
return String.fromCharCode((code$1 >> 10) + 55296, (code$1 & 1023) + 56320);
}
/**
The amount of positions a character takes up a JavaScript string.
*/
function codePointSize(code$1) {
return code$1 < 65536 ? 1 : 2;
}
function addSection$1(sections, len, ins, forceJoin = false) {
if (len == 0 && ins <= 0) return;
let last = sections.length - 2;
if (last >= 0 && ins <= 0 && ins == sections[last + 1]) sections[last] += len;else if (len == 0 && sections[last] == 0) sections[last + 1] += ins;else if (forceJoin) {
sections[last] += len;
sections[last + 1] += ins;
} else sections.push(len, ins);
}
function addInsert$1(values, sections, value) {
if (value.length == 0) return;
let index = sections.length - 2 >> 1;
if (index < values.length) values[values.length - 1] = values[values.length - 1].append(value);else {
while (values.length < index) values.push(Text.empty);
values.push(value);
}
}
function iterChanges$1(desc, f, individual) {
let inserted = desc.inserted;
for (let posA = 0, posB = 0, i$1 = 0; i$1 < desc.sections.length;) {
let len = desc.sections[i$1++],
ins = desc.sections[i$1++];
if (ins < 0) {
posA += len;
posB += len;
} else {
let endA = posA,
endB = posB,
text = Text.empty;
for (;;) {
endA += len;
endB += ins;
if (ins && inserted) text = text.append(inserted[i$1 - 2 >> 1]);
if (individual || i$1 == desc.sections.length || desc.sections[i$1 + 1] < 0) break;
len = desc.sections[i$1++];
ins = desc.sections[i$1++];
}
f(posA, endA, posB, endB, text);
posA = endA;
posB = endB;
}
}
}
function mapSet$1(setA, setB, before, mkSet = false) {
let sections = [],
insert$2 = mkSet ? [] : null;
let a = new SectionIter$1(setA),
b = new SectionIter$1(setB);
for (let inserted = -1;;) if (a.ins == -1 && b.ins == -1) {
let len = Math.min(a.len, b.len);
addSection$1(sections, len, -1);
a.forward(len);
b.forward(len);
} else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
let len = b.len;
addSection$1(sections, b.ins, -1);
while (len) {
let piece = Math.min(a.len, len);
if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
addSection$1(sections, 0, a.ins);
if (insert$2) addInsert$1(insert$2, sections, a.text);
inserted = a.i;
}
a.forward(piece);
len -= piece;
}
b.next();
} else if (a.ins >= 0) {
let len = 0,
left = a.len;
while (left) if (b.ins == -1) {
let piece = Math.min(left, b.len);
len += piece;
left -= piece;
b.forward(piece);
} else if (b.ins == 0 && b.len < left) {
left -= b.len;
b.next();
} else break;
addSection$1(sections, len, inserted < a.i ? a.ins : 0);
if (insert$2 && inserted < a.i) addInsert$1(insert$2, sections, a.text);
inserted = a.i;
a.forward(a.len - left);
} else if (a.done && b.done) return insert$2 ? ChangeSet.createSet(sections, insert$2) : ChangeDesc$1.create(sections);else throw new Error("Mismatched change set lengths");
}
function composeSets$1(setA, setB, mkSet = false) {
let sections = [];
let insert$2 = mkSet ? [] : null;
let a = new SectionIter$1(setA),
b = new SectionIter$1(setB);
for (let open = false;;) if (a.done && b.done) return insert$2 ? ChangeSet.createSet(sections, insert$2) : ChangeDesc$1.create(sections);else if (a.ins == 0) {
addSection$1(sections, a.len, 0, open);
a.next();
} else if (b.len == 0 && !b.done) {
addSection$1(sections, 0, b.ins, open);
if (insert$2) addInsert$1(insert$2, sections, b.text);
b.next();
} else if (a.done || b.done) throw new Error("Mismatched change set lengths");else {
let len = Math.min(a.len2, b.len),
sectionLen = sections.length;
if (a.ins == -1) {
let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
addSection$1(sections, len, insB, open);
if (insert$2 && insB) addInsert$1(insert$2, sections, b.text);
} else if (b.ins == -1) {
addSection$1(sections, a.off ? 0 : a.len, len, open);
if (insert$2) addInsert$1(insert$2, sections, a.textBit(len));
} else {
addSection$1(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
if (insert$2 && !b.off) addInsert$1(insert$2, sections, b.text);
}
open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
a.forward2(len);
b.forward(len);
}
}
function checkSelection$1(selection, docLength) {
for (let range of selection.ranges) if (range.to > docLength) throw new RangeError("Selection points outside of document");
}
function sameArray$2(a, b) {
return a == b || a.length == b.length && a.every((e, i$1) => e === b[i$1]);
}
function compareArray$1(a, b, compare$2) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) if (!compare$2(a[i$1], b[i$1])) return false;
return true;
}
function ensureAll$1(state, addrs) {
let changed = false;
for (let addr of addrs) if (ensureAddr$1(state, addr) & 1) changed = true;
return changed;
}
function dynamicFacetSlot$1(addresses, facet, providers) {
let providerAddrs = providers.map(p => addresses[p.id]);
let providerTypes = providers.map(p => p.type);
let dynamic = providerAddrs.filter(p => !(p & 1));
let idx = addresses[facet.id] >> 1;
function get(state) {
let values = [];
for (let i$1 = 0; i$1 < providerAddrs.length; i$1++) {
let value = getAddr$1(state, providerAddrs[i$1]);
if (providerTypes[i$1] == 2) for (let val of value) values.push(val);else values.push(value);
}
return facet.combine(values);
}
return {
create(state) {
for (let addr of providerAddrs) ensureAddr$1(state, addr);
state.values[idx] = get(state);
return 1;
},
update(state, tr) {
if (!ensureAll$1(state, dynamic)) return 0;
let value = get(state);
if (facet.compare(value, state.values[idx])) return 0;
state.values[idx] = value;
return 1;
},
reconfigure(state, oldState) {
let depChanged = ensureAll$1(state, providerAddrs);
let oldProviders = oldState.config.facets[facet.id],
oldValue = oldState.facet(facet);
if (oldProviders && !depChanged && sameArray$2(providers, oldProviders)) {
state.values[idx] = oldValue;
return 0;
}
let value = get(state);
if (facet.compare(value, oldValue)) {
state.values[idx] = oldValue;
return 0;
}
state.values[idx] = value;
return 1;
}
};
}
function prec$1(value) {
return ext => new PrecExtension$1(ext, value);
}
/**
By default extensions are registered in the order they are found
in the flattened form of nested array that was provided.
Individual extension values can be assigned a precedence to
override this. Extensions that do not have a precedence set get
the precedence of the nearest parent with a precedence, or
[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
final ordering of extensions is determined by first sorting by
precedence and then by order within each precedence.
*/
function flatten$1(extension, compartments, newCompartments) {
let result = [[], [], [], [], []];
let seen = /* @__PURE__ */new Map();
function inner(ext, prec$2) {
let known = seen.get(ext);
if (known != null) {
if (known <= prec$2) return;
let found = result[known].indexOf(ext);
if (found > -1) result[known].splice(found, 1);
if (ext instanceof CompartmentInstance$1) newCompartments.delete(ext.compartment);
}
seen.set(ext, prec$2);
if (Array.isArray(ext)) for (let e of ext) inner(e, prec$2);else if (ext instanceof CompartmentInstance$1) {
if (newCompartments.has(ext.compartment)) throw new RangeError(`Duplicate use of compartment in extensions`);
let content$1 = compartments.get(ext.compartment) || ext.inner;
newCompartments.set(ext.compartment, content$1);
inner(content$1, prec$2);
} else if (ext instanceof PrecExtension$1) inner(ext.inner, ext.prec);else if (ext instanceof StateField$1) {
result[prec$2].push(ext);
if (ext.provides) inner(ext.provides, prec$2);
} else if (ext instanceof FacetProvider$1) {
result[prec$2].push(ext);
if (ext.facet.extensions) inner(ext.facet.extensions, Prec_$1.default);
} else {
let content$1 = ext.extension;
if (!content$1) throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
inner(content$1, prec$2);
}
}
inner(extension, Prec_$1.default);
return result.reduce((a, b) => a.concat(b));
}
function ensureAddr$1(state, addr) {
if (addr & 1) return 2;
let idx = addr >> 1;
let status = state.status[idx];
if (status == 4) throw new Error("Cyclic dependency between fields and/or facets");
if (status & 2) return status;
state.status[idx] = 4;
let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
return state.status[idx] = 2 | changed;
}
function getAddr$1(state, addr) {
return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
}
function joinRanges$1(a, b) {
let result = [];
for (let iA = 0, iB = 0;;) {
let from, to;
if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
from = a[iA++];
to = a[iA++];
} else if (iB < b.length) {
from = b[iB++];
to = b[iB++];
} else return result;
if (!result.length || result[result.length - 1] < from) result.push(from, to);else if (result[result.length - 1] < to) result[result.length - 1] = to;
}
}
function mergeTransaction$1(a, b, sequential) {
var _a$2;
let mapForA, mapForB, changes;
if (sequential) {
mapForA = b.changes;
mapForB = ChangeSet.empty(b.changes.length);
changes = a.changes.compose(b.changes);
} else {
mapForA = b.changes.map(a.changes);
mapForB = a.changes.mapDesc(b.changes, true);
changes = a.changes.compose(mapForA);
}
return {
changes,
selection: b.selection ? b.selection.map(mapForB) : (_a$2 = a.selection) === null || _a$2 === void 0 ? void 0 : _a$2.map(mapForA),
effects: StateEffect$1.mapEffects(a.effects, mapForA).concat(StateEffect$1.mapEffects(b.effects, mapForB)),
annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
scrollIntoView: a.scrollIntoView || b.scrollIntoView
};
}
function resolveTransactionInner$1(state, spec, docSize) {
let sel = spec.selection,
annotations = asArray$2(spec.annotations);
if (spec.userEvent) annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent));
return {
changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator$1)),
selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)),
effects: asArray$2(spec.effects),
annotations,
scrollIntoView: !!spec.scrollIntoView
};
}
function resolveTransaction$1(state, specs, filter) {
let s = resolveTransactionInner$1(state, specs.length ? specs[0] : {}, state.doc.length);
if (specs.length && specs[0].filter === false) filter = false;
for (let i$1 = 1; i$1 < specs.length; i$1++) {
if (specs[i$1].filter === false) filter = false;
let seq = !!specs[i$1].sequential;
s = mergeTransaction$1(s, resolveTransactionInner$1(state, specs[i$1], seq ? s.changes.newLength : state.doc.length), seq);
}
let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
return extendTransaction$1(filter ? filterTransaction$1(tr) : tr);
}
function filterTransaction$1(tr) {
let state = tr.startState;
let result = true;
for (let filter of state.facet(changeFilter$1)) {
let value = filter(tr);
if (value === false) {
result = false;
break;
}
if (Array.isArray(value)) result = result === true ? value : joinRanges$1(result, value);
}
if (result !== true) {
let changes, back;
if (result === false) {
back = tr.changes.invertedDesc;
changes = ChangeSet.empty(state.doc.length);
} else {
let filtered = tr.changes.filter(result);
changes = filtered.changes;
back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
}
tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect$1.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
}
let filters = state.facet(transactionFilter$1);
for (let i$1 = filters.length - 1; i$1 >= 0; i$1--) {
let filtered = filters[i$1](tr);
if (filtered instanceof Transaction) tr = filtered;else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) tr = filtered[0];else tr = resolveTransaction$1(state, asArray$2(filtered), false);
}
return tr;
}
function extendTransaction$1(tr) {
let state = tr.startState,
extenders = state.facet(transactionExtender$1),
spec = tr;
for (let i$1 = extenders.length - 1; i$1 >= 0; i$1--) {
let extension = extenders[i$1](tr);
if (extension && Object.keys(extension).length) spec = mergeTransaction$1(spec, resolveTransactionInner$1(state, extension, tr.changes.newLength), true);
}
return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
}
function asArray$2(value) {
return value == null ? none$3 : Array.isArray(value) ? value : [value];
}
/**
The categories produced by a [character
categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
do things like selecting by word.
*/
function hasWordChar$1(str) {
if (wordChar$1) return wordChar$1.test(str);
for (let i$1 = 0; i$1 < str.length; i$1++) {
let ch = str[i$1];
if (/\w/.test(ch) || ch > "" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar$1.test(ch))) return true;
}
return false;
}
function makeCategorizer$1(wordChars) {
return char => {
if (!/\S/.test(char)) return CharCategory.Space;
if (hasWordChar$1(char)) return CharCategory.Word;
for (let i$1 = 0; i$1 < wordChars.length; i$1++) if (char.indexOf(wordChars[i$1]) > -1) return CharCategory.Word;
return CharCategory.Other;
};
}
/**
The editor state class is a persistent (immutable) data structure.
To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
instance, without modifying the original object.
As such, _never_ mutate properties of a state directly. That'll
just break things.
*/
/**
Utility function for combining behaviors to fill in a config
object from an array of provided configs. `defaults` should hold
default values for all optional fields in `Config`.
The function will, by default, error
when a field gets two values that aren't `===`-equal, but you can
provide combine functions per field to do something else.
*/
function combineConfig$1(configs, defaults$2, combine = {}) {
let result = {};
for (let config$1 of configs) for (let key of Object.keys(config$1)) {
let value = config$1[key],
current = result[key];
if (current === void 0) result[key] = value;else if (current === value || value === void 0) ;else if (Object.hasOwnProperty.call(combine, key)) result[key] = combine[key](current, value);else throw new Error("Config merge conflict for field " + key);
}
for (let key in defaults$2) if (result[key] === void 0) result[key] = defaults$2[key];
return result;
}
/**
Each range is associated with a value, which must inherit from
this class.
*/
function cmpRange$1(a, b) {
return a.from - b.from || a.value.startSide - b.value.startSide;
}
function lazySort$1(ranges) {
if (ranges.length > 1) for (let prev = ranges[0], i$1 = 1; i$1 < ranges.length; i$1++) {
let cur$1 = ranges[i$1];
if (cmpRange$1(prev, cur$1) > 0) return ranges.slice().sort(cmpRange$1);
prev = cur$1;
}
return ranges;
}
function findSharedChunks$1(a, b, textDiff) {
let inA = /* @__PURE__ */new Map();
for (let set of a) for (let i$1 = 0; i$1 < set.chunk.length; i$1++) if (set.chunk[i$1].maxPoint <= 0) inA.set(set.chunk[i$1], set.chunkPos[i$1]);
let shared = /* @__PURE__ */new Set();
for (let set of b) for (let i$1 = 0; i$1 < set.chunk.length; i$1++) {
let known = inA.get(set.chunk[i$1]);
if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i$1] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i$1].length))) shared.add(set.chunk[i$1]);
}
return shared;
}
function heapBubble$1(heap, index) {
for (let cur$1 = heap[index];;) {
let childIndex = (index << 1) + 1;
if (childIndex >= heap.length) break;
let child = heap[childIndex];
if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
child = heap[childIndex + 1];
childIndex++;
}
if (cur$1.compare(child) < 0) break;
heap[childIndex] = cur$1;
heap[index] = child;
index = childIndex;
}
}
function compare$1(a, startA, b, startB, length, comparator) {
a.goto(startA);
b.goto(startB);
let endB = startB + length;
let pos = startB,
dPos = startB - startA;
for (;;) {
let diff = a.to + dPos - b.to || a.endSide - b.endSide;
let end = diff < 0 ? a.to + dPos : b.to,
clipEnd = Math.min(end, endB);
if (a.point || b.point) {
if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && sameValues$1(a.activeForPoint(a.to), b.activeForPoint(b.to)))) comparator.comparePoint(pos, clipEnd, a.point, b.point);
} else if (clipEnd > pos && !sameValues$1(a.active, b.active)) comparator.compareRange(pos, clipEnd, a.active, b.active);
if (end > endB) break;
pos = end;
if (diff <= 0) a.next();
if (diff >= 0) b.next();
}
}
function sameValues$1(a, b) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) if (a[i$1] != b[i$1] && !a[i$1].eq(b[i$1])) return false;
return true;
}
function remove$1(array, index) {
for (let i$1 = index, e = array.length - 1; i$1 < e; i$1++) array[i$1] = array[i$1 + 1];
array.pop();
}
function insert$1(array, index, value) {
for (let i$1 = array.length - 1; i$1 >= index; i$1--) array[i$1 + 1] = array[i$1];
array[index] = value;
}
function findMinIndex$1(value, array) {
let found = -1,
foundPos = 1e9;
for (let i$1 = 0; i$1 < array.length; i$1++) if ((array[i$1] - foundPos || value[i$1].endSide - value[found].endSide) < 0) {
found = i$1;
foundPos = array[i$1];
}
return found;
}
/**
Count the column position at the given offset into the string,
taking extending characters and tab size into account.
*/
function countColumn$1(string$1, tabSize, to = string$1.length) {
let n = 0;
for (let i$1 = 0; i$1 < to;) if (string$1.charCodeAt(i$1) == 9) {
n += tabSize - n % tabSize;
i$1++;
} else {
n++;
i$1 = findClusterBreak(string$1, i$1);
}
return n;
}
/**
Find the offset that corresponds to the given column position in a
string, taking extending characters and tab size into account. By
default, the string length is returned when it is too short to
reach the column. Pass `strict` true to make it return -1 in that
situation.
*/
function findColumn(string$1, col, tabSize, strict) {
for (let i$1 = 0, n = 0;;) {
if (n >= col) return i$1;
if (i$1 == string$1.length) break;
n += string$1.charCodeAt(i$1) == 9 ? tabSize - n % tabSize : 1;
i$1 = findClusterBreak(string$1, i$1);
}
return strict === true ? -1 : string$1.length;
}
//#endregion
//#region ../../../node_modules/.pnpm/style-mod@4.1.0/node_modules/style-mod/src/style-mod.js
function keyName(event) {
var name$1 = !(brokenModifierNames && (event.ctrlKey || event.altKey || event.metaKey) || ie$2 && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified") && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified";
if (name$1 == "Esc") name$1 = "Escape";
if (name$1 == "Del") name$1 = "Delete";
if (name$1 == "Left") name$1 = "ArrowLeft";
if (name$1 == "Up") name$1 = "ArrowUp";
if (name$1 == "Right") name$1 = "ArrowRight";
if (name$1 == "Down") name$1 = "ArrowDown";
return name$1;
}
//#endregion
//#region ../../../node_modules/.pnpm/@codemirror+view@6.26.3/node_modules/@codemirror/view/dist/index.js
function getSelection$1(root) {
let target;
if (root.nodeType == 11) target = root.getSelection ? root : root.ownerDocument;else target = root;
return target.getSelection();
}
function contains$1(dom, node) {
return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
}
function deepActiveElement$1(doc$2) {
let elt = doc$2.activeElement;
while (elt && elt.shadowRoot) elt = elt.shadowRoot.activeElement;
return elt;
}
function hasSelection$1(dom, selection) {
if (!selection.anchorNode) return false;
try {
return contains$1(dom, selection.anchorNode);
} catch (_) {
return false;
}
}
function clientRectsFor$1(dom) {
if (dom.nodeType == 3) return textRange$1(dom, 0, dom.nodeValue.length).getClientRects();else if (dom.nodeType == 1) return dom.getClientRects();else return [];
}
function isEquivalentPosition$1(node, off, targetNode, targetOff) {
return targetNode ? scanFor$1(node, off, targetNode, targetOff, -1) || scanFor$1(node, off, targetNode, targetOff, 1) : false;
}
function domIndex$1(node) {
for (var index = 0;; index++) {
node = node.previousSibling;
if (!node) return index;
}
}
function isBlockElement$1(node) {
return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
}
function scanFor$1(node, off, targetNode, targetOff, dir) {
for (;;) {
if (node == targetNode && off == targetOff) return true;
if (off == (dir < 0 ? 0 : maxOffset$1(node))) {
if (node.nodeName == "DIV") return false;
let parent = node.parentNode;
if (!parent || parent.nodeType != 1) return false;
off = domIndex$1(node) + (dir < 0 ? 0 : 1);
node = parent;
} else if (node.nodeType == 1) {
node = node.childNodes[off + (dir < 0 ? -1 : 0)];
if (node.nodeType == 1 && node.contentEditable == "false") return false;
off = dir < 0 ? maxOffset$1(node) : 0;
} else return false;
}
}
function maxOffset$1(node) {
return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function flattenRect$1(rect, left) {
let x = left ? rect.left : rect.right;
return {
left: x,
right: x,
top: rect.top,
bottom: rect.bottom
};
}
function windowRect$1(win) {
let vp = win.visualViewport;
if (vp) return {
left: 0,
right: vp.width,
top: 0,
bottom: vp.height
};
return {
left: 0,
right: win.innerWidth,
top: 0,
bottom: win.innerHeight
};
}
function getScale$1(elt, rect) {
let scaleX = rect.width / elt.offsetWidth;
let scaleY = rect.height / elt.offsetHeight;
if (scaleX > .995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1) scaleX = 1;
if (scaleY > .995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1) scaleY = 1;
return {
scaleX,
scaleY
};
}
function scrollRectIntoView$1(dom, rect, side, x, y, xMargin, yMargin, ltr) {
let doc$2 = dom.ownerDocument,
win = doc$2.defaultView || window;
for (let cur$1 = dom, stop = false; cur$1 && !stop;) if (cur$1.nodeType == 1) {
let bounding,
top$1 = cur$1 == doc$2.body;
let scaleX = 1,
scaleY = 1;
if (top$1) bounding = windowRect$1(win);else {
if (/^(fixed|sticky)$/.test(getComputedStyle(cur$1).position)) stop = true;
if (cur$1.scrollHeight <= cur$1.clientHeight && cur$1.scrollWidth <= cur$1.clientWidth) {
cur$1 = cur$1.assignedSlot || cur$1.parentNode;
continue;
}
let rect$1 = cur$1.getBoundingClientRect();
({
scaleX,
scaleY
} = getScale$1(cur$1, rect$1));
bounding = {
left: rect$1.left,
right: rect$1.left + cur$1.clientWidth * scaleX,
top: rect$1.top,
bottom: rect$1.top + cur$1.clientHeight * scaleY
};
}
let moveX = 0,
moveY = 0;
if (y == "nearest") {
if (rect.top < bounding.top) {
moveY = -(bounding.top - rect.top + yMargin);
if (side > 0 && rect.bottom > bounding.bottom + moveY) moveY = rect.bottom - bounding.bottom + moveY + yMargin;
} else if (rect.bottom > bounding.bottom) {
moveY = rect.bottom - bounding.bottom + yMargin;
if (side < 0 && rect.top - moveY < bounding.top) moveY = -(bounding.top + moveY - rect.top + yMargin);
}
} else {
let rectHeight = rect.bottom - rect.top,
boundingHeight = bounding.bottom - bounding.top;
moveY = (y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y == "start" || y == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin) - bounding.top;
}
if (x == "nearest") {
if (rect.left < bounding.left) {
moveX = -(bounding.left - rect.left + xMargin);
if (side > 0 && rect.right > bounding.right + moveX) moveX = rect.right - bounding.right + moveX + xMargin;
} else if (rect.right > bounding.right) {
moveX = rect.right - bounding.right + xMargin;
if (side < 0 && rect.left < bounding.left + moveX) moveX = -(bounding.left + moveX - rect.left + xMargin);
}
} else moveX = (x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin) - bounding.left;
if (moveX || moveY) if (top$1) win.scrollBy(moveX, moveY);else {
let movedX = 0,
movedY = 0;
if (moveY) {
let start = cur$1.scrollTop;
cur$1.scrollTop += moveY / scaleY;
movedY = (cur$1.scrollTop - start) * scaleY;
}
if (moveX) {
let start = cur$1.scrollLeft;
cur$1.scrollLeft += moveX / scaleX;
movedX = (cur$1.scrollLeft - start) * scaleX;
}
rect = {
left: rect.left - movedX,
top: rect.top - movedY,
right: rect.right - movedX,
bottom: rect.bottom - movedY
};
if (movedX && Math.abs(movedX - moveX) < 1) x = "nearest";
if (movedY && Math.abs(movedY - moveY) < 1) y = "nearest";
}
if (top$1) break;
cur$1 = cur$1.assignedSlot || cur$1.parentNode;
} else if (cur$1.nodeType == 11) cur$1 = cur$1.host;else break;
}
function scrollableParent$1(dom) {
let doc$2 = dom.ownerDocument;
for (let cur$1 = dom.parentNode; cur$1;) if (cur$1 == doc$2.body) break;else if (cur$1.nodeType == 1) {
if (cur$1.scrollHeight > cur$1.clientHeight || cur$1.scrollWidth > cur$1.clientWidth) return cur$1;
cur$1 = cur$1.assignedSlot || cur$1.parentNode;
} else if (cur$1.nodeType == 11) cur$1 = cur$1.host;else break;
return null;
}
function focusPreventScroll$1(dom) {
if (dom.setActive) return dom.setActive();
if (preventScrollSupported$1) return dom.focus(preventScrollSupported$1);
let stack = [];
for (let cur$1 = dom; cur$1; cur$1 = cur$1.parentNode) {
stack.push(cur$1, cur$1.scrollTop, cur$1.scrollLeft);
if (cur$1 == cur$1.ownerDocument) break;
}
dom.focus(preventScrollSupported$1 == null ? {
get preventScroll() {
preventScrollSupported$1 = {
preventScroll: true
};
return true;
}
} : void 0);
if (!preventScrollSupported$1) {
preventScrollSupported$1 = false;
for (let i$1 = 0; i$1 < stack.length;) {
let elt = stack[i$1++],
top$1 = stack[i$1++],
left = stack[i$1++];
if (elt.scrollTop != top$1) elt.scrollTop = top$1;
if (elt.scrollLeft != left) elt.scrollLeft = left;
}
}
}
function textRange$1(node, from, to = from) {
let range = scratchRange$1 || (scratchRange$1 = document.createRange());
range.setEnd(node, to);
range.setStart(node, from);
return range;
}
function dispatchKey$1(elt, name$1, code$1, mods) {
let options = {
key: name$1,
code: name$1,
keyCode: code$1,
which: code$1,
cancelable: true
};
if (mods) ({
altKey: options.altKey,
ctrlKey: options.ctrlKey,
shiftKey: options.shiftKey,
metaKey: options.metaKey
} = mods);
let down = new KeyboardEvent("keydown", options);
down.synthetic = true;
elt.dispatchEvent(down);
let up = new KeyboardEvent("keyup", options);
up.synthetic = true;
elt.dispatchEvent(up);
return down.defaultPrevented || up.defaultPrevented;
}
function getRoot$1(node) {
while (node) {
if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) return node;
node = node.assignedSlot || node.parentNode;
}
return null;
}
function clearAttributes$1(node) {
while (node.attributes.length) node.removeAttributeNode(node.attributes[0]);
}
function atElementStart$1(doc$2, selection) {
let node = selection.focusNode,
offset = selection.focusOffset;
if (!node || selection.anchorNode != node || selection.anchorOffset != offset) return false;
offset = Math.min(offset, maxOffset$1(node));
for (;;) if (offset) {
if (node.nodeType != 1) return false;
let prev = node.childNodes[offset - 1];
if (prev.contentEditable == "false") offset--;else {
node = prev;
offset = maxOffset$1(node);
}
} else if (node == doc$2) return true;else {
offset = domIndex$1(node);
node = node.parentNode;
}
}
function isScrolledToBottom$1(elt) {
return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
}
function textNodeBefore(startNode, startOffset) {
for (let node = startNode, offset = startOffset;;) if (node.nodeType == 3 && offset > 0) return {
node,
offset
};else if (node.nodeType == 1 && offset > 0) {
if (node.contentEditable == "false") return null;
node = node.childNodes[offset - 1];
offset = maxOffset$1(node);
} else if (node.parentNode && !isBlockElement$1(node)) {
offset = domIndex$1(node);
node = node.parentNode;
} else return null;
}
function textNodeAfter(startNode, startOffset) {
for (let node = startNode, offset = startOffset;;) if (node.nodeType == 3 && offset < node.nodeValue.length) return {
node,
offset
};else if (node.nodeType == 1 && offset < node.childNodes.length) {
if (node.contentEditable == "false") return null;
node = node.childNodes[offset];
offset = 0;
} else if (node.parentNode && !isBlockElement$1(node)) {
offset = domIndex$1(node) + 1;
node = node.parentNode;
} else return null;
}
function rm$1$1(dom) {
let next = dom.nextSibling;
dom.parentNode.removeChild(dom);
return next;
}
function replaceRange$1(parent, fromI, fromOff, toI, toOff, insert$2, breakAtStart, openStart, openEnd) {
let {
children
} = parent;
let before = children.length ? children[fromI] : null;
let last = insert$2.length ? insert$2[insert$2.length - 1] : null;
let breakAtEnd = last ? last.breakAfter : breakAtStart;
if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert$2.length < 2 && before.merge(fromOff, toOff, insert$2.length ? last : null, fromOff == 0, openStart, openEnd)) return;
if (toI < children.length) {
let after = children[toI];
if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {
if (fromI == toI) {
after = after.split(toOff);
toOff = 0;
}
if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) insert$2[insert$2.length - 1] = after;else {
if (toOff || after.children.length && !after.children[0].length) after.merge(0, toOff, null, false, 0, openEnd);
insert$2.push(after);
}
} else if (after === null || after === void 0 ? void 0 : after.breakAfter) if (last) last.breakAfter = 1;else breakAtStart = 1;
toI++;
}
if (before) {
before.breakAfter = breakAtStart;
if (fromOff > 0) {
if (!breakAtStart && insert$2.length && before.merge(fromOff, before.length, insert$2[0], false, openStart, 0)) before.breakAfter = insert$2.shift().breakAfter;else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) before.merge(fromOff, before.length, null, false, openStart, 0);
fromI++;
}
}
while (fromI < toI && insert$2.length) if (children[toI - 1].become(insert$2[insert$2.length - 1])) {
toI--;
insert$2.pop();
openEnd = insert$2.length ? 0 : openStart;
} else if (children[fromI].become(insert$2[0])) {
fromI++;
insert$2.shift();
openStart = insert$2.length ? 0 : openEnd;
} else break;
if (!insert$2.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) fromI--;
if (fromI < toI || insert$2.length) parent.replaceChildren(fromI, toI, insert$2);
}
function mergeChildrenInto$1(parent, from, to, insert$2, openStart, openEnd) {
let cur$1 = parent.childCursor();
let {
i: toI,
off: toOff
} = cur$1.findPos(to, 1);
let {
i: fromI,
off: fromOff
} = cur$1.findPos(from, -1);
let dLen = from - to;
for (let view of insert$2) dLen += view.length;
parent.length += dLen;
replaceRange$1(parent, fromI, fromOff, toI, toOff, insert$2, 0, openStart, openEnd);
}
function textCoords$1(text, pos, side) {
let length = text.nodeValue.length;
if (pos > length) pos = length;
let from = pos,
to = pos,
flatten$2 = 0;
if (pos == 0 && side < 0 || pos == length && side >= 0) {
if (!(browser$1.chrome || browser$1.gecko)) {
if (pos) {
from--;
flatten$2 = 1;
} else if (to < length) {
to++;
flatten$2 = -1;
}
}
} else if (side < 0) from--;else if (to < length) to++;
let rects = textRange$1(text, from, to).getClientRects();
if (!rects.length) return null;
let rect = rects[(flatten$2 ? flatten$2 < 0 : side >= 0) ? 0 : rects.length - 1];
if (browser$1.safari && !flatten$2 && rect.width == 0) rect = Array.prototype.find.call(rects, r => r.width) || rect;
return flatten$2 ? flattenRect$1(rect, flatten$2 < 0) : rect || null;
}
function inlineDOMAtPos$1(parent, pos) {
let dom = parent.dom,
{
children
} = parent,
i$1 = 0;
for (let off = 0; i$1 < children.length; i$1++) {
let child = children[i$1],
end = off + child.length;
if (end == off && child.getSide() <= 0) continue;
if (pos > off && pos < end && child.dom.parentNode == dom) return child.domAtPos(pos - off);
if (pos <= off) break;
off = end;
}
for (let j = i$1; j > 0; j--) {
let prev = children[j - 1];
if (prev.dom.parentNode == dom) return prev.domAtPos(prev.length);
}
for (let j = i$1; j < children.length; j++) {
let next = children[j];
if (next.dom.parentNode == dom) return next.domAtPos(0);
}
return new DOMPos$1(dom, 0);
}
function joinInlineInto$1(parent, view, open) {
let last,
{
children
} = parent;
if (open > 0 && view instanceof MarkView$1 && children.length && (last = children[children.length - 1]) instanceof MarkView$1 && last.mark.eq(view.mark)) joinInlineInto$1(last, view.children[0], open - 1);else {
children.push(view);
view.setParent(parent);
}
parent.length += view.length;
}
function coordsInChildren$1(view, pos, side) {
let before = null,
beforePos = -1,
after = null,
afterPos = -1;
function scan(view$1, pos$1) {
for (let i$1 = 0, off = 0; i$1 < view$1.children.length && off <= pos$1; i$1++) {
let child = view$1.children[i$1],
end = off + child.length;
if (end >= pos$1) {
if (child.children.length) scan(child, pos$1 - off);else if ((!after || after.isHidden && side > 0) && (end > pos$1 || off == end && child.getSide() > 0)) {
after = child;
afterPos = pos$1 - off;
} else if (off < pos$1 || off == end && child.getSide() < 0 && !child.isHidden) {
before = child;
beforePos = pos$1 - off;
}
}
off = end;
}
}
scan(view, pos);
let target = (side < 0 ? before : after) || before || after;
if (target) return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);
return fallbackRect$1(view);
}
function fallbackRect$1(view) {
let last = view.dom.lastChild;
if (!last) return view.dom.getBoundingClientRect();
let rects = clientRectsFor$1(last);
return rects[rects.length - 1] || null;
}
function combineAttrs$1(source, target) {
for (let name$1 in source) if (name$1 == "class" && target.class) target.class += " " + source.class;else if (name$1 == "style" && target.style) target.style += ";" + source.style;else target[name$1] = source[name$1];
return target;
}
function attrsEq$1(a, b, ignore) {
if (a == b) return true;
if (!a) a = noAttrs$1;
if (!b) b = noAttrs$1;
let keysA = Object.keys(a),
keysB = Object.keys(b);
if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) != keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0)) return false;
for (let key of keysA) if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key])) return false;
return true;
}
function updateAttrs$1(dom, prev, attrs) {
let changed = false;
if (prev) {
for (let name$1 in prev) if (!(attrs && name$1 in attrs)) {
changed = true;
if (name$1 == "style") dom.style.cssText = "";else dom.removeAttribute(name$1);
}
}
if (attrs) {
for (let name$1 in attrs) if (!(prev && prev[name$1] == attrs[name$1])) {
changed = true;
if (name$1 == "style") dom.style.cssText = attrs[name$1];else dom.setAttribute(name$1, attrs[name$1]);
}
}
return changed;
}
function getAttrs$1(dom) {
let attrs = Object.create(null);
for (let i$1 = 0; i$1 < dom.attributes.length; i$1++) {
let attr = dom.attributes[i$1];
attrs[attr.name] = attr.value;
}
return attrs;
}
function getInclusive$1(spec, block = false) {
let {
inclusiveStart: start,
inclusiveEnd: end
} = spec;
if (start == null) start = spec.inclusive;
if (end == null) end = spec.inclusive;
return {
start: start !== null && start !== void 0 ? start : block,
end: end !== null && end !== void 0 ? end : block
};
}
function widgetsEq$1(a, b) {
return a == b || !!(a && b && a.compare(b));
}
function addRange$1(from, to, ranges, margin = 0) {
let last = ranges.length - 1;
if (last >= 0 && ranges[last] + margin >= from) ranges[last] = Math.max(ranges[last], to);else ranges.push(from, to);
}
function wrapMarks$1(view, active) {
for (let mark of active) view = new MarkView$1(mark, [view], view.length);
return view;
}
function dec$1(str) {
let result = [];
for (let i$1 = 0; i$1 < str.length; i$1++) result.push(1 << +str[i$1]);
return result;
}
function charType$1(ch) {
return ch <= 247 ? LowTypes$1[ch] : 1424 <= ch && ch <= 1524 ? 2 : 1536 <= ch && ch <= 1785 ? ArabicTypes$1[ch - 1536] : 1774 <= ch && ch <= 2220 ? 4 : 8192 <= ch && ch <= 8204 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : 1;
}
function isolatesEq$1(a, b) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) {
let iA = a[i$1],
iB = b[i$1];
if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq$1(iA.inner, iB.inner)) return false;
}
return true;
}
function computeCharTypes$1(line, rFrom, rTo, isolates, outerType) {
for (let iI = 0; iI <= isolates.length; iI++) {
let from = iI ? isolates[iI - 1].to : rFrom,
to = iI < isolates.length ? isolates[iI].from : rTo;
let prevType = iI ? 256 : outerType;
for (let i$1 = from, prev = prevType, prevStrong = prevType; i$1 < to; i$1++) {
let type = charType$1(line.charCodeAt(i$1));
if (type == 512) type = prev;else if (type == 8 && prevStrong == 4) type = 16;
types$1[i$1] = type == 4 ? 2 : type;
if (type & 7) prevStrong = type;
prev = type;
}
for (let i$1 = from, prev = prevType, prevStrong = prevType; i$1 < to; i$1++) {
let type = types$1[i$1];
if (type == 128) {
if (i$1 < to - 1 && prev == types$1[i$1 + 1] && prev & 24) type = types$1[i$1] = prev;else types$1[i$1] = 256;
} else if (type == 64) {
let end = i$1 + 1;
while (end < to && types$1[end] == 64) end++;
let replace = i$1 && prev == 8 || end < rTo && types$1[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
for (let j = i$1; j < end; j++) types$1[j] = replace;
i$1 = end - 1;
} else if (type == 8 && prevStrong == 1) types$1[i$1] = 1;
prev = type;
if (type & 7) prevStrong = type;
}
}
}
function processBracketPairs$1(line, rFrom, rTo, isolates, outerType) {
let oppositeType = outerType == 1 ? 2 : 1;
for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
let from = iI ? isolates[iI - 1].to : rFrom,
to = iI < isolates.length ? isolates[iI].from : rTo;
for (let i$1 = from, ch, br, type; i$1 < to; i$1++) if (br = Brackets$1[ch = line.charCodeAt(i$1)]) {
if (br < 0) {
for (let sJ = sI - 3; sJ >= 0; sJ -= 3) if (BracketStack$1[sJ + 1] == -br) {
let flags = BracketStack$1[sJ + 2];
let type$1 = flags & 2 ? outerType : !(flags & 4) ? 0 : flags & 1 ? oppositeType : outerType;
if (type$1) types$1[i$1] = types$1[BracketStack$1[sJ]] = type$1;
sI = sJ;
break;
}
} else if (BracketStack$1.length == 189) break;else {
BracketStack$1[sI++] = i$1;
BracketStack$1[sI++] = ch;
BracketStack$1[sI++] = context;
}
} else if ((type = types$1[i$1]) == 2 || type == 1) {
let embed = type == outerType;
context = embed ? 0 : 1;
for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
let cur$1 = BracketStack$1[sJ + 2];
if (cur$1 & 2) break;
if (embed) BracketStack$1[sJ + 2] |= 2;else {
if (cur$1 & 4) break;
BracketStack$1[sJ + 2] |= 4;
}
}
}
}
}
function processNeutrals$1(rFrom, rTo, isolates, outerType) {
for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
let from = iI ? isolates[iI - 1].to : rFrom,
to = iI < isolates.length ? isolates[iI].from : rTo;
for (let i$1 = from; i$1 < to;) {
let type = types$1[i$1];
if (type == 256) {
let end = i$1 + 1;
for (;;) if (end == to) {
if (iI == isolates.length) break;
end = isolates[iI++].to;
to = iI < isolates.length ? isolates[iI].from : rTo;
} else if (types$1[end] == 256) end++;else break;
let beforeL = prev == 1;
let replace = beforeL == ((end < rTo ? types$1[end] : outerType) == 1) ? beforeL ? 1 : 2 : outerType;
for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i$1;) {
if (j == fromJ) {
j = isolates[--jI].from;
fromJ = jI ? isolates[jI - 1].to : rFrom;
}
types$1[--j] = replace;
}
i$1 = end;
} else {
prev = type;
i$1++;
}
}
}
}
function emitSpans$1(line, from, to, level, baseLevel, isolates, order) {
let ourType = level % 2 ? 2 : 1;
if (level % 2 == baseLevel % 2) for (let iCh = from, iI = 0; iCh < to;) {
let sameDir = true,
isNum = false;
if (iI == isolates.length || iCh < isolates[iI].from) {
let next = types$1[iCh];
if (next != ourType) {
sameDir = false;
isNum = next == 16;
}
}
let recurse = !sameDir && ourType == 1 ? [] : null;
let localLevel = sameDir ? level : level + 1;
let iScan = iCh;
run: for (;;) if (iI < isolates.length && iScan == isolates[iI].from) {
if (isNum) break run;
let iso = isolates[iI];
if (!sameDir) for (let upto = iso.to, jI = iI + 1;;) {
if (upto == to) break run;
if (jI < isolates.length && isolates[jI].from == upto) upto = isolates[jI++].to;else if (types$1[upto] == ourType) break run;else break;
}
iI++;
if (recurse) recurse.push(iso);else {
if (iso.from > iCh) order.push(new BidiSpan$1(iCh, iso.from, localLevel));
computeSectionOrder$1(line, iso.direction == LTR$1 != !(localLevel % 2) ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
iCh = iso.to;
}
iScan = iso.to;
} else if (iScan == to || (sameDir ? types$1[iScan] != ourType : types$1[iScan] == ourType)) break;else iScan++;
if (recurse) emitSpans$1(line, iCh, iScan, level + 1, baseLevel, recurse, order);else if (iCh < iScan) order.push(new BidiSpan$1(iCh, iScan, localLevel));
iCh = iScan;
} else for (let iCh = to, iI = isolates.length; iCh > from;) {
let sameDir = true,
isNum = false;
if (!iI || iCh > isolates[iI - 1].to) {
let next = types$1[iCh - 1];
if (next != ourType) {
sameDir = false;
isNum = next == 16;
}
}
let recurse = !sameDir && ourType == 1 ? [] : null;
let localLevel = sameDir ? level : level + 1;
let iScan = iCh;
run: for (;;) if (iI && iScan == isolates[iI - 1].to) {
if (isNum) break run;
let iso = isolates[--iI];
if (!sameDir) for (let upto = iso.from, jI = iI;;) {
if (upto == from) break run;
if (jI && isolates[jI - 1].to == upto) upto = isolates[--jI].from;else if (types$1[upto - 1] == ourType) break run;else break;
}
if (recurse) recurse.push(iso);else {
if (iso.to < iCh) order.push(new BidiSpan$1(iso.to, iCh, localLevel));
computeSectionOrder$1(line, iso.direction == LTR$1 != !(localLevel % 2) ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
iCh = iso.from;
}
iScan = iso.from;
} else if (iScan == from || (sameDir ? types$1[iScan - 1] != ourType : types$1[iScan - 1] == ourType)) break;else iScan--;
if (recurse) emitSpans$1(line, iScan, iCh, level + 1, baseLevel, recurse, order);else if (iScan < iCh) order.push(new BidiSpan$1(iScan, iCh, localLevel));
iCh = iScan;
}
}
function computeSectionOrder$1(line, level, baseLevel, isolates, from, to, order) {
let outerType = level % 2 ? 2 : 1;
computeCharTypes$1(line, from, to, isolates, outerType);
processBracketPairs$1(line, from, to, isolates, outerType);
processNeutrals$1(from, to, isolates, outerType);
emitSpans$1(line, from, to, level, baseLevel, isolates, order);
}
function computeOrder$1(line, direction, isolates) {
if (!line) return [new BidiSpan$1(0, 0, direction == RTL$1 ? 1 : 0)];
if (direction == LTR$1 && !isolates.length && !BidiRE$1.test(line)) return trivialOrder$1(line.length);
if (isolates.length) while (line.length > types$1.length) types$1[types$1.length] = 256;
let order = [],
level = direction == LTR$1 ? 0 : 1;
computeSectionOrder$1(line, level, level, isolates, 0, line.length, order);
return order;
}
function trivialOrder$1(length) {
return [new BidiSpan$1(0, length, 0)];
}
function moveVisually$1(line, order, dir, start, forward) {
var _a$2;
let startIndex = start.head - line.from;
let spanI = BidiSpan$1.find(order, startIndex, (_a$2 = start.bidiLevel) !== null && _a$2 !== void 0 ? _a$2 : -1, start.assoc);
let span = order[spanI],
spanEnd = span.side(forward, dir);
if (startIndex == spanEnd) {
let nextI = spanI += forward ? 1 : -1;
if (nextI < 0 || nextI >= order.length) return null;
span = order[spanI = nextI];
startIndex = span.side(!forward, dir);
spanEnd = span.side(forward, dir);
}
let nextIndex = findClusterBreak(line.text, startIndex, span.forward(forward, dir));
if (nextIndex < span.from || nextIndex > span.to) nextIndex = spanEnd;
movedOver$1 = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
if (nextSpan && nextIndex == spanEnd && nextSpan.level + (forward ? 0 : 1) < span.level) return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, nextSpan.forward(forward, dir) ? 1 : -1, nextSpan.level);
return EditorSelection.cursor(nextIndex + line.from, span.forward(forward, dir) ? -1 : 1, span.level);
}
function autoDirection(text, from, to) {
for (let i$1 = from; i$1 < to; i$1++) {
let type = charType$1(text.charCodeAt(i$1));
if (type == 1) return LTR$1;
if (type == 2 || type == 4) return RTL$1;
}
return LTR$1;
}
/**
Log or report an unhandled exception in client code. Should
probably only be used by extension code that allows client code to
provide functions, and calls those functions in a context where an
exception can't be propagated to calling code in a reasonable way
(for example when in an event handler).
Either calls a handler registered with
[`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),
`window.onerror`, if defined, or `console.error` (in which case
it'll pass `context`, when given, as first argument).
*/
function logException$1(state, exception, context) {
let handler = state.facet(exceptionSink$1);
if (handler.length) handler[0](exception);else if (window.onerror) window.onerror(String(exception), context, void 0, void 0, exception);else if (context) console.error(context + ":", exception);else console.error(exception);
}
function getIsolatedRanges$1(view, line) {
let isolates = view.state.facet(bidiIsolatedRanges$1);
if (!isolates.length) return isolates;
let sets = isolates.map(i$1 => i$1 instanceof Function ? i$1(view) : i$1);
let result = [];
RangeSet$1.spans(sets, line.from, line.to, {
point() {},
span(fromDoc, toDoc, active, open) {
let from = fromDoc - line.from,
to = toDoc - line.from;
let level = result;
for (let i$1 = active.length - 1; i$1 >= 0; i$1--, open--) {
let direction = active[i$1].spec.bidiIsolate,
update;
if (direction == null) direction = autoDirection(line.text, from, to);
if (open > 0 && level.length && (update = level[level.length - 1]).to == from && update.direction == direction) {
update.to = to;
level = update.inner;
} else {
let add$1 = {
from,
to,
direction,
inner: []
};
level.push(add$1);
level = add$1.inner;
}
}
}
});
return result;
}
function getScrollMargins$1(view) {
let left = 0,
right = 0,
top$1 = 0,
bottom = 0;
for (let source of view.state.facet(scrollMargins$1)) {
let m = source(view);
if (m) {
if (m.left != null) left = Math.max(left, m.left);
if (m.right != null) right = Math.max(right, m.right);
if (m.top != null) top$1 = Math.max(top$1, m.top);
if (m.bottom != null) bottom = Math.max(bottom, m.bottom);
}
}
return {
left,
right,
top: top$1,
bottom
};
}
function betweenUneditable$1(pos) {
return pos.node.nodeType == 1 && pos.node.firstChild && (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
}
function findCompositionNode$1(view, headPos) {
let sel = view.observer.selectionRange;
if (!sel.focusNode) return null;
let textBefore = textNodeBefore(sel.focusNode, sel.focusOffset);
let textAfter = textNodeAfter(sel.focusNode, sel.focusOffset);
let textNode = textBefore || textAfter;
if (textAfter && textBefore && textAfter.node != textBefore.node) {
let descAfter = ContentView$1.get(textAfter.node);
if (!descAfter || descAfter instanceof TextView$1 && descAfter.text != textAfter.node.nodeValue) textNode = textAfter;else if (view.docView.lastCompositionAfterCursor) {
let descBefore = ContentView$1.get(textBefore.node);
if (!(!descBefore || descBefore instanceof TextView$1 && descBefore.text != textBefore.node.nodeValue)) textNode = textAfter;
}
}
view.docView.lastCompositionAfterCursor = textNode != textBefore;
if (!textNode) return null;
let from = headPos - textNode.offset;
return {
from,
to: from + textNode.node.nodeValue.length,
node: textNode.node
};
}
function findCompositionRange$1(view, changes, headPos) {
let found = findCompositionNode$1(view, headPos);
if (!found) return null;
let {
node: textNode,
from,
to
} = found,
text = textNode.nodeValue;
if (/[\n\r]/.test(text)) return null;
if (view.state.doc.sliceString(found.from, found.to) != text) return null;
let inv = changes.invertedDesc;
let range = new ChangedRange$1(inv.mapPos(from), inv.mapPos(to), from, to);
let marks$1 = [];
for (let parent = textNode.parentNode;; parent = parent.parentNode) {
let parentView = ContentView$1.get(parent);
if (parentView instanceof MarkView$1) marks$1.push({
node: parent,
deco: parentView.mark
});else if (parentView instanceof LineView$1 || parent.nodeName == "DIV" && parent.parentNode == view.contentDOM) return {
range,
text: textNode,
marks: marks$1,
line: parent
};else if (parent != view.contentDOM) marks$1.push({
node: parent,
deco: new MarkDecoration$1({
inclusive: true,
attributes: getAttrs$1(parent),
tagName: parent.tagName.toLowerCase()
})
});else return null;
}
}
function nextToUneditable$1(node, offset) {
if (node.nodeType != 1) return 0;
return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 : 0);
}
function findChangedDeco$1(a, b, diff) {
let comp = new DecorationComparator$1$1();
RangeSet$1.compare(a, b, diff, comp);
return comp.changes;
}
function inUneditable$1(node, inside$2) {
for (let cur$1 = node; cur$1 && cur$1 != inside$2; cur$1 = cur$1.assignedSlot || cur$1.parentNode) if (cur$1.nodeType == 1 && cur$1.contentEditable == "false") return true;
return false;
}
function touchesComposition$1(changes, composition) {
let touched = false;
if (composition) changes.iterChangedRanges((from, to) => {
if (from < composition.to && to > composition.from) touched = true;
});
return touched;
}
function groupAt$1(state, pos, bias = 1) {
let categorize = state.charCategorizer(pos);
let line = state.doc.lineAt(pos),
linePos = pos - line.from;
if (line.length == 0) return EditorSelection.cursor(pos);
if (linePos == 0) bias = 1;else if (linePos == line.length) bias = -1;
let from = linePos,
to = linePos;
if (bias < 0) from = findClusterBreak(line.text, linePos, false);else to = findClusterBreak(line.text, linePos);
let cat = categorize(line.text.slice(from, to));
while (from > 0) {
let prev = findClusterBreak(line.text, from, false);
if (categorize(line.text.slice(prev, from)) != cat) break;
from = prev;
}
while (to < line.length) {
let next = findClusterBreak(line.text, to);
if (categorize(line.text.slice(to, next)) != cat) break;
to = next;
}
return EditorSelection.range(from + line.from, to + line.from);
}
function getdx$1(x, rect) {
return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);
}
function getdy$1(y, rect) {
return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);
}
function yOverlap$1(a, b) {
return a.top < b.bottom - 1 && a.bottom > b.top + 1;
}
function upTop$1(rect, top$1) {
return top$1 < rect.top ? {
top: top$1,
left: rect.left,
right: rect.right,
bottom: rect.bottom
} : rect;
}
function upBot$1(rect, bottom) {
return bottom > rect.bottom ? {
top: rect.top,
left: rect.left,
right: rect.right,
bottom
} : rect;
}
function domPosAtCoords$1(parent, x, y) {
let closest,
closestRect,
closestX,
closestY,
closestOverlap = false;
let above, below, aboveRect, belowRect;
for (let child = parent.firstChild; child; child = child.nextSibling) {
let rects = clientRectsFor$1(child);
for (let i$1 = 0; i$1 < rects.length; i$1++) {
let rect = rects[i$1];
if (closestRect && yOverlap$1(closestRect, rect)) rect = upTop$1(upBot$1(rect, closestRect.bottom), closestRect.top);
let dx = getdx$1(x, rect),
dy = getdy$1(y, rect);
if (dx == 0 && dy == 0) return child.nodeType == 3 ? domPosInText$1(child, x, y) : domPosAtCoords$1(child, x, y);
if (!closest || closestY > dy || closestY == dy && closestX > dx) {
closest = child;
closestRect = rect;
closestX = dx;
closestY = dy;
let side = dy ? y < rect.top ? -1 : 1 : dx ? x < rect.left ? -1 : 1 : 0;
closestOverlap = !side || (side > 0 ? i$1 < rects.length - 1 : i$1 > 0);
}
if (dx == 0) {
if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
above = child;
aboveRect = rect;
} else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {
below = child;
belowRect = rect;
}
} else if (aboveRect && yOverlap$1(aboveRect, rect)) aboveRect = upBot$1(aboveRect, rect.bottom);else if (belowRect && yOverlap$1(belowRect, rect)) belowRect = upTop$1(belowRect, rect.top);
}
}
if (aboveRect && aboveRect.bottom >= y) {
closest = above;
closestRect = aboveRect;
} else if (belowRect && belowRect.top <= y) {
closest = below;
closestRect = belowRect;
}
if (!closest) return {
node: parent,
offset: 0
};
let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));
if (closest.nodeType == 3) return domPosInText$1(closest, clipX, y);
if (closestOverlap && closest.contentEditable != "false") return domPosAtCoords$1(closest, clipX, y);
return {
node: parent,
offset: Array.prototype.indexOf.call(parent.childNodes, closest) + (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0)
};
}
function domPosInText$1(node, x, y) {
let len = node.nodeValue.length;
let closestOffset = -1,
closestDY = 1e9,
generalSide = 0;
for (let i$1 = 0; i$1 < len; i$1++) {
let rects = textRange$1(node, i$1, i$1 + 1).getClientRects();
for (let j = 0; j < rects.length; j++) {
let rect = rects[j];
if (rect.top == rect.bottom) continue;
if (!generalSide) generalSide = x - rect.left;
let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;
if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) {
let right = x >= (rect.left + rect.right) / 2,
after = right;
if (browser$1.chrome || browser$1.gecko) {
if (textRange$1(node, i$1).getBoundingClientRect().left == rect.right) after = !right;
}
if (dy <= 0) return {
node,
offset: i$1 + (after ? 1 : 0)
};
closestOffset = i$1 + (after ? 1 : 0);
closestDY = dy;
}
}
}
return {
node,
offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0
};
}
function posAtCoords$1(view, coords, precise, bias = -1) {
var _a$2, _b;
let content$1 = view.contentDOM.getBoundingClientRect(),
docTop = content$1.top + view.viewState.paddingTop;
let block,
{
docHeight
} = view.viewState;
let {
x,
y
} = coords,
yOffset = y - docTop;
if (yOffset < 0) return 0;
if (yOffset > docHeight) return view.state.doc.length;
for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false;;) {
block = view.elementAtHeight(yOffset);
if (block.type == BlockType$1.Text) break;
for (;;) {
yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;
if (yOffset >= 0 && yOffset <= docHeight) break;
if (bounced) return precise ? null : 0;
bounced = true;
bias = -bias;
}
}
y = docTop + yOffset;
let lineStart = block.from;
if (lineStart < view.viewport.from) return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise$1(view, content$1, block, x, y);
if (lineStart > view.viewport.to) return view.viewport.to == view.state.doc.length ? view.state.doc.length : precise ? null : posAtCoordsImprecise$1(view, content$1, block, x, y);
let doc$2 = view.dom.ownerDocument;
let root = view.root.elementFromPoint ? view.root : doc$2;
let element = root.elementFromPoint(x, y);
if (element && !view.contentDOM.contains(element)) element = null;
if (!element) {
x = Math.max(content$1.left + 1, Math.min(content$1.right - 1, x));
element = root.elementFromPoint(x, y);
if (element && !view.contentDOM.contains(element)) element = null;
}
let node,
offset = -1;
if (element && ((_a$2 = view.docView.nearest(element)) === null || _a$2 === void 0 ? void 0 : _a$2.isEditable) != false) {
if (doc$2.caretPositionFromPoint) {
let pos = doc$2.caretPositionFromPoint(x, y);
if (pos) ({
offsetNode: node,
offset
} = pos);
} else if (doc$2.caretRangeFromPoint) {
let range = doc$2.caretRangeFromPoint(x, y);
if (range) {
({
startContainer: node,
startOffset: offset
} = range);
if (!view.contentDOM.contains(node) || browser$1.safari && isSuspiciousSafariCaretResult$1(node, offset, x) || browser$1.chrome && isSuspiciousChromeCaretResult$1(node, offset, x)) node = void 0;
}
}
}
if (!node || !view.docView.dom.contains(node)) {
let line = LineView$1.find(view.docView, lineStart);
if (!line) return yOffset > block.top + block.height / 2 ? block.to : block.from;
({
node,
offset
} = domPosAtCoords$1(line.dom, x, y));
}
let nearest = view.docView.nearest(node);
if (!nearest) return null;
if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {
let rect = nearest.dom.getBoundingClientRect();
return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2 ? nearest.posAtStart : nearest.posAtEnd;
} else return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;
}
function posAtCoordsImprecise$1(view, contentRect, block, x, y) {
let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);
if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {
let textHeight = view.viewState.heightOracle.textHeight;
let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * .5) / textHeight);
into += line * view.viewState.heightOracle.lineLength;
}
let content$1 = view.state.sliceDoc(block.from, block.to);
return block.from + findColumn(content$1, into, view.state.tabSize);
}
function isSuspiciousSafariCaretResult$1(node, offset, x) {
let len;
if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) return false;
for (let next = node.nextSibling; next; next = next.nextSibling) if (next.nodeType != 1 || next.nodeName != "BR") return false;
return textRange$1(node, len - 1, len).getBoundingClientRect().left > x;
}
function isSuspiciousChromeCaretResult$1(node, offset, x) {
if (offset != 0) return false;
for (let cur$1 = node;;) {
let parent = cur$1.parentNode;
if (!parent || parent.nodeType != 1 || parent.firstChild != cur$1) return false;
if (parent.classList.contains("cm-line")) break;
cur$1 = parent;
}
return x - (node.nodeType == 1 ? node.getBoundingClientRect() : textRange$1(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect()).left > 5;
}
function blockAt$1(view, pos) {
let line = view.lineBlockAt(pos);
if (Array.isArray(line.type)) {
for (let l of line.type) if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType$1.Text)) return l;
}
return line;
}
function moveToLineBoundary$1(view, start, forward, includeWrap) {
let line = blockAt$1(view, start.head);
let coords = !includeWrap || line.type != BlockType$1.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
if (coords) {
let editorRect = view.dom.getBoundingClientRect();
let direction = view.textDirectionAt(line.from);
let pos = view.posAtCoords({
x: forward == (direction == Direction$1.LTR) ? editorRect.right - 1 : editorRect.left + 1,
y: (coords.top + coords.bottom) / 2
});
if (pos != null) return EditorSelection.cursor(pos, forward ? -1 : 1);
}
return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
}
function moveByChar$1(view, start, forward, by) {
let line = view.state.doc.lineAt(start.head),
spans = view.bidiSpans(line);
let direction = view.textDirectionAt(line.from);
for (let cur$1 = start, check = null;;) {
let next = moveVisually$1(line, spans, direction, cur$1, forward),
char = movedOver$1;
if (!next) {
if (line.number == (forward ? view.state.doc.lines : 1)) return cur$1;
char = "\n";
line = view.state.doc.line(line.number + (forward ? 1 : -1));
spans = view.bidiSpans(line);
next = view.visualLineSide(line, !forward);
}
if (!check) {
if (!by) return next;
check = by(char);
} else if (!check(char)) return cur$1;
cur$1 = next;
}
}
function byGroup$1(view, pos, start) {
let categorize = view.state.charCategorizer(pos);
let cat = categorize(start);
return next => {
let nextCat = categorize(next);
if (cat == CharCategory.Space) cat = nextCat;
return cat == nextCat;
};
}
function moveVertically$1(view, start, forward, distance) {
let startPos = start.head,
dir = forward ? 1 : -1;
if (startPos == (forward ? view.state.doc.length : 0)) return EditorSelection.cursor(startPos, start.assoc);
let goal = start.goalColumn,
startY;
let rect = view.contentDOM.getBoundingClientRect();
let startCoords = view.coordsAtPos(startPos, start.assoc || -1),
docTop = view.documentTop;
if (startCoords) {
if (goal == null) goal = startCoords.left - rect.left;
startY = dir < 0 ? startCoords.top : startCoords.bottom;
} else {
let line = view.viewState.lineBlockAt(startPos);
if (goal == null) goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
startY = (dir < 0 ? line.top : line.bottom) + docTop;
}
let resolvedGoal = rect.left + goal;
let dist$2 = distance !== null && distance !== void 0 ? distance : view.viewState.heightOracle.textHeight >> 1;
for (let extra = 0;; extra += 10) {
let curY = startY + (dist$2 + extra) * dir;
let pos = posAtCoords$1(view, {
x: resolvedGoal,
y: curY
}, false, dir);
if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {
let charRect = view.docView.coordsForChar(pos);
let assoc = !charRect || curY < charRect.top ? -1 : 1;
return EditorSelection.cursor(pos, assoc, void 0, goal);
}
}
}
function skipAtomicRanges$1(atoms, pos, bias) {
for (;;) {
let moved = 0;
for (let set of atoms) set.between(pos - 1, pos + 1, (from, to, value) => {
if (pos > from && pos < to) {
let side = moved || bias || (pos - from < to - pos ? -1 : 1);
pos = side < 0 ? from : to;
moved = side;
}
});
if (!moved) return pos;
}
}
function skipAtoms$1(view, oldPos, pos) {
let newPos = skipAtomicRanges$1(view.state.facet(atomicRanges$1).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
}
function bindHandler$1(plugin, handler) {
return (view, event) => {
try {
return handler.call(plugin, event, view);
} catch (e) {
logException$1(view.state, e);
}
};
}
function computeHandlers$1(plugins) {
let result = Object.create(null);
function record(type) {
return result[type] || (result[type] = {
observers: [],
handlers: []
});
}
for (let plugin of plugins) {
let spec = plugin.spec;
if (spec && spec.domEventHandlers) for (let type in spec.domEventHandlers) {
let f = spec.domEventHandlers[type];
if (f) record(type).handlers.push(bindHandler$1(plugin.value, f));
}
if (spec && spec.domEventObservers) for (let type in spec.domEventObservers) {
let f = spec.domEventObservers[type];
if (f) record(type).observers.push(bindHandler$1(plugin.value, f));
}
}
for (let type in handlers$1) record(type).handlers.push(handlers$1[type]);
for (let type in observers$1) record(type).observers.push(observers$1[type]);
return result;
}
function dragScrollSpeed$1(dist$2) {
return Math.max(0, dist$2) * .7 + 8;
}
function dist$1(a, b) {
return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
}
function addsSelectionRange$1(view, event) {
let facet = view.state.facet(clickAddsSelectionRange$1);
return facet.length ? facet[0](event) : browser$1.mac ? event.metaKey : event.ctrlKey;
}
function dragMovesSelection$2(view, event) {
let facet = view.state.facet(dragMovesSelection$1$1);
return facet.length ? facet[0](event) : browser$1.mac ? !event.altKey : !event.ctrlKey;
}
function isInPrimarySelection$1(view, event) {
let {
main
} = view.state.selection;
if (main.empty) return false;
let sel = getSelection$1(view.root);
if (!sel || sel.rangeCount == 0) return true;
let rects = sel.getRangeAt(0).getClientRects();
for (let i$1 = 0; i$1 < rects.length; i$1++) {
let rect = rects[i$1];
if (rect.left <= event.clientX && rect.right >= event.clientX && rect.top <= event.clientY && rect.bottom >= event.clientY) return true;
}
return false;
}
function eventBelongsToEditor$1(view, event) {
if (!event.bubbles) return true;
if (event.defaultPrevented) return false;
for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) if (!node || node.nodeType == 11 || (cView = ContentView$1.get(node)) && cView.ignoreEvent(event)) return false;
return true;
}
function capturePaste$1(view) {
let parent = view.dom.parentNode;
if (!parent) return;
let target = parent.appendChild(document.createElement("textarea"));
target.style.cssText = "position: fixed; left: -10000px; top: 10px";
target.focus();
setTimeout(() => {
view.focus();
target.remove();
doPaste$1(view, target.value);
}, 50);
}
function doPaste$1(view, input) {
let {
state
} = view,
changes,
i$1 = 1,
text = state.toText(input);
let byLine = text.lines == state.selection.ranges.length;
if (lastLinewiseCopy$1 != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy$1 == text.toString()) {
let lastLine = -1;
changes = state.changeByRange(range => {
let line = state.doc.lineAt(range.from);
if (line.from == lastLine) return {
range
};
lastLine = line.from;
let insert$2 = state.toText((byLine ? text.line(i$1++).text : input) + state.lineBreak);
return {
changes: {
from: line.from,
insert: insert$2
},
range: EditorSelection.cursor(range.from + insert$2.length)
};
});
} else if (byLine) changes = state.changeByRange(range => {
let line = text.line(i$1++);
return {
changes: {
from: range.from,
to: range.to,
insert: line.text
},
range: EditorSelection.cursor(range.from + line.length)
};
});else changes = state.replaceSelection(text);
view.dispatch(changes, {
userEvent: "input.paste",
scrollIntoView: true
});
}
function rangeForClick$1(view, pos, bias, type) {
if (type == 1) return EditorSelection.cursor(pos, bias);else if (type == 2) return groupAt$1(view.state, pos, bias);else {
let visual = LineView$1.find(view.docView, pos),
line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
let from = visual ? visual.posAtStart : line.from,
to = visual ? visual.posAtEnd : line.to;
if (to < view.state.doc.length && to == line.to) to++;
return EditorSelection.range(from, to);
}
}
function findPositionSide$1(view, pos, x, y) {
let line = LineView$1.find(view.docView, pos);
if (!line) return 1;
let off = pos - line.posAtStart;
if (off == 0) return 1;
if (off == line.length) return -1;
let before = line.coordsAt(off, -1);
if (before && inside$1(x, y, before)) return -1;
let after = line.coordsAt(off, 1);
if (after && inside$1(x, y, after)) return 1;
return before && insideY$1(y, before) ? -1 : 1;
}
function queryPos$1(view, event) {
let pos = view.posAtCoords({
x: event.clientX,
y: event.clientY
}, false);
return {
pos,
bias: findPositionSide$1(view, pos, event.clientX, event.clientY)
};
}
function getClickType$1(event) {
if (!BadMouseDetail$1) return event.detail;
let last = lastMouseDown$1,
lastTime = lastMouseDownTime$1;
lastMouseDown$1 = event;
lastMouseDownTime$1 = Date.now();
return lastMouseDownCount$1 = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && Math.abs(last.clientY - event.clientY) < 2 ? (lastMouseDownCount$1 + 1) % 3 : 1;
}
function basicMouseSelection$1(view, event) {
let start = queryPos$1(view, event),
type = getClickType$1(event);
let startSel = view.state.selection;
return {
update(update) {
if (update.docChanged) {
start.pos = update.changes.mapPos(start.pos);
startSel = startSel.map(update.changes);
}
},
get(event$1, extend$2, multiple) {
let cur$1 = queryPos$1(view, event$1),
removed;
let range = rangeForClick$1(view, cur$1.pos, cur$1.bias, type);
if (start.pos != cur$1.pos && !extend$2) {
let startRange = rangeForClick$1(view, start.pos, start.bias, type);
let from = Math.min(startRange.from, range.from),
to = Math.max(startRange.to, range.to);
range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
}
if (extend$2) return startSel.replaceRange(startSel.main.extend(range.from, range.to));else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround$1(startSel, cur$1.pos))) return removed;else if (multiple) return startSel.addRange(range);else return EditorSelection.create([range]);
}
};
}
function removeRangeAround$1(sel, pos) {
for (let i$1 = 0; i$1 < sel.ranges.length; i$1++) {
let {
from,
to
} = sel.ranges[i$1];
if (from <= pos && to >= pos) return EditorSelection.create(sel.ranges.slice(0, i$1).concat(sel.ranges.slice(i$1 + 1)), sel.mainIndex == i$1 ? 0 : sel.mainIndex - (sel.mainIndex > i$1 ? 1 : 0));
}
return null;
}
function dropText$1(view, event, text, direct) {
if (!text) return;
let dropPos = view.posAtCoords({
x: event.clientX,
y: event.clientY
}, false);
let {
draggedContent
} = view.inputState;
let del = direct && draggedContent && dragMovesSelection$2(view, event) ? {
from: draggedContent.from,
to: draggedContent.to
} : null;
let ins = {
from: dropPos,
insert: text
};
let changes = view.state.changes(del ? [del, ins] : ins);
view.focus();
view.dispatch({
changes,
selection: {
anchor: changes.mapPos(dropPos, -1),
head: changes.mapPos(dropPos, 1)
},
userEvent: del ? "move.drop" : "input.drop"
});
view.inputState.draggedContent = null;
}
function captureCopy$1(view, text) {
let parent = view.dom.parentNode;
if (!parent) return;
let target = parent.appendChild(document.createElement("textarea"));
target.style.cssText = "position: fixed; left: -10000px; top: 10px";
target.value = text;
target.focus();
target.selectionEnd = text.length;
target.selectionStart = 0;
setTimeout(() => {
target.remove();
view.focus();
}, 50);
}
function copiedRange$1(state) {
let content$1 = [],
ranges = [],
linewise = false;
for (let range of state.selection.ranges) if (!range.empty) {
content$1.push(state.sliceDoc(range.from, range.to));
ranges.push(range);
}
if (!content$1.length) {
let upto = -1;
for (let {
from
} of state.selection.ranges) {
let line = state.doc.lineAt(from);
if (line.number > upto) {
content$1.push(line.text);
ranges.push({
from: line.from,
to: Math.min(state.doc.length, line.to + 1)
});
}
upto = line.number;
}
linewise = true;
}
return {
text: content$1.join(state.lineBreak),
ranges,
linewise
};
}
function focusChangeTransaction$1(state, focus) {
let effects = [];
for (let getEffect of state.facet(focusChangeEffect$1)) {
let effect = getEffect(state, focus);
if (effect) effects.push(effect);
}
return effects ? state.update({
effects,
annotations: isFocusChange$1.of(true)
}) : null;
}
function updateForFocusChange$1(view) {
setTimeout(() => {
let focus = view.hasFocus;
if (focus != view.inputState.notifiedFocused) {
let tr = focusChangeTransaction$1(view.state, focus);
if (tr) view.dispatch(tr);else view.update([]);
}
}, 10);
}
function firefoxCopyCutHack$1(doc$2) {
if (!appliedFirefoxHack$1.has(doc$2)) {
appliedFirefoxHack$1.add(doc$2);
doc$2.addEventListener("copy", () => {});
doc$2.addEventListener("cut", () => {});
}
}
function mergeGaps$1(nodes, around) {
let before, after;
if (nodes[around] == null && (before = nodes[around - 1]) instanceof HeightMapGap$1 && (after = nodes[around + 1]) instanceof HeightMapGap$1) nodes.splice(around - 1, 3, new HeightMapGap$1(before.length + 1 + after.length));
}
function heightRelevantDecoChanges$1(a, b, diff) {
let comp = new DecorationComparator$2();
RangeSet$1.compare(a, b, diff, comp, 0);
return comp.changes;
}
function visiblePixelRange$1(dom, paddingTop) {
let rect = dom.getBoundingClientRect();
let doc$2 = dom.ownerDocument,
win = doc$2.defaultView || window;
let left = Math.max(0, rect.left),
right = Math.min(win.innerWidth, rect.right);
let top$1 = Math.max(0, rect.top),
bottom = Math.min(win.innerHeight, rect.bottom);
for (let parent = dom.parentNode; parent && parent != doc$2.body;) if (parent.nodeType == 1) {
let elt = parent;
let style = window.getComputedStyle(elt);
if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style.overflow != "visible") {
let parentRect = elt.getBoundingClientRect();
left = Math.max(left, parentRect.left);
right = Math.min(right, parentRect.right);
top$1 = Math.max(top$1, parentRect.top);
bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom);
}
parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
} else if (parent.nodeType == 11) parent = parent.host;else break;
return {
left: left - rect.left,
right: Math.max(left, right) - rect.left,
top: top$1 - (rect.top + paddingTop),
bottom: Math.max(top$1, bottom) - (rect.top + paddingTop)
};
}
function fullPixelRange$1(dom, paddingTop) {
let rect = dom.getBoundingClientRect();
return {
left: 0,
right: rect.right - rect.left,
top: paddingTop,
bottom: rect.bottom - (rect.top + paddingTop)
};
}
function lineStructure$1(from, to, stateDeco) {
let ranges = [],
pos = from,
total = 0;
RangeSet$1.spans(stateDeco, from, to, {
span() {},
point(from$1, to$1) {
if (from$1 > pos) {
ranges.push({
from: pos,
to: from$1
});
total += from$1 - pos;
}
pos = to$1;
}
}, 20);
if (pos < to) {
ranges.push({
from: pos,
to
});
total += to - pos;
}
return {
total,
ranges
};
}
function findPosition$1({
total,
ranges
}, ratio) {
if (ratio <= 0) return ranges[0].from;
if (ratio >= 1) return ranges[ranges.length - 1].to;
let dist$2 = Math.floor(total * ratio);
for (let i$1 = 0;; i$1++) {
let {
from,
to
} = ranges[i$1],
size = to - from;
if (dist$2 <= size) return from + dist$2;
dist$2 -= size;
}
}
function findFraction$1(structure, pos) {
let counted = 0;
for (let {
from,
to
} of structure.ranges) {
if (pos <= to) {
counted += pos - from;
break;
}
counted += to - from;
}
return counted / structure.total;
}
function find$1(array, f) {
for (let val of array) if (f(val)) return val;
}
function scaleBlock$1(block, scaler) {
if (scaler.scale == 1) return block;
let bTop = scaler.toDOM(block.top),
bBottom = scaler.toDOM(block.bottom);
return new BlockInfo$1(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock$1(b, scaler)) : block._content);
}
function buildTheme$1(main, spec, scopes) {
return new StyleModule(spec, {
finish(sel) {
return /&/.test(sel) ? sel.replace(/&\w*/, m => {
if (m == "&") return main;
if (!scopes || !scopes[m]) throw new RangeError(`Unsupported selector: ${m}`);
return scopes[m];
}) : main + " " + sel;
}
});
}
function isAtEnd$1(parent, node, offset) {
for (;;) {
if (!node || offset < maxOffset$1(node)) return false;
if (node == parent) return true;
offset = domIndex$1(node) + 1;
node = node.parentNode;
}
}
function applyDOMChange$1(view, domChange) {
let change;
let {
newSel
} = domChange,
sel = view.state.selection.main;
let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
if (domChange.bounds) {
let {
from,
to
} = domChange.bounds;
let preferredPos = sel.from,
preferredSide = null;
if (lastKey === 8 || browser$1.android && domChange.text.length < to - from) {
preferredPos = sel.to;
preferredSide = "end";
}
let diff = findDiff$1(view.state.doc.sliceString(from, to, LineBreakPlaceholder$1), domChange.text, preferredPos - from, preferredSide);
if (diff) {
if (browser$1.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder$1 + LineBreakPlaceholder$1) diff.toB--;
change = {
from: from + diff.from,
to: from + diff.toA,
insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder$1))
};
}
} else if (newSel && (!view.hasFocus && view.state.facet(editable$1) || newSel.main.eq(sel))) newSel = null;
if (!change && !newSel) return false;
if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) change = {
from: sel.from,
to: sel.to,
insert: view.state.doc.slice(sel.from, sel.to)
};else if (change && change.from >= sel.from && change.to <= sel.to && (change.from != sel.from || change.to != sel.to) && sel.to - sel.from - (change.to - change.from) <= 4) change = {
from: sel.from,
to: sel.to,
insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
};else if ((browser$1.mac || browser$1.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
if (newSel && change.insert.length == 2) newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
change = {
from: sel.from,
to: sel.to,
insert: Text.of([" "])
};
} else if (browser$1.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == "\n " && view.lineWrapping) {
if (newSel) newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
change = {
from: sel.from,
to: sel.to,
insert: Text.of([" "])
};
}
if (change) {
if (browser$1.ios && view.inputState.flushIOSKey(change)) return true;
if (browser$1.android && (change.to == sel.to && (change.from == sel.from || change.from == sel.from - 1 && view.state.sliceDoc(change.from, sel.from) == " ") && change.insert.length == 1 && change.insert.lines == 2 && dispatchKey$1(view.contentDOM, "Enter", 13) || (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 || lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) && dispatchKey$1(view.contentDOM, "Backspace", 8) || change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && dispatchKey$1(view.contentDOM, "Delete", 46))) return true;
let text = change.insert.toString();
if (view.inputState.composing >= 0) view.inputState.composing++;
let defaultTr;
let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert$1(view, change, newSel));
if (!view.state.facet(inputHandler$2).some(h => h(view, change.from, change.to, text, defaultInsert))) view.dispatch(defaultInsert());
return true;
} else if (newSel && !newSel.main.eq(sel)) {
let scrollIntoView$3 = false,
userEvent = "select";
if (view.inputState.lastSelectionTime > Date.now() - 50) {
if (view.inputState.lastSelectionOrigin == "select") scrollIntoView$3 = true;
userEvent = view.inputState.lastSelectionOrigin;
}
view.dispatch({
selection: newSel,
scrollIntoView: scrollIntoView$3,
userEvent
});
return true;
} else return false;
}
function applyDefaultInsert$1(view, change, newSel) {
let tr,
startState = view.state,
sel = startState.selection.main;
if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && view.inputState.composing < 0) {
let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, void 0, view.state.lineBreak) + after));
} else {
let changes = startState.changes(change);
let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : void 0;
if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && change.to <= sel.to && change.to >= sel.to - 10) {
let replaced = view.state.sliceDoc(change.from, change.to);
let compositionRange,
composition = newSel && findCompositionNode$1(view, newSel.main.head);
if (composition) {
let dLen = change.insert.length - (change.to - change.from);
compositionRange = {
from: composition.from,
to: composition.to - dLen
};
} else compositionRange = view.state.doc.lineAt(sel.head);
let offset = sel.to - change.to,
size = sel.to - sel.from;
tr = startState.changeByRange(range => {
if (range.from == sel.from && range.to == sel.to) return {
changes,
range: mainSel || range.map(changes)
};
let to = range.to - offset,
from = to - replaced.length;
if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || range.to >= compositionRange.from && range.from <= compositionRange.to) return {
range
};
let rangeChanges = startState.changes({
from,
to,
insert: change.insert
}),
selOff = range.to - sel.to;
return {
changes: rangeChanges,
range: !mainSel ? range.map(rangeChanges) : EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
};
});
} else tr = {
changes,
selection: mainSel && startState.selection.replaceRange(mainSel)
};
}
let userEvent = "input.type";
if (view.composing || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
view.inputState.compositionPendingChange = false;
userEvent += ".compose";
if (view.inputState.compositionFirstChange) {
userEvent += ".start";
view.inputState.compositionFirstChange = false;
}
}
return startState.update(tr, {
userEvent,
scrollIntoView: true
});
}
function findDiff$1(a, b, preferredPos, preferredSide) {
let minLen = Math.min(a.length, b.length);
let from = 0;
while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) from++;
if (from == minLen && a.length == b.length) return null;
let toA = a.length,
toB = b.length;
while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
toA--;
toB--;
}
if (preferredSide == "end") {
let adjust = Math.max(0, from - Math.min(toA, toB));
preferredPos -= toA + adjust - from;
}
if (toA < from && a.length < b.length) {
let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
from -= move;
toB = from + (toB - toA);
toA = from;
} else if (toB < from) {
let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
from -= move;
toA = from + (toA - toB);
toB = from;
}
return {
from,
toA,
toB
};
}
function selectionPoints$1(view) {
let result = [];
if (view.root.activeElement != view.contentDOM) return result;
let {
anchorNode,
anchorOffset,
focusNode,
focusOffset
} = view.observer.selectionRange;
if (anchorNode) {
result.push(new DOMPoint$1(anchorNode, anchorOffset));
if (focusNode != anchorNode || focusOffset != anchorOffset) result.push(new DOMPoint$1(focusNode, focusOffset));
}
return result;
}
function selectionFromPoints$1(points, base$1) {
if (points.length == 0) return null;
let anchor = points[0].pos,
head = points.length == 2 ? points[1].pos : anchor;
return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base$1, head + base$1) : null;
}
function findChild$1(cView, dom, dir) {
while (dom) {
let curView = ContentView$1.get(dom);
if (curView && curView.parent == cView) return curView;
let parent = dom.parentNode;
dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
}
return null;
}
function buildSelectionRangeFromRange(view, range) {
let anchorNode = range.startContainer,
anchorOffset = range.startOffset;
let focusNode = range.endContainer,
focusOffset = range.endOffset;
let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);
if (isEquivalentPosition$1(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
return {
anchorNode,
anchorOffset,
focusNode,
focusOffset
};
}
function safariSelectionRangeHack$1(view, selection) {
if (selection.getComposedRanges) {
let range = selection.getComposedRanges(view.root)[0];
if (range) return buildSelectionRangeFromRange(view, range);
}
let found = null;
function read$1(event) {
event.preventDefault();
event.stopImmediatePropagation();
found = event.getTargetRanges()[0];
}
view.contentDOM.addEventListener("beforeinput", read$1, true);
view.dom.ownerDocument.execCommand("indent");
view.contentDOM.removeEventListener("beforeinput", read$1, true);
return found ? buildSelectionRangeFromRange(view, found) : null;
}
/**
An editor view represents the editor's user interface. It holds
the editable DOM surface, and possibly other elements such as the
line number gutter. It handles events and dispatches state
transactions for editing actions.
*/
function attrsFromFacet$1(view, facet, base$1) {
for (let sources = view.state.facet(facet), i$1 = sources.length - 1; i$1 >= 0; i$1--) {
let source = sources[i$1],
value = typeof source == "function" ? source(view) : source;
if (value) combineAttrs$1(value, base$1);
}
return base$1;
}
function normalizeKeyName(name$1, platform) {
const parts = name$1.split(/-(?!$)/);
let result = parts[parts.length - 1];
if (result == "Space") result = " ";
let alt, ctrl, shift$1, meta$1;
for (let i$1 = 0; i$1 < parts.length - 1; ++i$1) {
const mod = parts[i$1];
if (/^(cmd|meta|m)$/i.test(mod)) meta$1 = true;else if (/^a(lt)?$/i.test(mod)) alt = true;else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true;else if (/^s(hift)?$/i.test(mod)) shift$1 = true;else if (/^mod$/i.test(mod)) {
if (platform == "mac") meta$1 = true;else ctrl = true;
} else throw new Error("Unrecognized modifier name: " + mod);
}
if (alt) result = "Alt-" + result;
if (ctrl) result = "Ctrl-" + result;
if (meta$1) result = "Meta-" + result;
if (shift$1) result = "Shift-" + result;
return result;
}
function modifiers(name$1, event, shift$1) {
if (event.altKey) name$1 = "Alt-" + name$1;
if (event.ctrlKey) name$1 = "Ctrl-" + name$1;
if (event.metaKey) name$1 = "Meta-" + name$1;
if (shift$1 !== false && event.shiftKey) name$1 = "Shift-" + name$1;
return name$1;
}
function getKeymap(state) {
let bindings = state.facet(keymap);
let map = Keymaps.get(bindings);
if (!map) Keymaps.set(bindings, map = buildKeymap(bindings.reduce((a, b) => a.concat(b), [])));
return map;
}
/**
Run the key handlers registered for a given scope. The event
object should be a `"keydown"` event. Returns true if any of the
handlers handled it.
*/
function runScopeHandlers(view, event, scope) {
return runHandlers(getKeymap(view.state), event, view, scope);
}
function buildKeymap(bindings, platform = currentPlatform$1) {
let bound = Object.create(null);
let isPrefix = Object.create(null);
let checkPrefix = (name$1, is) => {
let current = isPrefix[name$1];
if (current == null) isPrefix[name$1] = is;else if (current != is) throw new Error("Key binding " + name$1 + " is used both as a regular binding and as a multi-stroke prefix");
};
let add$1 = (scope, key, command$1, preventDefault, stopPropagation) => {
var _a$2, _b;
let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
let parts = key.split(/ (?!$)/).map(k => normalizeKeyName(k, platform));
for (let i$1 = 1; i$1 < parts.length; i$1++) {
let prefix = parts.slice(0, i$1).join(" ");
checkPrefix(prefix, true);
if (!scopeObj[prefix]) scopeObj[prefix] = {
preventDefault: true,
stopPropagation: false,
run: [view => {
let ourObj = storedPrefix = {
view,
prefix,
scope
};
setTimeout(() => {
if (storedPrefix == ourObj) storedPrefix = null;
}, PrefixTimeout);
return true;
}]
};
}
let full = parts.join(" ");
checkPrefix(full, false);
let binding = scopeObj[full] || (scopeObj[full] = {
preventDefault: false,
stopPropagation: false,
run: ((_b = (_a$2 = scopeObj._any) === null || _a$2 === void 0 ? void 0 : _a$2.run) === null || _b === void 0 ? void 0 : _b.slice()) || []
});
if (command$1) binding.run.push(command$1);
if (preventDefault) binding.preventDefault = true;
if (stopPropagation) binding.stopPropagation = true;
};
for (let b of bindings) {
let scopes = b.scope ? b.scope.split(" ") : ["editor"];
if (b.any) for (let scope of scopes) {
let scopeObj = bound[scope] || (bound[scope] = Object.create(null));
if (!scopeObj._any) scopeObj._any = {
preventDefault: false,
stopPropagation: false,
run: []
};
for (let key in scopeObj) scopeObj[key].run.push(b.any);
}
let name$1 = b[platform] || b.key;
if (!name$1) continue;
for (let scope of scopes) {
add$1(scope, name$1, b.run, b.preventDefault, b.stopPropagation);
if (b.shift) add$1(scope, "Shift-" + name$1, b.shift, b.preventDefault, b.stopPropagation);
}
}
return bound;
}
function runHandlers(map, event, view, scope) {
let name$1 = keyName(event);
let isChar = codePointSize(codePointAt(name$1, 0)) == name$1.length && name$1 != " ";
let prefix = "",
handled = false,
prevented = false,
stopPropagation = false;
if (storedPrefix && storedPrefix.view == view && storedPrefix.scope == scope) {
prefix = storedPrefix.prefix + " ";
if (modifierCodes$1.indexOf(event.keyCode) < 0) {
prevented = true;
storedPrefix = null;
}
}
let ran = /* @__PURE__ */new Set();
let runFor = binding => {
if (binding) {
for (let cmd$1 of binding.run) if (!ran.has(cmd$1)) {
ran.add(cmd$1);
if (cmd$1(view, event)) {
if (binding.stopPropagation) stopPropagation = true;
return true;
}
}
if (binding.preventDefault) {
if (binding.stopPropagation) stopPropagation = true;
prevented = true;
}
}
return false;
};
let scopeObj = map[scope],
baseName,
shiftName;
if (scopeObj) {
if (runFor(scopeObj[prefix + modifiers(name$1, event, !isChar)])) handled = true;else if (isChar && (event.altKey || event.metaKey || event.ctrlKey) && !(browser$1.windows && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name$1) {
if (runFor(scopeObj[prefix + modifiers(baseName, event, true)])) handled = true;else if (event.shiftKey && (shiftName = shift[event.keyCode]) != name$1 && shiftName != baseName && runFor(scopeObj[prefix + modifiers(shiftName, event, false)])) handled = true;
} else if (isChar && event.shiftKey && runFor(scopeObj[prefix + modifiers(name$1, event, true)])) handled = true;
if (!handled && runFor(scopeObj._any)) handled = true;
}
if (prevented) handled = true;
if (handled && stopPropagation) event.stopPropagation();
return handled;
}
/**
Implementation of [`LayerMarker`](https://codemirror.net/6/docs/ref/#view.LayerMarker) that creates
a rectangle at a given set of coordinates.
*/
function getBase(view) {
let rect = view.scrollDOM.getBoundingClientRect();
return {
left: (view.textDirection == Direction$1.LTR ? rect.left : rect.right - view.scrollDOM.clientWidth * view.scaleX) - view.scrollDOM.scrollLeft * view.scaleX,
top: rect.top - view.scrollDOM.scrollTop * view.scaleY
};
}
function wrappedLine(view, pos, inside$2) {
let range = EditorSelection.cursor(pos);
return {
from: Math.max(inside$2.from, view.moveToLineBoundary(range, false, true).from),
to: Math.min(inside$2.to, view.moveToLineBoundary(range, true, true).from),
type: BlockType$1.Text
};
}
function rectanglesForRange(view, className, range) {
if (range.to <= view.viewport.from || range.from >= view.viewport.to) return [];
let from = Math.max(range.from, view.viewport.from),
to = Math.min(range.to, view.viewport.to);
let ltr = view.textDirection == Direction$1.LTR;
let content$1 = view.contentDOM,
contentRect = content$1.getBoundingClientRect(),
base$1 = getBase(view);
let lineElt = content$1.querySelector(".cm-line"),
lineStyle = lineElt && window.getComputedStyle(lineElt);
let leftSide = contentRect.left + (lineStyle ? parseInt(lineStyle.paddingLeft) + Math.min(0, parseInt(lineStyle.textIndent)) : 0);
let rightSide = contentRect.right - (lineStyle ? parseInt(lineStyle.paddingRight) : 0);
let startBlock = blockAt$1(view, from),
endBlock = blockAt$1(view, to);
let visualStart = startBlock.type == BlockType$1.Text ? startBlock : null;
let visualEnd = endBlock.type == BlockType$1.Text ? endBlock : null;
if (visualStart && (view.lineWrapping || startBlock.widgetLineBreaks)) visualStart = wrappedLine(view, from, visualStart);
if (visualEnd && (view.lineWrapping || endBlock.widgetLineBreaks)) visualEnd = wrappedLine(view, to, visualEnd);
if (visualStart && visualEnd && visualStart.from == visualEnd.from) return pieces(drawForLine(range.from, range.to, visualStart));else {
let top$1 = visualStart ? drawForLine(range.from, null, visualStart) : drawForWidget(startBlock, false);
let bottom = visualEnd ? drawForLine(null, range.to, visualEnd) : drawForWidget(endBlock, true);
let between = [];
if ((visualStart || startBlock).to < (visualEnd || endBlock).from - (visualStart && visualEnd ? 1 : 0) || startBlock.widgetLineBreaks > 1 && top$1.bottom + view.defaultLineHeight / 2 < bottom.top) between.push(piece(leftSide, top$1.bottom, rightSide, bottom.top));else if (top$1.bottom < bottom.top && view.elementAtHeight((top$1.bottom + bottom.top) / 2).type == BlockType$1.Text) top$1.bottom = bottom.top = (top$1.bottom + bottom.top) / 2;
return pieces(top$1).concat(between).concat(pieces(bottom));
}
function piece(left, top$1, right, bottom) {
return new RectangleMarker(className, left - base$1.left, top$1 - base$1.top - .01, right - left, bottom - top$1 + .01);
}
function pieces({
top: top$1,
bottom,
horizontal
}) {
let pieces$1 = [];
for (let i$1 = 0; i$1 < horizontal.length; i$1 += 2) pieces$1.push(piece(horizontal[i$1], top$1, horizontal[i$1 + 1], bottom));
return pieces$1;
}
function drawForLine(from$1, to$1, line) {
let top$1 = 1e9,
bottom = -1e9,
horizontal = [];
function addSpan(from$2, fromOpen, to$2, toOpen, dir) {
let fromCoords = view.coordsAtPos(from$2, from$2 == line.to ? -2 : 2);
let toCoords = view.coordsAtPos(to$2, to$2 == line.from ? 2 : -2);
if (!fromCoords || !toCoords) return;
top$1 = Math.min(fromCoords.top, toCoords.top, top$1);
bottom = Math.max(fromCoords.bottom, toCoords.bottom, bottom);
if (dir == Direction$1.LTR) horizontal.push(ltr && fromOpen ? leftSide : fromCoords.left, ltr && toOpen ? rightSide : toCoords.right);else horizontal.push(!ltr && toOpen ? leftSide : toCoords.left, !ltr && fromOpen ? rightSide : fromCoords.right);
}
let start = from$1 !== null && from$1 !== void 0 ? from$1 : line.from,
end = to$1 !== null && to$1 !== void 0 ? to$1 : line.to;
for (let r of view.visibleRanges) if (r.to > start && r.from < end) for (let pos = Math.max(r.from, start), endPos = Math.min(r.to, end);;) {
let docLine = view.state.doc.lineAt(pos);
for (let span of view.bidiSpans(docLine)) {
let spanFrom = span.from + docLine.from,
spanTo = span.to + docLine.from;
if (spanFrom >= endPos) break;
if (spanTo > pos) addSpan(Math.max(spanFrom, pos), from$1 == null && spanFrom <= start, Math.min(spanTo, endPos), to$1 == null && spanTo >= end, span.dir);
}
pos = docLine.to + 1;
if (pos >= endPos) break;
}
if (horizontal.length == 0) addSpan(start, from$1 == null, end, to$1 == null, view.textDirection);
return {
top: top$1,
bottom,
horizontal
};
}
function drawForWidget(block, top$1) {
let y = contentRect.top + (top$1 ? block.top : block.bottom);
return {
top: y,
bottom: y,
horizontal: []
};
}
}
function sameMarker(a, b) {
return a.constructor == b.constructor && a.eq(b);
}
/**
Define a layer.
*/
function layer(config$1) {
return [ViewPlugin$1.define(v => new LayerView(v, config$1)), layerOrder.of(config$1)];
}
/**
Returns an extension that hides the browser's native selection and
cursor, replacing the selection with a background behind the text
(with the `cm-selectionBackground` class), and the
cursors with elements overlaid over the code (using
`cm-cursor-primary` and `cm-cursor-secondary`).
This allows the editor to display secondary selection ranges, and
tends to produce a type of selection more in line with that users
expect in a text editor (the native selection styling will often
leave gaps between lines and won't fill the horizontal space after
a line when the selection continues past it).
It does have a performance cost, in that it requires an extra DOM
layout cycle for many updates (the selection is drawn based on DOM
layout information that's only available after laying out the
content).
*/
function drawSelection(config$1 = {}) {
return [selectionConfig.of(config$1), cursorLayer, selectionLayer, hideNativeSelection, nativeSelectionHidden$1.of(true)];
}
function configChanged(update) {
return update.startState.facet(selectionConfig) != update.state.facet(selectionConfig);
}
function setBlinkRate(state, dom) {
dom.style.animationDuration = state.facet(selectionConfig).cursorBlinkRate + "ms";
}
/**
Draws a cursor at the current drop position when something is
dragged over the editor.
*/
function dropCursor() {
return [dropCursorPos$1, drawDropCursor$1];
}
function iterMatches(doc$2, re, from, to, f) {
re.lastIndex = 0;
for (let cursor = doc$2.iterRange(from, to), pos = from, m; !cursor.next().done; pos += cursor.value.length) if (!cursor.lineBreak) while (m = re.exec(cursor.value)) f(pos + m.index, m);
}
function matchRanges(view, maxLength) {
let visible = view.visibleRanges;
if (visible.length == 1 && visible[0].from == view.viewport.from && visible[0].to == view.viewport.to) return visible;
let result = [];
for (let {
from,
to
} of visible) {
from = Math.max(view.state.doc.lineAt(from).from, from - maxLength);
to = Math.min(view.state.doc.lineAt(to).to, to + maxLength);
if (result.length && result[result.length - 1].to >= from) result[result.length - 1].to = to;else result.push({
from,
to
});
}
return result;
}
/**
Helper class used to make it easier to maintain decorations on
visible code that matches a given regular expression. To be used
in a [view plugin](https://codemirror.net/6/docs/ref/#view.ViewPlugin). Instances of this object
represent a matching configuration.
*/
function supportsTabSize() {
var _a$2;
if (_supportsTabSize == null && typeof document != "undefined" && document.body) {
let styles = document.body.style;
_supportsTabSize = ((_a$2 = styles.tabSize) !== null && _a$2 !== void 0 ? _a$2 : styles.MozTabSize) != null;
}
return _supportsTabSize || false;
}
/**
Returns an extension that installs highlighting of special
characters.
*/
function highlightSpecialChars(config$1 = {}) {
return [specialCharConfig.of(config$1), specialCharPlugin()];
}
function specialCharPlugin() {
return _plugin || (_plugin = ViewPlugin$1.fromClass(class {
constructor(view) {
this.view = view;
this.decorations = Decoration$1.none;
this.decorationCache = Object.create(null);
this.decorator = this.makeDecorator(view.state.facet(specialCharConfig));
this.decorations = this.decorator.createDeco(view);
}
makeDecorator(conf) {
return new MatchDecorator({
regexp: conf.specialChars,
decoration: (m, view, pos) => {
let {
doc: doc$2
} = view.state;
let code$1 = codePointAt(m[0], 0);
if (code$1 == 9) {
let line = doc$2.lineAt(pos);
let size = view.state.tabSize,
col = countColumn$1(line.text, size, pos - line.from);
return Decoration$1.replace({
widget: new TabWidget((size - col % size) * this.view.defaultCharacterWidth / this.view.scaleX)
});
}
return this.decorationCache[code$1] || (this.decorationCache[code$1] = Decoration$1.replace({
widget: new SpecialCharWidget(conf, code$1)
}));
},
boundary: conf.replaceTabs ? void 0 : /[^]/
});
}
update(update) {
let conf = update.state.facet(specialCharConfig);
if (update.startState.facet(specialCharConfig) != conf) {
this.decorator = this.makeDecorator(conf);
this.decorations = this.decorator.createDeco(update.view);
} else this.decorations = this.decorator.updateDeco(update, this.decorations);
}
}, {
decorations: v => v.decorations
}));
}
function placeholder$1(code$1) {
if (code$1 >= 32) return DefaultPlaceholder;
if (code$1 == 10) return "";
return String.fromCharCode(9216 + code$1);
}
/**
Mark lines that have a cursor on them with the `"cm-activeLine"`
DOM class.
*/
function highlightActiveLine() {
return activeLineHighlighter;
}
/**
Creates an extension that configures tooltip behavior.
*/
function tooltips(config$1 = {}) {
return tooltipConfig.of(config$1);
}
function windowSpace(view) {
let {
win
} = view;
return {
top: 0,
left: 0,
bottom: win.innerHeight,
right: win.innerWidth
};
}
function isInTooltip(tooltip, event) {
let rect = tooltip.getBoundingClientRect();
return event.clientX >= rect.left - tooltipMargin && event.clientX <= rect.right + tooltipMargin && event.clientY >= rect.top - tooltipMargin && event.clientY <= rect.bottom + tooltipMargin;
}
function isOverRange(view, from, to, x, y, margin) {
let rect = view.scrollDOM.getBoundingClientRect();
let docBottom = view.documentTop + view.documentPadding.top + view.contentHeight;
if (rect.left > x || rect.right < x || rect.top > y || Math.min(rect.bottom, docBottom) < y) return false;
let pos = view.posAtCoords({
x,
y
}, false);
return pos >= from && pos <= to;
}
/**
Set up a hover tooltip, which shows up when the pointer hovers
over ranges of text. The callback is called when the mouse hovers
over the document text. It should, if there is a tooltip
associated with position `pos`, return the tooltip description
(either directly or in a promise). The `side` argument indicates
on which side of the position the pointer is—it will be -1 if the
pointer is before the position, 1 if after the position.
Note that all hover tooltips are hosted within a single tooltip
container element. This allows multiple tooltips over the same
range to be "merged" together without overlapping.
*/
function hoverTooltip(source, options = {}) {
let setHover = StateEffect$1.define();
let hoverState = StateField$1.define({
create() {
return [];
},
update(value, tr) {
if (value.length) {
if (options.hideOnChange && (tr.docChanged || tr.selection)) value = [];else if (options.hideOn) value = value.filter(v => !options.hideOn(tr, v));
if (tr.docChanged) {
let mapped = [];
for (let tooltip of value) {
let newPos = tr.changes.mapPos(tooltip.pos, -1, MapMode.TrackDel);
if (newPos != null) {
let copy = Object.assign(Object.create(null), tooltip);
copy.pos = newPos;
if (copy.end != null) copy.end = tr.changes.mapPos(copy.end);
mapped.push(copy);
}
}
value = mapped;
}
}
for (let effect of tr.effects) {
if (effect.is(setHover)) value = effect.value;
if (effect.is(closeHoverTooltipEffect)) value = [];
}
return value;
},
provide: f => showHoverTooltip.from(f)
});
return [hoverState, ViewPlugin$1.define(view => new HoverPlugin(view, source, hoverState, setHover, options.hoverTime || 300)), showHoverTooltipHost];
}
/**
Get the active tooltip view for a given tooltip, if available.
*/
function getTooltip(view, tooltip) {
let plugin = view.plugin(tooltipPlugin);
if (!plugin) return null;
let found = plugin.manager.tooltips.indexOf(tooltip);
return found < 0 ? null : plugin.manager.tooltipViews[found];
}
/**
Get the active panel created by the given constructor, if any.
This can be useful when you need access to your panels' DOM
structure.
*/
function getPanel(view, panel) {
let plugin = view.plugin(panelPlugin);
let index = plugin ? plugin.specs.indexOf(panel) : -1;
return index > -1 ? plugin.panels[index] : null;
}
function rm(node) {
let next = node.nextSibling;
node.remove();
return next;
}
/**
Opening a panel is done by providing a constructor function for
the panel through this facet. (The panel is closed again when its
constructor is no longer provided.) Values of `null` are ignored.
*/
/**
Define an editor gutter. The order in which the gutters appear is
determined by their extension priority.
*/
function gutter$1(config$1) {
return [gutters(), activeGutters.of(Object.assign(Object.assign({}, defaults$1), config$1))];
}
/**
The gutter-drawing plugin is automatically enabled when you add a
gutter, but you can use this function to explicitly configure it.
Unless `fixed` is explicitly set to `false`, the gutters are
fixed, meaning they don't scroll along with the content
horizontally (except on Internet Explorer, which doesn't support
CSS [`position:
sticky`](https://developer.mozilla.org/en-US/docs/Web/CSS/position#sticky)).
*/
function gutters(config$1) {
let result = [gutterView];
if (config$1 && config$1.fixed === false) result.push(unfixGutters.of(true));
return result;
}
function asArray$1(val) {
return Array.isArray(val) ? val : [val];
}
function advanceCursor(cursor, collect, pos) {
while (cursor.value && cursor.from <= pos) {
if (cursor.from == pos) collect.push(cursor.value);
cursor.next();
}
}
function sameMarkers(a, b) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) if (!a[i$1].compare(b[i$1])) return false;
return true;
}
/**
Facet used to provide markers to the line number gutter.
*/
function formatNumber(view, number$1) {
return view.state.facet(lineNumberConfig).formatNumber(number$1, view.state);
}
/**
Create a line number gutter extension.
*/
function lineNumbers(config$1 = {}) {
return [lineNumberConfig.of(config$1), gutters(), lineNumberGutter];
}
function maxLineNumber(lines) {
let last = 9;
while (last < lines) last = last * 10 + 9;
return last;
}
/**
Returns an extension that adds a `cm-activeLineGutter` class to
all gutter elements on the [active
line](https://codemirror.net/6/docs/ref/#view.highlightActiveLine).
*/
function highlightActiveLineGutter() {
return activeLineGutterHighlighter;
}
//#endregion
//#region ../../../node_modules/.pnpm/@lezer+common@1.2.1/node_modules/@lezer/common/dist/index.js
/**
The default maximum length of a `TreeBuffer` node.
*/
function checkSide(side, pos, from, to) {
switch (side) {
case -2:
return from < pos;
case -1:
return to >= pos && from < pos;
case 0:
return from < pos && to > pos;
case 1:
return from <= pos && to > pos;
case 2:
return to > pos;
case 4:
return true;
}
}
function resolveNode(node, pos, side, overlays) {
var _a$2;
while (node.from == node.to || (side < 1 ? node.from >= pos : node.from > pos) || (side > -1 ? node.to <= pos : node.to < pos)) {
let parent = !overlays && node instanceof TreeNode && node.index < 0 ? null : node.parent;
if (!parent) return node;
node = parent;
}
let mode = overlays ? 0 : IterMode.IgnoreOverlays;
if (overlays) {
for (let scan = node, parent = scan.parent; parent; scan = parent, parent = scan.parent) if (scan instanceof TreeNode && scan.index < 0 && ((_a$2 = parent.enter(pos, side, mode)) === null || _a$2 === void 0 ? void 0 : _a$2.from) != scan.from) node = parent;
}
for (;;) {
let inner = node.enter(pos, side, mode);
if (!inner) return node;
node = inner;
}
}
function getChildren(node, type, before, after) {
let cur$1 = node.cursor(),
result = [];
if (!cur$1.firstChild()) return result;
if (before != null) for (let found = false; !found;) {
found = cur$1.type.is(before);
if (!cur$1.nextSibling()) return result;
}
for (;;) {
if (after != null && cur$1.type.is(after)) return result;
if (cur$1.type.is(type)) result.push(cur$1.node);
if (!cur$1.nextSibling()) return after == null ? result : [];
}
}
function matchNodeContext(node, context, i$1 = context.length - 1) {
for (let p = node.parent; i$1 >= 0; p = p.parent) {
if (!p) return false;
if (!p.type.isAnonymous) {
if (context[i$1] && context[i$1] != p.name) return false;
i$1--;
}
}
return true;
}
function iterStack(heads) {
if (!heads.length) return null;
let pick = 0,
picked = heads[0];
for (let i$1 = 1; i$1 < heads.length; i$1++) {
let node = heads[i$1];
if (node.from > picked.from || node.to < picked.to) {
picked = node;
pick = i$1;
}
}
let next = picked instanceof TreeNode && picked.index < 0 ? null : picked.parent;
let newHeads = heads.slice();
if (next) newHeads[pick] = next;else newHeads.splice(pick, 1);
return new StackIterator(newHeads, picked);
}
function stackIterator(tree, pos, side) {
let inner = tree.resolveInner(pos, side),
layers = null;
for (let scan = inner instanceof TreeNode ? inner : inner.context.parent; scan; scan = scan.parent) if (scan.index < 0) {
let parent = scan.parent;
(layers || (layers = [inner])).push(parent.resolve(pos, side));
scan = parent;
} else {
let mount = MountedTree.get(scan.tree);
if (mount && mount.overlay && mount.overlay[0].from <= pos && mount.overlay[mount.overlay.length - 1].to >= pos) {
let root = new TreeNode(mount.tree, mount.overlay[0].from + scan.from, -1, scan);
(layers || (layers = [inner])).push(resolveNode(root, pos, side, false));
}
}
return layers ? iterStack(layers) : inner;
}
/**
A tree cursor object focuses on a given node in a syntax tree, and
allows you to move to adjacent nodes.
*/
function hasChild(tree) {
return tree.children.some(ch => ch instanceof TreeBuffer || !ch.type.isAnonymous || hasChild(ch));
}
function buildTree(data) {
var _a$2;
let {
buffer,
nodeSet,
maxBufferLength = DefaultBufferLength,
reused = [],
minRepeatType = nodeSet.types.length
} = data;
let cursor = Array.isArray(buffer) ? new FlatBufferCursor(buffer, buffer.length) : buffer;
let types$2 = nodeSet.types;
let contextHash = 0,
lookAhead = 0;
function takeNode(parentStart, minPos, children$1, positions$1, inRepeat, depth) {
let {
id: id$1,
start,
end,
size
} = cursor;
let lookAheadAtStart = lookAhead;
while (size < 0) {
cursor.next();
if (size == -1) {
let node$1 = reused[id$1];
children$1.push(node$1);
positions$1.push(start - parentStart);
return;
} else if (size == -3) {
contextHash = id$1;
return;
} else if (size == -4) {
lookAhead = id$1;
return;
} else throw new RangeError(`Unrecognized record size: ${size}`);
}
let type = types$2[id$1],
node,
buffer$1;
let startPos = start - parentStart;
if (end - start <= maxBufferLength && (buffer$1 = findBufferSize(cursor.pos - minPos, inRepeat))) {
let data$1 = new Uint16Array(buffer$1.size - buffer$1.skip);
let endPos = cursor.pos - buffer$1.size,
index = data$1.length;
while (cursor.pos > endPos) index = copyToBuffer(buffer$1.start, data$1, index);
node = new TreeBuffer(data$1, end - buffer$1.start, nodeSet);
startPos = buffer$1.start - parentStart;
} else {
let endPos = cursor.pos - size;
cursor.next();
let localChildren = [],
localPositions = [];
let localInRepeat = id$1 >= minRepeatType ? id$1 : -1;
let lastGroup = 0,
lastEnd = end;
while (cursor.pos > endPos) if (localInRepeat >= 0 && cursor.id == localInRepeat && cursor.size >= 0) {
if (cursor.end <= lastEnd - maxBufferLength) {
makeRepeatLeaf(localChildren, localPositions, start, lastGroup, cursor.end, lastEnd, localInRepeat, lookAheadAtStart);
lastGroup = localChildren.length;
lastEnd = cursor.end;
}
cursor.next();
} else if (depth > 2500) takeFlatNode(start, endPos, localChildren, localPositions);else takeNode(start, endPos, localChildren, localPositions, localInRepeat, depth + 1);
if (localInRepeat >= 0 && lastGroup > 0 && lastGroup < localChildren.length) makeRepeatLeaf(localChildren, localPositions, start, lastGroup, start, lastEnd, localInRepeat, lookAheadAtStart);
localChildren.reverse();
localPositions.reverse();
if (localInRepeat > -1 && lastGroup > 0) {
let make = makeBalanced(type);
node = balanceRange(type, localChildren, localPositions, 0, localChildren.length, 0, end - start, make, make);
} else node = makeTree(type, localChildren, localPositions, end - start, lookAheadAtStart - end);
}
children$1.push(node);
positions$1.push(startPos);
}
function takeFlatNode(parentStart, minPos, children$1, positions$1) {
let nodes = [];
let nodeCount = 0,
stopAt = -1;
while (cursor.pos > minPos) {
let {
id: id$1,
start,
end,
size
} = cursor;
if (size > 4) cursor.next();else if (stopAt > -1 && start < stopAt) break;else {
if (stopAt < 0) stopAt = end - maxBufferLength;
nodes.push(id$1, start, end);
nodeCount++;
cursor.next();
}
}
if (nodeCount) {
let buffer$1 = new Uint16Array(nodeCount * 4);
let start = nodes[nodes.length - 2];
for (let i$1 = nodes.length - 3, j = 0; i$1 >= 0; i$1 -= 3) {
buffer$1[j++] = nodes[i$1];
buffer$1[j++] = nodes[i$1 + 1] - start;
buffer$1[j++] = nodes[i$1 + 2] - start;
buffer$1[j++] = j;
}
children$1.push(new TreeBuffer(buffer$1, nodes[2] - start, nodeSet));
positions$1.push(start - parentStart);
}
}
function makeBalanced(type) {
return (children$1, positions$1, length$1) => {
let lookAhead$1 = 0,
lastI = children$1.length - 1,
last,
lookAheadProp;
if (lastI >= 0 && (last = children$1[lastI]) instanceof Tree) {
if (!lastI && last.type == type && last.length == length$1) return last;
if (lookAheadProp = last.prop(NodeProp.lookAhead)) lookAhead$1 = positions$1[lastI] + last.length + lookAheadProp;
}
return makeTree(type, children$1, positions$1, length$1, lookAhead$1);
};
}
function makeRepeatLeaf(children$1, positions$1, base$1, i$1, from, to, type, lookAhead$1) {
let localChildren = [],
localPositions = [];
while (children$1.length > i$1) {
localChildren.push(children$1.pop());
localPositions.push(positions$1.pop() + base$1 - from);
}
children$1.push(makeTree(nodeSet.types[type], localChildren, localPositions, to - from, lookAhead$1 - to));
positions$1.push(from - base$1);
}
function makeTree(type, children$1, positions$1, length$1, lookAhead$1 = 0, props) {
if (contextHash) {
let pair$1 = [NodeProp.contextHash, contextHash];
props = props ? [pair$1].concat(props) : [pair$1];
}
if (lookAhead$1 > 25) {
let pair$1 = [NodeProp.lookAhead, lookAhead$1];
props = props ? [pair$1].concat(props) : [pair$1];
}
return new Tree(type, children$1, positions$1, length$1, props);
}
function findBufferSize(maxSize, inRepeat) {
let fork = cursor.fork();
let size = 0,
start = 0,
skip = 0,
minStart = fork.end - maxBufferLength;
let result = {
size: 0,
start: 0,
skip: 0
};
scan: for (let minPos = fork.pos - maxSize; fork.pos > minPos;) {
let nodeSize$1 = fork.size;
if (fork.id == inRepeat && nodeSize$1 >= 0) {
result.size = size;
result.start = start;
result.skip = skip;
skip += 4;
size += 4;
fork.next();
continue;
}
let startPos = fork.pos - nodeSize$1;
if (nodeSize$1 < 0 || startPos < minPos || fork.start < minStart) break;
let localSkipped = fork.id >= minRepeatType ? 4 : 0;
let nodeStart$1 = fork.start;
fork.next();
while (fork.pos > startPos) {
if (fork.size < 0) {
if (fork.size == -3) localSkipped += 4;else break scan;
} else if (fork.id >= minRepeatType) localSkipped += 4;
fork.next();
}
start = nodeStart$1;
size += nodeSize$1;
skip += localSkipped;
}
if (inRepeat < 0 || size == maxSize) {
result.size = size;
result.start = start;
result.skip = skip;
}
return result.size > 4 ? result : void 0;
}
function copyToBuffer(bufferStart, buffer$1, index) {
let {
id: id$1,
start,
end,
size
} = cursor;
cursor.next();
if (size >= 0 && id$1 < minRepeatType) {
let startIndex = index;
if (size > 4) {
let endPos = cursor.pos - (size - 4);
while (cursor.pos > endPos) index = copyToBuffer(bufferStart, buffer$1, index);
}
buffer$1[--index] = startIndex;
buffer$1[--index] = end - bufferStart;
buffer$1[--index] = start - bufferStart;
buffer$1[--index] = id$1;
} else if (size == -3) contextHash = id$1;else if (size == -4) lookAhead = id$1;
return index;
}
let children = [],
positions = [];
while (cursor.pos > 0) takeNode(data.start || 0, data.bufferStart || 0, children, positions, -1, 0);
let length = (_a$2 = data.length) !== null && _a$2 !== void 0 ? _a$2 : children.length ? positions[0] + children[0].length : 0;
return new Tree(types$2[data.topID], children.reverse(), positions.reverse(), length);
}
function nodeSize(balanceType, node) {
if (!balanceType.isAnonymous || node instanceof TreeBuffer || node.type != balanceType) return 1;
let size = nodeSizeCache.get(node);
if (size == null) {
size = 1;
for (let child of node.children) {
if (child.type != balanceType || !(child instanceof Tree)) {
size = 1;
break;
}
size += nodeSize(balanceType, child);
}
nodeSizeCache.set(node, size);
}
return size;
}
function balanceRange(balanceType, children, positions, from, to, start, length, mkTop, mkTree) {
let total = 0;
for (let i$1 = from; i$1 < to; i$1++) total += nodeSize(balanceType, children[i$1]);
let maxChild = Math.ceil(total * 1.5 / 8);
let localChildren = [],
localPositions = [];
function divide(children$1, positions$1, from$1, to$1, offset) {
for (let i$1 = from$1; i$1 < to$1;) {
let groupFrom = i$1,
groupStart = positions$1[i$1],
groupSize = nodeSize(balanceType, children$1[i$1]);
i$1++;
for (; i$1 < to$1; i$1++) {
let nextSize = nodeSize(balanceType, children$1[i$1]);
if (groupSize + nextSize >= maxChild) break;
groupSize += nextSize;
}
if (i$1 == groupFrom + 1) {
if (groupSize > maxChild) {
let only = children$1[groupFrom];
divide(only.children, only.positions, 0, only.children.length, positions$1[groupFrom] + offset);
continue;
}
localChildren.push(children$1[groupFrom]);
} else {
let length$1 = positions$1[i$1 - 1] + children$1[i$1 - 1].length - groupStart;
localChildren.push(balanceRange(balanceType, children$1, positions$1, groupFrom, i$1, groupStart, length$1, null, mkTree));
}
localPositions.push(groupStart + offset - start);
}
}
divide(children, positions, from, to, 0);
return (mkTop || mkTree)(localChildren, localPositions, length);
}
/**
Provides a way to associate values with pieces of trees. As long
as that part of the tree is reused, the associated values can be
retrieved from an updated tree.
*/
/**
Create a parse wrapper that, after the inner parse completes,
scans its tree for mixed language regions with the `nest`
function, runs the resulting [inner parses](#common.NestedParse),
and then [mounts](#common.NodeProp^mounted) their results onto the
tree.
*/
function parseMixed(nest) {
return (parse, input, fragments, ranges) => new MixedParse(parse, nest, input, fragments, ranges);
}
function checkRanges(ranges) {
if (!ranges.length || ranges.some(r => r.from >= r.to)) throw new RangeError("Invalid inner parse ranges given: " + JSON.stringify(ranges));
}
function checkCover(covered, from, to) {
for (let range of covered) {
if (range.from >= to) break;
if (range.to > from) return range.from <= from && range.to >= to ? 2 : 1;
}
return 0;
}
function sliceBuf(buf, startI, endI, nodes, positions, off) {
if (startI < endI) {
let from = buf.buffer[startI + 1];
nodes.push(buf.slice(startI, endI, from));
positions.push(from - off);
}
}
function materialize(cursor) {
let {
node
} = cursor,
stack = [];
let buffer = node.context.buffer;
do {
stack.push(cursor.index);
cursor.parent();
} while (!cursor.tree);
let base$1 = cursor.tree,
i$1 = base$1.children.indexOf(buffer);
let buf = base$1.children[i$1],
b = buf.buffer,
newStack = [i$1];
function split(startI, endI, type, innerOffset, length, stackPos) {
let targetI = stack[stackPos];
let children = [],
positions = [];
sliceBuf(buf, startI, targetI, children, positions, innerOffset);
let from = b[targetI + 1],
to = b[targetI + 2];
newStack.push(children.length);
let child = stackPos ? split(targetI + 4, b[targetI + 3], buf.set.types[b[targetI]], from, to - from, stackPos - 1) : node.toTree();
children.push(child);
positions.push(from - innerOffset);
sliceBuf(buf, b[targetI + 3], endI, children, positions, innerOffset);
return new Tree(type, children, positions, length);
}
base$1.children[i$1] = split(0, b.length, NodeType.none, 0, buf.length, stack.length - 1);
for (let index of newStack) {
let tree = cursor.tree.children[index],
pos = cursor.tree.positions[index];
cursor.yield(new TreeNode(tree, pos + cursor.from, index, cursor._tree));
}
}
function punchRanges(outer, ranges) {
let copy = null,
current = ranges;
for (let i$1 = 1, j = 0; i$1 < outer.length; i$1++) {
let gapFrom = outer[i$1 - 1].to,
gapTo = outer[i$1].from;
for (; j < current.length; j++) {
let r = current[j];
if (r.from >= gapTo) break;
if (r.to <= gapFrom) continue;
if (!copy) current = copy = ranges.slice();
if (r.from < gapFrom) {
copy[j] = new Range$1(r.from, gapFrom);
if (r.to > gapTo) copy.splice(j + 1, 0, new Range$1(gapTo, r.to));
} else if (r.to > gapTo) copy[j--] = new Range$1(gapTo, r.to);else copy.splice(j--, 1);
}
}
return current;
}
function findCoverChanges(a, b, from, to) {
let iA = 0,
iB = 0,
inA = false,
inB = false,
pos = -1e9;
let result = [];
for (;;) {
let nextA = iA == a.length ? 1e9 : inA ? a[iA].to : a[iA].from;
let nextB = iB == b.length ? 1e9 : inB ? b[iB].to : b[iB].from;
if (inA != inB) {
let start = Math.max(pos, from),
end = Math.min(nextA, nextB, to);
if (start < end) result.push(new Range$1(start, end));
}
pos = Math.min(nextA, nextB);
if (pos == 1e9) break;
if (nextA == pos) if (!inA) inA = true;else {
inA = false;
iA++;
}
if (nextB == pos) if (!inB) inB = true;else {
inB = false;
iB++;
}
}
return result;
}
function enterFragments(mounts, ranges) {
let result = [];
for (let {
pos,
mount,
frag
} of mounts) {
let startPos = pos + (mount.overlay ? mount.overlay[0].from : 0),
endPos = startPos + mount.tree.length;
let from = Math.max(frag.from, startPos),
to = Math.min(frag.to, endPos);
if (mount.overlay) {
let changes = findCoverChanges(ranges, mount.overlay.map(r => new Range$1(r.from + pos, r.to + pos)), from, to);
for (let i$1 = 0, pos$1 = from;; i$1++) {
let last = i$1 == changes.length,
end = last ? to : changes[i$1].from;
if (end > pos$1) result.push(new TreeFragment(pos$1, end, mount.tree, -startPos, frag.from >= pos$1 || frag.openStart, frag.to <= end || frag.openEnd));
if (last) break;
pos$1 = changes[i$1].to;
}
} else result.push(new TreeFragment(from, to, mount.tree, -startPos, frag.from >= startPos || frag.openStart, frag.to <= endPos || frag.openEnd));
}
return result;
}
//#endregion
//#region ../../../node_modules/.pnpm/@lezer+highlight@1.1.1_patch_hash=97f85e6fe46f23015ea0dd420e33d584bc2dc71633910cf131321da31b27ca8c/node_modules/@lezer/highlight/dist/index.js
function sameArray$1(a, b) {
return a.length == b.length && a.every((x, i$1) => x == b[i$1]);
}
function permute(array) {
let result = [array];
for (let i$1 = 0; i$1 < array.length; i$1++) for (let a of permute(array.slice(0, i$1).concat(array.slice(i$1 + 1)))) result.push(a);
return result;
}
function styleTags(spec) {
let byName = Object.create(null);
for (let prop in spec) {
let tags$1 = spec[prop];
if (!Array.isArray(tags$1)) tags$1 = [tags$1];
for (let part of prop.split(" ")) if (part) {
let pieces = [],
mode = 2,
rest = part;
for (let pos = 0;;) {
if (rest == "..." && pos > 0 && pos + 3 == part.length) {
mode = 1;
break;
}
let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
if (!m) throw new RangeError("Invalid path: " + part);
pieces.push(m[0] == "*" ? "" : m[0][0] == "\"" ? JSON.parse(m[0]) : m[0]);
pos += m[0].length;
if (pos == part.length) break;
let next = part[pos++];
if (pos == part.length && next == "!") {
mode = 0;
break;
}
if (next != "/") throw new RangeError("Invalid path: " + part);
rest = part.slice(pos);
}
let last = pieces.length - 1,
inner = pieces[last];
if (!inner) throw new RangeError("Invalid path: " + part);
byName[inner] = new Rule(tags$1, mode, last > 0 ? pieces.slice(0, last) : null).sort(byName[inner]);
}
}
return ruleNodeProp.add(byName);
}
function tagHighlighter(tags$1, options) {
let map = Object.create(null);
for (let style of tags$1) if (!Array.isArray(style.tag)) map[style.tag.id] = style.class;else for (let tag of style.tag) map[tag.id] = style.class;
let {
scope,
all = null
} = options || {};
return {
style: tags$2 => {
let cls = all;
for (let tag of tags$2) for (let sub of tag.set) {
let tagClass = map[sub.id];
if (tagClass) {
cls = cls ? cls + " " + tagClass : tagClass;
break;
}
}
return cls;
},
scope
};
}
function highlightTags(highlighters, tags$1) {
let result = null;
for (let highlighter of highlighters) {
let value = highlighter.style(tags$1);
if (value) result = result ? result + " " + value : value;
}
return result;
}
function highlightTree(tree, highlighter, putStyle, from = 0, to = tree.length) {
let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
builder.flush(to);
}
function getStyleTags(node) {
let rule = node.type.prop(ruleNodeProp);
while (rule && rule.context && !node.matchContext(rule.context)) rule = rule.next;
return rule || null;
}
/**
Helper function to define a facet (to be added to the top syntax
node(s) for a language via
[`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
used to associate language data with the language. You
probably only need this when subclassing
[`Language`](https://codemirror.net/6/docs/ref/#language.Language).
*/
function defineLanguageFacet$1(baseData) {
return Facet$1.define({
combine: baseData ? values => values.concat(baseData) : void 0
});
}
/**
Syntax node prop used to register sublanguages. Should be added to
the top level node type for the language.
*/
function topNodeAt$1(state, pos, side) {
let topLang = state.facet(language$1),
tree = syntaxTree$1(state).topNode;
if (!topLang || topLang.allowsNesting) {
for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers)) if (node.type.isTop) tree = node;
}
return tree;
}
/**
A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
[LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
parsers.
*/
/**
Get the syntax tree for a state, which is the current (possibly
incomplete) parse tree of the active
[language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
language available.
*/
function syntaxTree$1(state) {
let field = state.field(Language$1.state, false);
return field ? field.tree : Tree.empty;
}
/**
Try to get a parse tree that spans at least up to `upto`. The
method will do at most `timeout` milliseconds of work to parse
up to that point if the tree isn't already available.
*/
function ensureSyntaxTree(state, upto, timeout = 50) {
var _a$2;
let parse = (_a$2 = state.field(Language$1.state, false)) === null || _a$2 === void 0 ? void 0 : _a$2.context;
if (!parse) return null;
let oldVieport = parse.viewport;
parse.updateViewport({
from: 0,
to: upto
});
let result = parse.isDone(upto) || parse.work(timeout, upto) ? parse.tree : null;
parse.updateViewport(oldVieport);
return result;
}
/**
Lezer-style
[`Input`](https://lezer.codemirror.net/docs/ref#common.Input)
object for a [`Text`](https://codemirror.net/6/docs/ref/#state.Text) object.
*/
function cutFragments$1(fragments, from, to) {
return TreeFragment.applyChanges(fragments, [{
fromA: from,
toA: to,
fromB: from,
toB: to
}]);
}
/**
Return the _column width_ of an indent unit in the state.
Determined by the [`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit)
facet, and [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) when that
contains tabs.
*/
function getIndentUnit(state) {
let unit = state.facet(indentUnit);
return unit.charCodeAt(0) == 9 ? state.tabSize * unit.length : unit.length;
}
/**
Create an indentation string that covers columns 0 to `cols`.
Will use tabs for as much of the columns as possible when the
[`indentUnit`](https://codemirror.net/6/docs/ref/#language.indentUnit) facet contains
tabs.
*/
function indentString(state, cols) {
let result = "",
ts = state.tabSize,
ch = state.facet(indentUnit)[0];
if (ch == " ") {
while (cols >= ts) {
result += " ";
cols -= ts;
}
ch = " ";
}
for (let i$1 = 0; i$1 < cols; i$1++) result += ch;
return result;
}
/**
Get the indentation, as a column number, at the given position.
Will first consult any [indent services](https://codemirror.net/6/docs/ref/#language.indentService)
that are registered, and if none of those return an indentation,
this will check the syntax tree for the [indent node
prop](https://codemirror.net/6/docs/ref/#language.indentNodeProp) and use that if found. Returns a
number when an indentation could be determined, and null
otherwise.
*/
function getIndentation(context, pos) {
if (context instanceof EditorState) context = new IndentContext(context);
for (let service of context.state.facet(indentService)) {
let result = service(context, pos);
if (result !== void 0) return result;
}
let tree = syntaxTree$1(context.state);
return tree.length >= pos ? syntaxIndentation(context, tree, pos) : null;
}
/**
Indentation contexts are used when calling [indentation
services](https://codemirror.net/6/docs/ref/#language.indentService). They provide helper utilities
useful in indentation logic, and can selectively override the
indentation reported for some lines.
*/
function syntaxIndentation(cx, ast, pos) {
let stack = ast.resolveStack(pos);
let inner = stack.node.enterUnfinishedNodesBefore(pos);
if (inner != stack.node) {
let add$1 = [];
for (let cur$1 = inner; cur$1 != stack.node; cur$1 = cur$1.parent) add$1.push(cur$1);
for (let i$1 = add$1.length - 1; i$1 >= 0; i$1--) stack = {
node: add$1[i$1],
next: stack
};
}
return indentFor(stack, cx, pos);
}
function indentFor(stack, cx, pos) {
for (let cur$1 = stack; cur$1; cur$1 = cur$1.next) {
let strategy = indentStrategy(cur$1.node);
if (strategy) return strategy(TreeIndentContext.create(cx, pos, cur$1));
}
return 0;
}
function ignoreClosed(cx) {
return cx.pos == cx.options.simulateBreak && cx.options.simulateDoubleBreak;
}
function indentStrategy(tree) {
let strategy = tree.type.prop(indentNodeProp);
if (strategy) return strategy;
let first = tree.firstChild,
close;
if (first && (close = first.type.prop(NodeProp.closedBy))) {
let last = tree.lastChild,
closed = last && close.indexOf(last.name) > -1;
return cx => delimitedStrategy(cx, true, 1, void 0, closed && !ignoreClosed(cx) ? last.from : void 0);
}
return tree.parent == null ? topIndent : null;
}
function topIndent() {
return 0;
}
/**
Objects of this type provide context information and helper
methods to indentation functions registered on syntax nodes.
*/
function isParent(parent, of) {
for (let cur$1 = of; cur$1; cur$1 = cur$1.parent) if (parent == cur$1) return true;
return false;
}
function bracketedAligned(context) {
let tree = context.node;
let openToken = tree.childAfter(tree.from),
last = tree.lastChild;
if (!openToken) return null;
let sim = context.options.simulateBreak;
let openLine = context.state.doc.lineAt(openToken.from);
let lineEnd = sim == null || sim <= openLine.from ? openLine.to : Math.min(openLine.to, sim);
for (let pos = openToken.to;;) {
let next = tree.childAfter(pos);
if (!next || next == last) return null;
if (!next.type.isSkipped) return next.from < lineEnd ? openToken : null;
pos = next.to;
}
}
/**
An indentation strategy for delimited (usually bracketed) nodes.
Will, by default, indent one unit more than the parent's base
indent unless the line starts with a closing token. When `align`
is true and there are non-skipped nodes on the node's opening
line, the content of the node will be aligned with the end of the
opening node, like this:
foo(bar,
baz)
*/
function delimitedIndent({
closing: closing$1,
align = true,
units = 1
}) {
return context => delimitedStrategy(context, align, units, closing$1);
}
function delimitedStrategy(context, align, units, closing$1, closedAt) {
let after = context.textAfter,
space$1 = after.match(/^\s*/)[0].length;
let closed = closing$1 && after.slice(space$1, space$1 + closing$1.length) == closing$1 || closedAt == context.pos + space$1;
let aligned = align ? bracketedAligned(context) : null;
if (aligned) return closed ? context.column(aligned.from) : context.column(aligned.to);
return context.baseIndent + (closed ? 0 : context.unit * units);
}
/**
An indentation strategy that aligns a node's content to its base
indentation.
*/
/**
Creates an indentation strategy that, by default, indents
continued lines one unit more than the node's base indentation.
You can provide `except` to prevent indentation of lines that
match a pattern (for example `/^else\b/` in `if`/`else`
constructs), and you can change the amount of units used with the
`units` option.
*/
function continuedIndent({
except,
units = 1
} = {}) {
return context => {
let matchExcept = except && except.test(context.textAfter);
return context.baseIndent + (matchExcept ? 0 : units * context.unit);
};
}
/**
Enables reindentation on input. When a language defines an
`indentOnInput` field in its [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt), which must hold a regular
expression, the line at the cursor will be reindented whenever new
text is typed and the input from the start of the line up to the
cursor matches that regexp.
To avoid unneccesary reindents, it is recommended to start the
regexp with `^` (usually followed by `\s*`), and end it with `$`.
For example, `/^\s*\}$/` will reindent when a closing brace is
added at the start of a line.
*/
function indentOnInput() {
return EditorState.transactionFilter.of(tr => {
if (!tr.docChanged || !tr.isUserEvent("input.type") && !tr.isUserEvent("input.complete")) return tr;
let rules = tr.startState.languageDataAt("indentOnInput", tr.startState.selection.main.head);
if (!rules.length) return tr;
let doc$2 = tr.newDoc,
{
head
} = tr.newSelection.main,
line = doc$2.lineAt(head);
if (head > line.from + DontIndentBeyond) return tr;
let lineStart = doc$2.sliceString(line.from, head);
if (!rules.some(r => r.test(lineStart))) return tr;
let {
state
} = tr,
last = -1,
changes = [];
for (let {
head: head$1
} of state.selection.ranges) {
let line$1 = state.doc.lineAt(head$1);
if (line$1.from == last) continue;
last = line$1.from;
let indent = getIndentation(state, line$1.from);
if (indent == null) continue;
let cur$1 = /^\s*/.exec(line$1.text)[0];
let norm = indentString(state, indent);
if (cur$1 != norm) changes.push({
from: line$1.from,
to: line$1.from + cur$1.length,
insert: norm
});
}
return changes.length ? [tr, {
changes,
sequential: true
}] : tr;
});
}
/**
A facet that registers a code folding service. When called with
the extent of a line, such a function should return a foldable
range that starts on that line (but continues beyond it), if one
can be found.
*/
/**
[Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
the first and the last child of a syntax node. Useful for nodes
that start and end with delimiters.
*/
function foldInside(node) {
let first = node.firstChild,
last = node.lastChild;
return first && first.to < last.from ? {
from: first.to,
to: last.type.isError ? node.to : last.from
} : null;
}
function syntaxFolding(state, start, end) {
let tree = syntaxTree$1(state);
if (tree.length < end) return null;
let stack = tree.resolveStack(end, 1);
let found = null;
for (let iter = stack; iter; iter = iter.next) {
let cur$1 = iter.node;
if (cur$1.to <= end || cur$1.from > end) continue;
if (found && cur$1.from < start) break;
let prop = cur$1.type.prop(foldNodeProp);
if (prop && (cur$1.to < tree.length - 50 || tree.length == state.doc.length || !isUnfinished(cur$1))) {
let value = prop(cur$1, state);
if (value && value.from <= end && value.from >= start && value.to > end) found = value;
}
}
return found;
}
function isUnfinished(node) {
let ch = node.lastChild;
return ch && ch.to == node.to && ch.type.isError;
}
/**
Check whether the given line is foldable. First asks any fold
services registered through
[`foldService`](https://codemirror.net/6/docs/ref/#language.foldService), and if none of them return
a result, tries to query the [fold node
prop](https://codemirror.net/6/docs/ref/#language.foldNodeProp) of syntax nodes that cover the end
of the line.
*/
function foldable(state, lineStart, lineEnd) {
for (let service of state.facet(foldService)) {
let result = service(state, lineStart, lineEnd);
if (result) return result;
}
return syntaxFolding(state, lineStart, lineEnd);
}
function mapRange(range, mapping) {
let from = mapping.mapPos(range.from, 1),
to = mapping.mapPos(range.to, -1);
return from >= to ? void 0 : {
from,
to
};
}
/**
State effect that can be attached to a transaction to fold the
given range. (You probably only need this in exceptional
circumstances—usually you'll just want to let
[`foldCode`](https://codemirror.net/6/docs/ref/#language.foldCode) and the [fold
gutter](https://codemirror.net/6/docs/ref/#language.foldGutter) create the transactions.)
*/
function selectedLines(view) {
let lines = [];
for (let {
head
} of view.state.selection.ranges) {
if (lines.some(l => l.from <= head && l.to >= head)) continue;
lines.push(view.lineBlockAt(head));
}
return lines;
}
/**
The state field that stores the folded ranges (as a [decoration
set](https://codemirror.net/6/docs/ref/#view.DecorationSet)). Can be passed to
[`EditorState.toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) and
[`fromJSON`](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) to serialize the fold
state.
*/
function findFold(state, from, to) {
var _a$2;
let found = null;
(_a$2 = state.field(foldState, false)) === null || _a$2 === void 0 || _a$2.between(from, to, (from$1, to$1) => {
if (!found || found.from > from$1) found = {
from: from$1,
to: to$1
};
});
return found;
}
function foldExists(folded, from, to) {
let found = false;
folded.between(from, from, (a, b) => {
if (a == from && b == to) found = true;
});
return found;
}
function maybeEnable(state, other) {
return state.field(foldState, false) ? other : other.concat(StateEffect$1.appendConfig.of(codeFolding()));
}
/**
Fold the lines that are selected, if possible.
*/
function announceFold(view, range, fold = true) {
let lineFrom = view.state.doc.lineAt(range.from).number,
lineTo = view.state.doc.lineAt(range.to).number;
return EditorView.announce.of(`${view.state.phrase(fold ? "Folded lines" : "Unfolded lines")} ${lineFrom} ${view.state.phrase("to")} ${lineTo}.`);
}
/**
Fold all top-level foldable ranges. Note that, in most cases,
folding information will depend on the [syntax
tree](https://codemirror.net/6/docs/ref/#language.syntaxTree), and folding everything may not work
reliably when the document hasn't been fully parsed (either
because the editor state was only just initialized, or because the
document is so big that the parser decided not to parse it
entirely).
*/
/**
Create an extension that configures code folding.
*/
function codeFolding(config$1) {
let result = [foldState, baseTheme$1$4];
if (config$1) result.push(foldConfig.of(config$1));
return result;
}
function widgetToDOM(view, prepared) {
let {
state
} = view,
conf = state.facet(foldConfig);
let onclick = event => {
let line = view.lineBlockAt(view.posAtDOM(event.target));
let folded = findFold(view.state, line.from, line.to);
if (folded) view.dispatch({
effects: unfoldEffect.of(folded)
});
event.preventDefault();
};
if (conf.placeholderDOM) return conf.placeholderDOM(view, onclick, prepared);
let element = document.createElement("span");
element.textContent = conf.placeholderText;
element.setAttribute("aria-label", state.phrase("folded code"));
element.title = state.phrase("unfold");
element.className = "cm-foldPlaceholder";
element.onclick = onclick;
return element;
}
/**
Create an extension that registers a fold gutter, which shows a
fold status indicator before foldable lines (which can be clicked
to fold or unfold the line).
*/
function foldGutter(config$1 = {}) {
let fullConfig = Object.assign(Object.assign({}, foldGutterDefaults), config$1);
let canFold = new FoldMarker(fullConfig, true),
canUnfold = new FoldMarker(fullConfig, false);
let markers = ViewPlugin$1.fromClass(class {
constructor(view) {
this.from = view.viewport.from;
this.markers = this.buildMarkers(view);
}
update(update) {
if (update.docChanged || update.viewportChanged || update.startState.facet(language$1) != update.state.facet(language$1) || update.startState.field(foldState, false) != update.state.field(foldState, false) || syntaxTree$1(update.startState) != syntaxTree$1(update.state) || fullConfig.foldingChanged(update)) this.markers = this.buildMarkers(update.view);
}
buildMarkers(view) {
let builder = new RangeSetBuilder$1();
for (let line of view.viewportLineBlocks) {
let mark = findFold(view.state, line.from, line.to) ? canUnfold : foldable(view.state, line.from, line.to) ? canFold : null;
if (mark) builder.add(line.from, line.from, mark);
}
return builder.finish();
}
});
let {
domEventHandlers
} = fullConfig;
return [markers, gutter$1({
class: "cm-foldGutter",
markers(view) {
var _a$2;
return ((_a$2 = view.plugin(markers)) === null || _a$2 === void 0 ? void 0 : _a$2.markers) || RangeSet$1.empty;
},
initialSpacer() {
return new FoldMarker(fullConfig, false);
},
domEventHandlers: Object.assign(Object.assign({}, domEventHandlers), {
click: (view, line, event) => {
if (domEventHandlers.click && domEventHandlers.click(view, line, event)) return true;
let folded = findFold(view.state, line.from, line.to);
if (folded) {
view.dispatch({
effects: unfoldEffect.of(folded)
});
return true;
}
let range = foldable(view.state, line.from, line.to);
if (range) {
view.dispatch({
effects: foldEffect.of(range)
});
return true;
}
return false;
}
})
}), codeFolding()];
}
function getHighlighters(state) {
let main = state.facet(highlighterFacet);
return main.length ? main : state.facet(fallbackHighlighter);
}
/**
Wrap a highlighter in an editor extension that uses it to apply
syntax highlighting to the editor content.
When multiple (non-fallback) styles are provided, the styling
applied is the union of the classes they emit.
*/
function syntaxHighlighting(highlighter, options) {
let ext = [treeHighlighter],
themeType;
if (highlighter instanceof HighlightStyle) {
if (highlighter.module) ext.push(EditorView.styleModule.of(highlighter.module));
themeType = highlighter.themeType;
}
if (options === null || options === void 0 ? void 0 : options.fallback) ext.push(fallbackHighlighter.of(highlighter));else if (themeType) ext.push(highlighterFacet.computeN([EditorView.darkTheme], state => {
return state.facet(EditorView.darkTheme) == (themeType == "dark") ? [highlighter] : [];
}));else ext.push(highlighterFacet.of(highlighter));
return ext;
}
function defaultRenderMatch(match) {
let decorations$2 = [];
let mark = match.matched ? matchingMark : nonmatchingMark;
decorations$2.push(mark.range(match.start.from, match.start.to));
if (match.end) decorations$2.push(mark.range(match.end.from, match.end.to));
return decorations$2;
}
/**
Create an extension that enables bracket matching. Whenever the
cursor is next to a bracket, that bracket and the one it matches
are highlighted. Or, when no matching bracket is found, another
highlighting style is used to indicate this.
*/
function bracketMatching(config$1 = {}) {
return [bracketMatchingConfig.of(config$1), bracketMatchingUnique];
}
/**
When larger syntax nodes, such as HTML tags, are marked as
opening/closing, it can be a bit messy to treat the whole node as
a matchable bracket. This node prop allows you to define, for such
a node, a ‘handle’—the part of the node that is highlighted, and
that the cursor must be on to activate highlighting in the first
place.
*/
function matchingNodes(node, dir, brackets) {
let byProp = node.prop(dir < 0 ? NodeProp.openedBy : NodeProp.closedBy);
if (byProp) return byProp;
if (node.name.length == 1) {
let index = brackets.indexOf(node.name);
if (index > -1 && index % 2 == (dir < 0 ? 1 : 0)) return [brackets[index + dir]];
}
return null;
}
function findHandle(node) {
let hasHandle = node.type.prop(bracketMatchingHandle);
return hasHandle ? hasHandle(node.node) : node;
}
/**
Find the matching bracket for the token at `pos`, scanning
direction `dir`. Only the `brackets` and `maxScanDistance`
properties are used from `config`, if given. Returns null if no
bracket was found at `pos`, or a match result otherwise.
*/
function matchBrackets(state, pos, dir, config$1 = {}) {
let maxScanDistance = config$1.maxScanDistance || DefaultScanDist,
brackets = config$1.brackets || DefaultBrackets;
let tree = syntaxTree$1(state),
node = tree.resolveInner(pos, dir);
for (let cur$1 = node; cur$1; cur$1 = cur$1.parent) {
let matches = matchingNodes(cur$1.type, dir, brackets);
if (matches && cur$1.from < cur$1.to) {
let handle = findHandle(cur$1);
if (handle && (dir > 0 ? pos >= handle.from && pos < handle.to : pos > handle.from && pos <= handle.to)) return matchMarkedBrackets(state, pos, dir, cur$1, handle, matches, brackets);
}
}
return matchPlainBrackets(state, pos, dir, tree, node.type, maxScanDistance, brackets);
}
function matchMarkedBrackets(_state, _pos, dir, token, handle, matching, brackets) {
let parent = token.parent,
firstToken = {
from: handle.from,
to: handle.to
};
let depth = 0,
cursor = parent === null || parent === void 0 ? void 0 : parent.cursor();
if (cursor && (dir < 0 ? cursor.childBefore(token.from) : cursor.childAfter(token.to))) do if (dir < 0 ? cursor.to <= token.from : cursor.from >= token.to) {
if (depth == 0 && matching.indexOf(cursor.type.name) > -1 && cursor.from < cursor.to) {
let endHandle = findHandle(cursor);
return {
start: firstToken,
end: endHandle ? {
from: endHandle.from,
to: endHandle.to
} : void 0,
matched: true
};
} else if (matchingNodes(cursor.type, dir, brackets)) depth++;else if (matchingNodes(cursor.type, -dir, brackets)) {
if (depth == 0) {
let endHandle = findHandle(cursor);
return {
start: firstToken,
end: endHandle && endHandle.from < endHandle.to ? {
from: endHandle.from,
to: endHandle.to
} : void 0,
matched: false
};
}
depth--;
}
} while (dir < 0 ? cursor.prevSibling() : cursor.nextSibling());
return {
start: firstToken,
matched: false
};
}
function matchPlainBrackets(state, pos, dir, tree, tokenType, maxScanDistance, brackets) {
let startCh = dir < 0 ? state.sliceDoc(pos - 1, pos) : state.sliceDoc(pos, pos + 1);
let bracket$1 = brackets.indexOf(startCh);
if (bracket$1 < 0 || bracket$1 % 2 == 0 != dir > 0) return null;
let startToken = {
from: dir < 0 ? pos - 1 : pos,
to: dir > 0 ? pos + 1 : pos
};
let iter = state.doc.iterRange(pos, dir > 0 ? state.doc.length : 0),
depth = 0;
for (let distance = 0; !iter.next().done && distance <= maxScanDistance;) {
let text = iter.value;
if (dir < 0) distance += text.length;
let basePos = pos + distance * dir;
for (let pos$1 = dir > 0 ? 0 : text.length - 1, end = dir > 0 ? text.length : -1; pos$1 != end; pos$1 += dir) {
let found = brackets.indexOf(text[pos$1]);
if (found < 0 || tree.resolveInner(basePos + pos$1, 1).type != tokenType) continue;
if (found % 2 == 0 == dir > 0) depth++;else if (depth == 1) return {
start: startToken,
end: {
from: basePos + pos$1,
to: basePos + pos$1 + 1
},
matched: found >> 1 == bracket$1 >> 1
};else depth--;
}
if (dir > 0) distance += text.length;
}
return iter.done ? {
start: startToken,
matched: false
} : null;
}
function warnForPart$1(part, msg) {
if (warned$1.indexOf(part) > -1) return;
warned$1.push(part);
console.warn(msg);
}
function createTokenType$1(extra, tagStr) {
let tags$1 = [];
for (let name$2 of tagStr.split(" ")) {
let found = [];
for (let part of name$2.split(".")) {
let value = extra[part] || tags[part];
if (!value) warnForPart$1(part, `Unknown highlighting tag ${part}`);else if (typeof value == "function") {
if (!found.length) warnForPart$1(part, `Modifier ${part} used at start of tag`);else found = found.map(value);
} else if (found.length) warnForPart$1(part, `Tag ${part} used as modifier`);else found = Array.isArray(value) ? value : [value];
}
for (let tag of found) tags$1.push(tag);
}
if (!tags$1.length) return 0;
let name$1 = tagStr.replace(/ /g, "_"),
key = name$1 + " " + tags$1.map(t$1 => t$1.id);
let known = byTag$1[key];
if (known) return known.id;
let type = byTag$1[key] = NodeType.define({
id: typeArray$1.length,
name: name$1,
props: [styleTags({
[name$1]: tags$1
})]
});
typeArray$1.push(type);
return type.id;
}
function command(f, option) {
return ({
state,
dispatch
}) => {
if (state.readOnly) return false;
let tr = f(option, state);
if (!tr) return false;
dispatch(state.update(tr));
return true;
};
}
/**
Comment or uncomment the current selection using line comments.
The line comment syntax is taken from the
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
*/
function getConfig(state, pos) {
let data = state.languageDataAt("commentTokens", pos);
return data.length ? data[0] : {};
}
/**
Determines if the given range is block-commented in the given
state.
*/
function findBlockComment(state, {
open,
close
}, from, to) {
let textBefore = state.sliceDoc(from - SearchMargin, from);
let textAfter = state.sliceDoc(to, to + SearchMargin);
let spaceBefore = /\s*$/.exec(textBefore)[0].length,
spaceAfter = /^\s*/.exec(textAfter)[0].length;
let beforeOff = textBefore.length - spaceBefore;
if (textBefore.slice(beforeOff - open.length, beforeOff) == open && textAfter.slice(spaceAfter, spaceAfter + close.length) == close) return {
open: {
pos: from - spaceBefore,
margin: spaceBefore && 1
},
close: {
pos: to + spaceAfter,
margin: spaceAfter && 1
}
};
let startText, endText;
if (to - from <= 2 * SearchMargin) startText = endText = state.sliceDoc(from, to);else {
startText = state.sliceDoc(from, from + SearchMargin);
endText = state.sliceDoc(to - SearchMargin, to);
}
let startSpace = /^\s*/.exec(startText)[0].length,
endSpace = /\s*$/.exec(endText)[0].length;
let endOff = endText.length - endSpace - close.length;
if (startText.slice(startSpace, startSpace + open.length) == open && endText.slice(endOff, endOff + close.length) == close) return {
open: {
pos: from + startSpace + open.length,
margin: /\s/.test(startText.charAt(startSpace + open.length)) ? 1 : 0
},
close: {
pos: to - endSpace - close.length,
margin: /\s/.test(endText.charAt(endOff - 1)) ? 1 : 0
}
};
return null;
}
function selectedLineRanges(state) {
let ranges = [];
for (let r of state.selection.ranges) {
let fromLine = state.doc.lineAt(r.from);
let toLine = r.to <= fromLine.to ? fromLine : state.doc.lineAt(r.to);
let last = ranges.length - 1;
if (last >= 0 && ranges[last].to > fromLine.from) ranges[last].to = toLine.to;else ranges.push({
from: fromLine.from + /^\s*/.exec(fromLine.text)[0].length,
to: toLine.to
});
}
return ranges;
}
function changeBlockComment(option, state, ranges = state.selection.ranges) {
let tokens = ranges.map(r => getConfig(state, r.from).block);
if (!tokens.every(c => c)) return null;
let comments = ranges.map((r, i$1) => findBlockComment(state, tokens[i$1], r.from, r.to));
if (option != 2 && !comments.every(c => c)) return {
changes: state.changes(ranges.map((range, i$1) => {
if (comments[i$1]) return [];
return [{
from: range.from,
insert: tokens[i$1].open + " "
}, {
from: range.to,
insert: " " + tokens[i$1].close
}];
}))
};else if (option != 1 && comments.some(c => c)) {
let changes = [];
for (let i$1 = 0, comment$1; i$1 < comments.length; i$1++) if (comment$1 = comments[i$1]) {
let token = tokens[i$1],
{
open,
close
} = comment$1;
changes.push({
from: open.pos - token.open.length,
to: open.pos + open.margin
}, {
from: close.pos - close.margin,
to: close.pos + token.close.length
});
}
return {
changes
};
}
return null;
}
function changeLineComment(option, state, ranges = state.selection.ranges) {
let lines = [];
let prevLine = -1;
for (let {
from,
to
} of ranges) {
let startI = lines.length,
minIndent = 1e9;
let token = getConfig(state, from).line;
if (!token) continue;
for (let pos = from; pos <= to;) {
let line = state.doc.lineAt(pos);
if (line.from > prevLine && (from == to || to > line.from)) {
prevLine = line.from;
let indent = /^\s*/.exec(line.text)[0].length;
let empty$1 = indent == line.length;
let comment$1 = line.text.slice(indent, indent + token.length) == token ? indent : -1;
if (indent < line.text.length && indent < minIndent) minIndent = indent;
lines.push({
line,
comment: comment$1,
token,
indent,
empty: empty$1,
single: false
});
}
pos = line.to + 1;
}
if (minIndent < 1e9) {
for (let i$1 = startI; i$1 < lines.length; i$1++) if (lines[i$1].indent < lines[i$1].line.text.length) lines[i$1].indent = minIndent;
}
if (lines.length == startI + 1) lines[startI].single = true;
}
if (option != 2 && lines.some(l => l.comment < 0 && (!l.empty || l.single))) {
let changes = [];
for (let {
line,
token,
indent,
empty: empty$1,
single
} of lines) if (single || !empty$1) changes.push({
from: line.from + indent,
insert: token + " "
});
let changeSet = state.changes(changes);
return {
changes: changeSet,
selection: state.selection.map(changeSet, 1)
};
} else if (option != 1 && lines.some(l => l.comment >= 0)) {
let changes = [];
for (let {
line,
comment: comment$1,
token
} of lines) if (comment$1 >= 0) {
let from = line.from + comment$1,
to = from + token.length;
if (line.text[to - line.from] == " ") to++;
changes.push({
from,
to
});
}
return {
changes
};
}
return null;
}
/**
Create a history extension with the given configuration.
*/
function history(config$1 = {}) {
return [historyField_, historyConfig.of(config$1), EditorView.domEventHandlers({
beforeinput(e, view) {
let command$1 = e.inputType == "historyUndo" ? undo : e.inputType == "historyRedo" ? redo : null;
if (!command$1) return false;
e.preventDefault();
return command$1(view);
}
})];
}
/**
The state field used to store the history data. Should probably
only be used when you want to
[serialize](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) or
[deserialize](https://codemirror.net/6/docs/ref/#state.EditorState^fromJSON) state objects in a way
that preserves history.
*/
function cmd(side, selection) {
return function ({
state,
dispatch
}) {
if (!selection && state.readOnly) return false;
let historyState = state.field(historyField_, false);
if (!historyState) return false;
let tr = historyState.pop(side, state, selection);
if (!tr) return false;
dispatch(tr);
return true;
};
}
/**
Undo a single group of history events. Returns false if no group
was available.
*/
function updateBranch(branch, to, maxLen, newEvent) {
let start = to + 1 > maxLen + 20 ? to - maxLen - 1 : 0;
let newBranch = branch.slice(start, to);
newBranch.push(newEvent);
return newBranch;
}
function isAdjacent(a, b) {
let ranges = [],
isAdjacent$1 = false;
a.iterChangedRanges((f, t$1) => ranges.push(f, t$1));
b.iterChangedRanges((_f, _t, f, t$1) => {
for (let i$1 = 0; i$1 < ranges.length;) {
let from = ranges[i$1++],
to = ranges[i$1++];
if (t$1 >= from && f <= to) isAdjacent$1 = true;
}
});
return isAdjacent$1;
}
function eqSelectionShape(a, b) {
return a.ranges.length == b.ranges.length && a.ranges.filter((r, i$1) => r.empty != b.ranges[i$1].empty).length === 0;
}
function conc(a, b) {
return !a.length ? b : !b.length ? a : a.concat(b);
}
function addSelection(branch, selection) {
if (!branch.length) return [HistEvent.selection([selection])];else {
let lastEvent = branch[branch.length - 1];
let sels = lastEvent.selectionsAfter.slice(Math.max(0, lastEvent.selectionsAfter.length - MaxSelectionsPerEvent));
if (sels.length && sels[sels.length - 1].eq(selection)) return branch;
sels.push(selection);
return updateBranch(branch, branch.length - 1, 1e9, lastEvent.setSelAfter(sels));
}
}
function popSelection(branch) {
let last = branch[branch.length - 1];
let newBranch = branch.slice();
newBranch[branch.length - 1] = last.setSelAfter(last.selectionsAfter.slice(0, last.selectionsAfter.length - 1));
return newBranch;
}
function addMappingToBranch(branch, mapping) {
if (!branch.length) return branch;
let length = branch.length,
selections = none$2;
while (length) {
let event = mapEvent(branch[length - 1], mapping, selections);
if (event.changes && !event.changes.empty || event.effects.length) {
let result = branch.slice(0, length);
result[length - 1] = event;
return result;
} else {
mapping = event.mapped;
length--;
selections = event.selectionsAfter;
}
}
return selections.length ? [HistEvent.selection(selections)] : none$2;
}
function mapEvent(event, mapping, extraSelections) {
let selections = conc(event.selectionsAfter.length ? event.selectionsAfter.map(s => s.map(mapping)) : none$2, extraSelections);
if (!event.changes) return HistEvent.selection(selections);
let mappedChanges = event.changes.map(mapping),
before = mapping.mapDesc(event.changes, true);
let fullMapping = event.mapped ? event.mapped.composeDesc(before) : before;
return new HistEvent(mappedChanges, StateEffect$1.mapEffects(event.effects, mapping), fullMapping, event.startSelection.map(before), selections);
}
function updateSel(sel, by) {
return EditorSelection.create(sel.ranges.map(by), sel.mainIndex);
}
function setSel(state, selection) {
return state.update({
selection,
scrollIntoView: true,
userEvent: "select"
});
}
function moveSel({
state,
dispatch
}, how) {
let selection = updateSel(state.selection, how);
if (selection.eq(state.selection, true)) return false;
dispatch(setSel(state, selection));
return true;
}
function rangeEnd(range, forward) {
return EditorSelection.cursor(forward ? range.to : range.from);
}
function cursorByChar(view, forward) {
return moveSel(view, range => range.empty ? view.moveByChar(range, forward) : rangeEnd(range, forward));
}
function ltrAtCursor(view) {
return view.textDirectionAt(view.state.selection.main.head) == Direction$1.LTR;
}
/**
Move the selection one character to the left (which is backward in
left-to-right text, forward in right-to-left text).
*/
function cursorByGroup(view, forward) {
return moveSel(view, range => range.empty ? view.moveByGroup(range, forward) : rangeEnd(range, forward));
}
/**
Move the selection to the left across one group of word or
non-word (but also non-space) characters.
*/
function cursorByLine(view, forward) {
return moveSel(view, range => {
if (!range.empty) return rangeEnd(range, forward);
let moved = view.moveVertically(range, forward);
return moved.head != range.head ? moved : view.moveToLineBoundary(range, forward);
});
}
/**
Move the selection one line up.
*/
function pageInfo(view) {
let selfScroll = view.scrollDOM.clientHeight < view.scrollDOM.scrollHeight - 2;
let marginTop = 0,
marginBottom = 0,
height;
if (selfScroll) {
for (let source of view.state.facet(EditorView.scrollMargins)) {
let margins = source(view);
if (margins === null || margins === void 0 ? void 0 : margins.top) marginTop = Math.max(margins === null || margins === void 0 ? void 0 : margins.top, marginTop);
if (margins === null || margins === void 0 ? void 0 : margins.bottom) marginBottom = Math.max(margins === null || margins === void 0 ? void 0 : margins.bottom, marginBottom);
}
height = view.scrollDOM.clientHeight - marginTop - marginBottom;
} else height = (view.dom.ownerDocument.defaultView || window).innerHeight;
return {
marginTop,
marginBottom,
selfScroll,
height: Math.max(view.defaultLineHeight, height - 5)
};
}
function cursorByPage(view, forward) {
let page = pageInfo(view);
let {
state
} = view,
selection = updateSel(state.selection, range => {
return range.empty ? view.moveVertically(range, forward, page.height) : rangeEnd(range, forward);
});
if (selection.eq(state.selection)) return false;
let effect;
if (page.selfScroll) {
let startPos = view.coordsAtPos(state.selection.main.head);
let scrollRect = view.scrollDOM.getBoundingClientRect();
let scrollTop = scrollRect.top + page.marginTop,
scrollBottom = scrollRect.bottom - page.marginBottom;
if (startPos && startPos.top > scrollTop && startPos.bottom < scrollBottom) effect = EditorView.scrollIntoView(selection.main.head, {
y: "start",
yMargin: startPos.top - scrollTop
});
}
view.dispatch(setSel(state, selection), {
effects: effect
});
return true;
}
/**
Move the selection one page up.
*/
function moveByLineBoundary(view, start, forward) {
let line = view.lineBlockAt(start.head),
moved = view.moveToLineBoundary(start, forward);
if (moved.head == start.head && moved.head != (forward ? line.to : line.from)) moved = view.moveToLineBoundary(start, forward, false);
if (!forward && moved.head == line.from && line.length) {
let space$1 = /^\s*/.exec(view.state.sliceDoc(line.from, Math.min(line.from + 100, line.to)))[0].length;
if (space$1 && start.head != line.from + space$1) moved = EditorSelection.cursor(line.from + space$1);
}
return moved;
}
/**
Move the selection to the next line wrap point, or to the end of
the line if there isn't one left on this line.
*/
function toMatchingBracket(state, dispatch, extend$2) {
let found = false,
selection = updateSel(state.selection, range => {
let matching = matchBrackets(state, range.head, -1) || matchBrackets(state, range.head, 1) || range.head > 0 && matchBrackets(state, range.head - 1, 1) || range.head < state.doc.length && matchBrackets(state, range.head + 1, -1);
if (!matching || !matching.end) return range;
found = true;
let head = matching.start.from == range.head ? matching.end.to : matching.end.from;
return extend$2 ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head);
});
if (!found) return false;
dispatch(setSel(state, selection));
return true;
}
/**
Move the selection to the bracket matching the one it is currently
on, if any.
*/
function extendSel(view, how) {
let selection = updateSel(view.state.selection, range => {
let head = how(range);
return EditorSelection.range(range.anchor, head.head, head.goalColumn, head.bidiLevel || void 0);
});
if (selection.eq(view.state.selection)) return false;
view.dispatch(setSel(view.state, selection));
return true;
}
function selectByChar(view, forward) {
return extendSel(view, range => view.moveByChar(range, forward));
}
/**
Move the selection head one character to the left, while leaving
the anchor in place.
*/
function selectByGroup(view, forward) {
return extendSel(view, range => view.moveByGroup(range, forward));
}
/**
Move the selection head one [group](https://codemirror.net/6/docs/ref/#commands.cursorGroupLeft) to
the left.
*/
function selectByLine(view, forward) {
return extendSel(view, range => view.moveVertically(range, forward));
}
/**
Move the selection head one line up.
*/
function selectByPage(view, forward) {
return extendSel(view, range => view.moveVertically(range, forward, pageInfo(view).height));
}
/**
Move the selection head one page up.
*/
function deleteBy(target, by) {
if (target.state.readOnly) return false;
let event = "delete.selection",
{
state
} = target;
let changes = state.changeByRange(range => {
let {
from,
to
} = range;
if (from == to) {
let towards = by(range);
if (towards < from) {
event = "delete.backward";
towards = skipAtomic(target, towards, false);
} else if (towards > from) {
event = "delete.forward";
towards = skipAtomic(target, towards, true);
}
from = Math.min(from, towards);
to = Math.max(to, towards);
} else {
from = skipAtomic(target, from, false);
to = skipAtomic(target, to, true);
}
return from == to ? {
range
} : {
changes: {
from,
to
},
range: EditorSelection.cursor(from, from < range.head ? -1 : 1)
};
});
if (changes.changes.empty) return false;
target.dispatch(state.update(changes, {
scrollIntoView: true,
userEvent: event,
effects: event == "delete.selection" ? EditorView.announce.of(state.phrase("Selection deleted")) : void 0
}));
return true;
}
function skipAtomic(target, pos, forward) {
if (target instanceof EditorView) for (let ranges of target.state.facet(EditorView.atomicRanges).map(f => f(target))) ranges.between(pos, pos, (from, to) => {
if (from < pos && to > pos) pos = forward ? to : from;
});
return pos;
}
function selectedLineBlocks(state) {
let blocks = [],
upto = -1;
for (let range of state.selection.ranges) {
let startLine = state.doc.lineAt(range.from),
endLine = state.doc.lineAt(range.to);
if (!range.empty && range.to == endLine.from) endLine = state.doc.lineAt(range.to - 1);
if (upto >= startLine.number) {
let prev = blocks[blocks.length - 1];
prev.to = endLine.to;
prev.ranges.push(range);
} else blocks.push({
from: startLine.from,
to: endLine.to,
ranges: [range]
});
upto = endLine.number + 1;
}
return blocks;
}
function moveLine(state, dispatch, forward) {
if (state.readOnly) return false;
let changes = [],
ranges = [];
for (let block of selectedLineBlocks(state)) {
if (forward ? block.to == state.doc.length : block.from == 0) continue;
let nextLine = state.doc.lineAt(forward ? block.to + 1 : block.from - 1);
let size = nextLine.length + 1;
if (forward) {
changes.push({
from: block.to,
to: nextLine.to
}, {
from: block.from,
insert: nextLine.text + state.lineBreak
});
for (let r of block.ranges) ranges.push(EditorSelection.range(Math.min(state.doc.length, r.anchor + size), Math.min(state.doc.length, r.head + size)));
} else {
changes.push({
from: nextLine.from,
to: block.from
}, {
from: block.to,
insert: state.lineBreak + nextLine.text
});
for (let r of block.ranges) ranges.push(EditorSelection.range(r.anchor - size, r.head - size));
}
}
if (!changes.length) return false;
dispatch(state.update({
changes,
scrollIntoView: true,
selection: EditorSelection.create(ranges, state.selection.mainIndex),
userEvent: "move.line"
}));
return true;
}
/**
Move the selected lines up one line.
*/
function copyLine(state, dispatch, forward) {
if (state.readOnly) return false;
let changes = [];
for (let block of selectedLineBlocks(state)) if (forward) changes.push({
from: block.from,
insert: state.doc.slice(block.from, block.to) + state.lineBreak
});else changes.push({
from: block.to,
insert: state.lineBreak + state.doc.slice(block.from, block.to)
});
dispatch(state.update({
changes,
scrollIntoView: true,
userEvent: "input.copyline"
}));
return true;
}
/**
Create a copy of the selected lines. Keep the selection in the top copy.
*/
function isBetweenBrackets(state, pos) {
if (/\(\)|\[\]|\{\}/.test(state.sliceDoc(pos - 1, pos + 1))) return {
from: pos,
to: pos
};
let context = syntaxTree$1(state).resolveInner(pos);
let before = context.childBefore(pos),
after = context.childAfter(pos),
closedBy;
if (before && after && before.to <= pos && after.from >= pos && (closedBy = before.type.prop(NodeProp.closedBy)) && closedBy.indexOf(after.name) > -1 && state.doc.lineAt(before.to).from == state.doc.lineAt(after.from).from && !/\S/.test(state.sliceDoc(before.to, after.from))) return {
from: before.to,
to: after.from
};
return null;
}
/**
Replace the selection with a newline and indent the newly created
line(s). If the current line consists only of whitespace, this
will also delete that whitespace. When the cursor is between
matching brackets, an additional newline will be inserted after
the cursor.
*/
function newlineAndIndent(atEof) {
return ({
state,
dispatch
}) => {
if (state.readOnly) return false;
let changes = state.changeByRange(range => {
let {
from,
to
} = range,
line = state.doc.lineAt(from);
let explode = !atEof && from == to && isBetweenBrackets(state, from);
if (atEof) from = to = (to <= line.to ? line : state.doc.lineAt(to)).to;
let cx = new IndentContext(state, {
simulateBreak: from,
simulateDoubleBreak: !!explode
});
let indent = getIndentation(cx, from);
if (indent == null) indent = countColumn$1(/^\s*/.exec(state.doc.lineAt(from).text)[0], state.tabSize);
while (to < line.to && /\s/.test(line.text[to - line.from])) to++;
if (explode) ({
from,
to
} = explode);else if (from > line.from && from < line.from + 100 && !/\S/.test(line.text.slice(0, from))) from = line.from;
let insert$2 = ["", indentString(state, indent)];
if (explode) insert$2.push(indentString(state, cx.lineIndent(line.from, -1)));
return {
changes: {
from,
to,
insert: Text.of(insert$2)
},
range: EditorSelection.cursor(from + 1 + insert$2[1].length)
};
});
dispatch(state.update(changes, {
scrollIntoView: true,
userEvent: "input"
}));
return true;
};
}
function changeBySelectedLine(state, f) {
let atLine = -1;
return state.changeByRange(range => {
let changes = [];
for (let pos = range.from; pos <= range.to;) {
let line = state.doc.lineAt(pos);
if (line.number > atLine && (range.empty || range.to > line.from)) {
f(line, changes, range);
atLine = line.number;
}
pos = line.to + 1;
}
let changeSet = state.changes(changes);
return {
changes,
range: EditorSelection.range(changeSet.mapPos(range.anchor, 1), changeSet.mapPos(range.head, 1))
};
});
}
/**
Add a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation to all selected
lines.
*/
function toSet(chars) {
let flat = Object.keys(chars).join("");
let words = /\w/.test(flat);
if (words) flat = flat.replace(/\w/g, "");
return `[${words ? "\\w" : ""}${flat.replace(/[^\w\s]/g, "\\$&")}]`;
}
function prefixMatch$1(options) {
let first = Object.create(null),
rest = Object.create(null);
for (let {
label
} of options) {
first[label[0]] = true;
for (let i$1 = 1; i$1 < label.length; i$1++) rest[label[i$1]] = true;
}
let source = toSet(first) + toSet(rest) + "*$";
return [/* @__PURE__ */new RegExp("^" + source), new RegExp(source)];
}
/**
Given a a fixed array of options, return an autocompleter that
completes them.
*/
function completeFromList(list) {
let options = list.map(o => typeof o == "string" ? {
label: o
} : o);
let [validFor, match] = options.every(o => /^\w+$/.test(o.label)) ? [/\w*$/, /\w+$/] : prefixMatch$1(options);
return context => {
let token = context.matchBefore(match);
return token || context.explicit ? {
from: token ? token.from : context.pos,
options,
validFor
} : null;
};
}
/**
Wrap the given completion source so that it will only fire when the
cursor is in a syntax node with one of the given names.
*/
function ifIn(nodes, source) {
return context => {
for (let pos = syntaxTree$1(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {
if (nodes.indexOf(pos.name) > -1) return source(context);
if (pos.type.isTop) break;
}
return null;
};
}
/**
Wrap the given completion source so that it will not fire when the
cursor is in a syntax node with one of the given names.
*/
function ifNotIn(nodes, source) {
return context => {
for (let pos = syntaxTree$1(context.state).resolveInner(context.pos, -1); pos; pos = pos.parent) {
if (nodes.indexOf(pos.name) > -1) return null;
if (pos.type.isTop) break;
}
return source(context);
};
}
function cur(state) {
return state.selection.main.from;
}
function ensureAnchor(expr, start) {
var _a$2;
let {
source
} = expr;
let addStart = start && source[0] != "^",
addEnd = source[source.length - 1] != "$";
if (!addStart && !addEnd) return expr;
return new RegExp(`${addStart ? "^" : ""}(?:${source})${addEnd ? "$" : ""}`, (_a$2 = expr.flags) !== null && _a$2 !== void 0 ? _a$2 : expr.ignoreCase ? "i" : "");
}
/**
This annotation is added to transactions that are produced by
picking a completion.
*/
/**
Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
function insertCompletionText(state, text, from, to) {
let {
main
} = state.selection,
fromOff = from - main.from,
toOff = to - main.from;
return Object.assign(Object.assign({}, state.changeByRange(range => {
if (range != main && from != to && state.sliceDoc(range.from + fromOff, range.from + toOff) != state.sliceDoc(from, to)) return {
range
};
return {
changes: {
from: range.from + fromOff,
to: to == main.from ? range.to : range.from + toOff,
insert: text
},
range: EditorSelection.cursor(range.from + fromOff + text.length)
};
})), {
scrollIntoView: true,
userEvent: "input.complete"
});
}
function asSource(source) {
if (!Array.isArray(source)) return source;
let known = SourceCache.get(source);
if (!known) SourceCache.set(source, known = completeFromList(source));
return known;
}
function joinClass(a, b) {
return a ? b ? a + " " + b : a : b;
}
function defaultPositionInfo(view, list, option, info, space$1, tooltip) {
let rtl = view.textDirection == Direction$1.RTL,
left = rtl,
narrow = false;
let side = "top",
offset,
maxWidth;
let spaceLeft = list.left - space$1.left,
spaceRight = space$1.right - list.right;
let infoWidth = info.right - info.left,
infoHeight = info.bottom - info.top;
if (left && spaceLeft < Math.min(infoWidth, spaceRight)) left = false;else if (!left && spaceRight < Math.min(infoWidth, spaceLeft)) left = true;
if (infoWidth <= (left ? spaceLeft : spaceRight)) {
offset = Math.max(space$1.top, Math.min(option.top, space$1.bottom - infoHeight)) - list.top;
maxWidth = Math.min(400, left ? spaceLeft : spaceRight);
} else {
narrow = true;
maxWidth = Math.min(400, (rtl ? list.right : space$1.right - list.left) - 30);
let spaceBelow = space$1.bottom - list.bottom;
if (spaceBelow >= infoHeight || spaceBelow > list.top) offset = option.bottom - list.top;else {
side = "bottom";
offset = list.bottom - option.top;
}
}
let scaleY = (list.bottom - list.top) / tooltip.offsetHeight;
let scaleX = (list.right - list.left) / tooltip.offsetWidth;
return {
style: `${side}: ${offset / scaleY}px; max-width: ${maxWidth / scaleX}px`,
class: "cm-completionInfo-" + (narrow ? rtl ? "left-narrow" : "right-narrow" : left ? "left" : "right")
};
}
function optionContent(config$1) {
let content$1 = config$1.addToOptions.slice();
if (config$1.icons) content$1.push({
render(completion) {
let icon$2 = document.createElement("div");
icon$2.classList.add("cm-completionIcon");
if (completion.type) icon$2.classList.add(...completion.type.split(/\s+/g).map(cls => "cm-completionIcon-" + cls));
icon$2.setAttribute("aria-hidden", "true");
return icon$2;
},
position: 20
});
content$1.push({
render(completion, _s, _v, match) {
let labelElt = document.createElement("span");
labelElt.className = "cm-completionLabel";
let label = completion.displayLabel || completion.label,
off = 0;
for (let j = 0; j < match.length;) {
let from = match[j++],
to = match[j++];
if (from > off) labelElt.appendChild(document.createTextNode(label.slice(off, from)));
let span = labelElt.appendChild(document.createElement("span"));
span.appendChild(document.createTextNode(label.slice(from, to)));
span.className = "cm-completionMatchedText";
off = to;
}
if (off < label.length) labelElt.appendChild(document.createTextNode(label.slice(off)));
return labelElt;
},
position: 50
}, {
render(completion) {
if (!completion.detail) return null;
let detailElt = document.createElement("span");
detailElt.className = "cm-completionDetail";
detailElt.textContent = completion.detail;
return detailElt;
},
position: 80
});
return content$1.sort((a, b) => a.position - b.position).map(a => a.render);
}
function rangeAroundSelected(total, selected, max) {
if (total <= max) return {
from: 0,
to: total
};
if (selected < 0) selected = 0;
if (selected <= total >> 1) {
let off$1 = Math.floor(selected / max);
return {
from: off$1 * max,
to: (off$1 + 1) * max
};
}
let off = Math.floor((total - selected) / max);
return {
from: total - (off + 1) * max,
to: total - off * max
};
}
function completionTooltip(stateField, applyCompletion$2) {
return view => new CompletionTooltip(view, stateField, applyCompletion$2);
}
function scrollIntoView$1(container$1, element) {
let parent = container$1.getBoundingClientRect();
let self = element.getBoundingClientRect();
let scaleY = parent.height / container$1.offsetHeight;
if (self.top < parent.top) container$1.scrollTop -= (parent.top - self.top) / scaleY;else if (self.bottom > parent.bottom) container$1.scrollTop += (self.bottom - parent.bottom) / scaleY;
}
function score(option) {
return (option.boost || 0) * 100 + (option.apply ? 10 : 0) + (option.info ? 5 : 0) + (option.type ? 1 : 0);
}
function sortOptions(active, state) {
let options = [];
let sections = null;
let addOption = option => {
options.push(option);
let {
section
} = option.completion;
if (section) {
if (!sections) sections = [];
let name$1 = typeof section == "string" ? section : section.name;
if (!sections.some(s => s.name == name$1)) sections.push(typeof section == "string" ? {
name: name$1
} : section);
}
};
let conf = state.facet(completionConfig);
for (let a of active) if (a.hasResult()) {
let getMatch = a.result.getMatch;
if (a.result.filter === false) for (let option of a.result.options) addOption(new Option(option, a.source, getMatch ? getMatch(option) : [], 1e9 - options.length));else {
let pattern = state.sliceDoc(a.from, a.to),
match;
let matcher = conf.filterStrict ? new StrictMatcher(pattern) : new FuzzyMatcher(pattern);
for (let option of a.result.options) if (match = matcher.match(option.label)) {
let matched = !option.displayLabel ? match.matched : getMatch ? getMatch(option, match.matched) : [];
addOption(new Option(option, a.source, matched, match.score + (option.boost || 0)));
}
}
}
if (sections) {
let sectionOrder = Object.create(null),
pos = 0;
let cmp = (a, b) => {
var _a$2, _b;
return ((_a$2 = a.rank) !== null && _a$2 !== void 0 ? _a$2 : 1e9) - ((_b = b.rank) !== null && _b !== void 0 ? _b : 1e9) || (a.name < b.name ? -1 : 1);
};
for (let s of sections.sort(cmp)) {
pos -= 1e5;
sectionOrder[s.name] = pos;
}
for (let option of options) {
let {
section
} = option.completion;
if (section) option.score += sectionOrder[typeof section == "string" ? section : section.name];
}
}
let result = [],
prev = null;
let compare$2 = conf.compareCompletions;
for (let opt of options.sort((a, b) => b.score - a.score || compare$2(a.completion, b.completion))) {
let cur$1 = opt.completion;
if (!prev || prev.label != cur$1.label || prev.detail != cur$1.detail || prev.type != null && cur$1.type != null && prev.type != cur$1.type || prev.apply != cur$1.apply || prev.boost != cur$1.boost) result.push(opt);else if (score(opt.completion) > score(prev)) result[result.length - 1] = opt;
prev = opt.completion;
}
return result;
}
function sameResults(a, b) {
if (a == b) return true;
for (let iA = 0, iB = 0;;) {
while (iA < a.length && !a[iA].hasResult) iA++;
while (iB < b.length && !b[iB].hasResult) iB++;
let endA = iA == a.length,
endB = iB == b.length;
if (endA || endB) return endA == endB;
if (a[iA++].result != b[iB++].result) return false;
}
}
function makeAttrs(id$1, selected) {
let result = {
"aria-autocomplete": "list",
"aria-haspopup": "listbox",
"aria-controls": id$1
};
if (selected > -1) result["aria-activedescendant"] = id$1 + "-" + selected;
return result;
}
function getUserEvent(tr, conf) {
if (tr.isUserEvent("input.complete")) {
let completion = tr.annotation(pickedCompletion);
if (completion && conf.activateOnCompletion(completion)) return "input";
}
return tr.isUserEvent("input.type") ? "input" : tr.isUserEvent("delete.backward") ? "delete" : null;
}
function checkValid(validFor, state, from, to) {
if (!validFor) return false;
let text = state.sliceDoc(from, to);
return typeof validFor == "function" ? validFor(text, from, to, state) : ensureAnchor(validFor, true).test(text);
}
function applyCompletion$1(view, option) {
const apply = option.completion.apply || option.completion.label;
let result = view.state.field(completionState).active.find(a => a.source == option.source);
if (!(result instanceof ActiveResult)) return false;
if (typeof apply == "string") view.dispatch(Object.assign(Object.assign({}, insertCompletionText(view.state, apply, result.from, result.to)), {
annotations: pickedCompletion.of(option.completion)
}));else apply(view, option.completion, result.from, result.to);
return true;
}
/**
Returns a command that moves the completion selection forward or
backward by the given amount.
*/
function moveCompletionSelection(forward, by = "option") {
return view => {
let cState = view.state.field(completionState, false);
if (!cState || !cState.open || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) return false;
let step = 1,
tooltip;
if (by == "page" && (tooltip = getTooltip(view, cState.open.tooltip))) step = Math.max(2, Math.floor(tooltip.dom.offsetHeight / tooltip.dom.querySelector("li").offsetHeight) - 1);
let {
length
} = cState.open.options;
let selected = cState.open.selected > -1 ? cState.open.selected + step * (forward ? 1 : -1) : forward ? 0 : length - 1;
if (selected < 0) selected = by == "page" ? 0 : length - 1;else if (selected >= length) selected = by == "page" ? length - 1 : 0;
view.dispatch({
effects: setSelectedEffect.of(selected)
});
return true;
};
}
/**
Accept the current completion.
*/
function fieldSelection(ranges, field) {
return EditorSelection.create(ranges.filter(r => r.field == field).map(r => EditorSelection.range(r.from, r.to)));
}
/**
Convert a snippet template to a function that can
[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
using syntax like this:
"for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
Each `${}` placeholder (you may also use `#{}`) indicates a field
that the user can fill in. Its name, if any, will be the default
content for the field.
When the snippet is activated by calling the returned function,
the code is inserted at the given position. Newlines in the
template are indented by the indentation of the start line, plus
one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
the newline.
On activation, (all instances of) the first field are selected.
The user can move between fields with Tab and Shift-Tab as long as
the fields are active. Moving to the last field or moving the
cursor out of the current field deactivates the fields.
The order of fields defaults to textual order, but you can add
numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
a custom order.
To include a literal `{` or `}` in your template, put a backslash
in front of it. This will be removed and the brace will not be
interpreted as indicating a placeholder.
*/
function snippet(template$1) {
let snippet$1 = Snippet.parse(template$1);
return (editor, completion, from, to) => {
let {
text,
ranges
} = snippet$1.instantiate(editor.state, from);
let spec = {
changes: {
from,
to,
insert: Text.of(text)
},
scrollIntoView: true,
annotations: completion ? [pickedCompletion.of(completion), Transaction.userEvent.of("input.complete")] : void 0
};
if (ranges.length) spec.selection = fieldSelection(ranges, 0);
if (ranges.some(r => r.field > 0)) {
let active = new ActiveSnippet(ranges, 0);
let effects = spec.effects = [setActive.of(active)];
if (editor.state.field(snippetState, false) === void 0) effects.push(StateEffect$1.appendConfig.of([snippetState, addSnippetKeymap, snippetPointerHandler, baseTheme$3]));
}
editor.dispatch(editor.state.update(spec));
};
}
function moveField(dir) {
return ({
state,
dispatch
}) => {
let active = state.field(snippetState, false);
if (!active || dir < 0 && active.active == 0) return false;
let next = active.active + dir,
last = dir > 0 && !active.ranges.some(r => r.field == next + dir);
dispatch(state.update({
selection: fieldSelection(active.ranges, next),
effects: setActive.of(last ? null : new ActiveSnippet(active.ranges, next)),
scrollIntoView: true
}));
return true;
};
}
/**
A command that clears the active snippet, if any.
*/
/**
Create a completion from a snippet. Returns an object with the
properties from `completion`, plus an `apply` function that
applies the snippet.
*/
function snippetCompletion(template$1, completion) {
return Object.assign(Object.assign({}, completion), {
apply: snippet(template$1)
});
}
/**
Extension to enable bracket-closing behavior. When a closeable
bracket is typed, its closing bracket is immediately inserted
after the cursor. When closing a bracket directly in front of a
closing bracket inserted by the extension, the cursor moves over
that bracket.
*/
function closeBrackets() {
return [inputHandler$1, bracketState];
}
function closing(ch) {
for (let i$1 = 0; i$1 < 8; i$1 += 2) if (definedClosing.charCodeAt(i$1) == ch) return definedClosing.charAt(i$1 + 1);
return fromCodePoint(ch < 128 ? ch : ch + 1);
}
function config(state, pos) {
return state.languageDataAt("closeBrackets", pos)[0] || defaults;
}
/**
Implements the extension's behavior on text insertion. If the
given string counts as a bracket in the language around the
selection, and replacing the selection with it requires custom
behavior (inserting a closing version or skipping past a
previously-closed bracket), this function returns a transaction
representing that custom behavior. (You only need this if you want
to programmatically insert brackets—the
[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
take care of running this for user input.)
*/
function insertBracket(state, bracket$1) {
let conf = config(state, state.selection.main.head);
let tokens = conf.brackets || defaults.brackets;
for (let tok of tokens) {
let closed = closing(codePointAt(tok, 0));
if (bracket$1 == tok) return closed == tok ? handleSame(state, tok, tokens.indexOf(tok + tok + tok) > -1, conf) : handleOpen(state, tok, closed, conf.before || defaults.before);
if (bracket$1 == closed && closedBracketAt(state, state.selection.main.from)) return handleClose(state, tok, closed);
}
return null;
}
function closedBracketAt(state, pos) {
let found = false;
state.field(bracketState).between(0, state.doc.length, from => {
if (from == pos) found = true;
});
return found;
}
function nextChar(doc$2, pos) {
let next = doc$2.sliceString(pos, pos + 2);
return next.slice(0, codePointSize(codePointAt(next, 0)));
}
function prevChar(doc$2, pos) {
let prev = doc$2.sliceString(pos - 2, pos);
return codePointSize(codePointAt(prev, 0)) == prev.length ? prev : prev.slice(1);
}
function handleOpen(state, open, close, closeBefore) {
let dont = null,
changes = state.changeByRange(range => {
if (!range.empty) return {
changes: [{
insert: open,
from: range.from
}, {
insert: close,
from: range.to
}],
effects: closeBracketEffect.of(range.to + open.length),
range: EditorSelection.range(range.anchor + open.length, range.head + open.length)
};
let next = nextChar(state.doc, range.head);
if (!next || /\s/.test(next) || closeBefore.indexOf(next) > -1) return {
changes: {
insert: open + close,
from: range.head
},
effects: closeBracketEffect.of(range.head + open.length),
range: EditorSelection.cursor(range.head + open.length)
};
return {
range: dont = range
};
});
return dont ? null : state.update(changes, {
scrollIntoView: true,
userEvent: "input.type"
});
}
function handleClose(state, _open, close) {
let dont = null,
changes = state.changeByRange(range => {
if (range.empty && nextChar(state.doc, range.head) == close) return {
changes: {
from: range.head,
to: range.head + close.length,
insert: close
},
range: EditorSelection.cursor(range.head + close.length)
};
return dont = {
range
};
});
return dont ? null : state.update(changes, {
scrollIntoView: true,
userEvent: "input.type"
});
}
function handleSame(state, token, allowTriple, config$1) {
let stringPrefixes = config$1.stringPrefixes || defaults.stringPrefixes;
let dont = null,
changes = state.changeByRange(range => {
if (!range.empty) return {
changes: [{
insert: token,
from: range.from
}, {
insert: token,
from: range.to
}],
effects: closeBracketEffect.of(range.to + token.length),
range: EditorSelection.range(range.anchor + token.length, range.head + token.length)
};
let pos = range.head,
next = nextChar(state.doc, pos),
start;
if (next == token) {
if (nodeStart(state, pos)) return {
changes: {
insert: token + token,
from: pos
},
effects: closeBracketEffect.of(pos + token.length),
range: EditorSelection.cursor(pos + token.length)
};else if (closedBracketAt(state, pos)) {
let content$1 = allowTriple && state.sliceDoc(pos, pos + token.length * 3) == token + token + token ? token + token + token : token;
return {
changes: {
from: pos,
to: pos + content$1.length,
insert: content$1
},
range: EditorSelection.cursor(pos + content$1.length)
};
}
} else if (allowTriple && state.sliceDoc(pos - 2 * token.length, pos) == token + token && (start = canStartStringAt(state, pos - 2 * token.length, stringPrefixes)) > -1 && nodeStart(state, start)) return {
changes: {
insert: token + token + token + token,
from: pos
},
effects: closeBracketEffect.of(pos + token.length),
range: EditorSelection.cursor(pos + token.length)
};else if (state.charCategorizer(pos)(next) != CharCategory.Word) {
if (canStartStringAt(state, pos, stringPrefixes) > -1 && !probablyInString(state, pos, token, stringPrefixes)) return {
changes: {
insert: token + token,
from: pos
},
effects: closeBracketEffect.of(pos + token.length),
range: EditorSelection.cursor(pos + token.length)
};
}
return {
range: dont = range
};
});
return dont ? null : state.update(changes, {
scrollIntoView: true,
userEvent: "input.type"
});
}
function nodeStart(state, pos) {
let tree = syntaxTree$1(state).resolveInner(pos + 1);
return tree.parent && tree.from == pos;
}
function probablyInString(state, pos, quoteToken, prefixes) {
let node = syntaxTree$1(state).resolveInner(pos, -1);
let maxPrefix = prefixes.reduce((m, p) => Math.max(m, p.length), 0);
for (let i$1 = 0; i$1 < 5; i$1++) {
let start = state.sliceDoc(node.from, Math.min(node.to, node.from + quoteToken.length + maxPrefix));
let quotePos = start.indexOf(quoteToken);
if (!quotePos || quotePos > -1 && prefixes.indexOf(start.slice(0, quotePos)) > -1) {
let first = node.firstChild;
while (first && first.from == node.from && first.to - first.from > quoteToken.length + quotePos) {
if (state.sliceDoc(first.to - quoteToken.length, first.to) == quoteToken) return false;
first = first.firstChild;
}
return true;
}
let parent = node.to == pos && node.parent;
if (!parent) break;
node = parent;
}
return false;
}
function canStartStringAt(state, pos, prefixes) {
let charCat = state.charCategorizer(pos);
if (charCat(state.sliceDoc(pos - 1, pos)) != CharCategory.Word) return pos;
for (let prefix of prefixes) {
let start = pos - prefix.length;
if (state.sliceDoc(start, pos) == prefix && charCat(state.sliceDoc(start - 1, start)) != CharCategory.Word) return start;
}
return -1;
}
/**
Returns an extension that enables autocompletion.
*/
function autocompletion(config$1 = {}) {
return [commitCharacters, completionState, completionConfig.of(config$1), completionPlugin, completionKeymapExt, baseTheme$3];
}
/**
Basic keybindings for autocompletion.
- Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
- Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
- ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
- ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
- PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
- PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
- Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
*/
/**
Get the current completion status. When completions are available,
this will return `"active"`. When completions are pending (in the
process of being queried), this returns `"pending"`. Otherwise, it
returns `null`.
*/
function completionStatus(state) {
let cState = state.field(completionState, false);
return cState && cState.active.some(a => a.state == 1) ? "pending" : cState && cState.active.some(a => a.state != 0) ? "active" : null;
}
//#endregion
//#region ../../../node_modules/.pnpm/@lezer+lr@1.4.0/node_modules/@lezer/lr/dist/index.js
function decodeArray(input, Type = Uint16Array) {
if (typeof input != "string") return input;
let array = null;
for (let pos = 0, out = 0; pos < input.length;) {
let value = 0;
for (;;) {
let next = input.charCodeAt(pos++),
stop = false;
if (next == 126) {
value = 65535;
break;
}
if (next >= 92) next--;
if (next >= 34) next--;
let digit = next - 32;
if (digit >= 46) {
digit -= 46;
stop = true;
}
value += digit;
if (stop) break;
value *= 46;
}
if (array) array[out++] = value;else array = new Type(value);
}
return array;
}
function readToken(data, input, stack, group, precTable, precOffset) {
let state = 0,
groupMask = 1 << group,
{
dialect
} = stack.p.parser;
scan: for (;;) {
if ((groupMask & data[state]) == 0) break;
let accEnd = data[state + 1];
for (let i$1 = state + 3; i$1 < accEnd; i$1 += 2) if ((data[i$1 + 1] & groupMask) > 0) {
let term = data[i$1];
if (dialect.allows(term) && (input.token.value == -1 || input.token.value == term || overrides(term, input.token.value, precTable, precOffset))) {
input.acceptToken(term);
break;
}
}
let next = input.next,
low = 0,
high = data[state + 2];
if (input.next < 0 && high > low && data[accEnd + high * 3 - 3] == 65535) {
state = data[accEnd + high * 3 - 1];
continue scan;
}
for (; low < high;) {
let mid = low + high >> 1;
let index = accEnd + mid + (mid << 1);
let from = data[index],
to = data[index + 1] || 65536;
if (next < from) high = mid;else if (next >= to) low = mid + 1;else {
state = data[index + 2];
input.advance();
continue scan;
}
}
break;
}
}
function findOffset(data, start, term) {
for (let i$1 = start, next; (next = data[i$1]) != 65535; i$1++) if (next == term) return i$1 - start;
return -1;
}
function overrides(token, prev, tableData, tableOffset) {
let iPrev = findOffset(tableData, tableOffset, prev);
return iPrev < 0 || findOffset(tableData, tableOffset, token) < iPrev;
}
function cutAt(tree, pos, side) {
let cursor = tree.cursor(IterMode.IncludeAnonymous);
cursor.moveTo(pos);
for (;;) if (!(side < 0 ? cursor.childBefore(pos) : cursor.childAfter(pos))) for (;;) {
if ((side < 0 ? cursor.to < pos : cursor.from > pos) && !cursor.type.isError) return side < 0 ? Math.max(0, Math.min(cursor.to - 1, pos - 25)) : Math.min(tree.length, Math.max(cursor.from + 1, pos + 25));
if (side < 0 ? cursor.prevSibling() : cursor.nextSibling()) break;
if (!cursor.parent()) return side < 0 ? 0 : tree.length;
}
}
function pushStackDedup(stack, newStacks) {
for (let i$1 = 0; i$1 < newStacks.length; i$1++) {
let other = newStacks[i$1];
if (other.pos == stack.pos && other.sameState(stack)) {
if (newStacks[i$1].score < stack.score) newStacks[i$1] = stack;
return;
}
}
newStacks.push(stack);
}
function pair(data, off) {
return data[off] | data[off + 1] << 16;
}
function findFinished(stacks) {
let best = null;
for (let stack of stacks) {
let stopped = stack.p.stoppedAt;
if ((stack.pos == stack.p.stream.end || stopped != null && stack.pos > stopped) && stack.p.parser.stateFlag(stack.state, 2) && (!best || best.score < stack.score)) best = stack;
}
return best;
}
function getSpecializer(spec) {
if (spec.external) {
let mask = spec.extend ? 1 : 0;
return (value, stack) => spec.external(value, stack) << 1 | mask;
}
return spec.get;
}
//#endregion
//#region ../../../node_modules/.pnpm/@lezer+javascript@1.0.2/node_modules/@lezer/javascript/dist/index.es.js
function defID(type) {
return (node, def) => {
let id$1 = node.node.getChild("VariableDefinition");
if (id$1) def(id$1, type);
return true;
};
}
function getScope(doc$2, node) {
let cached = cache.get(node);
if (cached) return cached;
let completions = [],
top$1 = true;
function def(node$1, type) {
let name$1 = doc$2.sliceString(node$1.from, node$1.to);
completions.push({
label: name$1,
type
});
}
node.cursor(IterMode.IncludeAnonymous).iterate(node$1 => {
if (top$1) top$1 = false;else if (node$1.name) {
let gather = gatherCompletions[node$1.name];
if (gather && gather(node$1, def) || ScopeNodes.has(node$1.name)) return false;
} else if (node$1.to - node$1.from > 8192) {
for (let c of getScope(doc$2, node$1.node)) completions.push(c);
return false;
}
});
cache.set(node, completions);
return completions;
}
/**
Completion source that looks up locally defined names in
JavaScript code.
*/
function localCompletionSource(context) {
let inner = syntaxTree$1(context.state).resolveInner(context.pos, -1);
if (dontComplete.indexOf(inner.name) > -1) return null;
let isWord = inner.name == "VariableName" || inner.to - inner.from < 20 && Identifier.test(context.state.sliceDoc(inner.from, inner.to));
if (!isWord && !context.explicit) return null;
let options = [];
for (let pos = inner; pos; pos = pos.parent) if (ScopeNodes.has(pos.name)) options = options.concat(getScope(context.state.doc, pos));
return {
options,
from: isWord ? inner.from : context.pos,
validFor: Identifier
};
}
/**
A language provider based on the [Lezer JavaScript
parser](https://github.com/lezer-parser/javascript), extended with
highlighting and indentation information.
*/
/**
JavaScript support. Includes [snippet](https://codemirror.net/6/docs/ref/#lang-javascript.snippets)
and local variable completion.
*/
function javascript(config$1 = {}) {
let lang = config$1.jsx ? config$1.typescript ? tsxLanguage : jsxLanguage : config$1.typescript ? typescriptLanguage : javascriptLanguage;
let completions = config$1.typescript ? typescriptSnippets.concat(typescriptKeywords) : snippets.concat(keywords);
return new LanguageSupport(lang, [javascriptLanguage.data.of({
autocomplete: ifNotIn(dontComplete, completeFromList(completions))
}), javascriptLanguage.data.of({
autocomplete: localCompletionSource
}), config$1.jsx ? autoCloseTags : []]);
}
function findOpenTag(node) {
for (;;) {
if (node.name == "JSXOpenTag" || node.name == "JSXSelfClosingTag" || node.name == "JSXFragmentTag") return node;
if (node.name == "JSXEscape" || !node.parent) return null;
node = node.parent;
}
}
function elementName(doc$2, tree, max = doc$2.length) {
for (let ch = tree === null || tree === void 0 ? void 0 : tree.firstChild; ch; ch = ch.nextSibling) if (ch.name == "JSXIdentifier" || ch.name == "JSXBuiltin" || ch.name == "JSXNamespacedName" || ch.name == "JSXMemberExpression") return doc$2.sliceString(ch.from, Math.min(ch.to, max));
return "";
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/utils.ts
/**
* Split user input into base (to resolve) and tail (to filter).
*/
function splitBaseTail(syntaxTree$2, userInput) {
const lastNode = syntaxTree$2.resolveInner(userInput.length, -1);
switch (lastNode.type.name) {
case ".":
return [read(lastNode.parent, userInput).slice(0, -1), ""];
case "MemberExpression":
return [read(lastNode.parent, userInput), read(lastNode, userInput)];
case "PropertyName":
const tail = read(lastNode, userInput);
return [read(lastNode.parent, userInput).slice(0, -(tail.length + 1)), tail];
default:
return ["", ""];
}
}
function replaceSyntaxNode(source, node, replacement) {
return source.slice(0, node.from) + replacement + source.slice(node.to);
}
function isInputNodeCall(node, source) {
return node.name === "VariableName" && read(node, source) === "$" && node.parent?.name === "CallExpression";
}
function isInputVariable(node, source) {
return node?.name === "VariableName" && read(node, source) === "$input";
}
function isItemProperty(node, source) {
return node?.parent?.name === "MemberExpression" && node.name === "PropertyName" && read(node, source) === "item";
}
function isItemMatchingCall(node, source) {
return node?.name === "CallExpression" && node.firstChild?.lastChild?.name === "PropertyName" && read(node.firstChild.lastChild, source) === "itemMatching";
}
function read(node, source) {
return node ? source.slice(node.from, node.to) : "";
}
/**
* Replace expressions that depend on pairedItem with the first item when possible
* $input.item.json.foo -> $input.first().json.foo
* $('Node').item.json.foo -> $('Node').item.json.foo
*/
function expressionWithFirstItem(syntaxTree$2, expression) {
let result = expression;
syntaxTree$2.cursor().iterate(({
node
}) => {
if (isInputVariable(node, expression)) {
if (isItemProperty(node.parent?.lastChild, expression)) result = replaceSyntaxNode(expression, node.parent.lastChild, "first()");else if (isItemMatchingCall(node.parent?.parent, expression)) result = replaceSyntaxNode(expression, node.parent.parent, "$input.first()");
}
if (isInputNodeCall(node, expression)) {
if (isItemProperty(node.parent?.parent?.lastChild, expression)) result = replaceSyntaxNode(expression, node.parent.parent.lastChild, "first()");else if (isItemMatchingCall(node.parent?.parent?.parent, expression)) result = replaceSyntaxNode(expression, node.parent.parent.parent, `${read(node.parent, expression)}.first()`);
}
});
return result;
}
function longestCommonPrefix(...strings) {
if (strings.length < 2) return "";
return strings.reduce((prefix, str) => {
while (!str.startsWith(prefix)) {
prefix = prefix.slice(0, -1);
if (prefix === "") return "";
}
return prefix;
}, strings[0]);
}
function receivesNoBinaryData(contextNodeName) {
try {
return resolveAutocompleteExpression("={{ $binary }}", contextNodeName)?.data === void 0;
} catch {
return true;
}
}
function hasNoParams(toResolve, contextNodeName) {
let params;
try {
params = resolveAutocompleteExpression(`={{ ${toResolve}.params }}`, contextNodeName);
} catch {
return true;
}
if (!params) return true;
const paramKeys = Object.keys(params);
return paramKeys.length === 1 && isPseudoParam(paramKeys[0]);
}
function resolveAutocompleteExpression(expression, contextNodeName) {
const ndvStore = useNDVStore();
return resolveParameter(expression, {
...(contextNodeName === void 0 && ndvStore.isInputParentOfActiveNode ? {
targetItem: ndvStore.expressionTargetItem ?? void 0,
inputNodeName: ndvStore.ndvInputNodeName,
inputRunIndex: ndvStore.ndvInputRunIndex,
inputBranchIndex: ndvStore.ndvInputBranchIndex
} : {}),
contextNodeName
});
}
function autocompletableNodeNames(targetNodeParameterContext) {
const activeNode = targetNodeParameterContext === void 0 ? useNDVStore().activeNode : useWorkflowsStore().getNodeByName(targetNodeParameterContext.nodeName);
if (!activeNode) return [];
const activeNodeName = activeNode.name;
const nonMainChildren = useWorkflowsStore().workflowObject.getChildNodes(activeNodeName, "ALL_NON_MAIN");
if (nonMainChildren.length > 0) return nonMainChildren.map(getPreviousNodes).flat();
return getPreviousNodes(activeNodeName);
}
function getPreviousNodes(nodeName) {
return useWorkflowsStore().workflowObject.getParentNodesByDepth(nodeName).map(node => node.name).filter(name$1 => name$1 !== nodeName);
}
/**
* Finds the amount of common chars at the end of the source and the start of the target.
* Example: "hello world", "world peace" => 5 ("world" is the overlap)
*/
function findCommonBoundary(source, target) {
return [...source].reverse().map((_, i$1) => source.slice(-i$1 - 1)).find(end => target.startsWith(end))?.length ?? 0;
}
function getClosingChars(input) {
const match = input.match(/^['"\])]+/);
return match ? match[0] : "";
}
/**
* Remove excess parens from an option label when the cursor is already
* followed by parens, e.g. `$json.myStr.|()` -> `isNumeric` or `$(|)` -> `$("Node Name")|`
*/
function attempt(fn, onError) {
try {
return fn();
} catch (error) {
if (onError) return onError(error);
return null;
}
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/infoBoxRenderer.ts
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/dollar.completions.ts
/**
* Completions offered at the dollar position: `$|`
*/
function dollarCompletions(context) {
const word = context.matchBefore(/\$[^$]*/);
if (!word) return null;
if (word.from === word.to && !context.explicit) return null;
let options = dollarOptions(context).map(stripExcessParens(context));
const userInput = word.text;
if (userInput !== "$") options = options.filter(o => prefixMatch(o.label, userInput));
if (options.length === 0) return null;
return {
from: word.to - userInput.length,
options,
filter: false,
getMatch(completion) {
return [0, longestCommonPrefix(userInput, completion.label).length];
}
};
}
function dollarOptions(context) {
const SKIP = /* @__PURE__ */new Set();
let recommendedCompletions = [];
if (isInHttpNodePagination()) recommendedCompletions = [{
label: "$pageCount",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$pageCount",
returnType: "number",
docURL: "https://docs.n8n.io/code/builtin/http-node-variables/",
description: i18n.baseText("codeNodeEditor.completer.$pageCount")
})
}, {
label: "$response",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$response",
returnType: "HTTPResponse",
docURL: "https://docs.n8n.io/code/builtin/http-node-variables/",
description: i18n.baseText("codeNodeEditor.completer.$response")
})
}, {
label: "$request",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$request",
returnType: "Object",
docURL: "https://docs.n8n.io/code/builtin/http-node-variables/",
description: i18n.baseText("codeNodeEditor.completer.$request")
})
}];
if (isCredentialsModalOpen()) return useExternalSecretsStore().isEnterpriseExternalSecretsEnabled ? [{
label: "$vars",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$vars",
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.$vars")
})
}, {
label: "$secrets",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$secrets",
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.$secrets")
})
}] : [];
const targetNodeParameterContext = context.state.facet(TARGET_NODE_PARAMETER_FACET);
if (!hasActiveNode(targetNodeParameterContext)) return [];
if (receivesNoBinaryData(targetNodeParameterContext?.nodeName)) SKIP.add("$binary");
const previousNodesCompletions = autocompletableNodeNames(targetNodeParameterContext).map(nodeName => {
const label = `$('${escapeMappingString(nodeName)}')`;
return {
label,
info: createInfoBoxRenderer({
name: label,
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.$()", {
interpolate: {
nodeName
}
})
}),
section: PREVIOUS_NODES_SECTION
};
});
return recommendedCompletions.concat(ROOT_DOLLAR_COMPLETIONS).filter(({
label
}) => !SKIP.has(label)).concat(previousNodesCompletions).map(completion => ({
...completion,
apply: applyCompletion()
}));
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/blank.completions.ts
/**
* Completions offered at the blank position: `{{ | }}`
*/
function blankCompletions(context) {
const word = context.matchBefore(/\{\{\s/);
if (!word) return null;
if (word.from === word.to && !context.explicit) return null;
if (context.state.sliceDoc(context.pos, context.pos + 3) !== " }}") return null;
return {
from: word.to,
options: dollarOptions(context).map(stripExcessParens(context)),
filter: false
};
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/bracketAccess.completions.ts
/**
* Resolution-based completions offered at the start of bracket access notation.
*
* - `$json[|`
* - `$input.item.json[|`
* - `$json['field'][|`
* - `$json.myObj[|`
* - `$('Test').last().json.myArr[|`
* - `$input.first().json.myStr[|`
*/
function bracketAccessCompletions(context) {
const targetNodeParameterContext = context.state.facet(TARGET_NODE_PARAMETER_FACET);
const word = context.matchBefore(/\$[\S\s]*\[.*/);
if (!word) return null;
if (word.from === word.to && !context.explicit) return null;
if (["$input[", "$now[", "$today["].includes(word.text)) return null;
const base$1 = word.text.substring(0, word.text.lastIndexOf("["));
const tail = word.text.split("[").pop() ?? "";
let resolved;
try {
resolved = resolveAutocompleteExpression(`={{ ${base$1} }}`, targetNodeParameterContext?.nodeName);
} catch {
return null;
}
if (resolved === null || resolved === void 0 || typeof resolved !== "object") return null;
let options = bracketAccessOptions(resolved);
if (tail !== "") options = options.filter(o => prefixMatch(o.label, tail));
if (options.length === 0) return null;
return {
from: word.to - tail.length,
options,
filter: false,
getMatch(completion) {
return [0, longestCommonPrefix(tail, completion.label).length];
}
};
}
function bracketAccessOptions(resolved) {
const SKIP = new Set(["__ob__", "pairedItem"]);
return Object.keys(resolved).filter(key => !SKIP.has(key)).map(key => {
return {
label: !isNaN(parseInt(key)) ? `${key}]` : `'${escapeMappingString(key)}']`,
type: "keyword"
};
});
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/nativesAutocompleteDocs/luxon.instance.docs.ts
/**
* Resolution-based completions offered according to datatype.
*/
function datatypeCompletions(context) {
const targetNodeParameterContext = context.state.facet(TARGET_NODE_PARAMETER_FACET);
const word = context.matchBefore(DATATYPE_REGEX);
if (!word) return null;
if (word.from === word.to && !context.explicit) return null;
const syntaxTree$2 = javascriptLanguage.parser.parse(word.text);
const [base$1, tail] = splitBaseTail(syntaxTree$2, word.text);
let options = [];
const isCredential = isCredentialsModalOpen();
if (base$1 === "DateTime") options = luxonStaticOptions().map(stripExcessParens(context));else if (base$1 === "Object") options = objectGlobalOptions().map(stripExcessParens(context));else if (base$1 === "$vars") options = variablesOptions();else if (/\$secrets\./.test(base$1) && isCredential) options = secretOptions(base$1).map(stripExcessParens(context));else if (base$1 === "$secrets" && isCredential) options = secretProvidersOptions();else {
const resolved = attempt(() => resolveAutocompleteExpression(`={{ ${base$1} }}`, targetNodeParameterContext?.nodeName), error => {
if (!isPairedItemIntermediateNodesError(error)) return null;
return attempt(() => resolveAutocompleteExpression(`={{ ${expressionWithFirstItem(syntaxTree$2, base$1)} }}`, targetNodeParameterContext?.nodeName));
});
if (resolved === null) return null;
options = attempt(() => datatypeOptions({
resolved,
base: base$1,
tail
}).map(stripExcessParens(context)), () => []);
}
if (tail !== "") options = options.filter(o => prefixMatch(o.label, tail));
let from = word.to - tail.length;
if (context.explicit && !word.text.endsWith(".") && options.length === 0) {
options = explicitDataTypeOptions(word.text, targetNodeParameterContext);
from = word.to;
}
if (options.length === 0) return null;
return {
from,
options,
filter: false,
getMatch(completion) {
return [0, longestCommonPrefix(tail, completion.label).length];
}
};
}
function explicitDataTypeOptions(expression, targetNodeParameterContext) {
return attempt(() => {
return datatypeOptions({
resolved: resolveAutocompleteExpression(`={{ ${expression} }}`, targetNodeParameterContext?.nodeName),
base: expression,
tail: "",
transformLabel: label => "." + label
});
}, () => []);
}
function datatypeOptions(input) {
const {
resolved
} = input;
if (resolved === null) return [];
if (typeof resolved === "number") return numberOptions(input);
if (typeof resolved === "string") return stringOptions(input);
if (typeof resolved === "boolean") return booleanOptions();
if (attempt(() => DateTime.isDateTime(resolved), () => false)) return luxonOptions(input);
if (resolved instanceof Date) return dateOptions(input);
if (Array.isArray(resolved)) return arrayOptions(input);
if (typeof resolved === "object") return objectOptions(input);
return [];
}
function ensureKeyCanBeResolved(obj, key) {
try {
obj[key];
} catch (error) {
throw new Error("Cannot generate options", {
cause: error
});
}
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/nonDollar.completions.ts
/**
* Completions offered at the initial position for any char other than `$`.
*/
function nonDollarCompletions(context) {
const combinedRegex = new RegExp([/(\s+)D[ateTim]*/.source, /(\s+)M[ath]*/.source, /(\s+)O[bject]*/.source].join("|"));
const word = context.matchBefore(combinedRegex);
if (!word) return null;
if (word.from === word.to && !context.explicit) return null;
const userInput = word.text.trim();
const options = [{
label: "DateTime",
info: createInfoBoxRenderer({
name: "DateTime",
returnType: "DateTimeGlobal",
description: i18n.baseText("codeNodeEditor.completer.dateTime"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetime"
})
}, {
label: "Math",
info: createInfoBoxRenderer({
name: "Math",
returnType: "MathGlobal",
description: i18n.baseText("codeNodeEditor.completer.math"),
docURL: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math"
})
}, {
label: "Object",
info: createInfoBoxRenderer({
name: "Object",
returnType: "ObjectGlobal",
description: i18n.baseText("codeNodeEditor.completer.globalObject"),
docURL: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object"
})
}].filter(o => prefixMatch(o.label, userInput));
return {
from: word.to - userInput.length,
filter: false,
options
};
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/addCompletions.ts
function n8nCompletionSources() {
return [blankCompletions, bracketAccessCompletions, datatypeCompletions, dollarCompletions, nonDollarCompletions].map(source => ({
autocomplete: ifIn(["Resolvable"], source)
}));
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/dragAndDrop.ts
function eventToCoord(event) {
return {
x: event.clientX,
y: event.clientY
};
}
function dropValueInEditor(view, pos, value) {
const changes = view.state.changes({
from: pos,
insert: value
});
const anchor = changes.mapPos(pos, -1);
const head = changes.mapPos(pos, 1);
const selection = EditorSelection.single(anchor, head);
view.dispatch({
changes,
selection,
userEvent: "input.drop"
});
setTimeout(() => view.focus());
return selection;
}
async function dropInExpressionEditor(view, event, value) {
const dropPos = view.posAtCoords(eventToCoord(event), false);
const node = syntaxTree$1(view.state).resolve(dropPos);
let valueToInsert = value;
if (node.name === "Resolvable") valueToInsert = unwrapExpression(value);
return dropValueInEditor(view, dropPos, valueToInsert);
}
async function dropInCodeEditor(view, event, value) {
return dropValueInEditor(view, view.posAtCoords(eventToCoord(event), false), unwrapExpression(value));
}
function mappingDropCursor() {
return [dropCursorPos, drawDropCursor];
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/expressionCloseBrackets.ts
//#endregion
//#region ../../../node_modules/.pnpm/crelt@1.0.5/node_modules/crelt/index.es.js
function crelt() {
var elt = arguments[0];
if (typeof elt == "string") elt = document.createElement(elt);
var i$1 = 1,
next = arguments[1];
if (next && typeof next == "object" && next.nodeType == null && !Array.isArray(next)) {
for (var name$1 in next) if (Object.prototype.hasOwnProperty.call(next, name$1)) {
var value = next[name$1];
if (typeof value == "string") elt.setAttribute(name$1, value);else if (value != null) elt[name$1] = value;
}
i$1++;
}
for (; i$1 < arguments.length; i$1++) add(elt, arguments[i$1]);
return elt;
}
function add(elt, child) {
if (typeof child == "string") elt.appendChild(document.createTextNode(child));else if (child == null) {} else if (child.nodeType != null) elt.appendChild(child);else if (Array.isArray(child)) for (var i$1 = 0; i$1 < child.length; i$1++) add(elt, child[i$1]);else throw new RangeError("Unsupported child node: " + child);
}
//#endregion
//#region ../../../node_modules/.pnpm/@codemirror+search@6.5.6/node_modules/@codemirror/search/dist/index.js
function validRegExp(source) {
try {
new RegExp(source, baseFlags);
return true;
} catch (_a$2) {
return false;
}
}
function toCharEnd(text, pos) {
if (pos >= text.length) return pos;
let line = text.lineAt(pos),
next;
while (pos < line.to && (next = line.text.charCodeAt(pos - line.from)) >= 56320 && next < 57344) pos++;
return pos;
}
function createLineDialog(view) {
let input = crelt("input", {
class: "cm-textfield",
name: "line",
value: String(view.state.doc.lineAt(view.state.selection.main.head).number)
});
let dom = crelt("form", {
class: "cm-gotoLine",
onkeydown: event => {
if (event.keyCode == 27) {
event.preventDefault();
view.dispatch({
effects: dialogEffect.of(false)
});
view.focus();
} else if (event.keyCode == 13) {
event.preventDefault();
go();
}
},
onsubmit: event => {
event.preventDefault();
go();
}
}, crelt("label", view.state.phrase("Go to line"), ": ", input), " ", crelt("button", {
class: "cm-button",
type: "submit"
}, view.state.phrase("go")));
function go() {
let match = /^([+-])?(\d+)?(:\d+)?(%)?$/.exec(input.value);
if (!match) return;
let {
state
} = view,
startLine = state.doc.lineAt(state.selection.main.head);
let [, sign, ln, cl, percent] = match;
let col = cl ? +cl.slice(1) : 0;
let line = ln ? +ln : startLine.number;
if (ln && percent) {
let pc = line / 100;
if (sign) pc = pc * (sign == "-" ? -1 : 1) + startLine.number / state.doc.lines;
line = Math.round(state.doc.lines * pc);
} else if (ln && sign) line = line * (sign == "-" ? -1 : 1) + startLine.number;
let docLine = state.doc.line(Math.max(1, Math.min(state.doc.lines, line)));
let selection = EditorSelection.cursor(docLine.from + Math.max(0, Math.min(col, docLine.length)));
view.dispatch({
effects: [dialogEffect.of(false), EditorView.scrollIntoView(selection.from, {
y: "center"
})],
selection
});
view.focus();
}
return {
dom
};
}
/**
This extension highlights text that matches the selection. It uses
the `"cm-selectionMatch"` class for the highlighting. When
`highlightWordAroundCursor` is enabled, the word at the cursor
itself will be highlighted with `"cm-selectionMatch-main"`.
*/
function highlightSelectionMatches(options) {
let ext = [defaultTheme, matchHighlighter];
if (options) ext.push(highlightConfig.of(options));
return ext;
}
function insideWordBoundaries(check, state, from, to) {
return (from == 0 || check(state.sliceDoc(from - 1, from)) != CharCategory.Word) && (to == state.doc.length || check(state.sliceDoc(to, to + 1)) != CharCategory.Word);
}
function insideWord(check, state, from, to) {
return check(state.sliceDoc(from, from + 1)) == CharCategory.Word && check(state.sliceDoc(to - 1, to)) == CharCategory.Word;
}
function findNextOccurrence(state, query) {
let {
main,
ranges
} = state.selection;
let word = state.wordAt(main.head),
fullWord = word && word.from == main.from && word.to == main.to;
for (let cycled = false, cursor = new SearchCursor(state.doc, query, ranges[ranges.length - 1].to);;) {
cursor.next();
if (cursor.done) {
if (cycled) return null;
cursor = new SearchCursor(state.doc, query, 0, Math.max(0, ranges[ranges.length - 1].from - 1));
cycled = true;
} else {
if (cycled && ranges.some(r => r.from == cursor.value.from)) continue;
if (fullWord) {
let word$1 = state.wordAt(cursor.value.from);
if (!word$1 || word$1.from != cursor.value.from || word$1.to != cursor.value.to) continue;
}
return cursor.value;
}
}
}
/**
Select next occurrence of the current selection. Expand selection
to the surrounding word when the selection is empty.
*/
function stringCursor(spec, state, from, to) {
return new SearchCursor(state.doc, spec.unquoted, from, to, spec.caseSensitive ? void 0 : x => x.toLowerCase(), spec.wholeWord ? stringWordTest(state.doc, state.charCategorizer(state.selection.main.head)) : void 0);
}
function stringWordTest(doc$2, categorizer) {
return (from, to, buf, bufPos) => {
if (bufPos > from || bufPos + buf.length < to) {
bufPos = Math.max(0, from - 2);
buf = doc$2.sliceString(bufPos, Math.min(doc$2.length, to + 2));
}
return (categorizer(charBefore(buf, from - bufPos)) != CharCategory.Word || categorizer(charAfter(buf, from - bufPos)) != CharCategory.Word) && (categorizer(charAfter(buf, to - bufPos)) != CharCategory.Word || categorizer(charBefore(buf, to - bufPos)) != CharCategory.Word);
};
}
function regexpCursor(spec, state, from, to) {
return new RegExpCursor(state.doc, spec.search, {
ignoreCase: !spec.caseSensitive,
test: spec.wholeWord ? regexpWordTest(state.charCategorizer(state.selection.main.head)) : void 0
}, from, to);
}
function charBefore(str, index) {
return str.slice(findClusterBreak(str, index, false), index);
}
function charAfter(str, index) {
return str.slice(index, findClusterBreak(str, index));
}
function regexpWordTest(categorizer) {
return (_from, _to, match) => !match[0].length || (categorizer(charBefore(match.input, match.index)) != CharCategory.Word || categorizer(charAfter(match.input, match.index)) != CharCategory.Word) && (categorizer(charAfter(match.input, match.index + match[0].length)) != CharCategory.Word || categorizer(charBefore(match.input, match.index + match[0].length)) != CharCategory.Word);
}
function searchCommand(f) {
return view => {
let state = view.state.field(searchState, false);
return state && state.query.spec.valid ? f(view, state) : openSearchPanel(view);
};
}
/**
Open the search panel if it isn't already open, and move the
selection to the first match after the current main selection.
Will wrap around to the start of the document when it reaches the
end.
*/
function createSearchPanel(view) {
return view.state.facet(searchConfigFacet).createPanel(view);
}
function defaultQuery(state, fallback) {
var _a$2, _b, _c, _d, _e;
let sel = state.selection.main;
let selText = sel.empty || sel.to > sel.from + 100 ? "" : state.sliceDoc(sel.from, sel.to);
if (fallback && !selText) return fallback;
let config$1 = state.facet(searchConfigFacet);
return new SearchQuery({
search: ((_a$2 = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _a$2 !== void 0 ? _a$2 : config$1.literal) ? selText : selText.replace(/\n/g, "\\n"),
caseSensitive: (_b = fallback === null || fallback === void 0 ? void 0 : fallback.caseSensitive) !== null && _b !== void 0 ? _b : config$1.caseSensitive,
literal: (_c = fallback === null || fallback === void 0 ? void 0 : fallback.literal) !== null && _c !== void 0 ? _c : config$1.literal,
regexp: (_d = fallback === null || fallback === void 0 ? void 0 : fallback.regexp) !== null && _d !== void 0 ? _d : config$1.regexp,
wholeWord: (_e = fallback === null || fallback === void 0 ? void 0 : fallback.wholeWord) !== null && _e !== void 0 ? _e : config$1.wholeWord
});
}
function getSearchInput(view) {
let panel = getPanel(view, createSearchPanel);
return panel && panel.dom.querySelector("[main-field]");
}
function selectSearchInput(view) {
let input = getSearchInput(view);
if (input && input == view.root.activeElement) input.select();
}
/**
Make sure the search panel is open and focused.
*/
function phrase(view, phrase$1) {
return view.state.phrase(phrase$1);
}
function announceMatch(view, {
from,
to
}) {
let line = view.state.doc.lineAt(from),
lineEnd = view.state.doc.lineAt(to).to;
let start = Math.max(line.from, from - AnnounceMargin),
end = Math.min(lineEnd, to + AnnounceMargin);
let text = view.state.sliceDoc(start, end);
if (start != line.from) {
for (let i$1 = 0; i$1 < AnnounceMargin; i$1++) if (!Break.test(text[i$1 + 1]) && Break.test(text[i$1])) {
text = text.slice(i$1);
break;
}
}
if (end != lineEnd) {
for (let i$1 = text.length - 1; i$1 > text.length - AnnounceMargin; i$1--) if (!Break.test(text[i$1 - 1]) && Break.test(text[i$1])) {
text = text.slice(0, i$1);
break;
}
}
return EditorView.announce.of(`${view.state.phrase("current match")}. ${text} ${view.state.phrase("on line")} ${line.number}.`);
}
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
let found = null;
diagnostics.between(after, 1e9, (from, to, {
spec
}) => {
if (diagnostic && spec.diagnostic != diagnostic) return;
found = new SelectedDiagnostic(from, to, spec.diagnostic);
return false;
});
return found;
}
function hideTooltip(tr, tooltip) {
let from = tooltip.pos,
to = tooltip.end || from;
let result = tr.state.facet(lintConfig).hideOn(tr, from, to);
if (result != null) return result;
let line = tr.startState.doc.lineAt(tooltip.pos);
return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(line.from, Math.max(line.to, to)));
}
function maybeEnableLint(state, effects) {
return state.field(lintState, false) ? effects : effects.concat(StateEffect$1.appendConfig.of(lintExtensions));
}
/**
Returns a transaction spec which updates the current set of
diagnostics, and enables the lint extension if if wasn't already
active.
*/
function setDiagnostics(state, diagnostics) {
return {
effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)])
};
}
/**
The state effect that updates the set of active diagnostics. Can
be useful when writing an extension that needs to track these.
*/
function lintTooltip(view, pos, side) {
let {
diagnostics
} = view.state.field(lintState);
let found = [],
stackStart = 2e8,
stackEnd = 0;
diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, {
spec
}) => {
if (pos >= from && pos <= to && (from == to || (pos > from || side > 0) && (pos < to || side < 0))) {
found.push(spec.diagnostic);
stackStart = Math.min(from, stackStart);
stackEnd = Math.max(to, stackEnd);
}
});
let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
if (diagnosticFilter) found = diagnosticFilter(found, view.state);
if (!found.length) return null;
return {
pos: stackStart,
end: stackEnd,
above: view.state.doc.lineAt(stackStart).to < stackEnd,
create() {
return {
dom: diagnosticsTooltip(view, found)
};
}
};
}
function diagnosticsTooltip(view, diagnostics) {
return crelt("ul", {
class: "cm-tooltip-lint"
}, diagnostics.map(d => renderDiagnostic(view, d, false)));
}
/**
Command to open and focus the lint panel.
*/
/**
Given a diagnostic source, this function returns an extension that
enables linting with that source. It will be called whenever the
editor is idle (after its content changed). If `null` is given as
source, this only configures the lint extension.
*/
function linter(source, config$1 = {}) {
return [lintConfig.of({
source,
config: config$1
}), lintPlugin, lintExtensions];
}
function assignKeys(actions) {
let assigned = [];
if (actions) actions: for (let {
name: name$1
} of actions) {
for (let i$1 = 0; i$1 < name$1.length; i$1++) {
let ch = name$1[i$1];
if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) {
assigned.push(ch);
continue actions;
}
}
assigned.push("");
}
return assigned;
}
function renderDiagnostic(view, diagnostic, inPanel) {
var _a$2;
let keys = inPanel ? assignKeys(diagnostic.actions) : [];
return crelt("li", {
class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity
}, crelt("span", {
class: "cm-diagnosticText"
}, diagnostic.renderMessage ? diagnostic.renderMessage(view) : diagnostic.message), (_a$2 = diagnostic.actions) === null || _a$2 === void 0 ? void 0 : _a$2.map((action, i$1) => {
let fired = false,
click = e => {
e.preventDefault();
if (fired) return;
fired = true;
let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
if (found) action.apply(view, found.from, found.to);
};
let {
name: name$1
} = action,
keyIndex = keys[i$1] ? name$1.indexOf(keys[i$1]) : -1;
let nameElt = keyIndex < 0 ? name$1 : [name$1.slice(0, keyIndex), crelt("u", name$1.slice(keyIndex, keyIndex + 1)), name$1.slice(keyIndex + 1)];
return crelt("button", {
type: "button",
class: "cm-diagnosticAction",
onclick: click,
onmousedown: click,
"aria-label": ` Action: ${name$1}${keyIndex < 0 ? "" : ` (access key "${keys[i$1]})"`}.`
}, nameElt);
}), diagnostic.source && crelt("div", {
class: "cm-diagnosticSource"
}, diagnostic.source));
}
function svg(content$1, attrs = `viewBox="0 0 40 40"`) {
return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content$1)}</svg>')`;
}
function underline(color) {
return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
}
function severityWeight(sev) {
return sev == "error" ? 4 : sev == "warning" ? 3 : sev == "info" ? 2 : 1;
}
function trackHoverOn(view, marker) {
let mousemove = event => {
let rect = marker.getBoundingClientRect();
if (event.clientX > rect.left - 10 && event.clientX < rect.right + 10 && event.clientY > rect.top - 10 && event.clientY < rect.bottom + 10) return;
for (let target = event.target; target; target = target.parentNode) if (target.nodeType == 1 && target.classList.contains("cm-tooltip-lint")) return;
window.removeEventListener("mousemove", mousemove);
if (view.state.field(lintGutterTooltip)) view.dispatch({
effects: setLintGutterTooltip.of(null)
});
};
window.addEventListener("mousemove", mousemove);
}
function gutterMarkerMouseOver(view, marker, diagnostics) {
function hovered() {
let line = view.elementAtHeight(marker.getBoundingClientRect().top + 5 - view.documentTop);
if (view.coordsAtPos(line.from)) view.dispatch({
effects: setLintGutterTooltip.of({
pos: line.from,
above: false,
create() {
return {
dom: diagnosticsTooltip(view, diagnostics),
getCoords: () => marker.getBoundingClientRect()
};
}
})
});
marker.onmouseout = marker.onmousemove = null;
trackHoverOn(view, marker);
}
let {
hoverTime
} = view.state.facet(lintGutterConfig);
let hoverTimeout = setTimeout(hovered, hoverTime);
marker.onmouseout = () => {
clearTimeout(hoverTimeout);
marker.onmouseout = marker.onmousemove = null;
};
marker.onmousemove = () => {
clearTimeout(hoverTimeout);
hoverTimeout = setTimeout(hovered, hoverTime);
};
}
function markersForDiagnostics(doc$2, diagnostics) {
let byLine = Object.create(null);
for (let diagnostic of diagnostics) {
let line = doc$2.lineAt(diagnostic.from);
(byLine[line.from] || (byLine[line.from] = [])).push(diagnostic);
}
let markers = [];
for (let line in byLine) markers.push(new LintGutterMarker(byLine[line]).range(+line));
return RangeSet$1.of(markers, true);
}
/**
Returns an extension that installs a gutter showing markers for
each line that has diagnostics, which can be hovered over to see
the diagnostics.
*/
function lintGutter(config$1 = {}) {
return [lintGutterConfig.of(config$1), lintGutterMarkers, lintGutterExtension, lintGutterTheme, lintGutterTooltip];
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/format.ts
function formatDocument(view) {
function format(parser$3) {
Cu(view.state.doc.toString(), {
cursorOffset: view.state.selection.main.anchor,
parser: parser$3,
plugins: [Ln, $d]
}).then(({
formatted,
cursorOffset
}) => {
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: formatted
},
selection: EditorSelection.single(cursorOffset)
});
});
}
switch (view.state.facet(languageFacet)) {
case "javaScript":
format("babel");
break;
case "html":
format("html");
break;
case "json":
format("json");
break;
default:
return false;
}
return true;
}
//#endregion
//#region src/features/shared/editors/plugins/codemirror/keymap.ts
function textLength(text) {
let length = -1;
for (let line of text) length += line.length + 1;
return length;
}
function appendText(text, target, from = 0, to = 1e9) {
for (let pos = 0, i$1 = 0, first = true; i$1 < text.length && pos <= to; i$1++) {
let line = text[i$1],
end = pos + line.length;
if (end >= from) {
if (end > to) line = line.slice(0, to - pos);
if (pos < from) line = line.slice(from - pos);
if (first) {
target[target.length - 1] += line;
first = false;
} else target.push(line);
}
pos = end + 1;
}
return target;
}
function sliceText(text, from, to) {
return appendText(text, [""], from, to);
}
function clip(text, from, to) {
from = Math.max(0, Math.min(text.length, from));
return [from, Math.max(from, Math.min(text.length, to))];
}
function isExtendingChar(code$1) {
for (let i$1 = 1; i$1 < extend.length; i$1 += 2) if (extend[i$1] > code$1) return extend[i$1 - 1] <= code$1;
return false;
}
function isRegionalIndicator(code$1) {
return code$1 >= 127462 && code$1 <= 127487;
}
/**
Returns a next grapheme cluster break _after_ (not equal to)
`pos`, if `forward` is true, or before otherwise. Returns `pos`
itself if no further cluster break is available in the string.
Moves across surrogate pairs, extending characters (when
`includeExtending` is true), characters joined with zero-width
joiners, and flag emoji.
*/
function findClusterBreak$1(str, pos, forward = true, includeExtending = true) {
return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending);
}
function nextClusterBreak(str, pos, includeExtending) {
if (pos == str.length) return pos;
if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--;
let prev = codePointAt$1(str, pos);
pos += codePointSize$1(prev);
while (pos < str.length) {
let next = codePointAt$1(str, pos);
if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) {
pos += codePointSize$1(next);
prev = next;
} else if (isRegionalIndicator(next)) {
let countBefore = 0,
i$1 = pos - 2;
while (i$1 >= 0 && isRegionalIndicator(codePointAt$1(str, i$1))) {
countBefore++;
i$1 -= 2;
}
if (countBefore % 2 == 0) break;else pos += 2;
} else break;
}
return pos;
}
function prevClusterBreak(str, pos, includeExtending) {
while (pos > 0) {
let found = nextClusterBreak(str, pos - 2, includeExtending);
if (found < pos) return found;
pos--;
}
return 0;
}
function surrogateLow(ch) {
return ch >= 56320 && ch < 57344;
}
function surrogateHigh(ch) {
return ch >= 55296 && ch < 56320;
}
/**
Find the code point at the given position in a string (like the
[`codePointAt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt)
string method).
*/
function codePointAt$1(str, pos) {
let code0 = str.charCodeAt(pos);
if (!surrogateHigh(code0) || pos + 1 == str.length) return code0;
let code1 = str.charCodeAt(pos + 1);
if (!surrogateLow(code1)) return code0;
return (code0 - 55296 << 10) + (code1 - 56320) + 65536;
}
/**
The amount of positions a character takes up a JavaScript string.
*/
function codePointSize$1(code$1) {
return code$1 < 65536 ? 1 : 2;
}
function addSection(sections, len, ins, forceJoin = false) {
if (len == 0 && ins <= 0) return;
let last = sections.length - 2;
if (last >= 0 && ins <= 0 && ins == sections[last + 1]) sections[last] += len;else if (len == 0 && sections[last] == 0) sections[last + 1] += ins;else if (forceJoin) {
sections[last] += len;
sections[last + 1] += ins;
} else sections.push(len, ins);
}
function addInsert(values, sections, value) {
if (value.length == 0) return;
let index = sections.length - 2 >> 1;
if (index < values.length) values[values.length - 1] = values[values.length - 1].append(value);else {
while (values.length < index) values.push(Text$1.empty);
values.push(value);
}
}
function iterChanges(desc, f, individual) {
let inserted = desc.inserted;
for (let posA = 0, posB = 0, i$1 = 0; i$1 < desc.sections.length;) {
let len = desc.sections[i$1++],
ins = desc.sections[i$1++];
if (ins < 0) {
posA += len;
posB += len;
} else {
let endA = posA,
endB = posB,
text = Text$1.empty;
for (;;) {
endA += len;
endB += ins;
if (ins && inserted) text = text.append(inserted[i$1 - 2 >> 1]);
if (individual || i$1 == desc.sections.length || desc.sections[i$1 + 1] < 0) break;
len = desc.sections[i$1++];
ins = desc.sections[i$1++];
}
f(posA, endA, posB, endB, text);
posA = endA;
posB = endB;
}
}
}
function mapSet(setA, setB, before, mkSet = false) {
let sections = [],
insert$2 = mkSet ? [] : null;
let a = new SectionIter(setA),
b = new SectionIter(setB);
for (let inserted = -1;;) if (a.ins == -1 && b.ins == -1) {
let len = Math.min(a.len, b.len);
addSection(sections, len, -1);
a.forward(len);
b.forward(len);
} else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) {
let len = b.len;
addSection(sections, b.ins, -1);
while (len) {
let piece = Math.min(a.len, len);
if (a.ins >= 0 && inserted < a.i && a.len <= piece) {
addSection(sections, 0, a.ins);
if (insert$2) addInsert(insert$2, sections, a.text);
inserted = a.i;
}
a.forward(piece);
len -= piece;
}
b.next();
} else if (a.ins >= 0) {
let len = 0,
left = a.len;
while (left) if (b.ins == -1) {
let piece = Math.min(left, b.len);
len += piece;
left -= piece;
b.forward(piece);
} else if (b.ins == 0 && b.len < left) {
left -= b.len;
b.next();
} else break;
addSection(sections, len, inserted < a.i ? a.ins : 0);
if (insert$2 && inserted < a.i) addInsert(insert$2, sections, a.text);
inserted = a.i;
a.forward(a.len - left);
} else if (a.done && b.done) return insert$2 ? ChangeSet$1.createSet(sections, insert$2) : ChangeDesc.create(sections);else throw new Error("Mismatched change set lengths");
}
function composeSets(setA, setB, mkSet = false) {
let sections = [];
let insert$2 = mkSet ? [] : null;
let a = new SectionIter(setA),
b = new SectionIter(setB);
for (let open = false;;) if (a.done && b.done) return insert$2 ? ChangeSet$1.createSet(sections, insert$2) : ChangeDesc.create(sections);else if (a.ins == 0) {
addSection(sections, a.len, 0, open);
a.next();
} else if (b.len == 0 && !b.done) {
addSection(sections, 0, b.ins, open);
if (insert$2) addInsert(insert$2, sections, b.text);
b.next();
} else if (a.done || b.done) throw new Error("Mismatched change set lengths");else {
let len = Math.min(a.len2, b.len),
sectionLen = sections.length;
if (a.ins == -1) {
let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins;
addSection(sections, len, insB, open);
if (insert$2 && insB) addInsert(insert$2, sections, b.text);
} else if (b.ins == -1) {
addSection(sections, a.off ? 0 : a.len, len, open);
if (insert$2) addInsert(insert$2, sections, a.textBit(len));
} else {
addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open);
if (insert$2 && !b.off) addInsert(insert$2, sections, b.text);
}
open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen);
a.forward2(len);
b.forward(len);
}
}
function checkSelection(selection, docLength) {
for (let range of selection.ranges) if (range.to > docLength) throw new RangeError("Selection points outside of document");
}
function sameArray(a, b) {
return a == b || a.length == b.length && a.every((e, i$1) => e === b[i$1]);
}
function compareArray(a, b, compare$2) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) if (!compare$2(a[i$1], b[i$1])) return false;
return true;
}
function ensureAll(state, addrs) {
let changed = false;
for (let addr of addrs) if (ensureAddr(state, addr) & 1) changed = true;
return changed;
}
function dynamicFacetSlot(addresses, facet, providers) {
let providerAddrs = providers.map(p => addresses[p.id]);
let providerTypes = providers.map(p => p.type);
let dynamic = providerAddrs.filter(p => !(p & 1));
let idx = addresses[facet.id] >> 1;
function get(state) {
let values = [];
for (let i$1 = 0; i$1 < providerAddrs.length; i$1++) {
let value = getAddr(state, providerAddrs[i$1]);
if (providerTypes[i$1] == 2) for (let val of value) values.push(val);else values.push(value);
}
return facet.combine(values);
}
return {
create(state) {
for (let addr of providerAddrs) ensureAddr(state, addr);
state.values[idx] = get(state);
return 1;
},
update(state, tr) {
if (!ensureAll(state, dynamic)) return 0;
let value = get(state);
if (facet.compare(value, state.values[idx])) return 0;
state.values[idx] = value;
return 1;
},
reconfigure(state, oldState) {
let depChanged = ensureAll(state, providerAddrs);
let oldProviders = oldState.config.facets[facet.id],
oldValue = oldState.facet(facet);
if (oldProviders && !depChanged && sameArray(providers, oldProviders)) {
state.values[idx] = oldValue;
return 0;
}
let value = get(state);
if (facet.compare(value, oldValue)) {
state.values[idx] = oldValue;
return 0;
}
state.values[idx] = value;
return 1;
}
};
}
function prec(value) {
return ext => new PrecExtension(ext, value);
}
/**
By default extensions are registered in the order they are found
in the flattened form of nested array that was provided.
Individual extension values can be assigned a precedence to
override this. Extensions that do not have a precedence set get
the precedence of the nearest parent with a precedence, or
[`default`](https://codemirror.net/6/docs/ref/#state.Prec.default) if there is no such parent. The
final ordering of extensions is determined by first sorting by
precedence and then by order within each precedence.
*/
function flatten(extension, compartments, newCompartments) {
let result = [[], [], [], [], []];
let seen = /* @__PURE__ */new Map();
function inner(ext, prec$2) {
let known = seen.get(ext);
if (known != null) {
if (known <= prec$2) return;
let found = result[known].indexOf(ext);
if (found > -1) result[known].splice(found, 1);
if (ext instanceof CompartmentInstance) newCompartments.delete(ext.compartment);
}
seen.set(ext, prec$2);
if (Array.isArray(ext)) for (let e of ext) inner(e, prec$2);else if (ext instanceof CompartmentInstance) {
if (newCompartments.has(ext.compartment)) throw new RangeError(`Duplicate use of compartment in extensions`);
let content$1 = compartments.get(ext.compartment) || ext.inner;
newCompartments.set(ext.compartment, content$1);
inner(content$1, prec$2);
} else if (ext instanceof PrecExtension) inner(ext.inner, ext.prec);else if (ext instanceof StateField) {
result[prec$2].push(ext);
if (ext.provides) inner(ext.provides, prec$2);
} else if (ext instanceof FacetProvider) {
result[prec$2].push(ext);
if (ext.facet.extensions) inner(ext.facet.extensions, Prec_.default);
} else {
let content$1 = ext.extension;
if (!content$1) throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);
inner(content$1, prec$2);
}
}
inner(extension, Prec_.default);
return result.reduce((a, b) => a.concat(b));
}
function ensureAddr(state, addr) {
if (addr & 1) return 2;
let idx = addr >> 1;
let status = state.status[idx];
if (status == 4) throw new Error("Cyclic dependency between fields and/or facets");
if (status & 2) return status;
state.status[idx] = 4;
let changed = state.computeSlot(state, state.config.dynamicSlots[idx]);
return state.status[idx] = 2 | changed;
}
function getAddr(state, addr) {
return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1];
}
function joinRanges(a, b) {
let result = [];
for (let iA = 0, iB = 0;;) {
let from, to;
if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) {
from = a[iA++];
to = a[iA++];
} else if (iB < b.length) {
from = b[iB++];
to = b[iB++];
} else return result;
if (!result.length || result[result.length - 1] < from) result.push(from, to);else if (result[result.length - 1] < to) result[result.length - 1] = to;
}
}
function mergeTransaction(a, b, sequential) {
var _a$2;
let mapForA, mapForB, changes;
if (sequential) {
mapForA = b.changes;
mapForB = ChangeSet$1.empty(b.changes.length);
changes = a.changes.compose(b.changes);
} else {
mapForA = b.changes.map(a.changes);
mapForB = a.changes.mapDesc(b.changes, true);
changes = a.changes.compose(mapForA);
}
return {
changes,
selection: b.selection ? b.selection.map(mapForB) : (_a$2 = a.selection) === null || _a$2 === void 0 ? void 0 : _a$2.map(mapForA),
effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)),
annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations,
scrollIntoView: a.scrollIntoView || b.scrollIntoView
};
}
function resolveTransactionInner(state, spec, docSize) {
let sel = spec.selection,
annotations = asArray(spec.annotations);
if (spec.userEvent) annotations = annotations.concat(Transaction$1.userEvent.of(spec.userEvent));
return {
changes: spec.changes instanceof ChangeSet$1 ? spec.changes : ChangeSet$1.of(spec.changes || [], docSize, state.facet(lineSeparator)),
selection: sel && (sel instanceof EditorSelection$1 ? sel : EditorSelection$1.single(sel.anchor, sel.head)),
effects: asArray(spec.effects),
annotations,
scrollIntoView: !!spec.scrollIntoView
};
}
function resolveTransaction(state, specs, filter) {
let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length);
if (specs.length && specs[0].filter === false) filter = false;
for (let i$1 = 1; i$1 < specs.length; i$1++) {
if (specs[i$1].filter === false) filter = false;
let seq = !!specs[i$1].sequential;
s = mergeTransaction(s, resolveTransactionInner(state, specs[i$1], seq ? s.changes.newLength : state.doc.length), seq);
}
let tr = Transaction$1.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView);
return extendTransaction(filter ? filterTransaction(tr) : tr);
}
function filterTransaction(tr) {
let state = tr.startState;
let result = true;
for (let filter of state.facet(changeFilter)) {
let value = filter(tr);
if (value === false) {
result = false;
break;
}
if (Array.isArray(value)) result = result === true ? value : joinRanges(result, value);
}
if (result !== true) {
let changes, back;
if (result === false) {
back = tr.changes.invertedDesc;
changes = ChangeSet$1.empty(state.doc.length);
} else {
let filtered = tr.changes.filter(result);
changes = filtered.changes;
back = filtered.filtered.mapDesc(filtered.changes).invertedDesc;
}
tr = Transaction$1.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView);
}
let filters = state.facet(transactionFilter);
for (let i$1 = filters.length - 1; i$1 >= 0; i$1--) {
let filtered = filters[i$1](tr);
if (filtered instanceof Transaction$1) tr = filtered;else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction$1) tr = filtered[0];else tr = resolveTransaction(state, asArray(filtered), false);
}
return tr;
}
function extendTransaction(tr) {
let state = tr.startState,
extenders = state.facet(transactionExtender),
spec = tr;
for (let i$1 = extenders.length - 1; i$1 >= 0; i$1--) {
let extension = extenders[i$1](tr);
if (extension && Object.keys(extension).length) spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true);
}
return spec == tr ? tr : Transaction$1.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView);
}
function asArray(value) {
return value == null ? none : Array.isArray(value) ? value : [value];
}
/**
The categories produced by a [character
categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer). These are used
do things like selecting by word.
*/
function hasWordChar(str) {
if (wordChar) return wordChar.test(str);
for (let i$1 = 0; i$1 < str.length; i$1++) {
let ch = str[i$1];
if (/\w/.test(ch) || ch > "" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) return true;
}
return false;
}
function makeCategorizer(wordChars) {
return char => {
if (!/\S/.test(char)) return CharCategory$1.Space;
if (hasWordChar(char)) return CharCategory$1.Word;
for (let i$1 = 0; i$1 < wordChars.length; i$1++) if (char.indexOf(wordChars[i$1]) > -1) return CharCategory$1.Word;
return CharCategory$1.Other;
};
}
/**
The editor state class is a persistent (immutable) data structure.
To update a state, you [create](https://codemirror.net/6/docs/ref/#state.EditorState.update) a
[transaction](https://codemirror.net/6/docs/ref/#state.Transaction), which produces a _new_ state
instance, without modifying the original object.
As such, _never_ mutate properties of a state directly. That'll
just break things.
*/
function cmpRange(a, b) {
return a.from - b.from || a.value.startSide - b.value.startSide;
}
function lazySort(ranges) {
if (ranges.length > 1) for (let prev = ranges[0], i$1 = 1; i$1 < ranges.length; i$1++) {
let cur$1 = ranges[i$1];
if (cmpRange(prev, cur$1) > 0) return ranges.slice().sort(cmpRange);
prev = cur$1;
}
return ranges;
}
function findSharedChunks(a, b, textDiff) {
let inA = /* @__PURE__ */new Map();
for (let set of a) for (let i$1 = 0; i$1 < set.chunk.length; i$1++) if (set.chunk[i$1].maxPoint <= 0) inA.set(set.chunk[i$1], set.chunkPos[i$1]);
let shared = /* @__PURE__ */new Set();
for (let set of b) for (let i$1 = 0; i$1 < set.chunk.length; i$1++) {
let known = inA.get(set.chunk[i$1]);
if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i$1] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i$1].length))) shared.add(set.chunk[i$1]);
}
return shared;
}
function heapBubble(heap, index) {
for (let cur$1 = heap[index];;) {
let childIndex = (index << 1) + 1;
if (childIndex >= heap.length) break;
let child = heap[childIndex];
if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) {
child = heap[childIndex + 1];
childIndex++;
}
if (cur$1.compare(child) < 0) break;
heap[childIndex] = cur$1;
heap[index] = child;
index = childIndex;
}
}
function compare(a, startA, b, startB, length, comparator) {
a.goto(startA);
b.goto(startB);
let endB = startB + length;
let pos = startB,
dPos = startB - startA;
for (;;) {
let diff = a.to + dPos - b.to || a.endSide - b.endSide;
let end = diff < 0 ? a.to + dPos : b.to,
clipEnd = Math.min(end, endB);
if (a.point || b.point) {
if (!(a.point && b.point && (a.point == b.point || a.point.eq(b.point)) && sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to)))) comparator.comparePoint(pos, clipEnd, a.point, b.point);
} else if (clipEnd > pos && !sameValues(a.active, b.active)) comparator.compareRange(pos, clipEnd, a.active, b.active);
if (end > endB) break;
pos = end;
if (diff <= 0) a.next();
if (diff >= 0) b.next();
}
}
function sameValues(a, b) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) if (a[i$1] != b[i$1] && !a[i$1].eq(b[i$1])) return false;
return true;
}
function remove(array, index) {
for (let i$1 = index, e = array.length - 1; i$1 < e; i$1++) array[i$1] = array[i$1 + 1];
array.pop();
}
function insert(array, index, value) {
for (let i$1 = array.length - 1; i$1 >= index; i$1--) array[i$1 + 1] = array[i$1];
array[index] = value;
}
function findMinIndex(value, array) {
let found = -1,
foundPos = 1e9;
for (let i$1 = 0; i$1 < array.length; i$1++) if ((array[i$1] - foundPos || value[i$1].endSide - value[found].endSide) < 0) {
found = i$1;
foundPos = array[i$1];
}
return found;
}
//#endregion
//#region ../../../node_modules/.pnpm/@codemirror+view@6.22.3/node_modules/@codemirror/view/dist/index.js
function getSelection(root) {
let target;
if (root.nodeType == 11) target = root.getSelection ? root : root.ownerDocument;else target = root;
return target.getSelection();
}
function contains(dom, node) {
return node ? dom == node || dom.contains(node.nodeType != 1 ? node.parentNode : node) : false;
}
function deepActiveElement(doc$2) {
let elt = doc$2.activeElement;
while (elt && elt.shadowRoot) elt = elt.shadowRoot.activeElement;
return elt;
}
function hasSelection(dom, selection) {
if (!selection.anchorNode) return false;
try {
return contains(dom, selection.anchorNode);
} catch (_) {
return false;
}
}
function clientRectsFor(dom) {
if (dom.nodeType == 3) return textRange(dom, 0, dom.nodeValue.length).getClientRects();else if (dom.nodeType == 1) return dom.getClientRects();else return [];
}
function isEquivalentPosition(node, off, targetNode, targetOff) {
return targetNode ? scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1) : false;
}
function domIndex(node) {
for (var index = 0;; index++) {
node = node.previousSibling;
if (!node) return index;
}
}
function scanFor(node, off, targetNode, targetOff, dir) {
for (;;) {
if (node == targetNode && off == targetOff) return true;
if (off == (dir < 0 ? 0 : maxOffset(node))) {
if (node.nodeName == "DIV") return false;
let parent = node.parentNode;
if (!parent || parent.nodeType != 1) return false;
off = domIndex(node) + (dir < 0 ? 0 : 1);
node = parent;
} else if (node.nodeType == 1) {
node = node.childNodes[off + (dir < 0 ? -1 : 0)];
if (node.nodeType == 1 && node.contentEditable == "false") return false;
off = dir < 0 ? maxOffset(node) : 0;
} else return false;
}
}
function maxOffset(node) {
return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length;
}
function flattenRect(rect, left) {
let x = left ? rect.left : rect.right;
return {
left: x,
right: x,
top: rect.top,
bottom: rect.bottom
};
}
function windowRect(win) {
return {
left: 0,
right: win.innerWidth,
top: 0,
bottom: win.innerHeight
};
}
function getScale(elt, rect) {
let scaleX = rect.width / elt.offsetWidth;
let scaleY = rect.height / elt.offsetHeight;
if (scaleX > .995 && scaleX < 1.005 || !isFinite(scaleX) || Math.abs(rect.width - elt.offsetWidth) < 1) scaleX = 1;
if (scaleY > .995 && scaleY < 1.005 || !isFinite(scaleY) || Math.abs(rect.height - elt.offsetHeight) < 1) scaleY = 1;
return {
scaleX,
scaleY
};
}
function scrollRectIntoView(dom, rect, side, x, y, xMargin, yMargin, ltr) {
let doc$2 = dom.ownerDocument,
win = doc$2.defaultView || window;
for (let cur$1 = dom, stop = false; cur$1 && !stop;) if (cur$1.nodeType == 1) {
let bounding,
top$1 = cur$1 == doc$2.body;
let scaleX = 1,
scaleY = 1;
if (top$1) bounding = windowRect(win);else {
if (/^(fixed|sticky)$/.test(getComputedStyle(cur$1).position)) stop = true;
if (cur$1.scrollHeight <= cur$1.clientHeight && cur$1.scrollWidth <= cur$1.clientWidth) {
cur$1 = cur$1.assignedSlot || cur$1.parentNode;
continue;
}
let rect$1 = cur$1.getBoundingClientRect();
({
scaleX,
scaleY
} = getScale(cur$1, rect$1));
bounding = {
left: rect$1.left,
right: rect$1.left + cur$1.clientWidth * scaleX,
top: rect$1.top,
bottom: rect$1.top + cur$1.clientHeight * scaleY
};
}
let moveX = 0,
moveY = 0;
if (y == "nearest") {
if (rect.top < bounding.top) {
moveY = -(bounding.top - rect.top + yMargin);
if (side > 0 && rect.bottom > bounding.bottom + moveY) moveY = rect.bottom - bounding.bottom + moveY + yMargin;
} else if (rect.bottom > bounding.bottom) {
moveY = rect.bottom - bounding.bottom + yMargin;
if (side < 0 && rect.top - moveY < bounding.top) moveY = -(bounding.top + moveY - rect.top + yMargin);
}
} else {
let rectHeight = rect.bottom - rect.top,
boundingHeight = bounding.bottom - bounding.top;
moveY = (y == "center" && rectHeight <= boundingHeight ? rect.top + rectHeight / 2 - boundingHeight / 2 : y == "start" || y == "center" && side < 0 ? rect.top - yMargin : rect.bottom - boundingHeight + yMargin) - bounding.top;
}
if (x == "nearest") {
if (rect.left < bounding.left) {
moveX = -(bounding.left - rect.left + xMargin);
if (side > 0 && rect.right > bounding.right + moveX) moveX = rect.right - bounding.right + moveX + xMargin;
} else if (rect.right > bounding.right) {
moveX = rect.right - bounding.right + xMargin;
if (side < 0 && rect.left < bounding.left + moveX) moveX = -(bounding.left + moveX - rect.left + xMargin);
}
} else moveX = (x == "center" ? rect.left + (rect.right - rect.left) / 2 - (bounding.right - bounding.left) / 2 : x == "start" == ltr ? rect.left - xMargin : rect.right - (bounding.right - bounding.left) + xMargin) - bounding.left;
if (moveX || moveY) if (top$1) win.scrollBy(moveX, moveY);else {
let movedX = 0,
movedY = 0;
if (moveY) {
let start = cur$1.scrollTop;
cur$1.scrollTop += moveY / scaleY;
movedY = (cur$1.scrollTop - start) * scaleY;
}
if (moveX) {
let start = cur$1.scrollLeft;
cur$1.scrollLeft += moveX / scaleX;
movedX = (cur$1.scrollLeft - start) * scaleX;
}
rect = {
left: rect.left - movedX,
top: rect.top - movedY,
right: rect.right - movedX,
bottom: rect.bottom - movedY
};
if (movedX && Math.abs(movedX - moveX) < 1) x = "nearest";
if (movedY && Math.abs(movedY - moveY) < 1) y = "nearest";
}
if (top$1) break;
cur$1 = cur$1.assignedSlot || cur$1.parentNode;
} else if (cur$1.nodeType == 11) cur$1 = cur$1.host;else break;
}
function scrollableParent(dom) {
let doc$2 = dom.ownerDocument;
for (let cur$1 = dom.parentNode; cur$1;) if (cur$1 == doc$2.body) break;else if (cur$1.nodeType == 1) {
if (cur$1.scrollHeight > cur$1.clientHeight || cur$1.scrollWidth > cur$1.clientWidth) return cur$1;
cur$1 = cur$1.assignedSlot || cur$1.parentNode;
} else if (cur$1.nodeType == 11) cur$1 = cur$1.host;else break;
return null;
}
function focusPreventScroll(dom) {
if (dom.setActive) return dom.setActive();
if (preventScrollSupported) return dom.focus(preventScrollSupported);
let stack = [];
for (let cur$1 = dom; cur$1; cur$1 = cur$1.parentNode) {
stack.push(cur$1, cur$1.scrollTop, cur$1.scrollLeft);
if (cur$1 == cur$1.ownerDocument) break;
}
dom.focus(preventScrollSupported == null ? {
get preventScroll() {
preventScrollSupported = {
preventScroll: true
};
return true;
}
} : void 0);
if (!preventScrollSupported) {
preventScrollSupported = false;
for (let i$1 = 0; i$1 < stack.length;) {
let elt = stack[i$1++],
top$1 = stack[i$1++],
left = stack[i$1++];
if (elt.scrollTop != top$1) elt.scrollTop = top$1;
if (elt.scrollLeft != left) elt.scrollLeft = left;
}
}
}
function textRange(node, from, to = from) {
let range = scratchRange || (scratchRange = document.createRange());
range.setEnd(node, to);
range.setStart(node, from);
return range;
}
function dispatchKey(elt, name$1, code$1) {
let options = {
key: name$1,
code: name$1,
keyCode: code$1,
which: code$1,
cancelable: true
};
let down = new KeyboardEvent("keydown", options);
down.synthetic = true;
elt.dispatchEvent(down);
let up = new KeyboardEvent("keyup", options);
up.synthetic = true;
elt.dispatchEvent(up);
return down.defaultPrevented || up.defaultPrevented;
}
function getRoot(node) {
while (node) {
if (node && (node.nodeType == 9 || node.nodeType == 11 && node.host)) return node;
node = node.assignedSlot || node.parentNode;
}
return null;
}
function clearAttributes(node) {
while (node.attributes.length) node.removeAttributeNode(node.attributes[0]);
}
function atElementStart(doc$2, selection) {
let node = selection.focusNode,
offset = selection.focusOffset;
if (!node || selection.anchorNode != node || selection.anchorOffset != offset) return false;
offset = Math.min(offset, maxOffset(node));
for (;;) if (offset) {
if (node.nodeType != 1) return false;
let prev = node.childNodes[offset - 1];
if (prev.contentEditable == "false") offset--;else {
node = prev;
offset = maxOffset(node);
}
} else if (node == doc$2) return true;else {
offset = domIndex(node);
node = node.parentNode;
}
}
function isScrolledToBottom(elt) {
return elt.scrollTop > Math.max(1, elt.scrollHeight - elt.clientHeight - 4);
}
function rm$1(dom) {
let next = dom.nextSibling;
dom.parentNode.removeChild(dom);
return next;
}
function replaceRange(parent, fromI, fromOff, toI, toOff, insert$2, breakAtStart, openStart, openEnd) {
let {
children
} = parent;
let before = children.length ? children[fromI] : null;
let last = insert$2.length ? insert$2[insert$2.length - 1] : null;
let breakAtEnd = last ? last.breakAfter : breakAtStart;
if (fromI == toI && before && !breakAtStart && !breakAtEnd && insert$2.length < 2 && before.merge(fromOff, toOff, insert$2.length ? last : null, fromOff == 0, openStart, openEnd)) return;
if (toI < children.length) {
let after = children[toI];
if (after && (toOff < after.length || after.breakAfter && (last === null || last === void 0 ? void 0 : last.breakAfter))) {
if (fromI == toI) {
after = after.split(toOff);
toOff = 0;
}
if (!breakAtEnd && last && after.merge(0, toOff, last, true, 0, openEnd)) insert$2[insert$2.length - 1] = after;else {
if (toOff || after.children.length && !after.children[0].length) after.merge(0, toOff, null, false, 0, openEnd);
insert$2.push(after);
}
} else if (after === null || after === void 0 ? void 0 : after.breakAfter) if (last) last.breakAfter = 1;else breakAtStart = 1;
toI++;
}
if (before) {
before.breakAfter = breakAtStart;
if (fromOff > 0) {
if (!breakAtStart && insert$2.length && before.merge(fromOff, before.length, insert$2[0], false, openStart, 0)) before.breakAfter = insert$2.shift().breakAfter;else if (fromOff < before.length || before.children.length && before.children[before.children.length - 1].length == 0) before.merge(fromOff, before.length, null, false, openStart, 0);
fromI++;
}
}
while (fromI < toI && insert$2.length) if (children[toI - 1].become(insert$2[insert$2.length - 1])) {
toI--;
insert$2.pop();
openEnd = insert$2.length ? 0 : openStart;
} else if (children[fromI].become(insert$2[0])) {
fromI++;
insert$2.shift();
openStart = insert$2.length ? 0 : openEnd;
} else break;
if (!insert$2.length && fromI && toI < children.length && !children[fromI - 1].breakAfter && children[toI].merge(0, 0, children[fromI - 1], false, openStart, openEnd)) fromI--;
if (fromI < toI || insert$2.length) parent.replaceChildren(fromI, toI, insert$2);
}
function mergeChildrenInto(parent, from, to, insert$2, openStart, openEnd) {
let cur$1 = parent.childCursor();
let {
i: toI,
off: toOff
} = cur$1.findPos(to, 1);
let {
i: fromI,
off: fromOff
} = cur$1.findPos(from, -1);
let dLen = from - to;
for (let view of insert$2) dLen += view.length;
parent.length += dLen;
replaceRange(parent, fromI, fromOff, toI, toOff, insert$2, 0, openStart, openEnd);
}
function textCoords(text, pos, side) {
let length = text.nodeValue.length;
if (pos > length) pos = length;
let from = pos,
to = pos,
flatten$2 = 0;
if (pos == 0 && side < 0 || pos == length && side >= 0) {
if (!(browser.chrome || browser.gecko)) {
if (pos) {
from--;
flatten$2 = 1;
} else if (to < length) {
to++;
flatten$2 = -1;
}
}
} else if (side < 0) from--;else if (to < length) to++;
let rects = textRange(text, from, to).getClientRects();
if (!rects.length) return null;
let rect = rects[(flatten$2 ? flatten$2 < 0 : side >= 0) ? 0 : rects.length - 1];
if (browser.safari && !flatten$2 && rect.width == 0) rect = Array.prototype.find.call(rects, r => r.width) || rect;
return flatten$2 ? flattenRect(rect, flatten$2 < 0) : rect || null;
}
function inlineDOMAtPos(parent, pos) {
let dom = parent.dom,
{
children
} = parent,
i$1 = 0;
for (let off = 0; i$1 < children.length; i$1++) {
let child = children[i$1],
end = off + child.length;
if (end == off && child.getSide() <= 0) continue;
if (pos > off && pos < end && child.dom.parentNode == dom) return child.domAtPos(pos - off);
if (pos <= off) break;
off = end;
}
for (let j = i$1; j > 0; j--) {
let prev = children[j - 1];
if (prev.dom.parentNode == dom) return prev.domAtPos(prev.length);
}
for (let j = i$1; j < children.length; j++) {
let next = children[j];
if (next.dom.parentNode == dom) return next.domAtPos(0);
}
return new DOMPos(dom, 0);
}
function joinInlineInto(parent, view, open) {
let last,
{
children
} = parent;
if (open > 0 && view instanceof MarkView && children.length && (last = children[children.length - 1]) instanceof MarkView && last.mark.eq(view.mark)) joinInlineInto(last, view.children[0], open - 1);else {
children.push(view);
view.setParent(parent);
}
parent.length += view.length;
}
function coordsInChildren(view, pos, side) {
let before = null,
beforePos = -1,
after = null,
afterPos = -1;
function scan(view$1, pos$1) {
for (let i$1 = 0, off = 0; i$1 < view$1.children.length && off <= pos$1; i$1++) {
let child = view$1.children[i$1],
end = off + child.length;
if (end >= pos$1) {
if (child.children.length) scan(child, pos$1 - off);else if ((!after || after.isHidden && side > 0) && (end > pos$1 || off == end && child.getSide() > 0)) {
after = child;
afterPos = pos$1 - off;
} else if (off < pos$1 || off == end && child.getSide() < 0 && !child.isHidden) {
before = child;
beforePos = pos$1 - off;
}
}
off = end;
}
}
scan(view, pos);
let target = (side < 0 ? before : after) || before || after;
if (target) return target.coordsAt(Math.max(0, target == before ? beforePos : afterPos), side);
return fallbackRect(view);
}
function fallbackRect(view) {
let last = view.dom.lastChild;
if (!last) return view.dom.getBoundingClientRect();
let rects = clientRectsFor(last);
return rects[rects.length - 1] || null;
}
function combineAttrs(source, target) {
for (let name$1 in source) if (name$1 == "class" && target.class) target.class += " " + source.class;else if (name$1 == "style" && target.style) target.style += ";" + source.style;else target[name$1] = source[name$1];
return target;
}
function attrsEq(a, b, ignore) {
if (a == b) return true;
if (!a) a = noAttrs;
if (!b) b = noAttrs;
let keysA = Object.keys(a),
keysB = Object.keys(b);
if (keysA.length - (ignore && keysA.indexOf(ignore) > -1 ? 1 : 0) != keysB.length - (ignore && keysB.indexOf(ignore) > -1 ? 1 : 0)) return false;
for (let key of keysA) if (key != ignore && (keysB.indexOf(key) == -1 || a[key] !== b[key])) return false;
return true;
}
function updateAttrs(dom, prev, attrs) {
let changed = false;
if (prev) {
for (let name$1 in prev) if (!(attrs && name$1 in attrs)) {
changed = true;
if (name$1 == "style") dom.style.cssText = "";else dom.removeAttribute(name$1);
}
}
if (attrs) {
for (let name$1 in attrs) if (!(prev && prev[name$1] == attrs[name$1])) {
changed = true;
if (name$1 == "style") dom.style.cssText = attrs[name$1];else dom.setAttribute(name$1, attrs[name$1]);
}
}
return changed;
}
function getAttrs(dom) {
let attrs = Object.create(null);
for (let i$1 = 0; i$1 < dom.attributes.length; i$1++) {
let attr = dom.attributes[i$1];
attrs[attr.name] = attr.value;
}
return attrs;
}
function getInclusive(spec, block = false) {
let {
inclusiveStart: start,
inclusiveEnd: end
} = spec;
if (start == null) start = spec.inclusive;
if (end == null) end = spec.inclusive;
return {
start: start !== null && start !== void 0 ? start : block,
end: end !== null && end !== void 0 ? end : block
};
}
function widgetsEq(a, b) {
return a == b || !!(a && b && a.compare(b));
}
function addRange(from, to, ranges, margin = 0) {
let last = ranges.length - 1;
if (last >= 0 && ranges[last] + margin >= from) ranges[last] = Math.max(ranges[last], to);else ranges.push(from, to);
}
function wrapMarks(view, active) {
for (let mark of active) view = new MarkView(mark, [view], view.length);
return view;
}
/**
Log or report an unhandled exception in client code. Should
probably only be used by extension code that allows client code to
provide functions, and calls those functions in a context where an
exception can't be propagated to calling code in a reasonable way
(for example when in an event handler).
Either calls a handler registered with
[`EditorView.exceptionSink`](https://codemirror.net/6/docs/ref/#view.EditorView^exceptionSink),
`window.onerror`, if defined, or `console.error` (in which case
it'll pass `context`, when given, as first argument).
*/
function logException(state, exception, context) {
let handler = state.facet(exceptionSink);
if (handler.length) handler[0](exception);else if (window.onerror) window.onerror(String(exception), context, void 0, void 0, exception);else if (context) console.error(context + ":", exception);else console.error(exception);
}
function getIsolatedRanges(view, from, to) {
let isolates = view.state.facet(bidiIsolatedRanges);
if (!isolates.length) return isolates;
let sets = isolates.map(i$1 => i$1 instanceof Function ? i$1(view) : i$1);
let result = [];
RangeSet$1.spans(sets, from, to, {
point() {},
span(from$1, to$1, active, open) {
let level = result;
for (let i$1 = active.length - 1; i$1 >= 0; i$1--, open--) {
let iso = active[i$1].spec.bidiIsolate,
update;
if (iso == null) continue;
if (open > 0 && level.length && (update = level[level.length - 1]).to == from$1 && update.direction == iso) {
update.to = to$1;
level = update.inner;
} else {
let add$1 = {
from: from$1,
to: to$1,
direction: iso,
inner: []
};
level.push(add$1);
level = add$1.inner;
}
}
}
});
return result;
}
function getScrollMargins(view) {
let left = 0,
right = 0,
top$1 = 0,
bottom = 0;
for (let source of view.state.facet(scrollMargins)) {
let m = source(view);
if (m) {
if (m.left != null) left = Math.max(left, m.left);
if (m.right != null) right = Math.max(right, m.right);
if (m.top != null) top$1 = Math.max(top$1, m.top);
if (m.bottom != null) bottom = Math.max(bottom, m.bottom);
}
}
return {
left,
right,
top: top$1,
bottom
};
}
function dec(str) {
let result = [];
for (let i$1 = 0; i$1 < str.length; i$1++) result.push(1 << +str[i$1]);
return result;
}
function charType(ch) {
return ch <= 247 ? LowTypes[ch] : 1424 <= ch && ch <= 1524 ? 2 : 1536 <= ch && ch <= 1785 ? ArabicTypes[ch - 1536] : 1774 <= ch && ch <= 2220 ? 4 : 8192 <= ch && ch <= 8204 ? 256 : 64336 <= ch && ch <= 65023 ? 4 : 1;
}
function isolatesEq(a, b) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) {
let iA = a[i$1],
iB = b[i$1];
if (iA.from != iB.from || iA.to != iB.to || iA.direction != iB.direction || !isolatesEq(iA.inner, iB.inner)) return false;
}
return true;
}
function computeCharTypes(line, rFrom, rTo, isolates, outerType) {
for (let iI = 0; iI <= isolates.length; iI++) {
let from = iI ? isolates[iI - 1].to : rFrom,
to = iI < isolates.length ? isolates[iI].from : rTo;
let prevType = iI ? 256 : outerType;
for (let i$1 = from, prev = prevType, prevStrong = prevType; i$1 < to; i$1++) {
let type = charType(line.charCodeAt(i$1));
if (type == 512) type = prev;else if (type == 8 && prevStrong == 4) type = 16;
types[i$1] = type == 4 ? 2 : type;
if (type & 7) prevStrong = type;
prev = type;
}
for (let i$1 = from, prev = prevType, prevStrong = prevType; i$1 < to; i$1++) {
let type = types[i$1];
if (type == 128) {
if (i$1 < to - 1 && prev == types[i$1 + 1] && prev & 24) type = types[i$1] = prev;else types[i$1] = 256;
} else if (type == 64) {
let end = i$1 + 1;
while (end < to && types[end] == 64) end++;
let replace = i$1 && prev == 8 || end < rTo && types[end] == 8 ? prevStrong == 1 ? 1 : 8 : 256;
for (let j = i$1; j < end; j++) types[j] = replace;
i$1 = end - 1;
} else if (type == 8 && prevStrong == 1) types[i$1] = 1;
prev = type;
if (type & 7) prevStrong = type;
}
}
}
function processBracketPairs(line, rFrom, rTo, isolates, outerType) {
let oppositeType = outerType == 1 ? 2 : 1;
for (let iI = 0, sI = 0, context = 0; iI <= isolates.length; iI++) {
let from = iI ? isolates[iI - 1].to : rFrom,
to = iI < isolates.length ? isolates[iI].from : rTo;
for (let i$1 = from, ch, br, type; i$1 < to; i$1++) if (br = Brackets[ch = line.charCodeAt(i$1)]) {
if (br < 0) {
for (let sJ = sI - 3; sJ >= 0; sJ -= 3) if (BracketStack[sJ + 1] == -br) {
let flags = BracketStack[sJ + 2];
let type$1 = flags & 2 ? outerType : !(flags & 4) ? 0 : flags & 1 ? oppositeType : outerType;
if (type$1) types[i$1] = types[BracketStack[sJ]] = type$1;
sI = sJ;
break;
}
} else if (BracketStack.length == 189) break;else {
BracketStack[sI++] = i$1;
BracketStack[sI++] = ch;
BracketStack[sI++] = context;
}
} else if ((type = types[i$1]) == 2 || type == 1) {
let embed = type == outerType;
context = embed ? 0 : 1;
for (let sJ = sI - 3; sJ >= 0; sJ -= 3) {
let cur$1 = BracketStack[sJ + 2];
if (cur$1 & 2) break;
if (embed) BracketStack[sJ + 2] |= 2;else {
if (cur$1 & 4) break;
BracketStack[sJ + 2] |= 4;
}
}
}
}
}
function processNeutrals(rFrom, rTo, isolates, outerType) {
for (let iI = 0, prev = outerType; iI <= isolates.length; iI++) {
let from = iI ? isolates[iI - 1].to : rFrom,
to = iI < isolates.length ? isolates[iI].from : rTo;
for (let i$1 = from; i$1 < to;) {
let type = types[i$1];
if (type == 256) {
let end = i$1 + 1;
for (;;) if (end == to) {
if (iI == isolates.length) break;
end = isolates[iI++].to;
to = iI < isolates.length ? isolates[iI].from : rTo;
} else if (types[end] == 256) end++;else break;
let beforeL = prev == 1;
let replace = beforeL == ((end < rTo ? types[end] : outerType) == 1) ? beforeL ? 1 : 2 : outerType;
for (let j = end, jI = iI, fromJ = jI ? isolates[jI - 1].to : rFrom; j > i$1;) {
if (j == fromJ) {
j = isolates[--jI].from;
fromJ = jI ? isolates[jI - 1].to : rFrom;
}
types[--j] = replace;
}
i$1 = end;
} else {
prev = type;
i$1++;
}
}
}
}
function emitSpans(line, from, to, level, baseLevel, isolates, order) {
let ourType = level % 2 ? 2 : 1;
if (level % 2 == baseLevel % 2) for (let iCh = from, iI = 0; iCh < to;) {
let sameDir = true,
isNum = false;
if (iI == isolates.length || iCh < isolates[iI].from) {
let next = types[iCh];
if (next != ourType) {
sameDir = false;
isNum = next == 16;
}
}
let recurse = !sameDir && ourType == 1 ? [] : null;
let localLevel = sameDir ? level : level + 1;
let iScan = iCh;
run: for (;;) if (iI < isolates.length && iScan == isolates[iI].from) {
if (isNum) break run;
let iso = isolates[iI];
if (!sameDir) for (let upto = iso.to, jI = iI + 1;;) {
if (upto == to) break run;
if (jI < isolates.length && isolates[jI].from == upto) upto = isolates[jI++].to;else if (types[upto] == ourType) break run;else break;
}
iI++;
if (recurse) recurse.push(iso);else {
if (iso.from > iCh) order.push(new BidiSpan(iCh, iso.from, localLevel));
computeSectionOrder(line, iso.direction == LTR != !(localLevel % 2) ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
iCh = iso.to;
}
iScan = iso.to;
} else if (iScan == to || (sameDir ? types[iScan] != ourType : types[iScan] == ourType)) break;else iScan++;
if (recurse) emitSpans(line, iCh, iScan, level + 1, baseLevel, recurse, order);else if (iCh < iScan) order.push(new BidiSpan(iCh, iScan, localLevel));
iCh = iScan;
} else for (let iCh = to, iI = isolates.length; iCh > from;) {
let sameDir = true,
isNum = false;
if (!iI || iCh > isolates[iI - 1].to) {
let next = types[iCh - 1];
if (next != ourType) {
sameDir = false;
isNum = next == 16;
}
}
let recurse = !sameDir && ourType == 1 ? [] : null;
let localLevel = sameDir ? level : level + 1;
let iScan = iCh;
run: for (;;) if (iI && iScan == isolates[iI - 1].to) {
if (isNum) break run;
let iso = isolates[--iI];
if (!sameDir) for (let upto = iso.from, jI = iI;;) {
if (upto == from) break run;
if (jI && isolates[jI - 1].to == upto) upto = isolates[--jI].from;else if (types[upto - 1] == ourType) break run;else break;
}
if (recurse) recurse.push(iso);else {
if (iso.to < iCh) order.push(new BidiSpan(iso.to, iCh, localLevel));
computeSectionOrder(line, iso.direction == LTR != !(localLevel % 2) ? level + 1 : level, baseLevel, iso.inner, iso.from, iso.to, order);
iCh = iso.from;
}
iScan = iso.from;
} else if (iScan == from || (sameDir ? types[iScan - 1] != ourType : types[iScan - 1] == ourType)) break;else iScan--;
if (recurse) emitSpans(line, iScan, iCh, level + 1, baseLevel, recurse, order);else if (iScan < iCh) order.push(new BidiSpan(iScan, iCh, localLevel));
iCh = iScan;
}
}
function computeSectionOrder(line, level, baseLevel, isolates, from, to, order) {
let outerType = level % 2 ? 2 : 1;
computeCharTypes(line, from, to, isolates, outerType);
processBracketPairs(line, from, to, isolates, outerType);
processNeutrals(from, to, isolates, outerType);
emitSpans(line, from, to, level, baseLevel, isolates, order);
}
function computeOrder(line, direction, isolates) {
if (!line) return [new BidiSpan(0, 0, direction == RTL ? 1 : 0)];
if (direction == LTR && !isolates.length && !BidiRE.test(line)) return trivialOrder(line.length);
if (isolates.length) while (line.length > types.length) types[types.length] = 256;
let order = [],
level = direction == LTR ? 0 : 1;
computeSectionOrder(line, level, level, isolates, 0, line.length, order);
return order;
}
function trivialOrder(length) {
return [new BidiSpan(0, length, 0)];
}
function moveVisually(line, order, dir, start, forward) {
var _a$2;
let startIndex = start.head - line.from,
spanI = -1;
if (startIndex == 0) {
if (!forward || !line.length) return null;
if (order[0].level != dir) {
startIndex = order[0].side(false, dir);
spanI = 0;
}
} else if (startIndex == line.length) {
if (forward) return null;
let last = order[order.length - 1];
if (last.level != dir) {
startIndex = last.side(true, dir);
spanI = order.length - 1;
}
}
if (spanI < 0) spanI = BidiSpan.find(order, startIndex, (_a$2 = start.bidiLevel) !== null && _a$2 !== void 0 ? _a$2 : -1, start.assoc);
let span = order[spanI];
if (startIndex == span.side(forward, dir)) {
span = order[spanI += forward ? 1 : -1];
startIndex = span.side(!forward, dir);
}
let indexForward = forward == (span.dir == dir);
let nextIndex = findClusterBreak(line.text, startIndex, indexForward);
movedOver = line.text.slice(Math.min(startIndex, nextIndex), Math.max(startIndex, nextIndex));
if (nextIndex > span.from && nextIndex < span.to) return EditorSelection.cursor(nextIndex + line.from, indexForward ? -1 : 1, span.level);
let nextSpan = spanI == (forward ? order.length - 1 : 0) ? null : order[spanI + (forward ? 1 : -1)];
if (!nextSpan && span.level != dir) return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1, dir);
if (nextSpan && nextSpan.level < span.level) return EditorSelection.cursor(nextSpan.side(!forward, dir) + line.from, forward ? 1 : -1, nextSpan.level);
return EditorSelection.cursor(nextIndex + line.from, forward ? -1 : 1, span.level);
}
function betweenUneditable(pos) {
return pos.node.nodeType == 1 && pos.node.firstChild && (pos.offset == 0 || pos.node.childNodes[pos.offset - 1].contentEditable == "false") && (pos.offset == pos.node.childNodes.length || pos.node.childNodes[pos.offset].contentEditable == "false");
}
function findCompositionNode(view, headPos) {
let sel = view.observer.selectionRange;
let textNode = sel.focusNode && nearbyTextNode(sel.focusNode, sel.focusOffset, 0);
if (!textNode) return null;
let from = headPos - textNode.offset;
return {
from,
to: from + textNode.node.nodeValue.length,
node: textNode.node
};
}
function findCompositionRange(view, changes, headPos) {
let found = findCompositionNode(view, headPos);
if (!found) return null;
let {
node: textNode,
from,
to
} = found,
text = textNode.nodeValue;
if (/[\n\r]/.test(text)) return null;
if (view.state.doc.sliceString(found.from, found.to) != text) return null;
let inv = changes.invertedDesc;
let range = new ChangedRange(inv.mapPos(from), inv.mapPos(to), from, to);
let marks$1 = [];
for (let parent = textNode.parentNode;; parent = parent.parentNode) {
let parentView = ContentView.get(parent);
if (parentView instanceof MarkView) marks$1.push({
node: parent,
deco: parentView.mark
});else if (parentView instanceof LineView || parent.nodeName == "DIV" && parent.parentNode == view.contentDOM) return {
range,
text: textNode,
marks: marks$1,
line: parent
};else if (parent != view.contentDOM) marks$1.push({
node: parent,
deco: new MarkDecoration({
inclusive: true,
attributes: getAttrs(parent),
tagName: parent.tagName.toLowerCase()
})
});else return null;
}
}
function nearbyTextNode(startNode, startOffset, side) {
if (side <= 0) for (let node = startNode, offset = startOffset;;) {
if (node.nodeType == 3) return {
node,
offset
};
if (node.nodeType == 1 && offset > 0) {
node = node.childNodes[offset - 1];
offset = maxOffset(node);
} else break;
}
if (side >= 0) for (let node = startNode, offset = startOffset;;) {
if (node.nodeType == 3) return {
node,
offset
};
if (node.nodeType == 1 && offset < node.childNodes.length && side >= 0) {
node = node.childNodes[offset];
offset = 0;
} else break;
}
return null;
}
function nextToUneditable(node, offset) {
if (node.nodeType != 1) return 0;
return (offset && node.childNodes[offset - 1].contentEditable == "false" ? 1 : 0) | (offset < node.childNodes.length && node.childNodes[offset].contentEditable == "false" ? 2 : 0);
}
function findChangedDeco(a, b, diff) {
let comp = new DecorationComparator$1();
RangeSet$1.compare(a, b, diff, comp);
return comp.changes;
}
function inUneditable(node, inside$2) {
for (let cur$1 = node; cur$1 && cur$1 != inside$2; cur$1 = cur$1.assignedSlot || cur$1.parentNode) if (cur$1.nodeType == 1 && cur$1.contentEditable == "false") return true;
return false;
}
function touchesComposition(changes, composition) {
let touched = false;
if (composition) changes.iterChangedRanges((from, to) => {
if (from < composition.to && to > composition.from) touched = true;
});
return touched;
}
function groupAt(state, pos, bias = 1) {
let categorize = state.charCategorizer(pos);
let line = state.doc.lineAt(pos),
linePos = pos - line.from;
if (line.length == 0) return EditorSelection.cursor(pos);
if (linePos == 0) bias = 1;else if (linePos == line.length) bias = -1;
let from = linePos,
to = linePos;
if (bias < 0) from = findClusterBreak(line.text, linePos, false);else to = findClusterBreak(line.text, linePos);
let cat = categorize(line.text.slice(from, to));
while (from > 0) {
let prev = findClusterBreak(line.text, from, false);
if (categorize(line.text.slice(prev, from)) != cat) break;
from = prev;
}
while (to < line.length) {
let next = findClusterBreak(line.text, to);
if (categorize(line.text.slice(to, next)) != cat) break;
to = next;
}
return EditorSelection.range(from + line.from, to + line.from);
}
function getdx(x, rect) {
return rect.left > x ? rect.left - x : Math.max(0, x - rect.right);
}
function getdy(y, rect) {
return rect.top > y ? rect.top - y : Math.max(0, y - rect.bottom);
}
function yOverlap(a, b) {
return a.top < b.bottom - 1 && a.bottom > b.top + 1;
}
function upTop(rect, top$1) {
return top$1 < rect.top ? {
top: top$1,
left: rect.left,
right: rect.right,
bottom: rect.bottom
} : rect;
}
function upBot(rect, bottom) {
return bottom > rect.bottom ? {
top: rect.top,
left: rect.left,
right: rect.right,
bottom
} : rect;
}
function domPosAtCoords(parent, x, y) {
let closest,
closestRect,
closestX,
closestY,
closestOverlap = false;
let above, below, aboveRect, belowRect;
for (let child = parent.firstChild; child; child = child.nextSibling) {
let rects = clientRectsFor(child);
for (let i$1 = 0; i$1 < rects.length; i$1++) {
let rect = rects[i$1];
if (closestRect && yOverlap(closestRect, rect)) rect = upTop(upBot(rect, closestRect.bottom), closestRect.top);
let dx = getdx(x, rect),
dy = getdy(y, rect);
if (dx == 0 && dy == 0) return child.nodeType == 3 ? domPosInText(child, x, y) : domPosAtCoords(child, x, y);
if (!closest || closestY > dy || closestY == dy && closestX > dx) {
closest = child;
closestRect = rect;
closestX = dx;
closestY = dy;
let side = dy ? y < rect.top ? -1 : 1 : dx ? x < rect.left ? -1 : 1 : 0;
closestOverlap = !side || (side > 0 ? i$1 < rects.length - 1 : i$1 > 0);
}
if (dx == 0) {
if (y > rect.bottom && (!aboveRect || aboveRect.bottom < rect.bottom)) {
above = child;
aboveRect = rect;
} else if (y < rect.top && (!belowRect || belowRect.top > rect.top)) {
below = child;
belowRect = rect;
}
} else if (aboveRect && yOverlap(aboveRect, rect)) aboveRect = upBot(aboveRect, rect.bottom);else if (belowRect && yOverlap(belowRect, rect)) belowRect = upTop(belowRect, rect.top);
}
}
if (aboveRect && aboveRect.bottom >= y) {
closest = above;
closestRect = aboveRect;
} else if (belowRect && belowRect.top <= y) {
closest = below;
closestRect = belowRect;
}
if (!closest) return {
node: parent,
offset: 0
};
let clipX = Math.max(closestRect.left, Math.min(closestRect.right, x));
if (closest.nodeType == 3) return domPosInText(closest, clipX, y);
if (closestOverlap && closest.contentEditable != "false") return domPosAtCoords(closest, clipX, y);
return {
node: parent,
offset: Array.prototype.indexOf.call(parent.childNodes, closest) + (x >= (closestRect.left + closestRect.right) / 2 ? 1 : 0)
};
}
function domPosInText(node, x, y) {
let len = node.nodeValue.length;
let closestOffset = -1,
closestDY = 1e9,
generalSide = 0;
for (let i$1 = 0; i$1 < len; i$1++) {
let rects = textRange(node, i$1, i$1 + 1).getClientRects();
for (let j = 0; j < rects.length; j++) {
let rect = rects[j];
if (rect.top == rect.bottom) continue;
if (!generalSide) generalSide = x - rect.left;
let dy = (rect.top > y ? rect.top - y : y - rect.bottom) - 1;
if (rect.left - 1 <= x && rect.right + 1 >= x && dy < closestDY) {
let right = x >= (rect.left + rect.right) / 2,
after = right;
if (browser.chrome || browser.gecko) {
if (textRange(node, i$1).getBoundingClientRect().left == rect.right) after = !right;
}
if (dy <= 0) return {
node,
offset: i$1 + (after ? 1 : 0)
};
closestOffset = i$1 + (after ? 1 : 0);
closestDY = dy;
}
}
}
return {
node,
offset: closestOffset > -1 ? closestOffset : generalSide > 0 ? node.nodeValue.length : 0
};
}
function posAtCoords(view, coords, precise, bias = -1) {
var _a$2, _b;
let content$1 = view.contentDOM.getBoundingClientRect(),
docTop = content$1.top + view.viewState.paddingTop;
let block,
{
docHeight
} = view.viewState;
let {
x,
y
} = coords,
yOffset = y - docTop;
if (yOffset < 0) return 0;
if (yOffset > docHeight) return view.state.doc.length;
for (let halfLine = view.viewState.heightOracle.textHeight / 2, bounced = false;;) {
block = view.elementAtHeight(yOffset);
if (block.type == BlockType.Text) break;
for (;;) {
yOffset = bias > 0 ? block.bottom + halfLine : block.top - halfLine;
if (yOffset >= 0 && yOffset <= docHeight) break;
if (bounced) return precise ? null : 0;
bounced = true;
bias = -bias;
}
}
y = docTop + yOffset;
let lineStart = block.from;
if (lineStart < view.viewport.from) return view.viewport.from == 0 ? 0 : precise ? null : posAtCoordsImprecise(view, content$1, block, x, y);
if (lineStart > view.viewport.to) return view.viewport.to == view.state.doc.length ? view.state.doc.length : precise ? null : posAtCoordsImprecise(view, content$1, block, x, y);
let doc$2 = view.dom.ownerDocument;
let root = view.root.elementFromPoint ? view.root : doc$2;
let element = root.elementFromPoint(x, y);
if (element && !view.contentDOM.contains(element)) element = null;
if (!element) {
x = Math.max(content$1.left + 1, Math.min(content$1.right - 1, x));
element = root.elementFromPoint(x, y);
if (element && !view.contentDOM.contains(element)) element = null;
}
let node,
offset = -1;
if (element && ((_a$2 = view.docView.nearest(element)) === null || _a$2 === void 0 ? void 0 : _a$2.isEditable) != false) {
if (doc$2.caretPositionFromPoint) {
let pos = doc$2.caretPositionFromPoint(x, y);
if (pos) ({
offsetNode: node,
offset
} = pos);
} else if (doc$2.caretRangeFromPoint) {
let range = doc$2.caretRangeFromPoint(x, y);
if (range) {
({
startContainer: node,
startOffset: offset
} = range);
if (!view.contentDOM.contains(node) || browser.safari && isSuspiciousSafariCaretResult(node, offset, x) || browser.chrome && isSuspiciousChromeCaretResult(node, offset, x)) node = void 0;
}
}
}
if (!node || !view.docView.dom.contains(node)) {
let line = LineView.find(view.docView, lineStart);
if (!line) return yOffset > block.top + block.height / 2 ? block.to : block.from;
({
node,
offset
} = domPosAtCoords(line.dom, x, y));
}
let nearest = view.docView.nearest(node);
if (!nearest) return null;
if (nearest.isWidget && ((_b = nearest.dom) === null || _b === void 0 ? void 0 : _b.nodeType) == 1) {
let rect = nearest.dom.getBoundingClientRect();
return coords.y < rect.top || coords.y <= rect.bottom && coords.x <= (rect.left + rect.right) / 2 ? nearest.posAtStart : nearest.posAtEnd;
} else return nearest.localPosFromDOM(node, offset) + nearest.posAtStart;
}
function posAtCoordsImprecise(view, contentRect, block, x, y) {
let into = Math.round((x - contentRect.left) * view.defaultCharacterWidth);
if (view.lineWrapping && block.height > view.defaultLineHeight * 1.5) {
let textHeight = view.viewState.heightOracle.textHeight;
let line = Math.floor((y - block.top - (view.defaultLineHeight - textHeight) * .5) / textHeight);
into += line * view.viewState.heightOracle.lineLength;
}
let content$1 = view.state.sliceDoc(block.from, block.to);
return block.from + findColumn(content$1, into, view.state.tabSize);
}
function isSuspiciousSafariCaretResult(node, offset, x) {
let len;
if (node.nodeType != 3 || offset != (len = node.nodeValue.length)) return false;
for (let next = node.nextSibling; next; next = next.nextSibling) if (next.nodeType != 1 || next.nodeName != "BR") return false;
return textRange(node, len - 1, len).getBoundingClientRect().left > x;
}
function isSuspiciousChromeCaretResult(node, offset, x) {
if (offset != 0) return false;
for (let cur$1 = node;;) {
let parent = cur$1.parentNode;
if (!parent || parent.nodeType != 1 || parent.firstChild != cur$1) return false;
if (parent.classList.contains("cm-line")) break;
cur$1 = parent;
}
return x - (node.nodeType == 1 ? node.getBoundingClientRect() : textRange(node, 0, Math.max(node.nodeValue.length, 1)).getBoundingClientRect()).left > 5;
}
function blockAt(view, pos) {
let line = view.lineBlockAt(pos);
if (Array.isArray(line.type)) {
for (let l of line.type) if (l.to > pos || l.to == pos && (l.to == line.to || l.type == BlockType.Text)) return l;
}
return line;
}
function moveToLineBoundary(view, start, forward, includeWrap) {
let line = blockAt(view, start.head);
let coords = !includeWrap || line.type != BlockType.Text || !(view.lineWrapping || line.widgetLineBreaks) ? null : view.coordsAtPos(start.assoc < 0 && start.head > line.from ? start.head - 1 : start.head);
if (coords) {
let editorRect = view.dom.getBoundingClientRect();
let direction = view.textDirectionAt(line.from);
let pos = view.posAtCoords({
x: forward == (direction == Direction.LTR) ? editorRect.right - 1 : editorRect.left + 1,
y: (coords.top + coords.bottom) / 2
});
if (pos != null) return EditorSelection.cursor(pos, forward ? -1 : 1);
}
return EditorSelection.cursor(forward ? line.to : line.from, forward ? -1 : 1);
}
function moveByChar(view, start, forward, by) {
let line = view.state.doc.lineAt(start.head),
spans = view.bidiSpans(line);
let direction = view.textDirectionAt(line.from);
for (let cur$1 = start, check = null;;) {
let next = moveVisually(line, spans, direction, cur$1, forward),
char = movedOver;
if (!next) {
if (line.number == (forward ? view.state.doc.lines : 1)) return cur$1;
char = "\n";
line = view.state.doc.line(line.number + (forward ? 1 : -1));
spans = view.bidiSpans(line);
next = EditorSelection.cursor(forward ? line.from : line.to);
}
if (!check) {
if (!by) return next;
check = by(char);
} else if (!check(char)) return cur$1;
cur$1 = next;
}
}
function byGroup(view, pos, start) {
let categorize = view.state.charCategorizer(pos);
let cat = categorize(start);
return next => {
let nextCat = categorize(next);
if (cat == CharCategory.Space) cat = nextCat;
return cat == nextCat;
};
}
function moveVertically(view, start, forward, distance) {
let startPos = start.head,
dir = forward ? 1 : -1;
if (startPos == (forward ? view.state.doc.length : 0)) return EditorSelection.cursor(startPos, start.assoc);
let goal = start.goalColumn,
startY;
let rect = view.contentDOM.getBoundingClientRect();
let startCoords = view.coordsAtPos(startPos, start.assoc || -1),
docTop = view.documentTop;
if (startCoords) {
if (goal == null) goal = startCoords.left - rect.left;
startY = dir < 0 ? startCoords.top : startCoords.bottom;
} else {
let line = view.viewState.lineBlockAt(startPos);
if (goal == null) goal = Math.min(rect.right - rect.left, view.defaultCharacterWidth * (startPos - line.from));
startY = (dir < 0 ? line.top : line.bottom) + docTop;
}
let resolvedGoal = rect.left + goal;
let dist$2 = distance !== null && distance !== void 0 ? distance : view.viewState.heightOracle.textHeight >> 1;
for (let extra = 0;; extra += 10) {
let curY = startY + (dist$2 + extra) * dir;
let pos = posAtCoords(view, {
x: resolvedGoal,
y: curY
}, false, dir);
if (curY < rect.top || curY > rect.bottom || (dir < 0 ? pos < startPos : pos > startPos)) {
let charRect = view.docView.coordsForChar(pos);
let assoc = !charRect || curY < charRect.top ? -1 : 1;
return EditorSelection.cursor(pos, assoc, void 0, goal);
}
}
}
function skipAtomicRanges(atoms, pos, bias) {
for (;;) {
let moved = 0;
for (let set of atoms) set.between(pos - 1, pos + 1, (from, to, value) => {
if (pos > from && pos < to) {
let side = moved || bias || (pos - from < to - pos ? -1 : 1);
pos = side < 0 ? from : to;
moved = side;
}
});
if (!moved) return pos;
}
}
function skipAtoms(view, oldPos, pos) {
let newPos = skipAtomicRanges(view.state.facet(atomicRanges).map(f => f(view)), pos.from, oldPos.head > pos.from ? -1 : 1);
return newPos == pos.from ? pos : EditorSelection.cursor(newPos, newPos < pos.from ? 1 : -1);
}
function bindHandler(plugin, handler) {
return (view, event) => {
try {
return handler.call(plugin, event, view);
} catch (e) {
logException(view.state, e);
}
};
}
function computeHandlers(plugins) {
let result = Object.create(null);
function record(type) {
return result[type] || (result[type] = {
observers: [],
handlers: []
});
}
for (let plugin of plugins) {
let spec = plugin.spec;
if (spec && spec.domEventHandlers) for (let type in spec.domEventHandlers) {
let f = spec.domEventHandlers[type];
if (f) record(type).handlers.push(bindHandler(plugin.value, f));
}
if (spec && spec.domEventObservers) for (let type in spec.domEventObservers) {
let f = spec.domEventObservers[type];
if (f) record(type).observers.push(bindHandler(plugin.value, f));
}
}
for (let type in handlers) record(type).handlers.push(handlers[type]);
for (let type in observers) record(type).observers.push(observers[type]);
return result;
}
function dragScrollSpeed(dist$2) {
return Math.max(0, dist$2) * .7 + 8;
}
function dist(a, b) {
return Math.max(Math.abs(a.clientX - b.clientX), Math.abs(a.clientY - b.clientY));
}
function addsSelectionRange(view, event) {
let facet = view.state.facet(clickAddsSelectionRange);
return facet.length ? facet[0](event) : browser.mac ? event.metaKey : event.ctrlKey;
}
function dragMovesSelection(view, event) {
let facet = view.state.facet(dragMovesSelection$1);
return facet.length ? facet[0](event) : browser.mac ? !event.altKey : !event.ctrlKey;
}
function isInPrimarySelection(view, event) {
let {
main
} = view.state.selection;
if (main.empty) return false;
let sel = getSelection(view.root);
if (!sel || sel.rangeCount == 0) return true;
let rects = sel.getRangeAt(0).getClientRects();
for (let i$1 = 0; i$1 < rects.length; i$1++) {
let rect = rects[i$1];
if (rect.left <= event.clientX && rect.right >= event.clientX && rect.top <= event.clientY && rect.bottom >= event.clientY) return true;
}
return false;
}
function eventBelongsToEditor(view, event) {
if (!event.bubbles) return true;
if (event.defaultPrevented) return false;
for (let node = event.target, cView; node != view.contentDOM; node = node.parentNode) if (!node || node.nodeType == 11 || (cView = ContentView.get(node)) && cView.ignoreEvent(event)) return false;
return true;
}
function capturePaste(view) {
let parent = view.dom.parentNode;
if (!parent) return;
let target = parent.appendChild(document.createElement("textarea"));
target.style.cssText = "position: fixed; left: -10000px; top: 10px";
target.focus();
setTimeout(() => {
view.focus();
target.remove();
doPaste(view, target.value);
}, 50);
}
function doPaste(view, input) {
let {
state
} = view,
changes,
i$1 = 1,
text = state.toText(input);
let byLine = text.lines == state.selection.ranges.length;
if (lastLinewiseCopy != null && state.selection.ranges.every(r => r.empty) && lastLinewiseCopy == text.toString()) {
let lastLine = -1;
changes = state.changeByRange(range => {
let line = state.doc.lineAt(range.from);
if (line.from == lastLine) return {
range
};
lastLine = line.from;
let insert$2 = state.toText((byLine ? text.line(i$1++).text : input) + state.lineBreak);
return {
changes: {
from: line.from,
insert: insert$2
},
range: EditorSelection.cursor(range.from + insert$2.length)
};
});
} else if (byLine) changes = state.changeByRange(range => {
let line = text.line(i$1++);
return {
changes: {
from: range.from,
to: range.to,
insert: line.text
},
range: EditorSelection.cursor(range.from + line.length)
};
});else changes = state.replaceSelection(text);
view.dispatch(changes, {
userEvent: "input.paste",
scrollIntoView: true
});
}
function rangeForClick(view, pos, bias, type) {
if (type == 1) return EditorSelection.cursor(pos, bias);else if (type == 2) return groupAt(view.state, pos, bias);else {
let visual = LineView.find(view.docView, pos),
line = view.state.doc.lineAt(visual ? visual.posAtEnd : pos);
let from = visual ? visual.posAtStart : line.from,
to = visual ? visual.posAtEnd : line.to;
if (to < view.state.doc.length && to == line.to) to++;
return EditorSelection.range(from, to);
}
}
function findPositionSide(view, pos, x, y) {
let line = LineView.find(view.docView, pos);
if (!line) return 1;
let off = pos - line.posAtStart;
if (off == 0) return 1;
if (off == line.length) return -1;
let before = line.coordsAt(off, -1);
if (before && inside(x, y, before)) return -1;
let after = line.coordsAt(off, 1);
if (after && inside(x, y, after)) return 1;
return before && insideY(y, before) ? -1 : 1;
}
function queryPos(view, event) {
let pos = view.posAtCoords({
x: event.clientX,
y: event.clientY
}, false);
return {
pos,
bias: findPositionSide(view, pos, event.clientX, event.clientY)
};
}
function getClickType(event) {
if (!BadMouseDetail) return event.detail;
let last = lastMouseDown,
lastTime = lastMouseDownTime;
lastMouseDown = event;
lastMouseDownTime = Date.now();
return lastMouseDownCount = !last || lastTime > Date.now() - 400 && Math.abs(last.clientX - event.clientX) < 2 && Math.abs(last.clientY - event.clientY) < 2 ? (lastMouseDownCount + 1) % 3 : 1;
}
function basicMouseSelection(view, event) {
let start = queryPos(view, event),
type = getClickType(event);
let startSel = view.state.selection;
return {
update(update) {
if (update.docChanged) {
start.pos = update.changes.mapPos(start.pos);
startSel = startSel.map(update.changes);
}
},
get(event$1, extend$2, multiple) {
let cur$1 = queryPos(view, event$1),
removed;
let range = rangeForClick(view, cur$1.pos, cur$1.bias, type);
if (start.pos != cur$1.pos && !extend$2) {
let startRange = rangeForClick(view, start.pos, start.bias, type);
let from = Math.min(startRange.from, range.from),
to = Math.max(startRange.to, range.to);
range = from < range.from ? EditorSelection.range(from, to) : EditorSelection.range(to, from);
}
if (extend$2) return startSel.replaceRange(startSel.main.extend(range.from, range.to));else if (multiple && type == 1 && startSel.ranges.length > 1 && (removed = removeRangeAround(startSel, cur$1.pos))) return removed;else if (multiple) return startSel.addRange(range);else return EditorSelection.create([range]);
}
};
}
function removeRangeAround(sel, pos) {
for (let i$1 = 0; i$1 < sel.ranges.length; i$1++) {
let {
from,
to
} = sel.ranges[i$1];
if (from <= pos && to >= pos) return EditorSelection.create(sel.ranges.slice(0, i$1).concat(sel.ranges.slice(i$1 + 1)), sel.mainIndex == i$1 ? 0 : sel.mainIndex - (sel.mainIndex > i$1 ? 1 : 0));
}
return null;
}
function dropText(view, event, text, direct) {
if (!text) return;
let dropPos = view.posAtCoords({
x: event.clientX,
y: event.clientY
}, false);
let {
draggedContent
} = view.inputState;
let del = direct && draggedContent && dragMovesSelection(view, event) ? {
from: draggedContent.from,
to: draggedContent.to
} : null;
let ins = {
from: dropPos,
insert: text
};
let changes = view.state.changes(del ? [del, ins] : ins);
view.focus();
view.dispatch({
changes,
selection: {
anchor: changes.mapPos(dropPos, -1),
head: changes.mapPos(dropPos, 1)
},
userEvent: del ? "move.drop" : "input.drop"
});
view.inputState.draggedContent = null;
}
function captureCopy(view, text) {
let parent = view.dom.parentNode;
if (!parent) return;
let target = parent.appendChild(document.createElement("textarea"));
target.style.cssText = "position: fixed; left: -10000px; top: 10px";
target.value = text;
target.focus();
target.selectionEnd = text.length;
target.selectionStart = 0;
setTimeout(() => {
target.remove();
view.focus();
}, 50);
}
function copiedRange(state) {
let content$1 = [],
ranges = [],
linewise = false;
for (let range of state.selection.ranges) if (!range.empty) {
content$1.push(state.sliceDoc(range.from, range.to));
ranges.push(range);
}
if (!content$1.length) {
let upto = -1;
for (let {
from
} of state.selection.ranges) {
let line = state.doc.lineAt(from);
if (line.number > upto) {
content$1.push(line.text);
ranges.push({
from: line.from,
to: Math.min(state.doc.length, line.to + 1)
});
}
upto = line.number;
}
linewise = true;
}
return {
text: content$1.join(state.lineBreak),
ranges,
linewise
};
}
function focusChangeTransaction(state, focus) {
let effects = [];
for (let getEffect of state.facet(focusChangeEffect)) {
let effect = getEffect(state, focus);
if (effect) effects.push(effect);
}
return effects ? state.update({
effects,
annotations: isFocusChange.of(true)
}) : null;
}
function updateForFocusChange(view) {
setTimeout(() => {
let focus = view.hasFocus;
if (focus != view.inputState.notifiedFocused) {
let tr = focusChangeTransaction(view.state, focus);
if (tr) view.dispatch(tr);else view.update([]);
}
}, 10);
}
function firefoxCopyCutHack(doc$2) {
if (!appliedFirefoxHack.has(doc$2)) {
appliedFirefoxHack.add(doc$2);
doc$2.addEventListener("copy", () => {});
doc$2.addEventListener("cut", () => {});
}
}
function mergeGaps(nodes, around) {
let before, after;
if (nodes[around] == null && (before = nodes[around - 1]) instanceof HeightMapGap && (after = nodes[around + 1]) instanceof HeightMapGap) nodes.splice(around - 1, 3, new HeightMapGap(before.length + 1 + after.length));
}
function heightRelevantDecoChanges(a, b, diff) {
let comp = new DecorationComparator();
RangeSet$1.compare(a, b, diff, comp, 0);
return comp.changes;
}
function visiblePixelRange(dom, paddingTop) {
let rect = dom.getBoundingClientRect();
let doc$2 = dom.ownerDocument,
win = doc$2.defaultView || window;
let left = Math.max(0, rect.left),
right = Math.min(win.innerWidth, rect.right);
let top$1 = Math.max(0, rect.top),
bottom = Math.min(win.innerHeight, rect.bottom);
for (let parent = dom.parentNode; parent && parent != doc$2.body;) if (parent.nodeType == 1) {
let elt = parent;
let style = window.getComputedStyle(elt);
if ((elt.scrollHeight > elt.clientHeight || elt.scrollWidth > elt.clientWidth) && style.overflow != "visible") {
let parentRect = elt.getBoundingClientRect();
left = Math.max(left, parentRect.left);
right = Math.min(right, parentRect.right);
top$1 = Math.max(top$1, parentRect.top);
bottom = parent == dom.parentNode ? parentRect.bottom : Math.min(bottom, parentRect.bottom);
}
parent = style.position == "absolute" || style.position == "fixed" ? elt.offsetParent : elt.parentNode;
} else if (parent.nodeType == 11) parent = parent.host;else break;
return {
left: left - rect.left,
right: Math.max(left, right) - rect.left,
top: top$1 - (rect.top + paddingTop),
bottom: Math.max(top$1, bottom) - (rect.top + paddingTop)
};
}
function fullPixelRange(dom, paddingTop) {
let rect = dom.getBoundingClientRect();
return {
left: 0,
right: rect.right - rect.left,
top: paddingTop,
bottom: rect.bottom - (rect.top + paddingTop)
};
}
function lineStructure(from, to, stateDeco) {
let ranges = [],
pos = from,
total = 0;
RangeSet$1.spans(stateDeco, from, to, {
span() {},
point(from$1, to$1) {
if (from$1 > pos) {
ranges.push({
from: pos,
to: from$1
});
total += from$1 - pos;
}
pos = to$1;
}
}, 20);
if (pos < to) {
ranges.push({
from: pos,
to
});
total += to - pos;
}
return {
total,
ranges
};
}
function findPosition({
total,
ranges
}, ratio) {
if (ratio <= 0) return ranges[0].from;
if (ratio >= 1) return ranges[ranges.length - 1].to;
let dist$2 = Math.floor(total * ratio);
for (let i$1 = 0;; i$1++) {
let {
from,
to
} = ranges[i$1],
size = to - from;
if (dist$2 <= size) return from + dist$2;
dist$2 -= size;
}
}
function findFraction(structure, pos) {
let counted = 0;
for (let {
from,
to
} of structure.ranges) {
if (pos <= to) {
counted += pos - from;
break;
}
counted += to - from;
}
return counted / structure.total;
}
function find(array, f) {
for (let val of array) if (f(val)) return val;
}
function scaleBlock(block, scaler) {
if (scaler.scale == 1) return block;
let bTop = scaler.toDOM(block.top),
bBottom = scaler.toDOM(block.bottom);
return new BlockInfo(block.from, block.length, bTop, bBottom - bTop, Array.isArray(block._content) ? block._content.map(b => scaleBlock(b, scaler)) : block._content);
}
function buildTheme(main, spec, scopes) {
return new StyleModule(spec, {
finish(sel) {
return /&/.test(sel) ? sel.replace(/&\w*/, m => {
if (m == "&") return main;
if (!scopes || !scopes[m]) throw new RangeError(`Unsupported selector: ${m}`);
return scopes[m];
}) : main + " " + sel;
}
});
}
function isAtEnd(parent, node, offset) {
for (;;) {
if (!node || offset < maxOffset(node)) return false;
if (node == parent) return true;
offset = domIndex(node) + 1;
node = node.parentNode;
}
}
function isBlockElement(node) {
return node.nodeType == 1 && /^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(node.nodeName);
}
function applyDOMChange(view, domChange) {
let change;
let {
newSel
} = domChange,
sel = view.state.selection.main;
let lastKey = view.inputState.lastKeyTime > Date.now() - 100 ? view.inputState.lastKeyCode : -1;
if (domChange.bounds) {
let {
from,
to
} = domChange.bounds;
let preferredPos = sel.from,
preferredSide = null;
if (lastKey === 8 || browser.android && domChange.text.length < to - from) {
preferredPos = sel.to;
preferredSide = "end";
}
let diff = findDiff(view.state.doc.sliceString(from, to, LineBreakPlaceholder), domChange.text, preferredPos - from, preferredSide);
if (diff) {
if (browser.chrome && lastKey == 13 && diff.toB == diff.from + 2 && domChange.text.slice(diff.from, diff.toB) == LineBreakPlaceholder + LineBreakPlaceholder) diff.toB--;
change = {
from: from + diff.from,
to: from + diff.toA,
insert: Text.of(domChange.text.slice(diff.from, diff.toB).split(LineBreakPlaceholder))
};
}
} else if (newSel && (!view.hasFocus && view.state.facet(editable) || newSel.main.eq(sel))) newSel = null;
if (!change && !newSel) return false;
if (!change && domChange.typeOver && !sel.empty && newSel && newSel.main.empty) change = {
from: sel.from,
to: sel.to,
insert: view.state.doc.slice(sel.from, sel.to)
};else if (change && change.from >= sel.from && change.to <= sel.to && (change.from != sel.from || change.to != sel.to) && sel.to - sel.from - (change.to - change.from) <= 4) change = {
from: sel.from,
to: sel.to,
insert: view.state.doc.slice(sel.from, change.from).append(change.insert).append(view.state.doc.slice(change.to, sel.to))
};else if ((browser.mac || browser.android) && change && change.from == change.to && change.from == sel.head - 1 && /^\. ?$/.test(change.insert.toString()) && view.contentDOM.getAttribute("autocorrect") == "off") {
if (newSel && change.insert.length == 2) newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
change = {
from: sel.from,
to: sel.to,
insert: Text.of([" "])
};
} else if (browser.chrome && change && change.from == change.to && change.from == sel.head && change.insert.toString() == "\n " && view.lineWrapping) {
if (newSel) newSel = EditorSelection.single(newSel.main.anchor - 1, newSel.main.head - 1);
change = {
from: sel.from,
to: sel.to,
insert: Text.of([" "])
};
}
if (change) {
if (browser.ios && view.inputState.flushIOSKey()) return true;
if (browser.android && (change.from == sel.from && change.to == sel.to && change.insert.length == 1 && change.insert.lines == 2 && dispatchKey(view.contentDOM, "Enter", 13) || (change.from == sel.from - 1 && change.to == sel.to && change.insert.length == 0 || lastKey == 8 && change.insert.length < change.to - change.from && change.to > sel.head) && dispatchKey(view.contentDOM, "Backspace", 8) || change.from == sel.from && change.to == sel.to + 1 && change.insert.length == 0 && dispatchKey(view.contentDOM, "Delete", 46))) return true;
let text = change.insert.toString();
if (view.inputState.composing >= 0) view.inputState.composing++;
let defaultTr;
let defaultInsert = () => defaultTr || (defaultTr = applyDefaultInsert(view, change, newSel));
if (!view.state.facet(inputHandler).some(h => h(view, change.from, change.to, text, defaultInsert))) view.dispatch(defaultInsert());
return true;
} else if (newSel && !newSel.main.eq(sel)) {
let scrollIntoView$3 = false,
userEvent = "select";
if (view.inputState.lastSelectionTime > Date.now() - 50) {
if (view.inputState.lastSelectionOrigin == "select") scrollIntoView$3 = true;
userEvent = view.inputState.lastSelectionOrigin;
}
view.dispatch({
selection: newSel,
scrollIntoView: scrollIntoView$3,
userEvent
});
return true;
} else return false;
}
function applyDefaultInsert(view, change, newSel) {
let tr,
startState = view.state,
sel = startState.selection.main;
if (change.from >= sel.from && change.to <= sel.to && change.to - change.from >= (sel.to - sel.from) / 3 && (!newSel || newSel.main.empty && newSel.main.from == change.from + change.insert.length) && view.inputState.composing < 0) {
let before = sel.from < change.from ? startState.sliceDoc(sel.from, change.from) : "";
let after = sel.to > change.to ? startState.sliceDoc(change.to, sel.to) : "";
tr = startState.replaceSelection(view.state.toText(before + change.insert.sliceString(0, void 0, view.state.lineBreak) + after));
} else {
let changes = startState.changes(change);
let mainSel = newSel && newSel.main.to <= changes.newLength ? newSel.main : void 0;
if (startState.selection.ranges.length > 1 && view.inputState.composing >= 0 && change.to <= sel.to && change.to >= sel.to - 10) {
let replaced = view.state.sliceDoc(change.from, change.to);
let compositionRange,
composition = newSel && findCompositionNode(view, newSel.main.head);
if (composition) {
let dLen = change.insert.length - (change.to - change.from);
compositionRange = {
from: composition.from,
to: composition.to - dLen
};
} else compositionRange = view.state.doc.lineAt(sel.head);
let offset = sel.to - change.to,
size = sel.to - sel.from;
tr = startState.changeByRange(range => {
if (range.from == sel.from && range.to == sel.to) return {
changes,
range: mainSel || range.map(changes)
};
let to = range.to - offset,
from = to - replaced.length;
if (range.to - range.from != size || view.state.sliceDoc(from, to) != replaced || range.to >= compositionRange.from && range.from <= compositionRange.to) return {
range
};
let rangeChanges = startState.changes({
from,
to,
insert: change.insert
}),
selOff = range.to - sel.to;
return {
changes: rangeChanges,
range: !mainSel ? range.map(rangeChanges) : EditorSelection.range(Math.max(0, mainSel.anchor + selOff), Math.max(0, mainSel.head + selOff))
};
});
} else tr = {
changes,
selection: mainSel && startState.selection.replaceRange(mainSel)
};
}
let userEvent = "input.type";
if (view.composing || view.inputState.compositionPendingChange && view.inputState.compositionEndedAt > Date.now() - 50) {
view.inputState.compositionPendingChange = false;
userEvent += ".compose";
if (view.inputState.compositionFirstChange) {
userEvent += ".start";
view.inputState.compositionFirstChange = false;
}
}
return startState.update(tr, {
userEvent,
scrollIntoView: true
});
}
function findDiff(a, b, preferredPos, preferredSide) {
let minLen = Math.min(a.length, b.length);
let from = 0;
while (from < minLen && a.charCodeAt(from) == b.charCodeAt(from)) from++;
if (from == minLen && a.length == b.length) return null;
let toA = a.length,
toB = b.length;
while (toA > 0 && toB > 0 && a.charCodeAt(toA - 1) == b.charCodeAt(toB - 1)) {
toA--;
toB--;
}
if (preferredSide == "end") {
let adjust = Math.max(0, from - Math.min(toA, toB));
preferredPos -= toA + adjust - from;
}
if (toA < from && a.length < b.length) {
let move = preferredPos <= from && preferredPos >= toA ? from - preferredPos : 0;
from -= move;
toB = from + (toB - toA);
toA = from;
} else if (toB < from) {
let move = preferredPos <= from && preferredPos >= toB ? from - preferredPos : 0;
from -= move;
toA = from + (toA - toB);
toB = from;
}
return {
from,
toA,
toB
};
}
function selectionPoints(view) {
let result = [];
if (view.root.activeElement != view.contentDOM) return result;
let {
anchorNode,
anchorOffset,
focusNode,
focusOffset
} = view.observer.selectionRange;
if (anchorNode) {
result.push(new DOMPoint(anchorNode, anchorOffset));
if (focusNode != anchorNode || focusOffset != anchorOffset) result.push(new DOMPoint(focusNode, focusOffset));
}
return result;
}
function selectionFromPoints(points, base$1) {
if (points.length == 0) return null;
let anchor = points[0].pos,
head = points.length == 2 ? points[1].pos : anchor;
return anchor > -1 && head > -1 ? EditorSelection.single(anchor + base$1, head + base$1) : null;
}
function findChild(cView, dom, dir) {
while (dom) {
let curView = ContentView.get(dom);
if (curView && curView.parent == cView) return curView;
let parent = dom.parentNode;
dom = parent != cView.dom ? parent : dir > 0 ? dom.nextSibling : dom.previousSibling;
}
return null;
}
function safariSelectionRangeHack(view) {
let found = null;
function read$1(event) {
event.preventDefault();
event.stopImmediatePropagation();
found = event.getTargetRanges()[0];
}
view.contentDOM.addEventListener("beforeinput", read$1, true);
view.dom.ownerDocument.execCommand("indent");
view.contentDOM.removeEventListener("beforeinput", read$1, true);
if (!found) return null;
let anchorNode = found.startContainer,
anchorOffset = found.startOffset;
let focusNode = found.endContainer,
focusOffset = found.endOffset;
let curAnchor = view.docView.domAtPos(view.state.selection.main.anchor);
if (isEquivalentPosition(curAnchor.node, curAnchor.offset, focusNode, focusOffset)) [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset];
return {
anchorNode,
anchorOffset,
focusNode,
focusOffset
};
}
/**
An editor view represents the editor's user interface. It holds
the editable DOM surface, and possibly other elements such as the
line number gutter. It handles events and dispatches state
transactions for editing actions.
*/
function attrsFromFacet(view, facet, base$1) {
for (let sources = view.state.facet(facet), i$1 = sources.length - 1; i$1 >= 0; i$1--) {
let source = sources[i$1],
value = typeof source == "function" ? source(view) : source;
if (value) combineAttrs(value, base$1);
}
return base$1;
}
/**
Helper function to define a facet (to be added to the top syntax
node(s) for a language via
[`languageDataProp`](https://codemirror.net/6/docs/ref/#language.languageDataProp)), that will be
used to associate language data with the language. You
probably only need this when subclassing
[`Language`](https://codemirror.net/6/docs/ref/#language.Language).
*/
function defineLanguageFacet(baseData) {
return Facet.define({
combine: baseData ? values => values.concat(baseData) : void 0
});
}
/**
Syntax node prop used to register sublanguages. Should be added to
the top level node type for the language.
*/
function topNodeAt(state, pos, side) {
let topLang = state.facet(language),
tree = syntaxTree(state).topNode;
if (!topLang || topLang.allowsNesting) {
for (let node = tree; node; node = node.enter(pos, side, IterMode.ExcludeBuffers)) if (node.type.isTop) tree = node;
}
return tree;
}
/**
A subclass of [`Language`](https://codemirror.net/6/docs/ref/#language.Language) for use with Lezer
[LR parsers](https://lezer.codemirror.net/docs/ref#lr.LRParser)
parsers.
*/
/**
Get the syntax tree for a state, which is the current (possibly
incomplete) parse tree of the active
[language](https://codemirror.net/6/docs/ref/#language.Language), or the empty tree if there is no
language available.
*/
function syntaxTree(state) {
let field = state.field(Language.state, false);
return field ? field.tree : Tree.empty;
}
/**
Lezer-style
[`Input`](https://lezer.codemirror.net/docs/ref#common.Input)
object for a [`Text`](https://codemirror.net/6/docs/ref/#state.Text) object.
*/
function cutFragments(fragments, from, to) {
return TreeFragment.applyChanges(fragments, [{
fromA: from,
toA: to,
fromB: from,
toB: to
}]);
}
/**
[Fold](https://codemirror.net/6/docs/ref/#language.foldNodeProp) function that folds everything but
the first and the last child of a syntax node. Useful for nodes
that start and end with delimiters.
*/
function foldInside$1(node) {
let first = node.firstChild,
last = node.lastChild;
return first && first.to < last.from ? {
from: first.to,
to: last.type.isError ? node.to : last.from
} : null;
}
/**
A highlight style associates CSS styles with higlighting
[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
*/
function warnForPart(part, msg) {
if (warned.indexOf(part) > -1) return;
warned.push(part);
console.warn(msg);
}
function createTokenType(extra, tagStr) {
let tags$1 = [];
for (let name$2 of tagStr.split(" ")) {
let found = [];
for (let part of name$2.split(".")) {
let value = extra[part] || tags[part];
if (!value) warnForPart(part, `Unknown highlighting tag ${part}`);else if (typeof value == "function") {
if (!found.length) warnForPart(part, `Modifier ${part} used at start of tag`);else found = found.map(value);
} else if (found.length) warnForPart(part, `Tag ${part} used as modifier`);else found = Array.isArray(value) ? value : [value];
}
for (let tag of found) tags$1.push(tag);
}
if (!tags$1.length) return 0;
let name$1 = tagStr.replace(/ /g, "_"),
key = name$1 + " " + tags$1.map(t$1 => t$1.id);
let known = byTag[key];
if (known) return known.id;
let type = byTag[key] = NodeType.define({
id: typeArray.length,
name: name$1,
props: [styleTags({
[name$1]: tags$1
})]
});
typeArray.push(type);
return type.id;
}
//#endregion
//#region ../../@n8n/codemirror-lang/src/expressions/grammar.ts
function n8nLang() {
return new LanguageSupport(n8nLanguage, [n8nLanguage.data.of(expressionCloseBracketsConfig), ...n8nCompletionSources().map(source => n8nLanguage.data.of(source))]);
}
function getErrorPosition(error, doc$2) {
let m;
if (m = error.message.match(/at position (\d+)/)) return Math.min(+m[1], doc$2.length);
if (m = error.message.match(/at line (\d+) column (\d+)/)) return Math.min(doc$2.line(+m[1]).from + +m[2] - 1, doc$2.length);
return 0;
}
/**
A language provider that provides JSON parsing.
*/
/**
JSON language support.
*/
function json() {
return new LanguageSupport(jsonLanguage);
}
//#endregion
//#region ~icons/mdi/close
function render(_ctx, _cache) {
return openBlock(), createElementBlock("svg", _hoisted_1$9, _cache[0] || (_cache[0] = [createBaseVNode("path", {
fill: "currentColor",
d: "M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12z"
}, null, -1)]));
}
_export({
$: completionStatus,
B: localCompletionSource,
Bt: tooltips,
C: dropInExpressionEditor,
Ct: styleTags,
Dt: parseMixed,
E: datatypeCompletions,
F: longestCommonPrefix,
Ft: highlightSpecialChars,
It: hoverTooltip,
J: autocompletion,
L: javascript,
M: autocompletableNodeNames,
Mt: dropCursor,
Nt: highlightActiveLine,
Pt: highlightActiveLineGutter,
Q: completeFromList,
Rt: lineNumbers,
S: dropInCodeEditor,
St: syntaxTree$1,
T: n8nCompletionSources,
Y: closeBrackets,
Zt: combineConfig$1,
_: lintGutter,
at: history,
bt: indentOnInput,
dt: continuedIndent,
et: ifNotIn,
ft: delimitedIndent,
ht: foldInside,
jt: drawSelection,
mt: foldGutter,
p: n8nLang,
pt: ensureSyntaxTree,
rt: snippetCompletion,
tt: insertCompletionText,
u: json,
ut: bracketMatching,
v: linter,
vt: getIndentUnit,
w: mappingDropCursor,
xt: syntaxHighlighting,
y: highlightSelectionMatches,
Tt: void 0
});
return {
setters: [function (_chunkLegacy001Js) {
__toESM = _chunkLegacy001Js.o;
__commonJS = _chunkLegacy001Js.t;
}, function (_vueRuntimeEsmBundlerLegacy003Js) {
computed = _vueRuntimeEsmBundlerLegacy003Js.C;
toDisplayString = _vueRuntimeEsmBundlerLegacy003Js.Cn;
createElementBlock = _vueRuntimeEsmBundlerLegacy003Js.D;
createCommentVNode = _vueRuntimeEsmBundlerLegacy003Js.E;
unref = _vueRuntimeEsmBundlerLegacy003Js.Gt;
guardReactiveProps = _vueRuntimeEsmBundlerLegacy003Js.I;
ref = _vueRuntimeEsmBundlerLegacy003Js.It;
onBeforeUnmount = _vueRuntimeEsmBundlerLegacy003Js.J;
createVNode = _vueRuntimeEsmBundlerLegacy003Js.M;
defineAsyncComponent = _vueRuntimeEsmBundlerLegacy003Js.N;
defineComponent = _vueRuntimeEsmBundlerLegacy003Js.P;
createBlock = _vueRuntimeEsmBundlerLegacy003Js.T;
toRef = _vueRuntimeEsmBundlerLegacy003Js.Vt;
onMounted = _vueRuntimeEsmBundlerLegacy003Js.Z;
Fragment = _vueRuntimeEsmBundlerLegacy003Js._;
watch = _vueRuntimeEsmBundlerLegacy003Js._t;
renderSlot = _vueRuntimeEsmBundlerLegacy003Js.at;
withCtx = _vueRuntimeEsmBundlerLegacy003Js.bt;
openBlock = _vueRuntimeEsmBundlerLegacy003Js.et;
withModifiers = _vueRuntimeEsmBundlerLegacy003Js.h;
renderList = _vueRuntimeEsmBundlerLegacy003Js.it;
createTextVNode = _vueRuntimeEsmBundlerLegacy003Js.j;
createSlots = _vueRuntimeEsmBundlerLegacy003Js.k;
vShow = _vueRuntimeEsmBundlerLegacy003Js.p;
resolveDirective = _vueRuntimeEsmBundlerLegacy003Js.st;
normalizeClass = _vueRuntimeEsmBundlerLegacy003Js.vn;
createBaseVNode = _vueRuntimeEsmBundlerLegacy003Js.w;
withDirectives = _vueRuntimeEsmBundlerLegacy003Js.xt;
Suspense = _vueRuntimeEsmBundlerLegacy003Js.y;
normalizeProps = _vueRuntimeEsmBundlerLegacy003Js.yn;
}, function (_MapCacheLegacy005Js) {
I18nT = _MapCacheLegacy005Js._t;
require_isObject = _MapCacheLegacy005Js.c;
useI18n = _MapCacheLegacy005Js.gt;
computedAsync = _MapCacheLegacy005Js.h;
require_isArray = _MapCacheLegacy005Js.m;
i18n = _MapCacheLegacy005Js.pt;
}, function (_srcLegacy007Js) {
N8nBlockUi_default = _srcLegacy007Js.$;
N8nCallout_default = _srcLegacy007Js.Bn;
ElPagination = _srcLegacy007Js.Dt;
N8nInfoTip_default = _srcLegacy007Js.F;
N8nSelect_default = _srcLegacy007Js.G;
N8nButton_default = _srcLegacy007Js.Hn;
N8nOption_default = _srcLegacy007Js.K;
InlineAskAssistantButton_default = _srcLegacy007Js.L;
N8nRadioButtons_default = _srcLegacy007Js.S;
N8nSpinner_default = _srcLegacy007Js.Un;
N8nText_default = _srcLegacy007Js.Vn;
N8nIcon_default = _srcLegacy007Js.Wn;
N8nTabs_default = _srcLegacy007Js.g;
N8nTooltip_default = _srcLegacy007Js.mt;
N8nLink_default = _srcLegacy007Js.ut;
N8nIconButton_default = _srcLegacy007Js.xt;
}, function (_preloadHelperLegacy00dJs) {
__vitePreload = _preloadHelperLegacy00dJs.t;
}, function (_pluginVue_exportHelperLegacy00fJs) {
__plugin_vue_export_helper_default = _pluginVue_exportHelperLegacy00fJs.t;
}, function (_truncateLegacy00hJs) {
useRoute = _truncateLegacy00hJs.v;
useRouter = _truncateLegacy00hJs.y;
}, function (_emptyLegacy00vJs) {
process$1 = _emptyLegacy00vJs.C;
init_dist = _emptyLegacy00vJs.S;
}, function (_useTelemetryLegacy00HJs) {
escapeMappingString = _useTelemetryLegacy00HJs.$t;
searchInObject = _useTelemetryLegacy00HJs.Di;
useSourceControlStore = _useTelemetryLegacy00HJs.Dn;
CREDENTIAL_EDIT_MODAL_KEY = _useTelemetryLegacy00HJs.Do;
useUIStore = _useTelemetryLegacy00HJs.Fi;
parseAiContent = _useTelemetryLegacy00HJs.J;
dataPinningEventBus = _useTelemetryLegacy00HJs.Mi;
injectWorkflowState = _useTelemetryLegacy00HJs.Sn;
useStorage = _useTelemetryLegacy00HJs.Vo;
executionDataToJson = _useTelemetryLegacy00HJs.Vr;
useAIAssistantHelpers = _useTelemetryLegacy00HJs.Xt;
getGenericHints = _useTelemetryLegacy00HJs._;
useNDVStore = _useTelemetryLegacy00HJs.a;
useNodeTypesStore = _useTelemetryLegacy00HJs.at;
isPresent = _useTelemetryLegacy00HJs.bi;
useEnvironmentsStore = _useTelemetryLegacy00HJs.bn;
unwrapExpression = _useTelemetryLegacy00HJs.dn;
clearJsonKey = _useTelemetryLegacy00HJs.fi;
resolveParameter = _useTelemetryLegacy00HJs.fn;
usePostHog = _useTelemetryLegacy00HJs.i;
hasTrimmedRunData = _useTelemetryLegacy00HJs.nt;
useWorkflowsStore = _useTelemetryLegacy00HJs.o;
isPairedItemIntermediateNodesError = _useTelemetryLegacy00HJs.on;
useTelemetry = _useTelemetryLegacy00HJs.t;
isEmpty$1 = _useTelemetryLegacy00HJs.vi;
useNodeHelpers = _useTelemetryLegacy00HJs.xn;
}, function (_useToastLegacy00JJs) {
sanitizeHtml = _useToastLegacy00JJs.s;
useToast = _useToastLegacy00JJs.t;
}, function (_constantsLegacy00TJs) {
jsonParse = _constantsLegacy00TJs.Aa;
MAX_DISPLAY_DATA_SIZE_SCHEMA_VIEW = _constantsLegacy00TJs.Bs;
base64DecodeUTF8 = _constantsLegacy00TJs.Ea;
NODE_TYPES_EXCLUDED_FROM_OUTPUT_NAME_APPEND = _constantsLegacy00TJs.Fn;
DateTime = _constantsLegacy00TJs.Ga;
VIEWS = _constantsLegacy00TJs.Io;
RUN_DATA_DEFAULT_PAGE_SIZE = _constantsLegacy00TJs.J;
NodeConnectionTypes = _constantsLegacy00TJs.Ka;
LOCAL_STORAGE_PIN_DATA_DISCOVERY_CANVAS_FLAG = _constantsLegacy00TJs.Ms;
LOCAL_STORAGE_PIN_DATA_DISCOVERY_NDV_FLAG = _constantsLegacy00TJs.Ns;
CODEMIRROR_TOOLTIP_CONTAINER_ELEMENT_ID = _constantsLegacy00TJs.O;
isCommunityPackageName = _constantsLegacy00TJs.Oa;
EXTENSION_OBJECTS = _constantsLegacy00TJs.Oi;
MAX_DISPLAY_DATA_SIZE = _constantsLegacy00TJs.Rs;
validateFieldType = _constantsLegacy00TJs.Ta;
Expression = _constantsLegacy00TJs.Ti;
ViewableMimeTypes = _constantsLegacy00TJs.Xr;
parseErrorMetadata = _constantsLegacy00TJs._i;
require_isEqual = _constantsLegacy00TJs._o;
CORE_NODES_CATEGORY = _constantsLegacy00TJs._t;
require__baseKeys = _constantsLegacy00TJs.bo;
getConnectionTypes = _constantsLegacy00TJs.ea;
NATIVE_METHODS = _constantsLegacy00TJs.fi;
HTTP_REQUEST_NODE_TYPE = _constantsLegacy00TJs.hn;
NDV_UI_OVERHAUL_EXPERIMENT = _constantsLegacy00TJs.ic;
VALID_EMAIL_REGEX = _constantsLegacy00TJs.j;
DATA_PINNING_DOCS_URL = _constantsLegacy00TJs.m;
HTML_NODE_TYPE = _constantsLegacy00TJs.mn;
getNodeOutputs = _constantsLegacy00TJs.na;
NEW_ASSISTANT_SESSION_MODAL = _constantsLegacy00TJs.ns;
SPLIT_IN_BATCHES_NODE_TYPE = _constantsLegacy00TJs.or;
DATA_EDITING_DOCS_URL = _constantsLegacy00TJs.p;
require__getTag = _constantsLegacy00TJs.vo;
}, function (_mergeLegacy00VJs) {
require_isTypedArray = _mergeLegacy00VJs.C;
require_isBuffer = _mergeLegacy00VJs.O;
require_isArguments = _mergeLegacy00VJs.k;
require__isPrototype = _mergeLegacy00VJs.x;
require_isArrayLike = _mergeLegacy00VJs.y;
}, function (_assistantStoreLegacy00XJs) {
ndvEventBus = _assistantStoreLegacy00XJs.n;
useAssistantStore = _assistantStoreLegacy00XJs.t;
}, function (_baseOrderByLegacy00ZJs) {
storeToRefs = _baseOrderByLegacy00ZJs.A;
useRootStore = _baseOrderByLegacy00ZJs.r;
}, function (_useExternalHooksLegacy013Js) {
useExternalHooks = _useExternalHooksLegacy013Js.t;
}, function (_chatPanelStoreLegacy017Js) {
useChatPanelStore = _chatPanelStoreLegacy017Js.t;
}, function (_useRunWorkflowLegacy01pJs) {
useRunWorkflow = _useRunWorkflowLegacy01pJs.t;
}, function (_usePinnedDataLegacy01rJs) {
useNodeType = _usePinnedDataLegacy01rJs.n;
usePinnedData = _usePinnedDataLegacy01rJs.t;
}, function (_useClipboardLegacy01xJs) {
useClipboard = _useClipboardLegacy01xJs.t;
}, function (_NDVEmptyStateLegacy023Js) {
Cu = _NDVEmptyStateLegacy023Js.a;
Ln = _NDVEmptyStateLegacy023Js.i;
$d = _NDVEmptyStateLegacy023Js.n;
NDVEmptyState_default = _NDVEmptyStateLegacy023Js.t;
}, function (_externalSecretsEeStoreLegacy027Js) {
useExternalSecretsStore = _externalSecretsEeStoreLegacy027Js.t;
}, function (_uniqByLegacy029Js) {
require_uniqBy = _uniqByLegacy029Js.t;
}, function (_RunDataHtmlLegacy02nJs) {
RunDataHtml_default = _RunDataHtmlLegacy02nJs.t;
}, function (_schemaPreviewStoreLegacy02BJs) {
useSchemaPreviewStore = _schemaPreviewStoreLegacy02BJs.t;
}, function (_FileSaverMinLegacy02HJs) {
require_FileSaver_min = _FileSaverMinLegacy02HJs.t;
}, function (_vueJsonPrettyLegacy02JJs) {
P = _vueJsonPrettyLegacy02JJs.t;
}, function (_useExecutionHelpersLegacy02NJs) {
useExecutionHelpers = _useExecutionHelpersLegacy02NJs.t;
}],
execute: function () {
__vite_style__ = document.createElement('style');
__vite_style__.textContent = "/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._editor-container_uiiyw_123 {\n position: relative;\n}\n._fillHeight_uiiyw_127 {\n height: 100%;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._settingsHint_1m3ps_123 {\n background-color: var(--callout--color--background--info);\n border-radius: var(--radius);\n border: var(--border-width) var(--border-style);\n border-color: var(--callout--border-color--info);\n color: var(--callout--color--text--info);\n margin-top: var(--spacing--2xs);\n margin-bottom: var(--spacing--xs);\n margin-left: var(--spacing--sm);\n margin-right: var(--spacing--sm);\n padding: var(--spacing--xs);\n}\n._settingItem_1m3ps_136 {\n display: flex;\n align-items: flex-start;\n gap: var(--spacing--xs);\n}\n._settingItem_1m3ps_136:not(:last-child) {\n margin-bottom: var(--spacing--xs);\n}\n._iconWrapper_1m3ps_145 {\n display: flex;\n align-items: center;\n flex-shrink: 0;\n margin-top: 1px;\n}\n._icon_1m3ps_145 {\n color: var(--callout--icon-color--info);\n font-size: var(--font-size--sm);\n line-height: 1;\n}\n._message_1m3ps_158 {\n line-height: var(--line-height--md);\n flex: 1;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\nimg,\nvideo {\n max-height: 100%;\n max-width: 100%;\n}\n.binary-data.other, .binary-data.pdf {\n height: 100%;\n width: 100%;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n.binary-data-window {\n position: absolute;\n top: 0;\n left: 0;\n z-index: 10;\n width: 100%;\n height: 100%;\n background-color: var(--run-data--color--background);\n overflow: hidden;\n text-align: center;\n}\n.binary-data-window.json {\n overflow: auto;\n}\n.binary-data-window .binary-data-window-wrapper {\n margin-top: 0.5em;\n padding: 0 1em;\n height: 100%;\n}\n.binary-data-window .binary-data-window-wrapper .el-row,\n.binary-data-window .binary-data-window-wrapper .el-col {\n height: 100%;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n.node-error-view__header {\n margin: 0 auto var(--spacing--sm) auto;\n padding-bottom: var(--spacing--3xs);\n background-color: var(--color--background--light-3);\n border: 1px solid var(--color--foreground);\n border-radius: var(--radius--lg);\n}\n.node-error-view_compact .node-error-view__header {\n margin: 0 auto var(--spacing--2xs) auto;\n border-radius: var(--radius);\n}\n.node-error-view__header-title {\n padding: var(--spacing--2xs) var(--spacing--sm);\n border-bottom: 1px solid var(--color--danger--tint-3);\n font-size: var(--font-size--3xs);\n font-weight: var(--font-weight--medium);\n background-color: var(--color--danger--tint-4);\n border-radius: var(--radius--lg) var(--radius--lg) 0 0;\n color: var(--color--danger);\n}\n.node-error-view_compact .node-error-view__header-title {\n border-radius: var(--radius);\n}\n.node-error-view__header-message {\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: var(--spacing--xs);\n padding: var(--spacing--xs) var(--spacing--sm) var(--spacing--3xs) var(--spacing--sm);\n color: var(--color--danger);\n font-weight: var(--font-weight--medium);\n font-size: var(--font-size--sm);\n}\n.node-error-view__header-description {\n overflow: hidden;\n padding: 0 var(--spacing--sm) var(--spacing--3xs) var(--spacing--sm);\n font-size: var(--font-size--xs);\n}\n.node-error-view__header-description ul {\n padding: var(--spacing--sm) 0;\n padding-left: var(--spacing--lg);\n}\n.node-error-view__header-description code {\n font-size: var(--font-size--xs);\n color: var(--color--text);\n background: var(--color--background);\n padding: var(--spacing--5xs);\n border-radius: var(--radius);\n}\n.node-error-view__button {\n margin-left: var(--spacing--sm);\n margin-bottom: var(--spacing--xs);\n margin-top: var(--spacing--xs);\n flex-direction: row-reverse;\n}\n.node-error-view__button span {\n margin-right: var(--spacing--5xs);\n margin-left: var(--spacing--5xs);\n}\n.node-error-view__debugging {\n font-size: var(--font-size--sm);\n}\n.node-error-view__debugging ul,\n.node-error-view__debugging ol,\n.node-error-view__debugging dl {\n padding-left: var(--spacing--sm);\n margin-top: var(--spacing--2xs);\n margin-bottom: var(--spacing--2xs);\n}\n.node-error-view__debugging pre {\n padding: var(--spacing--sm);\n width: 100%;\n overflow: auto;\n background: var(--color--background--light-2);\n}\n.node-error-view__debugging pre code {\n font-size: var(--font-size--sm);\n}\n.node-error-view__feedback-toolbar {\n display: flex;\n align-items: center;\n margin-top: var(--spacing--sm);\n padding-top: var(--spacing--3xs);\n border-top: 1px solid var(--color--foreground);\n}\n.node-error-view__feedback-button {\n width: var(--spacing--2xl);\n height: var(--spacing--2xl);\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n}\n.node-error-view__feedback-button:hover {\n color: var(--color--primary);\n}\n.node-error-view__info {\n margin: 0 auto;\n border: 1px solid var(--color--foreground);\n border-radius: var(--radius--lg);\n}\n.node-error-view_compact .node-error-view__info {\n border-radius: var(--radius);\n}\n.node-error-view__info-header {\n display: flex;\n align-items: center;\n justify-content: space-between;\n padding: var(--spacing--3xs) var(--spacing--3xs) var(--spacing--3xs) var(--spacing--sm);\n border-bottom: 1px solid var(--color--foreground);\n}\n.node-error-view__info-title {\n font-size: var(--font-size--2xs);\n font-weight: var(--font-weight--bold);\n color: var(--color--text--shade-1);\n}\n.node-error-view__info-content {\n padding: var(--spacing--2xs) var(--spacing--sm);\n}\n.node-error-view__details:not(:last-child) {\n margin-bottom: var(--spacing--2xs);\n}\n.node-error-view__details[open] .node-error-view__details-icon {\n transform: rotate(90deg);\n transition: transform 0.3s ease;\n}\n.node-error-view__details-summary {\n padding: var(--spacing--5xs) 0;\n font-size: var(--font-size--2xs);\n color: var(--color--text--shade-1);\n cursor: pointer;\n list-style-type: none;\n outline: none;\n}\n.node-error-view__details-content {\n padding: var(--spacing--2xs) var(--spacing--sm);\n}\n.node-error-view__details-row {\n display: flex;\n padding: var(--spacing--4xs) 0;\n}\n.node-error-view__details-row:not(:first-child) {\n border-top: 1px solid var(--color--foreground);\n}\n.node-error-view__details-icon {\n margin-right: var(--spacing--xs);\n}\n.node-error-view__details-label {\n flex-grow: 0;\n flex-shrink: 0;\n width: 120px;\n color: var(--color--text);\n font-size: var(--font-size--2xs);\n}\n.node-error-view__details-value {\n flex: 1;\n overflow: hidden;\n margin-right: auto;\n color: var(--color--text);\n font-size: var(--font-size--2xs);\n word-wrap: break-word;\n}\n.node-error-view__details-value code {\n color: var(--json--string--color);\n white-space: normal;\n word-wrap: break-word;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._pinDataButton_12tk2_123 svg {\n transition: transform 0.3s ease;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._relatedExecutionInfo_1d0kf_123 {\n font-size: var(--font-size--sm);\n margin-left: var(--spacing--3xs);\n}\n._relatedExecutionInfo_1d0kf_123 svg {\n padding-bottom: var(--spacing--5xs);\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._itemsText_1uijj_123 {\n flex-shrink: 0;\n overflow: hidden;\n white-space: nowrap;\n text-overflow: ellipsis;\n color: var(--color--text--tint-1);\n font-size: var(--font-size--2xs);\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._pagination_1hlvz_123 {\n width: 100%;\n display: flex;\n justify-content: space-between;\n align-items: center;\n padding: 5px;\n overflow-y: hidden;\n flex-shrink: 0;\n flex-grow: 0;\n}\n._pageSizeSelector_1hlvz_134 {\n text-transform: capitalize;\n max-width: 150px;\n flex: 0 1 auto;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._component_1e3w0_123 {\n position: absolute;\n top: 0;\n left: 0;\n padding: 0 var(--ndv--spacing) var(--spacing--3xl) var(--ndv--spacing);\n right: 0;\n overflow-y: auto;\n line-height: var(--line-height--xl);\n word-break: normal;\n height: 100%;\n}\n._binaryIndex_1e3w0_135 {\n display: block;\n padding: var(--spacing--2xs);\n font-size: var(--font-size--2xs);\n}\n._binaryIndex_1e3w0_135 > * {\n display: inline-block;\n width: 30px;\n height: 30px;\n line-height: 30px;\n border-radius: var(--radius);\n text-align: center;\n background-color: var(--color--foreground--shade-2);\n font-weight: var(--font-weight--bold);\n color: var(--color--text--tint-3);\n}\n._binaryRow_1e3w0_152 {\n display: inline-flex;\n font-size: var(--font-size--2xs);\n}\n._binaryCell_1e3w0_157 {\n display: inline-block;\n width: 300px;\n overflow: hidden;\n background-color: var(--color--foreground--tint-2);\n margin-right: var(--ndv--spacing);\n margin-bottom: var(--ndv--spacing);\n border-radius: var(--radius);\n border: var(--border);\n padding: var(--ndv--spacing);\n}\n._binaryHeader_1e3w0_169 {\n color: var(--color--primary);\n font-weight: var(--font-weight--bold);\n font-size: 1.2em;\n padding-bottom: var(--spacing--2xs);\n margin-bottom: var(--spacing--2xs);\n border-bottom: 1px solid var(--color--text--tint-1);\n}\n._binaryButtonContainer_1e3w0_178 {\n margin-top: 1.5em;\n display: flex;\n flex-direction: row;\n justify-content: center;\n}\n._binaryButtonContainer_1e3w0_178 > * {\n flex-grow: 0;\n margin-right: var(--spacing--3xs);\n}\n._binaryValue_1e3w0_189 {\n white-space: initial;\n word-wrap: break-word;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n._infoIcon_1ykz7_123 {\n color: var(--color--foreground--shade-1);\n}\n._center_1ykz7_127 {\n display: flex;\n height: 100%;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n padding: var(--ndv--spacing) var(--ndv--spacing) var(--spacing--xl) var(--ndv--spacing);\n text-align: center;\n}\n._center_1ykz7_127 > * {\n max-width: 316px;\n margin-bottom: var(--spacing--2xs);\n}\n._container_1ykz7_141 {\n --ndv--spacing: var(--spacing--sm);\n position: relative;\n width: 100%;\n height: 100%;\n display: flex;\n flex-direction: column;\n}\n._pinnedDataCallout_1ykz7_150 {\n border-radius: inherit;\n border-bottom-right-radius: 0;\n border-top: 0;\n border-left: 0;\n border-right: 0;\n height: 40px;\n}\n._header_1ykz7_159 {\n display: flex;\n align-items: center;\n margin-bottom: var(--ndv--spacing);\n padding: var(--ndv--spacing) var(--spacing--3xs) 0 var(--ndv--spacing);\n position: relative;\n overflow-x: auto;\n overflow-y: hidden;\n min-height: calc(30px + var(--ndv--spacing));\n scrollbar-width: thin;\n container-type: inline-size;\n}\n._compact_1ykz7_171 ._header_1ykz7_159 {\n margin-bottom: var(--spacing--4xs);\n padding: var(--spacing--2xs);\n margin-bottom: 0;\n flex-shrink: 0;\n flex-grow: 0;\n min-height: auto;\n gap: var(--spacing--2xs);\n}\n._header_1ykz7_159 > *:first-child {\n flex-grow: 1;\n}\n._dataContainer_1ykz7_184 {\n position: relative;\n overflow-y: auto;\n height: 100%;\n}\n._dataDisplay_1ykz7_190 {\n position: absolute;\n top: 0;\n left: 0;\n padding: 0 var(--ndv--spacing) var(--spacing--3xl) var(--ndv--spacing);\n right: 0;\n overflow-y: auto;\n line-height: var(--line-height--xl);\n word-break: normal;\n height: 100%;\n}\n._compact_1ykz7_171 ._dataDisplay_1ykz7_190 {\n padding: 0 var(--spacing--2xs);\n}\n._inlineError_1ykz7_205 {\n line-height: var(--line-height--xl);\n padding-left: var(--ndv--spacing);\n padding-right: var(--ndv--spacing);\n padding-bottom: var(--ndv--spacing);\n}\n._outputs_1ykz7_212 {\n display: flex;\n flex-direction: column;\n gap: var(--ndv--spacing);\n padding-left: var(--ndv--spacing);\n padding-right: var(--ndv--spacing);\n padding-bottom: var(--ndv--spacing);\n}\n._compact_1ykz7_171 ._outputs_1ykz7_212 {\n padding-left: var(--spacing--2xs);\n padding-right: var(--spacing--2xs);\n padding-bottom: var(--spacing--2xs);\n font-size: var(--font-size--2xs);\n}\n._tabs_1ykz7_227 {\n display: flex;\n justify-content: space-between;\n align-items: center;\n min-height: 30px;\n --tabs--arrow-buttons--color: var(--run-data--color--background);\n}\n._itemsCount_1ykz7_235 {\n display: flex;\n align-items: center;\n gap: var(--spacing--2xs);\n padding-left: var(--ndv--spacing);\n padding-right: var(--ndv--spacing);\n padding-bottom: var(--ndv--spacing);\n flex-flow: wrap;\n}\n._ndv-v2_1ykz7_245 ._itemsCount_1ykz7_235 {\n padding-left: var(--spacing--xs);\n}\n._inputSelect_1ykz7_249 {\n padding-left: var(--ndv--spacing);\n padding-right: var(--ndv--spacing);\n padding-bottom: var(--ndv--spacing);\n}\n._runSelector_1ykz7_255 {\n display: flex;\n align-items: center;\n flex-flow: wrap;\n padding-left: var(--ndv--spacing);\n padding-right: var(--ndv--spacing);\n margin-bottom: var(--ndv--spacing);\n gap: var(--spacing--3xs);\n}\n._runSelector_1ykz7_255 .el-input--suffix .el-input__inner {\n padding-right: var(--spacing--lg);\n}\n._runSelectorInner_1ykz7_268 {\n display: flex;\n gap: var(--spacing--4xs);\n align-items: center;\n}\n._runSelectorSelect_1ykz7_274 {\n max-width: 205px;\n}\n._search_1ykz7_278 {\n margin-left: auto;\n}\n._displayModes_1ykz7_282 {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n flex-grow: 1;\n gap: var(--spacing--2xs);\n}\n._compact_1ykz7_171 ._displayModes_1ykz7_282 {\n /* let title text alone decide the height */\n height: 0;\n}\n._showActionsOnHover_1ykz7_293 ._displayModes_1ykz7_282 {\n /* Using opacity instead of visibility so that search input can get focused through keyboard shortcut */\n opacity: 0;\n}\n._showActionsOnHover_1ykz7_293 ._displayModes_1ykz7_282 .el-input__prefix {\n transition-duration: 0ms;\n}\n._showActionsOnHover_1ykz7_293:focus-within ._displayModes_1ykz7_282, ._showActionsOnHover_1ykz7_293:hover ._displayModes_1ykz7_282 {\n opacity: 1;\n}\n._tooltipContain_1ykz7_304 {\n max-width: 240px;\n}\n._spinner_1ykz7_308 {\n display: flex;\n justify-content: center;\n margin-bottom: var(--ndv--spacing);\n}\n._spinner_1ykz7_308 * {\n color: var(--color--primary);\n min-height: 40px;\n min-width: 40px;\n}\n._editMode_1ykz7_319 {\n height: 100%;\n display: flex;\n flex-direction: column;\n justify-content: stretch;\n padding-left: var(--ndv--spacing);\n padding-right: var(--ndv--spacing);\n}\n._editModeBody_1ykz7_328 {\n flex: 1 1 auto;\n max-height: 100%;\n width: 100%;\n overflow: auto;\n}\n._editModeFooter_1ykz7_335 {\n flex: 0 1 auto;\n display: flex;\n width: 100%;\n justify-content: space-between;\n align-items: center;\n padding-top: var(--ndv--spacing);\n padding-bottom: var(--ndv--spacing);\n}\n._editModeFooterInfotip_1ykz7_345 {\n display: flex;\n flex: 1;\n width: 100%;\n}\n._editModeActions_1ykz7_351 {\n display: flex;\n justify-content: flex-end;\n align-items: center;\n margin-left: var(--ndv--spacing);\n}\n._stretchVertically_1ykz7_358 {\n height: 100%;\n}\n._uiBlocker_1ykz7_362 {\n border-top-left-radius: 0;\n border-bottom-left-radius: 0;\n}\n._uiBlockerNdvV2_1ykz7_367 {\n border-radius: 0;\n}\n._hintCallout_1ykz7_371 {\n margin-bottom: var(--spacing--xs);\n margin-left: var(--ndv--spacing);\n margin-right: var(--ndv--spacing);\n}\n._compact_1ykz7_171 ._hintCallout_1ykz7_371 {\n margin: 0 var(--spacing--2xs) var(--spacing--2xs) var(--spacing--2xs);\n}\n._schema_1ykz7_380 {\n padding: 0 var(--ndv--spacing);\n}\n._messageSection_1ykz7_384 {\n display: flex;\n align-items: center;\n width: 100%;\n}\n._singleIcon_1ykz7_390 {\n flex-direction: row;\n align-items: center;\n}\n._multipleIcons_1ykz7_395 {\n flex-direction: column;\n align-items: flex-start;\n gap: var(--spacing--2xs, 8px);\n}\n._multipleIcons_1ykz7_395 ._iconStack_1ykz7_401 {\n margin-right: 0;\n margin-bottom: 0;\n}\n._iconStack_1ykz7_401 {\n display: flex;\n align-items: center;\n gap: var(--spacing--4xs, 4px);\n flex-shrink: 0;\n margin-right: var(--spacing--xs);\n}\n._icon_1ykz7_401 {\n color: var(--callout--icon-color--info);\n line-height: 1;\n font-size: var(--font-size--xs);\n}\n._compact_1ykz7_171 ._executingMessage_1ykz7_420 {\n color: var(--color--text--tint-1);\n}\n._resetCollapseButton_1ykz7_424 {\n color: var(--color--foreground--shade-2);\n}\n@container (max-width: 240px) {\n /* Hide title when the panel is too narrow */\n._compact_1ykz7_171:hover ._title_1ykz7_430 {\n visibility: hidden;\n width: 0;\n}\n}\n._ndv-v2_1ykz7_245,\n._compact_1ykz7_171 {\n --ndv--spacing: var(--spacing--2xs);\n}\n._dataSizeWarning_1ykz7_440 {\n padding: var(--spacing--sm) var(--spacing--md);\n text-align: center;\n display: flex;\n flex-direction: column;\n align-items: center;\n gap: var(--spacing--sm);\n}\n._warningActions_1ykz7_449 {\n display: flex;\n flex-direction: row;\n flex-wrap: wrap;\n justify-content: center;\n gap: var(--spacing--2xs);\n width: 100%;\n align-items: center;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n.run-data .code-node-editor[data-v-fdcfc7f7] {\n height: 100%;\n}/* BEM support Func\n -------------------------- */\n/* Transition\n-------------------------- */\n/* Color\n-------------------------- */\n/* Link\n-------------------------- */\n/* Border\n-------------------------- */\n/* Outline\n-------------------------- */\n/* Box shadow\n-------------------------- */\n/* Fill\n-------------------------- */\n/* Typography\n-------------------------- */\n/* z-index\n-------------------------- */\n/* Disable base\n-------------------------- */\n/* Icon\n-------------------------- */\n/* Checkbox\n-------------------------- */\n/* Radio\n-------------------------- */\n/* Select\n-------------------------- */\n/* Alert\n-------------------------- */\n/* MessageBox\n-------------------------- */\n/* Message\n-------------------------- */\n/* Notification\n-------------------------- */\n/* Input\n-------------------------- */\n/* Cascader\n-------------------------- */\n/* Group\n-------------------------- */\n/* Tab\n-------------------------- */\n/* Button\n-------------------------- */\n/* cascader\n-------------------------- */\n/* Switch\n-------------------------- */\n/* Dialog\n-------------------------- */\n/* Table\n-------------------------- */\n/* Pagination\n-------------------------- */\n/* Popup\n-------------------------- */\n/* Popover\n-------------------------- */\n/* Tooltip\n-------------------------- */\n/* Tag\n-------------------------- */\n/* Tree\n-------------------------- */\n/* Dropdown\n-------------------------- */\n/* Badge\n-------------------------- */\n/* Card\n--------------------------*/\n/* Slider\n--------------------------*/\n/* Steps\n--------------------------*/\n/* Menu\n--------------------------*/\n/* Rate\n--------------------------*/\n/* DatePicker\n--------------------------*/\n/* Loading\n--------------------------*/\n/* Scrollbar\n--------------------------*/\n/* Carousel\n--------------------------*/\n/* Collapse\n--------------------------*/\n/* Transfer\n--------------------------*/\n/* Header\n --------------------------*/\n/* Footer\n--------------------------*/\n/* Main\n--------------------------*/\n/* Timeline\n--------------------------*/\n/* Backtop\n--------------------------*/\n/* Link\n--------------------------*/\n/* Calendar\n--------------------------*/\n/* Form\n-------------------------- */\n/* Avatar\n--------------------------*/\n/* Break-point\n--------------------------*/\n/* Break-points\n -------------------------- */\n/* Scrollbar\n -------------------------- */\n/* Placeholder\n -------------------------- */\n/* BEM\n -------------------------- */\n[data-v-fdcfc7f7] .highlight {\n background-color: #f7dc55;\n color: black;\n border-radius: var(--radius);\n padding: 0 1px;\n font-weight: var(--font-weight--regular);\n font-style: normal;\n}/*$vite$:1*/";
document.head.appendChild(__vite_style__);
//#region ../../../node_modules/.pnpm/@codemirror+state@6.4.1/node_modules/@codemirror/state/dist/index.js
/**
The data structure for documents. @nonabstract
*/
_export("Xt", Text = class Text {
/**
Get the line description around the given position.
*/
lineAt(pos) {
if (pos < 0 || pos > this.length) throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
return this.lineInner(pos, false, 1, 0);
}
/**
Get the description for the given (1-based) line number.
*/
line(n) {
if (n < 1 || n > this.lines) throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
return this.lineInner(n, true, 1, 0);
}
/**
Replace a range of the text with the given content.
*/
replace(from, to, text) {
[from, to] = clip$1(this, from, to);
let parts = [];
this.decompose(0, from, parts, 2);
if (text.length) text.decompose(0, text.length, parts, 3);
this.decompose(to, this.length, parts, 1);
return TextNode$1.from(parts, this.length - (to - from) + text.length);
}
/**
Append another document to this one.
*/
append(other) {
return this.replace(this.length, this.length, other);
}
/**
Retrieve the text between the given points.
*/
slice(from, to = this.length) {
[from, to] = clip$1(this, from, to);
let parts = [];
this.decompose(from, to, parts, 0);
return TextNode$1.from(parts, to - from);
}
/**
Test whether this text is equal to another instance.
*/
eq(other) {
if (other == this) return true;
if (other.length != this.length || other.lines != this.lines) return false;
let start = this.scanIdentical(other, 1),
end = this.length - this.scanIdentical(other, -1);
let a = new RawTextCursor$1(this),
b = new RawTextCursor$1(other);
for (let skip = start, pos = start;;) {
a.next(skip);
b.next(skip);
skip = 0;
if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) return false;
pos += a.value.length;
if (a.done || pos >= end) return true;
}
}
/**
Iterate over the text. When `dir` is `-1`, iteration happens
from end to start. This will return lines and the breaks between
them as separate strings.
*/
iter(dir = 1) {
return new RawTextCursor$1(this, dir);
}
/**
Iterate over a range of the text. When `from` > `to`, the
iterator will run in reverse.
*/
iterRange(from, to = this.length) {
return new PartialTextCursor$1(this, from, to);
}
/**
Return a cursor that iterates over the given range of lines,
_without_ returning the line breaks between, and yielding empty
strings for empty lines.
When `from` and `to` are given, they should be 1-based line numbers.
*/
iterLines(from, to) {
let inner;
if (from == null) inner = this.iter();else {
if (to == null) to = this.lines + 1;
let start = this.line(from).from;
inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
}
return new LineCursor$1(inner);
}
/**
Return the document as a string, using newline characters to
separate lines.
*/
toString() {
return this.sliceString(0);
}
/**
Convert the document to an array of lines (which can be
deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
*/
toJSON() {
let lines = [];
this.flatten(lines);
return lines;
}
/**
@internal
*/
constructor() {}
/**
Create a `Text` instance for the given array of lines.
*/
static of(text) {
if (text.length == 0) throw new RangeError("A document must have at least one line");
if (text.length == 1 && !text[0]) return Text.empty;
return text.length <= 32 ? new TextLeaf$1(text) : TextNode$1.from(TextLeaf$1.split(text, []));
}
});
TextLeaf$1 = class TextLeaf$1 extends Text {
constructor(text, length = textLength$1(text)) {
super();
this.text = text;
this.length = length;
}
get lines() {
return this.text.length;
}
get children() {
return null;
}
lineInner(target, isLine, line, offset) {
for (let i$1 = 0;; i$1++) {
let string$1 = this.text[i$1],
end = offset + string$1.length;
if ((isLine ? line : end) >= target) return new Line$1(offset, end, line, string$1);
offset = end + 1;
line++;
}
}
decompose(from, to, target, open) {
let text = from <= 0 && to >= this.length ? this : new TextLeaf$1(sliceText$1(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
if (open & 1) {
let prev = target.pop();
let joined = appendText$1(text.text, prev.text.slice(), 0, text.length);
if (joined.length <= 32) target.push(new TextLeaf$1(joined, prev.length + text.length));else {
let mid = joined.length >> 1;
target.push(new TextLeaf$1(joined.slice(0, mid)), new TextLeaf$1(joined.slice(mid)));
}
} else target.push(text);
}
replace(from, to, text) {
if (!(text instanceof TextLeaf$1)) return super.replace(from, to, text);
[from, to] = clip$1(this, from, to);
let lines = appendText$1(this.text, appendText$1(text.text, sliceText$1(this.text, 0, from)), to);
let newLen = this.length + text.length - (to - from);
if (lines.length <= 32) return new TextLeaf$1(lines, newLen);
return TextNode$1.from(TextLeaf$1.split(lines, []), newLen);
}
sliceString(from, to = this.length, lineSep = "\n") {
[from, to] = clip$1(this, from, to);
let result = "";
for (let pos = 0, i$1 = 0; pos <= to && i$1 < this.text.length; i$1++) {
let line = this.text[i$1],
end = pos + line.length;
if (pos > from && i$1) result += lineSep;
if (from < end && to > pos) result += line.slice(Math.max(0, from - pos), to - pos);
pos = end + 1;
}
return result;
}
flatten(target) {
for (let line of this.text) target.push(line);
}
scanIdentical() {
return 0;
}
static split(text, target) {
let part = [],
len = -1;
for (let line of text) {
part.push(line);
len += line.length + 1;
if (part.length == 32) {
target.push(new TextLeaf$1(part, len));
part = [];
len = -1;
}
}
if (len > -1) target.push(new TextLeaf$1(part, len));
return target;
}
};
TextNode$1 = class TextNode$1 extends Text {
constructor(children, length) {
super();
this.children = children;
this.length = length;
this.lines = 0;
for (let child of children) this.lines += child.lines;
}
lineInner(target, isLine, line, offset) {
for (let i$1 = 0;; i$1++) {
let child = this.children[i$1],
end = offset + child.length,
endLine = line + child.lines - 1;
if ((isLine ? endLine : end) >= target) return child.lineInner(target, isLine, line, offset);
offset = end + 1;
line = endLine + 1;
}
}
decompose(from, to, target, open) {
for (let i$1 = 0, pos = 0; pos <= to && i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (from <= end && to >= pos) {
let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0));
if (pos >= from && end <= to && !childOpen) target.push(child);else child.decompose(from - pos, to - pos, target, childOpen);
}
pos = end + 1;
}
}
replace(from, to, text) {
[from, to] = clip$1(this, from, to);
if (text.lines < this.lines) for (let i$1 = 0, pos = 0; i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (from >= pos && to <= end) {
let updated = child.replace(from - pos, to - pos, text);
let totalLines = this.lines - child.lines + updated.lines;
if (updated.lines < totalLines >> 4 && updated.lines > totalLines >> 6) {
let copy = this.children.slice();
copy[i$1] = updated;
return new TextNode$1(copy, this.length - (to - from) + text.length);
}
return super.replace(pos, end, updated);
}
pos = end + 1;
}
return super.replace(from, to, text);
}
sliceString(from, to = this.length, lineSep = "\n") {
[from, to] = clip$1(this, from, to);
let result = "";
for (let i$1 = 0, pos = 0; i$1 < this.children.length && pos <= to; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (pos > from && i$1) result += lineSep;
if (from < end && to > pos) result += child.sliceString(from - pos, to - pos, lineSep);
pos = end + 1;
}
return result;
}
flatten(target) {
for (let child of this.children) child.flatten(target);
}
scanIdentical(other, dir) {
if (!(other instanceof TextNode$1)) return 0;
let length = 0;
let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1];
for (;; iA += dir, iB += dir) {
if (iA == eA || iB == eB) return length;
let chA = this.children[iA],
chB = other.children[iB];
if (chA != chB) return length + chA.scanIdentical(chB, dir);
length += chA.length + 1;
}
}
static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
let lines = 0;
for (let ch of children) lines += ch.lines;
if (lines < 32) {
let flat = [];
for (let ch of children) ch.flatten(flat);
return new TextLeaf$1(flat, length);
}
let chunk = Math.max(32, lines >> 5),
maxChunk = chunk << 1,
minChunk = chunk >> 1;
let chunked = [],
currentLines = 0,
currentLen = -1,
currentChunk = [];
function add$1(child) {
let last;
if (child.lines > maxChunk && child instanceof TextNode$1) for (let node of child.children) add$1(node);else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
flush();
chunked.push(child);
} else if (child instanceof TextLeaf$1 && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf$1 && child.lines + last.lines <= 32) {
currentLines += child.lines;
currentLen += child.length + 1;
currentChunk[currentChunk.length - 1] = new TextLeaf$1(last.text.concat(child.text), last.length + 1 + child.length);
} else {
if (currentLines + child.lines > chunk) flush();
currentLines += child.lines;
currentLen += child.length + 1;
currentChunk.push(child);
}
}
function flush() {
if (currentLines == 0) return;
chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode$1.from(currentChunk, currentLen));
currentLen = -1;
currentLines = currentChunk.length = 0;
}
for (let child of children) add$1(child);
flush();
return chunked.length == 1 ? chunked[0] : new TextNode$1(chunked, length);
}
};
Text.empty = /* @__PURE__ */new TextLeaf$1([""], 0);
RawTextCursor$1 = class {
constructor(text, dir = 1) {
this.dir = dir;
this.done = false;
this.lineBreak = false;
this.value = "";
this.nodes = [text];
this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf$1 ? text.text.length : text.children.length) << 1];
}
nextInner(skip, dir) {
this.done = this.lineBreak = false;
for (;;) {
let last = this.nodes.length - 1;
let top$1 = this.nodes[last],
offsetValue = this.offsets[last],
offset = offsetValue >> 1;
let size = top$1 instanceof TextLeaf$1 ? top$1.text.length : top$1.children.length;
if (offset == (dir > 0 ? size : 0)) {
if (last == 0) {
this.done = true;
this.value = "";
return this;
}
if (dir > 0) this.offsets[last - 1]++;
this.nodes.pop();
this.offsets.pop();
} else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
this.offsets[last] += dir;
if (skip == 0) {
this.lineBreak = true;
this.value = "\n";
return this;
}
skip--;
} else if (top$1 instanceof TextLeaf$1) {
let next = top$1.text[offset + (dir < 0 ? -1 : 0)];
this.offsets[last] += dir;
if (next.length > Math.max(0, skip)) {
this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
return this;
}
skip -= next.length;
} else {
let next = top$1.children[offset + (dir < 0 ? -1 : 0)];
if (skip > next.length) {
skip -= next.length;
this.offsets[last] += dir;
} else {
if (dir < 0) this.offsets[last]--;
this.nodes.push(next);
this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf$1 ? next.text.length : next.children.length) << 1);
}
}
}
}
next(skip = 0) {
if (skip < 0) {
this.nextInner(-skip, -this.dir);
skip = this.value.length;
}
return this.nextInner(skip, this.dir);
}
};
PartialTextCursor$1 = class {
constructor(text, start, end) {
this.value = "";
this.done = false;
this.cursor = new RawTextCursor$1(text, start > end ? -1 : 1);
this.pos = start > end ? text.length : 0;
this.from = Math.min(start, end);
this.to = Math.max(start, end);
}
nextInner(skip, dir) {
if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
this.value = "";
this.done = true;
return this;
}
skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
if (skip > limit) skip = limit;
limit -= skip;
let {
value
} = this.cursor.next(skip);
this.pos += (value.length + skip) * dir;
this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
this.done = !this.value;
return this;
}
next(skip = 0) {
if (skip < 0) skip = Math.max(skip, this.from - this.pos);else if (skip > 0) skip = Math.min(skip, this.to - this.pos);
return this.nextInner(skip, this.cursor.dir);
}
get lineBreak() {
return this.cursor.lineBreak && this.value != "";
}
};
LineCursor$1 = class {
constructor(inner) {
this.inner = inner;
this.afterBreak = true;
this.value = "";
this.done = false;
}
next(skip = 0) {
let {
done,
lineBreak,
value
} = this.inner.next(skip);
if (done && this.afterBreak) {
this.value = "";
this.afterBreak = false;
} else if (done) {
this.done = true;
this.value = "";
} else if (lineBreak) {
if (this.afterBreak) this.value = "";else {
this.afterBreak = true;
this.next();
}
} else {
this.value = value;
this.afterBreak = false;
}
return this;
}
get lineBreak() {
return false;
}
};
if (typeof Symbol != "undefined") {
Text.prototype[Symbol.iterator] = function () {
return this.iter();
};
RawTextCursor$1.prototype[Symbol.iterator] = PartialTextCursor$1.prototype[Symbol.iterator] = LineCursor$1.prototype[Symbol.iterator] = function () {
return this;
};
}
/**
This type describes a line in the document. It is created
on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
*/
Line$1 = class {
/**
@internal
*/
constructor(from, to, number$1, text) {
this.from = from;
this.to = to;
this.number = number$1;
this.text = text;
}
/**
The length of the line (not including any line break after it).
*/
get length() {
return this.to - this.from;
}
};
extend$1 = /* @__PURE__ */"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1);
for (let i$1 = 1; i$1 < extend$1.length; i$1++) extend$1[i$1] += extend$1[i$1 - 1];
ZWJ$1 = 8205;
DefaultSplit$1 = /\r\n?|\n/;
/**
Distinguishes different ways in which positions can be mapped.
*/
MapMode = /* @__PURE__ */function (MapMode$2) {
/**
Map a position to a valid new position, even when its context
was deleted.
*/
MapMode$2[MapMode$2["Simple"] = 0] = "Simple";
/**
Return null if deletion happens across the position.
*/
MapMode$2[MapMode$2["TrackDel"] = 1] = "TrackDel";
/**
Return null if the character _before_ the position is deleted.
*/
MapMode$2[MapMode$2["TrackBefore"] = 2] = "TrackBefore";
/**
Return null if the character _after_ the position is deleted.
*/
MapMode$2[MapMode$2["TrackAfter"] = 3] = "TrackAfter";
return MapMode$2;
}(MapMode || (MapMode = {}));
/**
A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
that doesn't store the inserted text. As such, it can't be
applied, but is cheaper to store and manipulate.
*/
ChangeDesc$1 = class ChangeDesc$1 {
/**
@internal
*/
constructor(sections) {
this.sections = sections;
}
/**
The length of the document before the change.
*/
get length() {
let result = 0;
for (let i$1 = 0; i$1 < this.sections.length; i$1 += 2) result += this.sections[i$1];
return result;
}
/**
The length of the document after the change.
*/
get newLength() {
let result = 0;
for (let i$1 = 0; i$1 < this.sections.length; i$1 += 2) {
let ins = this.sections[i$1 + 1];
result += ins < 0 ? this.sections[i$1] : ins;
}
return result;
}
/**
False when there are actual changes in this set.
*/
get empty() {
return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
}
/**
Iterate over the unchanged parts left by these changes. `posA`
provides the position of the range in the old document, `posB`
the new position in the changed document.
*/
iterGaps(f) {
for (let i$1 = 0, posA = 0, posB = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++];
if (ins < 0) {
f(posA, posB, len);
posB += len;
} else posB += ins;
posA += len;
}
}
/**
Iterate over the ranges changed by these changes. (See
[`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
variant that also provides you with the inserted text.)
`fromA`/`toA` provides the extent of the change in the starting
document, `fromB`/`toB` the extent of the replacement in the
changed document.
When `individual` is true, adjacent changes (which are kept
separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
reported separately.
*/
iterChangedRanges(f, individual = false) {
iterChanges$1(this, f, individual);
}
/**
Get a description of the inverted form of these changes.
*/
get invertedDesc() {
let sections = [];
for (let i$1 = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++];
if (ins < 0) sections.push(len, ins);else sections.push(ins, len);
}
return new ChangeDesc$1(sections);
}
/**
Compute the combined effect of applying another set of changes
after this one. The length of the document after this set should
match the length before `other`.
*/
composeDesc(other) {
return this.empty ? other : other.empty ? this : composeSets$1(this, other);
}
/**
Map this description, which should start with the same document
as `other`, over another set of changes, so that it can be
applied after it. When `before` is true, map as if the changes
in `other` happened before the ones in `this`.
*/
mapDesc(other, before = false) {
return other.empty ? this : mapSet$1(this, other, before);
}
mapPos(pos, assoc = -1, mode = MapMode.Simple) {
let posA = 0,
posB = 0;
for (let i$1 = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++],
endA = posA + len;
if (ins < 0) {
if (endA > pos) return posB + (pos - posA);
posB += len;
} else {
if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos)) return null;
if (endA > pos || endA == pos && assoc < 0 && !len) return pos == posA || assoc < 0 ? posB : posB + ins;
posB += ins;
}
posA = endA;
}
if (pos > posA) throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
return posB;
}
/**
Check whether these changes touch a given range. When one of the
changes entirely covers the range, the string `"cover"` is
returned.
*/
touchesRange(from, to = from) {
for (let i$1 = 0, pos = 0; i$1 < this.sections.length && pos <= to;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++],
end = pos + len;
if (ins >= 0 && pos <= to && end >= from) return pos < from && end > to ? "cover" : true;
pos = end;
}
return false;
}
/**
@internal
*/
toString() {
let result = "";
for (let i$1 = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++];
result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
}
return result;
}
/**
Serialize this change desc to a JSON-representable value.
*/
toJSON() {
return this.sections;
}
/**
Create a change desc from its JSON representation (as produced
by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
*/
static fromJSON(json$1) {
if (!Array.isArray(json$1) || json$1.length % 2 || json$1.some(a => typeof a != "number")) throw new RangeError("Invalid JSON representation of ChangeDesc");
return new ChangeDesc$1(json$1);
}
/**
@internal
*/
static create(sections) {
return new ChangeDesc$1(sections);
}
};
/**
A change set represents a group of modifications to a document. It
stores the document length, and can only be applied to documents
with exactly that length.
*/
ChangeSet = class ChangeSet extends ChangeDesc$1 {
constructor(sections, inserted) {
super(sections);
this.inserted = inserted;
}
/**
Apply the changes to a document, returning the modified
document.
*/
apply(doc$2) {
if (this.length != doc$2.length) throw new RangeError("Applying change set to a document with the wrong length");
iterChanges$1(this, (fromA, toA, fromB, _toB, text) => doc$2 = doc$2.replace(fromB, fromB + (toA - fromA), text), false);
return doc$2;
}
mapDesc(other, before = false) {
return mapSet$1(this, other, before, true);
}
/**
Given the document as it existed _before_ the changes, return a
change set that represents the inverse of this set, which could
be used to go from the document created by the changes back to
the document as it existed before the changes.
*/
invert(doc$2) {
let sections = this.sections.slice(),
inserted = [];
for (let i$1 = 0, pos = 0; i$1 < sections.length; i$1 += 2) {
let len = sections[i$1],
ins = sections[i$1 + 1];
if (ins >= 0) {
sections[i$1] = ins;
sections[i$1 + 1] = len;
let index = i$1 >> 1;
while (inserted.length < index) inserted.push(Text.empty);
inserted.push(len ? doc$2.slice(pos, pos + len) : Text.empty);
}
pos += len;
}
return new ChangeSet(sections, inserted);
}
/**
Combine two subsequent change sets into a single set. `other`
must start in the document produced by `this`. If `this` goes
`docA` → `docB` and `other` represents `docB` → `docC`, the
returned value will represent the change `docA` → `docC`.
*/
compose(other) {
return this.empty ? other : other.empty ? this : composeSets$1(this, other, true);
}
/**
Given another change set starting in the same document, maps this
change set over the other, producing a new change set that can be
applied to the document produced by applying `other`. When
`before` is `true`, order changes as if `this` comes before
`other`, otherwise (the default) treat `other` as coming first.
Given two changes `A` and `B`, `A.compose(B.map(A))` and
`B.compose(A.map(B, true))` will produce the same document. This
provides a basic form of [operational
transformation](https://en.wikipedia.org/wiki/Operational_transformation),
and can be used for collaborative editing.
*/
map(other, before = false) {
return other.empty ? this : mapSet$1(this, other, before, true);
}
/**
Iterate over the changed ranges in the document, calling `f` for
each, with the range in the original document (`fromA`-`toA`)
and the range that replaces it in the new document
(`fromB`-`toB`).
When `individual` is true, adjacent changes are reported
separately.
*/
iterChanges(f, individual = false) {
iterChanges$1(this, f, individual);
}
/**
Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
set.
*/
get desc() {
return ChangeDesc$1.create(this.sections);
}
/**
@internal
*/
filter(ranges) {
let resultSections = [],
resultInserted = [],
filteredSections = [];
let iter = new SectionIter$1(this);
done: for (let i$1 = 0, pos = 0;;) {
let next = i$1 == ranges.length ? 1e9 : ranges[i$1++];
while (pos < next || pos == next && iter.len == 0) {
if (iter.done) break done;
let len = Math.min(iter.len, next - pos);
addSection$1(filteredSections, len, -1);
let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
addSection$1(resultSections, len, ins);
if (ins > 0) addInsert$1(resultInserted, resultSections, iter.text);
iter.forward(len);
pos += len;
}
let end = ranges[i$1++];
while (pos < end) {
if (iter.done) break done;
let len = Math.min(iter.len, end - pos);
addSection$1(resultSections, len, -1);
addSection$1(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
iter.forward(len);
pos += len;
}
}
return {
changes: new ChangeSet(resultSections, resultInserted),
filtered: ChangeDesc$1.create(filteredSections)
};
}
/**
Serialize this change set to a JSON-representable value.
*/
toJSON() {
let parts = [];
for (let i$1 = 0; i$1 < this.sections.length; i$1 += 2) {
let len = this.sections[i$1],
ins = this.sections[i$1 + 1];
if (ins < 0) parts.push(len);else if (ins == 0) parts.push([len]);else parts.push([len].concat(this.inserted[i$1 >> 1].toJSON()));
}
return parts;
}
/**
Create a change set for the given changes, for a document of the
given length, using `lineSep` as line separator.
*/
static of(changes, length, lineSep) {
let sections = [],
inserted = [],
pos = 0;
let total = null;
function flush(force = false) {
if (!force && !sections.length) return;
if (pos < length) addSection$1(sections, length - pos, -1);
let set = new ChangeSet(sections, inserted);
total = total ? total.compose(set.map(total)) : set;
sections = [];
inserted = [];
pos = 0;
}
function process(spec) {
if (Array.isArray(spec)) for (let sub of spec) process(sub);else if (spec instanceof ChangeSet) {
if (spec.length != length) throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
flush();
total = total ? total.compose(spec.map(total)) : spec;
} else {
let {
from,
to = from,
insert: insert$2
} = spec;
if (from > to || from < 0 || to > length) throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
let insText = !insert$2 ? Text.empty : typeof insert$2 == "string" ? Text.of(insert$2.split(lineSep || DefaultSplit$1)) : insert$2;
let insLen = insText.length;
if (from == to && insLen == 0) return;
if (from < pos) flush();
if (from > pos) addSection$1(sections, from - pos, -1);
addSection$1(sections, to - from, insLen);
addInsert$1(inserted, sections, insText);
pos = to;
}
}
process(changes);
flush(!total);
return total;
}
/**
Create an empty changeset of the given length.
*/
static empty(length) {
return new ChangeSet(length ? [length, -1] : [], []);
}
/**
Create a changeset from its JSON representation (as produced by
[`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
*/
static fromJSON(json$1) {
if (!Array.isArray(json$1)) throw new RangeError("Invalid JSON representation of ChangeSet");
let sections = [],
inserted = [];
for (let i$1 = 0; i$1 < json$1.length; i$1++) {
let part = json$1[i$1];
if (typeof part == "number") sections.push(part, -1);else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i$2) => i$2 && typeof e != "string")) throw new RangeError("Invalid JSON representation of ChangeSet");else if (part.length == 1) sections.push(part[0], 0);else {
while (inserted.length < i$1) inserted.push(Text.empty);
inserted[i$1] = Text.of(part.slice(1));
sections.push(part[0], inserted[i$1].length);
}
}
return new ChangeSet(sections, inserted);
}
/**
@internal
*/
static createSet(sections, inserted) {
return new ChangeSet(sections, inserted);
}
};
SectionIter$1 = class {
constructor(set) {
this.set = set;
this.i = 0;
this.next();
}
next() {
let {
sections
} = this.set;
if (this.i < sections.length) {
this.len = sections[this.i++];
this.ins = sections[this.i++];
} else {
this.len = 0;
this.ins = -2;
}
this.off = 0;
}
get done() {
return this.ins == -2;
}
get len2() {
return this.ins < 0 ? this.len : this.ins;
}
get text() {
let {
inserted
} = this.set,
index = this.i - 2 >> 1;
return index >= inserted.length ? Text.empty : inserted[index];
}
textBit(len) {
let {
inserted
} = this.set,
index = this.i - 2 >> 1;
return index >= inserted.length && !len ? Text.empty : inserted[index].slice(this.off, len == null ? void 0 : this.off + len);
}
forward(len) {
if (len == this.len) this.next();else {
this.len -= len;
this.off += len;
}
}
forward2(len) {
if (this.ins == -1) this.forward(len);else if (len == this.ins) this.next();else {
this.ins -= len;
this.off += len;
}
}
};
/**
A single selection range. When
[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
multiple ranges. By default, selections hold exactly one range.
*/
SelectionRange$1 = class SelectionRange$1 {
constructor(from, to, flags) {
this.from = from;
this.to = to;
this.flags = flags;
}
/**
The anchor of the range—the side that doesn't move when you
extend it.
*/
get anchor() {
return this.flags & 32 ? this.to : this.from;
}
/**
The head of the range, which is moved when the range is
[extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
*/
get head() {
return this.flags & 32 ? this.from : this.to;
}
/**
True when `anchor` and `head` are at the same position.
*/
get empty() {
return this.from == this.to;
}
/**
If this is a cursor that is explicitly associated with the
character on one of its sides, this returns the side. -1 means
the character before its position, 1 the character after, and 0
means no association.
*/
get assoc() {
return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0;
}
/**
The bidirectional text level associated with this cursor, if
any.
*/
get bidiLevel() {
let level = this.flags & 7;
return level == 7 ? null : level;
}
/**
The goal column (stored vertical offset) associated with a
cursor. This is used to preserve the vertical position when
[moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
lines of different length.
*/
get goalColumn() {
let value = this.flags >> 6;
return value == 16777215 ? void 0 : value;
}
/**
Map this range through a change, producing a valid range in the
updated document.
*/
map(change, assoc = -1) {
let from, to;
if (this.empty) from = to = change.mapPos(this.from, assoc);else {
from = change.mapPos(this.from, 1);
to = change.mapPos(this.to, -1);
}
return from == this.from && to == this.to ? this : new SelectionRange$1(from, to, this.flags);
}
/**
Extend this range to cover at least `from` to `to`.
*/
extend(from, to = from) {
if (from <= this.anchor && to >= this.anchor) return EditorSelection.range(from, to);
let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
return EditorSelection.range(this.anchor, head);
}
/**
Compare this range to another range.
*/
eq(other, includeAssoc = false) {
return this.anchor == other.anchor && this.head == other.head && (!includeAssoc || !this.empty || this.assoc == other.assoc);
}
/**
Return a JSON-serializable object representing the range.
*/
toJSON() {
return {
anchor: this.anchor,
head: this.head
};
}
/**
Convert a JSON representation of a range to a `SelectionRange`
instance.
*/
static fromJSON(json$1) {
if (!json$1 || typeof json$1.anchor != "number" || typeof json$1.head != "number") throw new RangeError("Invalid JSON representation for SelectionRange");
return EditorSelection.range(json$1.anchor, json$1.head);
}
/**
@internal
*/
static create(from, to, flags) {
return new SelectionRange$1(from, to, flags);
}
};
/**
An editor selection holds one or more selection ranges.
*/
_export("Ut", EditorSelection = class EditorSelection {
constructor(ranges, mainIndex) {
this.ranges = ranges;
this.mainIndex = mainIndex;
}
/**
Map a selection through a change. Used to adjust the selection
position for changes.
*/
map(change, assoc = -1) {
if (change.empty) return this;
return EditorSelection.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
}
/**
Compare this selection to another selection. By default, ranges
are compared only by position. When `includeAssoc` is true,
cursor ranges must also have the same
[`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value.
*/
eq(other, includeAssoc = false) {
if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex) return false;
for (let i$1 = 0; i$1 < this.ranges.length; i$1++) if (!this.ranges[i$1].eq(other.ranges[i$1], includeAssoc)) return false;
return true;
}
/**
Get the primary selection range. Usually, you should make sure
your code applies to _all_ ranges, by using methods like
[`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
*/
get main() {
return this.ranges[this.mainIndex];
}
/**
Make sure the selection only has one range. Returns a selection
holding only the main range from this selection.
*/
asSingle() {
return this.ranges.length == 1 ? this : new EditorSelection([this.main], 0);
}
/**
Extend this selection with an extra range.
*/
addRange(range, main = true) {
return EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
}
/**
Replace a given range with another range, and then normalize the
selection to merge and sort ranges if necessary.
*/
replaceRange(range, which = this.mainIndex) {
let ranges = this.ranges.slice();
ranges[which] = range;
return EditorSelection.create(ranges, this.mainIndex);
}
/**
Convert this selection to an object that can be serialized to
JSON.
*/
toJSON() {
return {
ranges: this.ranges.map(r => r.toJSON()),
main: this.mainIndex
};
}
/**
Create a selection from a JSON representation.
*/
static fromJSON(json$1) {
if (!json$1 || !Array.isArray(json$1.ranges) || typeof json$1.main != "number" || json$1.main >= json$1.ranges.length) throw new RangeError("Invalid JSON representation for EditorSelection");
return new EditorSelection(json$1.ranges.map(r => SelectionRange$1.fromJSON(r)), json$1.main);
}
/**
Create a selection holding a single range.
*/
static single(anchor, head = anchor) {
return new EditorSelection([EditorSelection.range(anchor, head)], 0);
}
/**
Sort and merge the given set of ranges, creating a valid
selection.
*/
static create(ranges, mainIndex = 0) {
if (ranges.length == 0) throw new RangeError("A selection needs at least one range");
for (let pos = 0, i$1 = 0; i$1 < ranges.length; i$1++) {
let range = ranges[i$1];
if (range.empty ? range.from <= pos : range.from < pos) return EditorSelection.normalized(ranges.slice(), mainIndex);
pos = range.to;
}
return new EditorSelection(ranges, mainIndex);
}
/**
Create a cursor selection range at the given position. You can
safely ignore the optional arguments in most situations.
*/
static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
return SelectionRange$1.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) | (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6);
}
/**
Create a selection range.
*/
static range(anchor, head, goalColumn, bidiLevel) {
let flags = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
return head < anchor ? SelectionRange$1.create(head, anchor, 48 | flags) : SelectionRange$1.create(anchor, head, (head > anchor ? 8 : 0) | flags);
}
/**
@internal
*/
static normalized(ranges, mainIndex = 0) {
let main = ranges[mainIndex];
ranges.sort((a, b) => a.from - b.from);
mainIndex = ranges.indexOf(main);
for (let i$1 = 1; i$1 < ranges.length; i$1++) {
let range = ranges[i$1],
prev = ranges[i$1 - 1];
if (range.empty ? range.from <= prev.to : range.from < prev.to) {
let from = prev.from,
to = Math.max(range.to, prev.to);
if (i$1 <= mainIndex) mainIndex--;
ranges.splice(--i$1, 2, range.anchor > range.head ? EditorSelection.range(to, from) : EditorSelection.range(from, to));
}
}
return new EditorSelection(ranges, mainIndex);
}
});
nextID$1 = 0;
/**
A facet is a labeled value that is associated with an editor
state. It takes inputs from any number of extensions, and combines
those into a single output value.
Examples of uses of facets are the [tab
size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
Note that `Facet` instances can be used anywhere where
[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.
*/
_export("Gt", Facet$1 = class Facet$1 {
constructor(combine, compareInput, compare$2, isStatic, enables) {
this.combine = combine;
this.compareInput = compareInput;
this.compare = compare$2;
this.isStatic = isStatic;
/**
@internal
*/
this.id = nextID$1++;
this.default = combine([]);
this.extensions = typeof enables == "function" ? enables(this) : enables;
}
/**
Returns a facet reader for this facet, which can be used to
[read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
*/
get reader() {
return this;
}
/**
Define a new facet.
*/
static define(config$1 = {}) {
return new Facet$1(config$1.combine || (a => a), config$1.compareInput || ((a, b) => a === b), config$1.compare || (!config$1.combine ? sameArray$2 : (a, b) => a === b), !!config$1.static, config$1.enables);
}
/**
Returns an extension that adds the given value to this facet.
*/
of(value) {
return new FacetProvider$1([], this, 0, value);
}
/**
Create an extension that computes a value for the facet from a
state. You must take care to declare the parts of the state that
this value depends on, since your function is only called again
for a new state when one of those parts changed.
In cases where your value depends only on a single field, you'll
want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
*/
compute(deps, get) {
if (this.isStatic) throw new Error("Can't compute a static facet");
return new FacetProvider$1(deps, this, 1, get);
}
/**
Create an extension that computes zero or more values for this
facet from a state.
*/
computeN(deps, get) {
if (this.isStatic) throw new Error("Can't compute a static facet");
return new FacetProvider$1(deps, this, 2, get);
}
from(field, get) {
if (!get) get = x => x;
return this.compute([field], state => get(state.field(field)));
}
});
FacetProvider$1 = class {
constructor(dependencies, facet, type, value) {
this.dependencies = dependencies;
this.facet = facet;
this.type = type;
this.value = value;
this.id = nextID$1++;
}
dynamicSlot(addresses) {
var _a$2;
let getter = this.value;
let compare$2 = this.facet.compareInput;
let id$1 = this.id,
idx = addresses[id$1] >> 1,
multi = this.type == 2;
let depDoc = false,
depSel = false,
depAddrs = [];
for (let dep of this.dependencies) if (dep == "doc") depDoc = true;else if (dep == "selection") depSel = true;else if ((((_a$2 = addresses[dep.id]) !== null && _a$2 !== void 0 ? _a$2 : 1) & 1) == 0) depAddrs.push(addresses[dep.id]);
return {
create(state) {
state.values[idx] = getter(state);
return 1;
},
update(state, tr) {
if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll$1(state, depAddrs)) {
let newVal = getter(state);
if (multi ? !compareArray$1(newVal, state.values[idx], compare$2) : !compare$2(newVal, state.values[idx])) {
state.values[idx] = newVal;
return 1;
}
}
return 0;
},
reconfigure: (state, oldState) => {
let newVal,
oldAddr = oldState.config.address[id$1];
if (oldAddr != null) {
let oldVal = getAddr$1(oldState, oldAddr);
if (this.dependencies.every(dep => {
return dep instanceof Facet$1 ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField$1 ? oldState.field(dep, false) == state.field(dep, false) : true;
}) || (multi ? compareArray$1(newVal = getter(state), oldVal, compare$2) : compare$2(newVal = getter(state), oldVal))) {
state.values[idx] = oldVal;
return 0;
}
} else newVal = getter(state);
state.values[idx] = newVal;
return 1;
}
};
}
};
initField$1 = /* @__PURE__ */Facet$1.define({
static: true
});
/**
Fields can store additional information in an editor state, and
keep it in sync with the rest of the state.
*/
_export("Yt", StateField$1 = class StateField$1 {
constructor(id$1, createF, updateF, compareF, spec) {
this.id = id$1;
this.createF = createF;
this.updateF = updateF;
this.compareF = compareF;
this.spec = spec;
/**
@internal
*/
this.provides = void 0;
}
/**
Define a state field.
*/
static define(config$1) {
let field = new StateField$1(nextID$1++, config$1.create, config$1.update, config$1.compare || ((a, b) => a === b), config$1);
if (config$1.provide) field.provides = config$1.provide(field);
return field;
}
create(state) {
let init = state.facet(initField$1).find(i$1 => i$1.field == this);
return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
}
/**
@internal
*/
slot(addresses) {
let idx = addresses[this.id] >> 1;
return {
create: state => {
state.values[idx] = this.create(state);
return 1;
},
update: (state, tr) => {
let oldVal = state.values[idx];
let value = this.updateF(oldVal, tr);
if (this.compareF(oldVal, value)) return 0;
state.values[idx] = value;
return 1;
},
reconfigure: (state, oldState) => {
if (oldState.config.address[this.id] != null) {
state.values[idx] = oldState.field(this);
return 0;
}
state.values[idx] = this.create(state);
return 1;
}
};
}
/**
Returns an extension that enables this field and overrides the
way it is initialized. Can be useful when you need to provide a
non-default starting value for the field.
*/
init(create) {
return [this, initField$1.of({
field: this,
create
})];
}
/**
State field instances can be used as
[`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
given state.
*/
get extension() {
return this;
}
});
Prec_$1 = {
lowest: 4,
low: 3,
default: 2,
high: 1,
highest: 0
};
_export("Kt", Prec = {
highest: /* @__PURE__ */prec$1(Prec_$1.highest),
high: /* @__PURE__ */prec$1(Prec_$1.high),
default: /* @__PURE__ */prec$1(Prec_$1.default),
low: /* @__PURE__ */prec$1(Prec_$1.low),
lowest: /* @__PURE__ */prec$1(Prec_$1.lowest)
});
PrecExtension$1 = class {
constructor(inner, prec$2) {
this.inner = inner;
this.prec = prec$2;
}
};
/**
Extension compartments can be used to make a configuration
dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
configuration in a compartment, you can later
[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
transaction.
*/
_export("Ht", Compartment$1 = class Compartment$1 {
/**
Create an instance of this compartment to add to your [state
configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
*/
of(ext) {
return new CompartmentInstance$1(this, ext);
}
/**
Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
reconfigures this compartment.
*/
reconfigure(content$1) {
return Compartment$1.reconfigure.of({
compartment: this,
extension: content$1
});
}
/**
Get the current content of the compartment in the state, or
`undefined` if it isn't present.
*/
get(state) {
return state.config.compartments.get(this);
}
});
CompartmentInstance$1 = class {
constructor(compartment, inner) {
this.compartment = compartment;
this.inner = inner;
}
};
Configuration$1 = class Configuration$1 {
constructor(base$1, compartments, dynamicSlots, address, staticValues, facets) {
this.base = base$1;
this.compartments = compartments;
this.dynamicSlots = dynamicSlots;
this.address = address;
this.staticValues = staticValues;
this.facets = facets;
this.statusTemplate = [];
while (this.statusTemplate.length < dynamicSlots.length) this.statusTemplate.push(0);
}
staticFacet(facet) {
let addr = this.address[facet.id];
return addr == null ? facet.default : this.staticValues[addr >> 1];
}
static resolve(base$1, compartments, oldState) {
let fields = [];
let facets = Object.create(null);
let newCompartments = /* @__PURE__ */new Map();
for (let ext of flatten$1(base$1, compartments, newCompartments)) if (ext instanceof StateField$1) fields.push(ext);else (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
let address = Object.create(null);
let staticValues = [];
let dynamicSlots = [];
for (let field of fields) {
address[field.id] = dynamicSlots.length << 1;
dynamicSlots.push(a => field.slot(a));
}
let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
for (let id$1 in facets) {
let providers = facets[id$1],
facet = providers[0].facet;
let oldProviders = oldFacets && oldFacets[id$1] || [];
if (providers.every(p => p.type == 0)) {
address[facet.id] = staticValues.length << 1 | 1;
if (sameArray$2(oldProviders, providers)) staticValues.push(oldState.facet(facet));else {
let value = facet.combine(providers.map(p => p.value));
staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
}
} else {
for (let p of providers) if (p.type == 0) {
address[p.id] = staticValues.length << 1 | 1;
staticValues.push(p.value);
} else {
address[p.id] = dynamicSlots.length << 1;
dynamicSlots.push(a => p.dynamicSlot(a));
}
address[facet.id] = dynamicSlots.length << 1;
dynamicSlots.push(a => dynamicFacetSlot$1(a, facet, providers));
}
}
return new Configuration$1(base$1, newCompartments, dynamicSlots.map(f => f(address)), address, staticValues, facets);
}
};
languageData$1 = /* @__PURE__ */Facet$1.define();
allowMultipleSelections$1 = /* @__PURE__ */Facet$1.define({
combine: values => values.some(v => v),
static: true
});
lineSeparator$1 = /* @__PURE__ */Facet$1.define({
combine: values => values.length ? values[0] : void 0,
static: true
});
changeFilter$1 = /* @__PURE__ */Facet$1.define();
transactionFilter$1 = /* @__PURE__ */Facet$1.define();
transactionExtender$1 = /* @__PURE__ */Facet$1.define();
readOnly$1 = /* @__PURE__ */Facet$1.define({
combine: values => values.length ? values[0] : false
});
/**
Annotations are tagged values that are used to add metadata to
transactions in an extensible way. They should be used to model
things that effect the entire transaction (such as its [time
stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
_alongside_ the other changes made by the transaction, [state
effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
*/
_export("Vt", Annotation = class {
/**
@internal
*/
constructor(type, value) {
this.type = type;
this.value = value;
}
/**
Define a new type of annotation.
*/
static define() {
return new AnnotationType$1();
}
});
/**
Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
*/
AnnotationType$1 = class {
/**
Create an instance of this annotation.
*/
of(value) {
return new Annotation(this, value);
}
};
/**
Representation of a type of state effect. Defined with
[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
*/
StateEffectType$1 = class {
/**
@internal
*/
constructor(map) {
this.map = map;
}
/**
Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
type.
*/
of(value) {
return new StateEffect$1(this, value);
}
};
/**
State effects can be used to represent additional effects
associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
are often useful to model changes to custom [state
fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
document or selection changes.
*/
_export("Jt", StateEffect$1 = class StateEffect$1 {
/**
@internal
*/
constructor(type, value) {
this.type = type;
this.value = value;
}
/**
Map this effect through a position mapping. Will return
`undefined` when that ends up deleting the effect.
*/
map(mapping) {
let mapped = this.type.map(this.value, mapping);
return mapped === void 0 ? void 0 : mapped == this.value ? this : new StateEffect$1(this.type, mapped);
}
/**
Tells you whether this effect object is of a given
[type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
*/
is(type) {
return this.type == type;
}
/**
Define a new effect type. The type parameter indicates the type
of values that his effect holds. It should be a type that
doesn't include `undefined`, since that is used in
[mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
removed.
*/
static define(spec = {}) {
return new StateEffectType$1(spec.map || (v => v));
}
/**
Map an array of effects through a change set.
*/
static mapEffects(effects, mapping) {
if (!effects.length) return effects;
let result = [];
for (let effect of effects) {
let mapped = effect.map(mapping);
if (mapped) result.push(mapped);
}
return result;
}
});
/**
This effect can be used to reconfigure the root extensions of
the editor. Doing this will discard any extensions
[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
compartments.
*/
StateEffect$1.reconfigure = /* @__PURE__ */StateEffect$1.define();
/**
Append extensions to the top-level configuration of the editor.
*/
StateEffect$1.appendConfig = /* @__PURE__ */StateEffect$1.define();
/**
Changes to the editor state are grouped into transactions.
Typically, a user action creates a single transaction, which may
contain any number of document changes, may change the selection,
or have other effects. Create a transaction by calling
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
dispatch one by calling
[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
*/
Transaction = class Transaction {
constructor(startState, changes, selection, effects, annotations, scrollIntoView$3) {
this.startState = startState;
this.changes = changes;
this.selection = selection;
this.effects = effects;
this.annotations = annotations;
this.scrollIntoView = scrollIntoView$3;
/**
@internal
*/
this._doc = null;
/**
@internal
*/
this._state = null;
if (selection) checkSelection$1(selection, changes.newLength);
if (!annotations.some(a => a.type == Transaction.time)) this.annotations = annotations.concat(Transaction.time.of(Date.now()));
}
/**
@internal
*/
static create(startState, changes, selection, effects, annotations, scrollIntoView$3) {
return new Transaction(startState, changes, selection, effects, annotations, scrollIntoView$3);
}
/**
The new document produced by the transaction. Contrary to
[`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
force the entire new state to be computed right away, so it is
recommended that [transaction
filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
when they need to look at the new document.
*/
get newDoc() {
return this._doc || (this._doc = this.changes.apply(this.startState.doc));
}
/**
The new selection produced by the transaction. If
[`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
current selection through the changes made by the transaction.
*/
get newSelection() {
return this.selection || this.startState.selection.map(this.changes);
}
/**
The new state created by the transaction. Computed on demand
(but retained for subsequent access), so it is recommended not to
access it in [transaction
filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
*/
get state() {
if (!this._state) this.startState.applyTransaction(this);
return this._state;
}
/**
Get the value of the given annotation type, if any.
*/
annotation(type) {
for (let ann of this.annotations) if (ann.type == type) return ann.value;
}
/**
Indicates whether the transaction changed the document.
*/
get docChanged() {
return !this.changes.empty;
}
/**
Indicates whether this transaction reconfigures the state
(through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
with a top-level configuration
[effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
*/
get reconfigured() {
return this.startState.config != this.state.config;
}
/**
Returns true if the transaction has a [user
event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
or more specific than `event`. For example, if the transaction
has `"select.pointer"` as user event, `"select"` and
`"select.pointer"` will match it.
*/
isUserEvent(event) {
let e = this.annotation(Transaction.userEvent);
return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
}
};
/**
Annotation used to store transaction timestamps. Automatically
added to every transaction, holding `Date.now()`.
*/
Transaction.time = /* @__PURE__ */Annotation.define();
/**
Annotation used to associate a transaction with a user interface
event. Holds a string identifying the event, using a
dot-separated format to support attaching more specific
information. The events used by the core libraries are:
- `"input"` when content is entered
- `"input.type"` for typed input
- `"input.type.compose"` for composition
- `"input.paste"` for pasted input
- `"input.drop"` when adding content with drag-and-drop
- `"input.complete"` when autocompleting
- `"delete"` when the user deletes content
- `"delete.selection"` when deleting the selection
- `"delete.forward"` when deleting forward from the selection
- `"delete.backward"` when deleting backward from the selection
- `"delete.cut"` when cutting to the clipboard
- `"move"` when content is moved
- `"move.drop"` when content is moved within the editor through drag-and-drop
- `"select"` when explicitly changing the selection
- `"select.pointer"` when selecting with a mouse or other pointing device
- `"undo"` and `"redo"` for history actions
Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
whether the annotation matches a given event.
*/
Transaction.userEvent = /* @__PURE__ */Annotation.define();
/**
Annotation indicating whether a transaction should be added to
the undo history or not.
*/
Transaction.addToHistory = /* @__PURE__ */Annotation.define();
/**
Annotation indicating (when present and true) that a transaction
represents a change made by some other actor, not the user. This
is used, for example, to tag other people's changes in
collaborative editing.
*/
Transaction.remote = /* @__PURE__ */Annotation.define();
none$3 = [];
CharCategory = /* @__PURE__ */function (CharCategory$2) {
/**
Word characters.
*/
CharCategory$2[CharCategory$2["Word"] = 0] = "Word";
/**
Whitespace.
*/
CharCategory$2[CharCategory$2["Space"] = 1] = "Space";
/**
Anything else.
*/
CharCategory$2[CharCategory$2["Other"] = 2] = "Other";
return CharCategory$2;
}(CharCategory || (CharCategory = {}));
nonASCIISingleCaseWordChar$1 = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
try {
wordChar$1 = /* @__PURE__ */new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
} catch (_) {}
_export("Wt", EditorState = class EditorState {
constructor(config$1, doc$2, selection, values, computeSlot, tr) {
this.config = config$1;
this.doc = doc$2;
this.selection = selection;
this.values = values;
this.status = config$1.statusTemplate.slice();
this.computeSlot = computeSlot;
if (tr) tr._state = this;
for (let i$1 = 0; i$1 < this.config.dynamicSlots.length; i$1++) ensureAddr$1(this, i$1 << 1);
this.computeSlot = null;
}
field(field, require$1 = true) {
let addr = this.config.address[field.id];
if (addr == null) {
if (require$1) throw new RangeError("Field is not present in this state");
return;
}
ensureAddr$1(this, addr);
return getAddr$1(this, addr);
}
/**
Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
can be passed. Unless
[`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
[changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
are assumed to start in the _current_ document (not the document
produced by previous specs), and its
[selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
to the document created by its _own_ changes. The resulting
transaction contains the combined effect of all the different
specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
specs take precedence over earlier ones.
*/
update(...specs) {
return resolveTransaction$1(this, specs, true);
}
/**
@internal
*/
applyTransaction(tr) {
let conf = this.config,
{
base: base$1,
compartments
} = conf;
for (let effect of tr.effects) if (effect.is(Compartment$1.reconfigure)) {
if (conf) {
compartments = /* @__PURE__ */new Map();
conf.compartments.forEach((val, key) => compartments.set(key, val));
conf = null;
}
compartments.set(effect.value.compartment, effect.value.extension);
} else if (effect.is(StateEffect$1.reconfigure)) {
conf = null;
base$1 = effect.value;
} else if (effect.is(StateEffect$1.appendConfig)) {
conf = null;
base$1 = asArray$2(base$1).concat(effect.value);
}
let startValues;
if (!conf) {
conf = Configuration$1.resolve(base$1, compartments, this);
startValues = new EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null).values;
} else startValues = tr.startState.values.slice();
let selection = tr.startState.facet(allowMultipleSelections$1) ? tr.newSelection : tr.newSelection.asSingle();
new EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
}
/**
Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
replaces every selection range with the given content.
*/
replaceSelection(text) {
if (typeof text == "string") text = this.toText(text);
return this.changeByRange(range => ({
changes: {
from: range.from,
to: range.to,
insert: text
},
range: EditorSelection.cursor(range.from + text.length)
}));
}
/**
Create a set of changes and a new selection by running the given
function for each range in the active selection. The function
can return an optional set of changes (in the coordinate space
of the start document), plus an updated range (in the coordinate
space of the document produced by the call's own changes). This
method will merge all the changes and ranges into a single
changeset and selection, and return it as a [transaction
spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
[`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
*/
changeByRange(f) {
let sel = this.selection;
let result1 = f(sel.ranges[0]);
let changes = this.changes(result1.changes),
ranges = [result1.range];
let effects = asArray$2(result1.effects);
for (let i$1 = 1; i$1 < sel.ranges.length; i$1++) {
let result = f(sel.ranges[i$1]);
let newChanges = this.changes(result.changes),
newMapped = newChanges.map(changes);
for (let j = 0; j < i$1; j++) ranges[j] = ranges[j].map(newMapped);
let mapBy = changes.mapDesc(newChanges, true);
ranges.push(result.range.map(mapBy));
changes = changes.compose(newMapped);
effects = StateEffect$1.mapEffects(effects, newMapped).concat(StateEffect$1.mapEffects(asArray$2(result.effects), mapBy));
}
return {
changes,
selection: EditorSelection.create(ranges, sel.mainIndex),
effects
};
}
/**
Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
description, taking the state's document length and line
separator into account.
*/
changes(spec = []) {
if (spec instanceof ChangeSet) return spec;
return ChangeSet.of(spec, this.doc.length, this.facet(EditorState.lineSeparator));
}
/**
Using the state's [line
separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
[`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
*/
toText(string$1) {
return Text.of(string$1.split(this.facet(EditorState.lineSeparator) || DefaultSplit$1));
}
/**
Return the given range of the document as a string.
*/
sliceDoc(from = 0, to = this.doc.length) {
return this.doc.sliceString(from, to, this.lineBreak);
}
/**
Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
*/
facet(facet) {
let addr = this.config.address[facet.id];
if (addr == null) return facet.default;
ensureAddr$1(this, addr);
return getAddr$1(this, addr);
}
/**
Convert this state to a JSON-serializable object. When custom
fields should be serialized, you can pass them in as an object
mapping property names (in the resulting object, which should
not use `doc` or `selection`) to fields.
*/
toJSON(fields) {
let result = {
doc: this.sliceDoc(),
selection: this.selection.toJSON()
};
if (fields) for (let prop in fields) {
let value = fields[prop];
if (value instanceof StateField$1 && this.config.address[value.id] != null) result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
}
return result;
}
/**
Deserialize a state from its JSON representation. When custom
fields should be deserialized, pass the same object you passed
to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
third argument.
*/
static fromJSON(json$1, config$1 = {}, fields) {
if (!json$1 || typeof json$1.doc != "string") throw new RangeError("Invalid JSON representation for EditorState");
let fieldInit = [];
if (fields) {
for (let prop in fields) if (Object.prototype.hasOwnProperty.call(json$1, prop)) {
let field = fields[prop],
value = json$1[prop];
fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
}
}
return EditorState.create({
doc: json$1.doc,
selection: EditorSelection.fromJSON(json$1.selection),
extensions: config$1.extensions ? fieldInit.concat([config$1.extensions]) : fieldInit
});
}
/**
Create a new state. You'll usually only need this when
initializing an editor—updated states are created by applying
transactions.
*/
static create(config$1 = {}) {
let configuration = Configuration$1.resolve(config$1.extensions || [], /* @__PURE__ */new Map());
let doc$2 = config$1.doc instanceof Text ? config$1.doc : Text.of((config$1.doc || "").split(configuration.staticFacet(EditorState.lineSeparator) || DefaultSplit$1));
let selection = !config$1.selection ? EditorSelection.single(0) : config$1.selection instanceof EditorSelection ? config$1.selection : EditorSelection.single(config$1.selection.anchor, config$1.selection.head);
checkSelection$1(selection, doc$2.length);
if (!configuration.staticFacet(allowMultipleSelections$1)) selection = selection.asSingle();
return new EditorState(configuration, doc$2, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
}
/**
The size (in columns) of a tab in the document, determined by
the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
*/
get tabSize() {
return this.facet(EditorState.tabSize);
}
/**
Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
string for this state.
*/
get lineBreak() {
return this.facet(EditorState.lineSeparator) || "\n";
}
/**
Returns true when the editor is
[configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
*/
get readOnly() {
return this.facet(readOnly$1);
}
/**
Look up a translation for the given phrase (via the
[`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
original string if no translation is found.
If additional arguments are passed, they will be inserted in
place of markers like `$1` (for the first value) and `$2`, etc.
A single `$` is equivalent to `$1`, and `$$` will produce a
literal dollar sign.
*/
phrase(phrase$1, ...insert$2) {
for (let map of this.facet(EditorState.phrases)) if (Object.prototype.hasOwnProperty.call(map, phrase$1)) {
phrase$1 = map[phrase$1];
break;
}
if (insert$2.length) phrase$1 = phrase$1.replace(/\$(\$|\d*)/g, (m, i$1) => {
if (i$1 == "$") return "$";
let n = +(i$1 || 1);
return !n || n > insert$2.length ? m : insert$2[n - 1];
});
return phrase$1;
}
/**
Find the values for a given language data field, provided by the
the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
Examples of language data fields are...
- [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
comment syntax.
- [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
for providing language-specific completion sources.
- [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
characters that should be considered part of words in this
language.
- [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
bracket closing behavior.
*/
languageDataAt(name$1, pos, side = -1) {
let values = [];
for (let provider of this.facet(languageData$1)) for (let result of provider(this, pos, side)) if (Object.prototype.hasOwnProperty.call(result, name$1)) values.push(result[name$1]);
return values;
}
/**
Return a function that can categorize strings (expected to
represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
into one of:
- Word (contains an alphanumeric character or a character
explicitly listed in the local language's `"wordChars"`
language data, which should be a string)
- Space (contains only whitespace)
- Other (anything else)
*/
charCategorizer(at) {
return makeCategorizer$1(this.languageDataAt("wordChars", at).join(""));
}
/**
Find the word at the given position, meaning the range
containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
around it. If no word characters are adjacent to the position,
this returns null.
*/
wordAt(pos) {
let {
text,
from,
length
} = this.doc.lineAt(pos);
let cat = this.charCategorizer(pos);
let start = pos - from,
end = pos - from;
while (start > 0) {
let prev = findClusterBreak(text, start, false);
if (cat(text.slice(prev, start)) != CharCategory.Word) break;
start = prev;
}
while (end < length) {
let next = findClusterBreak(text, end);
if (cat(text.slice(end, next)) != CharCategory.Word) break;
end = next;
}
return start == end ? null : EditorSelection.range(start + from, end + from);
}
});
/**
A facet that, when enabled, causes the editor to allow multiple
ranges to be selected. Be careful though, because by default the
editor relies on the native DOM selection, which cannot handle
multiple selections. An extension like
[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
secondary selections visible to the user.
*/
EditorState.allowMultipleSelections = allowMultipleSelections$1;
/**
Configures the tab size to use in this state. The first
(highest-precedence) value of the facet is used. If no value is
given, this defaults to 4.
*/
EditorState.tabSize = /* @__PURE__ */Facet$1.define({
combine: values => values.length ? values[0] : 4
});
/**
The line separator to use. By default, any of `"\n"`, `"\r\n"`
and `"\r"` is treated as a separator when splitting lines, and
lines are joined with `"\n"`.
When you configure a value here, only that precise separator
will be used, allowing you to round-trip documents through the
editor without normalizing line separators.
*/
EditorState.lineSeparator = lineSeparator$1;
/**
This facet controls the value of the
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
consulted by commands and extensions that implement editing
functionality to determine whether they should apply. It
defaults to false, but when its highest-precedence value is
`true`, such functionality disables itself.
Not to be confused with
[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
controls whether the editor's DOM is set to be editable (and
thus focusable).
*/
EditorState.readOnly = readOnly$1;
/**
Registers translation phrases. The
[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
all objects registered with this facet to find translations for
its argument.
*/
EditorState.phrases = /* @__PURE__ */Facet$1.define({
compare(a, b) {
let kA = Object.keys(a),
kB = Object.keys(b);
return kA.length == kB.length && kA.every(k => a[k] == b[k]);
}
});
/**
A facet used to register [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
*/
EditorState.languageData = languageData$1;
/**
Facet used to register change filters, which are called for each
transaction (unless explicitly
[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
part of the transaction's changes.
Such a function can return `true` to indicate that it doesn't
want to do anything, `false` to completely stop the changes in
the transaction, or a set of ranges in which changes should be
suppressed. Such ranges are represented as an array of numbers,
with each pair of two numbers indicating the start and end of a
range. So for example `[10, 20, 100, 110]` suppresses changes
between 10 and 20, and between 100 and 110.
*/
EditorState.changeFilter = changeFilter$1;
/**
Facet used to register a hook that gets a chance to update or
replace transaction specs before they are applied. This will
only be applied for transactions that don't have
[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
can either return a single transaction spec (possibly the input
transaction), or an array of specs (which will be combined in
the same way as the arguments to
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
When possible, it is recommended to avoid accessing
[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
since it will force creation of a state that will then be
discarded again, if the transaction is actually filtered.
(This functionality should be used with care. Indiscriminately
modifying transaction is likely to break something or degrade
the user experience.)
*/
EditorState.transactionFilter = transactionFilter$1;
/**
This is a more limited form of
[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
which can only add
[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
of filter runs even if the transaction has disabled regular
[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
for effects that don't need to touch the changes or selection,
but do want to process every transaction.
Extenders run _after_ filters, when both are present.
*/
EditorState.transactionExtender = transactionExtender$1;
Compartment$1.reconfigure = /* @__PURE__ */StateEffect$1.define();
RangeValue = class {
/**
Compare this value with another value. Used when comparing
rangesets. The default implementation compares by identity.
Unless you are only creating a fixed number of unique instances
of your value type, it is a good idea to implement this
properly.
*/
eq(other) {
return this == other;
}
/**
Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
*/
range(from, to = from) {
return Range$2.create(from, to, this);
}
};
RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0;
RangeValue.prototype.point = false;
RangeValue.prototype.mapMode = MapMode.TrackDel;
/**
A range associates a value with a range of positions.
*/
Range$2 = class Range$2 {
constructor(from, to, value) {
this.from = from;
this.to = to;
this.value = value;
}
/**
@internal
*/
static create(from, to, value) {
return new Range$2(from, to, value);
}
};
Chunk$1 = class Chunk$1 {
constructor(from, to, value, maxPoint) {
this.from = from;
this.to = to;
this.value = value;
this.maxPoint = maxPoint;
}
get length() {
return this.to[this.to.length - 1];
}
findIndex(pos, side, end, startAt = 0) {
let arr = end ? this.to : this.from;
for (let lo = startAt, hi = arr.length;;) {
if (lo == hi) return lo;
let mid = lo + hi >> 1;
let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
if (mid == lo) return diff >= 0 ? lo : hi;
if (diff >= 0) hi = mid;else lo = mid + 1;
}
}
between(offset, from, to, f) {
for (let i$1 = this.findIndex(from, -1e9, true), e = this.findIndex(to, 1e9, false, i$1); i$1 < e; i$1++) if (f(this.from[i$1] + offset, this.to[i$1] + offset, this.value[i$1]) === false) return false;
}
map(offset, changes) {
let value = [],
from = [],
to = [],
newPos = -1,
maxPoint = -1;
for (let i$1 = 0; i$1 < this.value.length; i$1++) {
let val = this.value[i$1],
curFrom = this.from[i$1] + offset,
curTo = this.to[i$1] + offset,
newFrom,
newTo;
if (curFrom == curTo) {
let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
if (mapped == null) continue;
newFrom = newTo = mapped;
if (val.startSide != val.endSide) {
newTo = changes.mapPos(curFrom, val.endSide);
if (newTo < newFrom) continue;
}
} else {
newFrom = changes.mapPos(curFrom, val.startSide);
newTo = changes.mapPos(curTo, val.endSide);
if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) continue;
}
if ((newTo - newFrom || val.endSide - val.startSide) < 0) continue;
if (newPos < 0) newPos = newFrom;
if (val.point) maxPoint = Math.max(maxPoint, newTo - newFrom);
value.push(val);
from.push(newFrom - newPos);
to.push(newTo - newPos);
}
return {
mapped: value.length ? new Chunk$1(from, to, value, maxPoint) : null,
pos: newPos
};
}
};
/**
A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
structure.
*/
RangeSet$1 = class RangeSet$1 {
constructor(chunkPos, chunk, nextLayer, maxPoint) {
this.chunkPos = chunkPos;
this.chunk = chunk;
this.nextLayer = nextLayer;
this.maxPoint = maxPoint;
}
/**
@internal
*/
static create(chunkPos, chunk, nextLayer, maxPoint) {
return new RangeSet$1(chunkPos, chunk, nextLayer, maxPoint);
}
/**
@internal
*/
get length() {
let last = this.chunk.length - 1;
return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
}
/**
The number of ranges in the set.
*/
get size() {
if (this.isEmpty) return 0;
let size = this.nextLayer.size;
for (let chunk of this.chunk) size += chunk.value.length;
return size;
}
/**
@internal
*/
chunkEnd(index) {
return this.chunkPos[index] + this.chunk[index].length;
}
/**
Update the range set, optionally adding new ranges or filtering
out existing ones.
(Note: The type parameter is just there as a kludge to work
around TypeScript variance issues that prevented `RangeSet<X>`
from being a subtype of `RangeSet<Y>` when `X` is a subtype of
`Y`.)
*/
update(updateSpec) {
let {
add: add$1 = [],
sort = false,
filterFrom = 0,
filterTo = this.length
} = updateSpec;
let filter = updateSpec.filter;
if (add$1.length == 0 && !filter) return this;
if (sort) add$1 = add$1.slice().sort(cmpRange$1);
if (this.isEmpty) return add$1.length ? RangeSet$1.of(add$1) : this;
let cur$1 = new LayerCursor$1(this, null, -1).goto(0),
i$1 = 0,
spill = [];
let builder = new RangeSetBuilder$1();
while (cur$1.value || i$1 < add$1.length) if (i$1 < add$1.length && (cur$1.from - add$1[i$1].from || cur$1.startSide - add$1[i$1].value.startSide) >= 0) {
let range = add$1[i$1++];
if (!builder.addInner(range.from, range.to, range.value)) spill.push(range);
} else if (cur$1.rangeIndex == 1 && cur$1.chunkIndex < this.chunk.length && (i$1 == add$1.length || this.chunkEnd(cur$1.chunkIndex) < add$1[i$1].from) && (!filter || filterFrom > this.chunkEnd(cur$1.chunkIndex) || filterTo < this.chunkPos[cur$1.chunkIndex]) && builder.addChunk(this.chunkPos[cur$1.chunkIndex], this.chunk[cur$1.chunkIndex])) cur$1.nextChunk();else {
if (!filter || filterFrom > cur$1.to || filterTo < cur$1.from || filter(cur$1.from, cur$1.to, cur$1.value)) {
if (!builder.addInner(cur$1.from, cur$1.to, cur$1.value)) spill.push(Range$2.create(cur$1.from, cur$1.to, cur$1.value));
}
cur$1.next();
}
return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet$1.empty : this.nextLayer.update({
add: spill,
filter,
filterFrom,
filterTo
}));
}
/**
Map this range set through a set of changes, return the new set.
*/
map(changes) {
if (changes.empty || this.isEmpty) return this;
let chunks = [],
chunkPos = [],
maxPoint = -1;
for (let i$1 = 0; i$1 < this.chunk.length; i$1++) {
let start = this.chunkPos[i$1],
chunk = this.chunk[i$1];
let touch = changes.touchesRange(start, start + chunk.length);
if (touch === false) {
maxPoint = Math.max(maxPoint, chunk.maxPoint);
chunks.push(chunk);
chunkPos.push(changes.mapPos(start));
} else if (touch === true) {
let {
mapped,
pos
} = chunk.map(start, changes);
if (mapped) {
maxPoint = Math.max(maxPoint, mapped.maxPoint);
chunks.push(mapped);
chunkPos.push(pos);
}
}
}
let next = this.nextLayer.map(changes);
return chunks.length == 0 ? next : new RangeSet$1(chunkPos, chunks, next || RangeSet$1.empty, maxPoint);
}
/**
Iterate over the ranges that touch the region `from` to `to`,
calling `f` for each. There is no guarantee that the ranges will
be reported in any specific order. When the callback returns
`false`, iteration stops.
*/
between(from, to, f) {
if (this.isEmpty) return;
for (let i$1 = 0; i$1 < this.chunk.length; i$1++) {
let start = this.chunkPos[i$1],
chunk = this.chunk[i$1];
if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === false) return;
}
this.nextLayer.between(from, to, f);
}
/**
Iterate over the ranges in this set, in order, including all
ranges that end at or after `from`.
*/
iter(from = 0) {
return HeapCursor$1.from([this]).goto(from);
}
/**
@internal
*/
get isEmpty() {
return this.nextLayer == this;
}
/**
Iterate over the ranges in a collection of sets, in order,
starting from `from`.
*/
static iter(sets, from = 0) {
return HeapCursor$1.from(sets).goto(from);
}
/**
Iterate over two groups of sets, calling methods on `comparator`
to notify it of possible differences.
*/
static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) {
let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
let sharedChunks = findSharedChunks$1(a, b, textDiff);
let sideA = new SpanCursor$1(a, sharedChunks, minPointSize);
let sideB = new SpanCursor$1(b, sharedChunks, minPointSize);
textDiff.iterGaps((fromA, fromB, length) => compare$1(sideA, fromA, sideB, fromB, length, comparator));
if (textDiff.empty && textDiff.length == 0) compare$1(sideA, 0, sideB, 0, 0, comparator);
}
/**
Compare the contents of two groups of range sets, returning true
if they are equivalent in the given range.
*/
static eq(oldSets, newSets, from = 0, to) {
if (to == null) to = 999999999;
let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
if (a.length != b.length) return false;
if (!a.length) return true;
let sharedChunks = findSharedChunks$1(a, b);
let sideA = new SpanCursor$1(a, sharedChunks, 0).goto(from),
sideB = new SpanCursor$1(b, sharedChunks, 0).goto(from);
for (;;) {
if (sideA.to != sideB.to || !sameValues$1(sideA.active, sideB.active) || sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) return false;
if (sideA.to > to) return true;
sideA.next();
sideB.next();
}
}
/**
Iterate over a group of range sets at the same time, notifying
the iterator about the ranges covering every given piece of
content. Returns the open count (see
[`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
of the iteration.
*/
static spans(sets, from, to, iterator, minPointSize = -1) {
let cursor = new SpanCursor$1(sets, null, minPointSize).goto(from),
pos = from;
let openRanges = cursor.openStart;
for (;;) {
let curTo = Math.min(cursor.to, to);
if (cursor.point) {
let active = cursor.activeForPoint(cursor.to);
let openCount = cursor.pointFrom < from ? active.length + 1 : cursor.point.startSide < 0 ? active.length : Math.min(active.length, openRanges);
iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
openRanges = Math.min(cursor.openEnd(curTo), active.length);
} else if (curTo > pos) {
iterator.span(pos, curTo, cursor.active, openRanges);
openRanges = cursor.openEnd(curTo);
}
if (cursor.to > to) return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
pos = cursor.to;
cursor.next();
}
}
/**
Create a range set for the given range or array of ranges. By
default, this expects the ranges to be _sorted_ (by start
position and, if two start at the same position,
`value.startSide`). You can pass `true` as second argument to
cause the method to sort them.
*/
static of(ranges, sort = false) {
let build = new RangeSetBuilder$1();
for (let range of ranges instanceof Range$2 ? [ranges] : sort ? lazySort$1(ranges) : ranges) build.add(range.from, range.to, range.value);
return build.finish();
}
/**
Join an array of range sets into a single set.
*/
static join(sets) {
if (!sets.length) return RangeSet$1.empty;
let result = sets[sets.length - 1];
for (let i$1 = sets.length - 2; i$1 >= 0; i$1--) for (let layer$1 = sets[i$1]; layer$1 != RangeSet$1.empty; layer$1 = layer$1.nextLayer) result = new RangeSet$1(layer$1.chunkPos, layer$1.chunk, result, Math.max(layer$1.maxPoint, result.maxPoint));
return result;
}
};
/**
The empty set of ranges.
*/
RangeSet$1.empty = /* @__PURE__ */new RangeSet$1([], [], null, -1);
RangeSet$1.empty.nextLayer = RangeSet$1.empty;
/**
A range set builder is a data structure that helps build up a
[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
*/
_export("qt", RangeSetBuilder$1 = class RangeSetBuilder$1 {
finishChunk(newArrays) {
this.chunks.push(new Chunk$1(this.from, this.to, this.value, this.maxPoint));
this.chunkPos.push(this.chunkStart);
this.chunkStart = -1;
this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
this.maxPoint = -1;
if (newArrays) {
this.from = [];
this.to = [];
this.value = [];
}
}
/**
Create an empty builder.
*/
constructor() {
this.chunks = [];
this.chunkPos = [];
this.chunkStart = -1;
this.last = null;
this.lastFrom = -1e9;
this.lastTo = -1e9;
this.from = [];
this.to = [];
this.value = [];
this.maxPoint = -1;
this.setMaxPoint = -1;
this.nextLayer = null;
}
/**
Add a range. Ranges should be added in sorted (by `from` and
`value.startSide`) order.
*/
add(from, to, value) {
if (!this.addInner(from, to, value)) (this.nextLayer || (this.nextLayer = new RangeSetBuilder$1())).add(from, to, value);
}
/**
@internal
*/
addInner(from, to, value) {
let diff = from - this.lastTo || value.startSide - this.last.endSide;
if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) throw new Error("Ranges must be added sorted by `from` position and `startSide`");
if (diff < 0) return false;
if (this.from.length == 250) this.finishChunk(true);
if (this.chunkStart < 0) this.chunkStart = from;
this.from.push(from - this.chunkStart);
this.to.push(to - this.chunkStart);
this.last = value;
this.lastFrom = from;
this.lastTo = to;
this.value.push(value);
if (value.point) this.maxPoint = Math.max(this.maxPoint, to - from);
return true;
}
/**
@internal
*/
addChunk(from, chunk) {
if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) return false;
if (this.from.length) this.finishChunk(true);
this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
this.chunks.push(chunk);
this.chunkPos.push(from);
let last = chunk.value.length - 1;
this.last = chunk.value[last];
this.lastFrom = chunk.from[last] + from;
this.lastTo = chunk.to[last] + from;
return true;
}
/**
Finish the range set. Returns the new set. The builder can't be
used anymore after this has been called.
*/
finish() {
return this.finishInner(RangeSet$1.empty);
}
/**
@internal
*/
finishInner(next) {
if (this.from.length) this.finishChunk(false);
if (this.chunks.length == 0) return next;
let result = RangeSet$1.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
this.from = null;
return result;
}
});
LayerCursor$1 = class {
constructor(layer$1, skip, minPoint, rank = 0) {
this.layer = layer$1;
this.skip = skip;
this.minPoint = minPoint;
this.rank = rank;
}
get startSide() {
return this.value ? this.value.startSide : 0;
}
get endSide() {
return this.value ? this.value.endSide : 0;
}
goto(pos, side = -1e9) {
this.chunkIndex = this.rangeIndex = 0;
this.gotoInner(pos, side, false);
return this;
}
gotoInner(pos, side, forward) {
while (this.chunkIndex < this.layer.chunk.length) {
let next = this.layer.chunk[this.chunkIndex];
if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint)) break;
this.chunkIndex++;
forward = false;
}
if (this.chunkIndex < this.layer.chunk.length) {
let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
if (!forward || this.rangeIndex < rangeIndex) this.setRangeIndex(rangeIndex);
}
this.next();
}
forward(pos, side) {
if ((this.to - pos || this.endSide - side) < 0) this.gotoInner(pos, side, true);
}
next() {
for (;;) if (this.chunkIndex == this.layer.chunk.length) {
this.from = this.to = 1e9;
this.value = null;
break;
} else {
let chunkPos = this.layer.chunkPos[this.chunkIndex],
chunk = this.layer.chunk[this.chunkIndex];
this.from = chunkPos + chunk.from[this.rangeIndex];
this.to = chunkPos + chunk.to[this.rangeIndex];
this.value = chunk.value[this.rangeIndex];
this.setRangeIndex(this.rangeIndex + 1);
if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) break;
}
}
setRangeIndex(index) {
if (index == this.layer.chunk[this.chunkIndex].value.length) {
this.chunkIndex++;
if (this.skip) while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) this.chunkIndex++;
this.rangeIndex = 0;
} else this.rangeIndex = index;
}
nextChunk() {
this.chunkIndex++;
this.rangeIndex = 0;
this.next();
}
compare(other) {
return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide;
}
};
HeapCursor$1 = class HeapCursor$1 {
constructor(heap) {
this.heap = heap;
}
static from(sets, skip = null, minPoint = -1) {
let heap = [];
for (let i$1 = 0; i$1 < sets.length; i$1++) for (let cur$1 = sets[i$1]; !cur$1.isEmpty; cur$1 = cur$1.nextLayer) if (cur$1.maxPoint >= minPoint) heap.push(new LayerCursor$1(cur$1, skip, minPoint, i$1));
return heap.length == 1 ? heap[0] : new HeapCursor$1(heap);
}
get startSide() {
return this.value ? this.value.startSide : 0;
}
goto(pos, side = -1e9) {
for (let cur$1 of this.heap) cur$1.goto(pos, side);
for (let i$1 = this.heap.length >> 1; i$1 >= 0; i$1--) heapBubble$1(this.heap, i$1);
this.next();
return this;
}
forward(pos, side) {
for (let cur$1 of this.heap) cur$1.forward(pos, side);
for (let i$1 = this.heap.length >> 1; i$1 >= 0; i$1--) heapBubble$1(this.heap, i$1);
if ((this.to - pos || this.value.endSide - side) < 0) this.next();
}
next() {
if (this.heap.length == 0) {
this.from = this.to = 1e9;
this.value = null;
this.rank = -1;
} else {
let top$1 = this.heap[0];
this.from = top$1.from;
this.to = top$1.to;
this.value = top$1.value;
this.rank = top$1.rank;
if (top$1.value) top$1.next();
heapBubble$1(this.heap, 0);
}
}
};
SpanCursor$1 = class {
constructor(sets, skip, minPoint) {
this.minPoint = minPoint;
this.active = [];
this.activeTo = [];
this.activeRank = [];
this.minActive = -1;
this.point = null;
this.pointFrom = 0;
this.pointRank = 0;
this.to = -1e9;
this.endSide = 0;
this.openStart = -1;
this.cursor = HeapCursor$1.from(sets, skip, minPoint);
}
goto(pos, side = -1e9) {
this.cursor.goto(pos, side);
this.active.length = this.activeTo.length = this.activeRank.length = 0;
this.minActive = -1;
this.to = pos;
this.endSide = side;
this.openStart = -1;
this.next();
return this;
}
forward(pos, side) {
while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) this.removeActive(this.minActive);
this.cursor.forward(pos, side);
}
removeActive(index) {
remove$1(this.active, index);
remove$1(this.activeTo, index);
remove$1(this.activeRank, index);
this.minActive = findMinIndex$1(this.active, this.activeTo);
}
addActive(trackOpen) {
let i$1 = 0,
{
value,
to,
rank
} = this.cursor;
while (i$1 < this.activeRank.length && (rank - this.activeRank[i$1] || to - this.activeTo[i$1]) > 0) i$1++;
insert$1(this.active, i$1, value);
insert$1(this.activeTo, i$1, to);
insert$1(this.activeRank, i$1, rank);
if (trackOpen) insert$1(trackOpen, i$1, this.cursor.from);
this.minActive = findMinIndex$1(this.active, this.activeTo);
}
next() {
let from = this.to,
wasPoint = this.point;
this.point = null;
let trackOpen = this.openStart < 0 ? [] : null;
for (;;) {
let a = this.minActive;
if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
if (this.activeTo[a] > from) {
this.to = this.activeTo[a];
this.endSide = this.active[a].endSide;
break;
}
this.removeActive(a);
if (trackOpen) remove$1(trackOpen, a);
} else if (!this.cursor.value) {
this.to = this.endSide = 1e9;
break;
} else if (this.cursor.from > from) {
this.to = this.cursor.from;
this.endSide = this.cursor.startSide;
break;
} else {
let nextVal = this.cursor.value;
if (!nextVal.point) {
this.addActive(trackOpen);
this.cursor.next();
} else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) this.cursor.next();else {
this.point = nextVal;
this.pointFrom = this.cursor.from;
this.pointRank = this.cursor.rank;
this.to = this.cursor.to;
this.endSide = nextVal.endSide;
this.cursor.next();
this.forward(this.to, this.endSide);
break;
}
}
}
if (trackOpen) {
this.openStart = 0;
for (let i$1 = trackOpen.length - 1; i$1 >= 0 && trackOpen[i$1] < from; i$1--) this.openStart++;
}
}
activeForPoint(to) {
if (!this.active.length) return this.active;
let active = [];
for (let i$1 = this.active.length - 1; i$1 >= 0; i$1--) {
if (this.activeRank[i$1] < this.pointRank) break;
if (this.activeTo[i$1] > to || this.activeTo[i$1] == to && this.active[i$1].endSide >= this.point.endSide) active.push(this.active[i$1]);
}
return active.reverse();
}
openEnd(to) {
let open = 0;
for (let i$1 = this.activeTo.length - 1; i$1 >= 0 && this.activeTo[i$1] > to; i$1--) open++;
return open;
}
};
C = "ͼ";
COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C);
SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : Symbol("styleSet");
top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {};
StyleModule = class {
constructor(spec, options) {
this.rules = [];
let {
finish
} = options || {};
function splitSelector(selector) {
return /^@/.test(selector) ? [selector] : selector.split(/,\s*/);
}
function render$1(selectors, spec$1, target, isKeyframes) {
let local = [],
isAt = /^@(\w+)\b/.exec(selectors[0]),
keyframes = isAt && isAt[1] == "keyframes";
if (isAt && spec$1 == null) return target.push(selectors[0] + ";");
for (let prop in spec$1) {
let value = spec$1[prop];
if (/&/.test(prop)) render$1(prop.split(/,\s*/).map(part => selectors.map(sel => part.replace(/&/, sel))).reduce((a, b) => a.concat(b)), value, target);else if (value && typeof value == "object") {
if (!isAt) throw new RangeError("The value of a property (" + prop + ") should be a primitive value.");
render$1(splitSelector(prop), value, local, keyframes);
} else if (value != null) local.push(prop.replace(/_.*/, "").replace(/[A-Z]/g, l => "-" + l.toLowerCase()) + ": " + value + ";");
}
if (local.length || keyframes) target.push((finish && !isAt && !isKeyframes ? selectors.map(finish) : selectors).join(", ") + " {" + local.join(" ") + "}");
}
for (let prop in spec) render$1(splitSelector(prop), spec[prop], this.rules);
}
getRules() {
return this.rules.join("\n");
}
static newName() {
let id$1 = top[COUNT] || 1;
top[COUNT] = id$1 + 1;
return C + id$1.toString(36);
}
static mount(root, modules, options) {
let set = root[SET],
nonce = options && options.nonce;
if (!set) set = new StyleSet(root, nonce);else if (nonce) set.setNonce(nonce);
set.mount(Array.isArray(modules) ? modules : [modules]);
}
};
adoptedSet = /* @__PURE__ */new Map();
StyleSet = class {
constructor(root, nonce) {
let doc$2 = root.ownerDocument || root,
win = doc$2.defaultView;
if (!root.head && root.adoptedStyleSheets && win.CSSStyleSheet) {
let adopted = adoptedSet.get(doc$2);
if (adopted) {
root.adoptedStyleSheets = [adopted.sheet, ...root.adoptedStyleSheets];
return root[SET] = adopted;
}
this.sheet = new win.CSSStyleSheet();
root.adoptedStyleSheets = [this.sheet, ...root.adoptedStyleSheets];
adoptedSet.set(doc$2, this);
} else {
this.styleTag = doc$2.createElement("style");
if (nonce) this.styleTag.setAttribute("nonce", nonce);
let target = root.head || root;
target.insertBefore(this.styleTag, target.firstChild);
}
this.modules = [];
root[SET] = this;
}
mount(modules) {
let sheet = this.sheet;
let pos = 0,
j = 0;
for (let i$1 = 0; i$1 < modules.length; i$1++) {
let mod = modules[i$1],
index = this.modules.indexOf(mod);
if (index < j && index > -1) {
this.modules.splice(index, 1);
j--;
index = -1;
}
if (index == -1) {
this.modules.splice(j++, 0, mod);
if (sheet) for (let k = 0; k < mod.rules.length; k++) sheet.insertRule(mod.rules[k], pos++);
} else {
while (j < index) pos += this.modules[j++].rules.length;
pos += mod.rules.length;
j++;
}
}
if (!sheet) {
let text = "";
for (let i$1 = 0; i$1 < this.modules.length; i$1++) text += this.modules[i$1].getRules() + "\n";
this.styleTag.textContent = text;
}
}
setNonce(nonce) {
if (this.styleTag && this.styleTag.getAttribute("nonce") != nonce) this.styleTag.setAttribute("nonce", nonce);
}
}; //#endregion
//#region ../../../node_modules/.pnpm/w3c-keyname@2.2.6/node_modules/w3c-keyname/index.es.js
base = {
8: "Backspace",
9: "Tab",
10: "Enter",
12: "NumLock",
13: "Enter",
16: "Shift",
17: "Control",
18: "Alt",
20: "CapsLock",
27: "Escape",
32: " ",
33: "PageUp",
34: "PageDown",
35: "End",
36: "Home",
37: "ArrowLeft",
38: "ArrowUp",
39: "ArrowRight",
40: "ArrowDown",
44: "PrintScreen",
45: "Insert",
46: "Delete",
59: ";",
61: "=",
91: "Meta",
92: "Meta",
106: "*",
107: "+",
108: ",",
109: "-",
110: ".",
111: "/",
144: "NumLock",
145: "ScrollLock",
160: "Shift",
161: "Shift",
162: "Control",
163: "Control",
164: "Alt",
165: "Alt",
173: "-",
186: ";",
187: "=",
188: ",",
189: "-",
190: ".",
191: "/",
192: "`",
219: "[",
220: "\\",
221: "]",
222: "'"
};
shift = {
48: ")",
49: "!",
50: "@",
51: "#",
52: "$",
53: "%",
54: "^",
55: "&",
56: "*",
57: "(",
59: ":",
61: "+",
173: "_",
186: ":",
187: "+",
188: "<",
189: "_",
190: ">",
191: "?",
192: "~",
219: "{",
220: "|",
221: "}",
222: "\""
};
chrome$2 = typeof navigator != "undefined" && /Chrome\/(\d+)/.exec(navigator.userAgent);
typeof navigator != "undefined" && /Gecko\/\d+/.test(navigator.userAgent);
mac = typeof navigator != "undefined" && /Mac/.test(navigator.platform);
ie$2 = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);
brokenModifierNames = mac || chrome$2 && +chrome$2[1] < 57;
for (i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i);
for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i;
for (var i = 65; i <= 90; i++) {
base[i] = String.fromCharCode(i + 32);
shift[i] = String.fromCharCode(i);
}
for (code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code];
DOMSelectionState$1 = class {
constructor() {
this.anchorNode = null;
this.anchorOffset = 0;
this.focusNode = null;
this.focusOffset = 0;
}
eq(domSel) {
return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
}
setRange(range) {
let {
anchorNode,
focusNode
} = range;
this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset$1(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset$1(focusNode) : 0));
}
set(anchorNode, anchorOffset, focusNode, focusOffset) {
this.anchorNode = anchorNode;
this.anchorOffset = anchorOffset;
this.focusNode = focusNode;
this.focusOffset = focusOffset;
}
};
preventScrollSupported$1 = null;
DOMPos$1 = class DOMPos$1 {
constructor(node, offset, precise = true) {
this.node = node;
this.offset = offset;
this.precise = precise;
}
static before(dom, precise) {
return new DOMPos$1(dom.parentNode, domIndex$1(dom), precise);
}
static after(dom, precise) {
return new DOMPos$1(dom.parentNode, domIndex$1(dom) + 1, precise);
}
};
noChildren$1 = [];
ContentView$1 = class ContentView$1 {
constructor() {
this.parent = null;
this.dom = null;
this.flags = 2;
}
get overrideDOMText() {
return null;
}
get posAtStart() {
return this.parent ? this.parent.posBefore(this) : 0;
}
get posAtEnd() {
return this.posAtStart + this.length;
}
posBefore(view) {
let pos = this.posAtStart;
for (let child of this.children) {
if (child == view) return pos;
pos += child.length + child.breakAfter;
}
throw new RangeError("Invalid child in posBefore");
}
posAfter(view) {
return this.posBefore(view) + view.length;
}
sync(view, track) {
if (this.flags & 2) {
let parent = this.dom;
let prev = null,
next;
for (let child of this.children) {
if (child.flags & 7) {
if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {
let contentView = ContentView$1.get(next);
if (!contentView || !contentView.parent && contentView.canReuseDOM(child)) child.reuseDOM(next);
}
child.sync(view, track);
child.flags &= -8;
}
next = prev ? prev.nextSibling : parent.firstChild;
if (track && !track.written && track.node == parent && next != child.dom) track.written = true;
if (child.dom.parentNode == parent) while (next && next != child.dom) next = rm$1$1(next);else parent.insertBefore(child.dom, next);
prev = child.dom;
}
next = prev ? prev.nextSibling : parent.firstChild;
if (next && track && track.node == parent) track.written = true;
while (next) next = rm$1$1(next);
} else if (this.flags & 1) {
for (let child of this.children) if (child.flags & 7) {
child.sync(view, track);
child.flags &= -8;
}
}
}
reuseDOM(_dom) {}
localPosFromDOM(node, offset) {
let after;
if (node == this.dom) after = this.dom.childNodes[offset];else {
let bias = maxOffset$1(node) == 0 ? 0 : offset == 0 ? -1 : 1;
for (;;) {
let parent = node.parentNode;
if (parent == this.dom) break;
if (bias == 0 && parent.firstChild != parent.lastChild) if (node == parent.firstChild) bias = -1;else bias = 1;
node = parent;
}
if (bias < 0) after = node;else after = node.nextSibling;
}
if (after == this.dom.firstChild) return 0;
while (after && !ContentView$1.get(after)) after = after.nextSibling;
if (!after) return this.length;
for (let i$1 = 0, pos = 0;; i$1++) {
let child = this.children[i$1];
if (child.dom == after) return pos;
pos += child.length + child.breakAfter;
}
}
domBoundsAround(from, to, offset = 0) {
let fromI = -1,
fromStart = -1,
toI = -1,
toEnd = -1;
for (let i$1 = 0, pos = offset, prevEnd = offset; i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (pos < from && end > to) return child.domBoundsAround(from, to, pos);
if (end >= from && fromI == -1) {
fromI = i$1;
fromStart = pos;
}
if (pos > to && child.dom.parentNode == this.dom) {
toI = i$1;
toEnd = prevEnd;
break;
}
prevEnd = end;
pos = end + child.breakAfter;
}
return {
from: fromStart,
to: toEnd < 0 ? offset + this.length : toEnd,
startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,
endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null
};
}
markDirty(andParent = false) {
this.flags |= 2;
this.markParentsDirty(andParent);
}
markParentsDirty(childList) {
for (let parent = this.parent; parent; parent = parent.parent) {
if (childList) parent.flags |= 2;
if (parent.flags & 1) return;
parent.flags |= 1;
childList = false;
}
}
setParent(parent) {
if (this.parent != parent) {
this.parent = parent;
if (this.flags & 7) this.markParentsDirty(true);
}
}
setDOM(dom) {
if (this.dom == dom) return;
if (this.dom) this.dom.cmView = null;
this.dom = dom;
dom.cmView = this;
}
get rootView() {
for (let v = this;;) {
let parent = v.parent;
if (!parent) return v;
v = parent;
}
}
replaceChildren(from, to, children = noChildren$1) {
this.markDirty();
for (let i$1 = from; i$1 < to; i$1++) {
let child = this.children[i$1];
if (child.parent == this && children.indexOf(child) < 0) child.destroy();
}
this.children.splice(from, to - from, ...children);
for (let i$1 = 0; i$1 < children.length; i$1++) children[i$1].setParent(this);
}
ignoreMutation(_rec) {
return false;
}
ignoreEvent(_event) {
return false;
}
childCursor(pos = this.length) {
return new ChildCursor$1(this.children, pos, this.children.length);
}
childPos(pos, bias = 1) {
return this.childCursor().findPos(pos, bias);
}
toString() {
let name$1 = this.constructor.name.replace("View", "");
return name$1 + (this.children.length ? "(" + this.children.join() + ")" : this.length ? "[" + (name$1 == "Text" ? this.text : this.length) + "]" : "") + (this.breakAfter ? "#" : "");
}
static get(node) {
return node.cmView;
}
get isEditable() {
return true;
}
get isWidget() {
return false;
}
get isHidden() {
return false;
}
merge(from, to, source, hasStart, openStart, openEnd) {
return false;
}
become(other) {
return false;
}
canReuseDOM(other) {
return other.constructor == this.constructor && !((this.flags | other.flags) & 8);
}
getSide() {
return 0;
}
destroy() {
for (let child of this.children) if (child.parent == this) child.destroy();
this.parent = null;
}
};
ContentView$1.prototype.breakAfter = 0;
ChildCursor$1 = class {
constructor(children, pos, i$1) {
this.children = children;
this.pos = pos;
this.i = i$1;
this.off = 0;
}
findPos(pos, bias = 1) {
for (;;) {
if (pos > this.pos || pos == this.pos && (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
this.off = pos - this.pos;
return this;
}
let next = this.children[--this.i];
this.pos -= next.length + next.breakAfter;
}
}
};
nav$1 = typeof navigator != "undefined" ? navigator : {
userAgent: "",
vendor: "",
platform: ""
};
doc$1 = typeof document != "undefined" ? document : {
documentElement: {
style: {}
}
};
ie_edge$1 = /* @__PURE__ *//Edge\/(\d+)/.exec(nav$1.userAgent);
ie_upto10$1 = /* @__PURE__ *//MSIE \d/.test(nav$1.userAgent);
ie_11up$1 = /* @__PURE__ *//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav$1.userAgent);
ie$1 = !!(ie_upto10$1 || ie_11up$1 || ie_edge$1);
gecko$1 = !ie$1 && /* @__PURE__ *//gecko\/(\d+)/i.test(nav$1.userAgent);
chrome$1 = !ie$1 && /* @__PURE__ *//Chrome\/(\d+)/.exec(nav$1.userAgent);
webkit$1 = "webkitFontSmoothing" in doc$1.documentElement.style;
safari$1 = !ie$1 && /* @__PURE__ *//Apple Computer/.test(nav$1.vendor);
ios$1 = safari$1 && (/* @__PURE__ *//Mobile\/\w+/.test(nav$1.userAgent) || nav$1.maxTouchPoints > 2);
browser$1 = {
mac: ios$1 || /* @__PURE__ *//Mac/.test(nav$1.platform),
windows: /* @__PURE__ *//Win/.test(nav$1.platform),
linux: /* @__PURE__ *//Linux|X11/.test(nav$1.platform),
ie: ie$1,
ie_version: ie_upto10$1 ? doc$1.documentMode || 6 : ie_11up$1 ? +ie_11up$1[1] : ie_edge$1 ? +ie_edge$1[1] : 0,
gecko: gecko$1,
gecko_version: gecko$1 ? +(/* @__PURE__ *//Firefox\/(\d+)/.exec(nav$1.userAgent) || [0, 0])[1] : 0,
chrome: !!chrome$1,
chrome_version: chrome$1 ? +chrome$1[1] : 0,
ios: ios$1,
android: /* @__PURE__ *//Android\b/.test(nav$1.userAgent),
webkit: webkit$1,
safari: safari$1,
webkit_version: webkit$1 ? +(/* @__PURE__ *//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0,
tabSize: doc$1.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
};
MaxJoinLen$1 = 256;
TextView$1 = class TextView$1 extends ContentView$1 {
constructor(text) {
super();
this.text = text;
}
get length() {
return this.text.length;
}
createDOM(textDOM) {
this.setDOM(textDOM || document.createTextNode(this.text));
}
sync(view, track) {
if (!this.dom) this.createDOM();
if (this.dom.nodeValue != this.text) {
if (track && track.node == this.dom) track.written = true;
this.dom.nodeValue = this.text;
}
}
reuseDOM(dom) {
if (dom.nodeType == 3) this.createDOM(dom);
}
merge(from, to, source) {
if (this.flags & 8 || source && (!(source instanceof TextView$1) || this.length - (to - from) + source.length > MaxJoinLen$1 || source.flags & 8)) return false;
this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to);
this.markDirty();
return true;
}
split(from) {
let result = new TextView$1(this.text.slice(from));
this.text = this.text.slice(0, from);
this.markDirty();
result.flags |= this.flags & 8;
return result;
}
localPosFromDOM(node, offset) {
return node == this.dom ? offset : offset ? this.text.length : 0;
}
domAtPos(pos) {
return new DOMPos$1(this.dom, pos);
}
domBoundsAround(_from, _to, offset) {
return {
from: offset,
to: offset + this.length,
startDOM: this.dom,
endDOM: this.dom.nextSibling
};
}
coordsAt(pos, side) {
return textCoords$1(this.dom, pos, side);
}
};
MarkView$1 = class MarkView$1 extends ContentView$1 {
constructor(mark, children = [], length = 0) {
super();
this.mark = mark;
this.children = children;
this.length = length;
for (let ch of children) ch.setParent(this);
}
setAttrs(dom) {
clearAttributes$1(dom);
if (this.mark.class) dom.className = this.mark.class;
if (this.mark.attrs) for (let name$1 in this.mark.attrs) dom.setAttribute(name$1, this.mark.attrs[name$1]);
return dom;
}
canReuseDOM(other) {
return super.canReuseDOM(other) && !((this.flags | other.flags) & 8);
}
reuseDOM(node) {
if (node.nodeName == this.mark.tagName.toUpperCase()) {
this.setDOM(node);
this.flags |= 6;
}
}
sync(view, track) {
if (!this.dom) this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));else if (this.flags & 4) this.setAttrs(this.dom);
super.sync(view, track);
}
merge(from, to, source, _hasStart, openStart, openEnd) {
if (source && (!(source instanceof MarkView$1 && source.mark.eq(this.mark)) || from && openStart <= 0 || to < this.length && openEnd <= 0)) return false;
mergeChildrenInto$1(this, from, to, source ? source.children.slice() : [], openStart - 1, openEnd - 1);
this.markDirty();
return true;
}
split(from) {
let result = [],
off = 0,
detachFrom = -1,
i$1 = 0;
for (let elt of this.children) {
let end = off + elt.length;
if (end > from) result.push(off < from ? elt.split(from - off) : elt);
if (detachFrom < 0 && off >= from) detachFrom = i$1;
off = end;
i$1++;
}
let length = this.length - from;
this.length = from;
if (detachFrom > -1) {
this.children.length = detachFrom;
this.markDirty();
}
return new MarkView$1(this.mark, result, length);
}
domAtPos(pos) {
return inlineDOMAtPos$1(this, pos);
}
coordsAt(pos, side) {
return coordsInChildren$1(this, pos, side);
}
};
WidgetView$1 = class WidgetView$1 extends ContentView$1 {
static create(widget, length, side) {
return new WidgetView$1(widget, length, side);
}
constructor(widget, length, side) {
super();
this.widget = widget;
this.length = length;
this.side = side;
this.prevWidget = null;
}
split(from) {
let result = WidgetView$1.create(this.widget, this.length - from, this.side);
this.length -= from;
return result;
}
sync(view) {
if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
if (this.dom && this.prevWidget) this.prevWidget.destroy(this.dom);
this.prevWidget = null;
this.setDOM(this.widget.toDOM(view));
if (!this.widget.editable) this.dom.contentEditable = "false";
}
}
getSide() {
return this.side;
}
merge(from, to, source, hasStart, openStart, openEnd) {
if (source && (!(source instanceof WidgetView$1) || !this.widget.compare(source.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) return false;
this.length = from + (source ? source.length : 0) + (this.length - to);
return true;
}
become(other) {
if (other instanceof WidgetView$1 && other.side == this.side && this.widget.constructor == other.widget.constructor) {
if (!this.widget.compare(other.widget)) this.markDirty(true);
if (this.dom && !this.prevWidget) this.prevWidget = this.widget;
this.widget = other.widget;
this.length = other.length;
return true;
}
return false;
}
ignoreMutation() {
return true;
}
ignoreEvent(event) {
return this.widget.ignoreEvent(event);
}
get overrideDOMText() {
if (this.length == 0) return Text.empty;
let top$1 = this;
while (top$1.parent) top$1 = top$1.parent;
let {
view
} = top$1,
text = view && view.state.doc,
start = this.posAtStart;
return text ? text.slice(start, start + this.length) : Text.empty;
}
domAtPos(pos) {
return (this.length ? pos == 0 : this.side > 0) ? DOMPos$1.before(this.dom) : DOMPos$1.after(this.dom, pos == this.length);
}
domBoundsAround() {
return null;
}
coordsAt(pos, side) {
let custom = this.widget.coordsAt(this.dom, pos, side);
if (custom) return custom;
let rects = this.dom.getClientRects(),
rect = null;
if (!rects.length) return null;
let fromBack = this.side ? this.side < 0 : pos > 0;
for (let i$1 = fromBack ? rects.length - 1 : 0;; i$1 += fromBack ? -1 : 1) {
rect = rects[i$1];
if (pos > 0 ? i$1 == 0 : i$1 == rects.length - 1 || rect.top < rect.bottom) break;
}
return flattenRect$1(rect, !fromBack);
}
get isEditable() {
return false;
}
get isWidget() {
return true;
}
get isHidden() {
return this.widget.isHidden;
}
destroy() {
super.destroy();
if (this.dom) this.widget.destroy(this.dom);
}
};
WidgetBufferView$1 = class WidgetBufferView$1 extends ContentView$1 {
constructor(side) {
super();
this.side = side;
}
get length() {
return 0;
}
merge() {
return false;
}
become(other) {
return other instanceof WidgetBufferView$1 && other.side == this.side;
}
split() {
return new WidgetBufferView$1(this.side);
}
sync() {
if (!this.dom) {
let dom = document.createElement("img");
dom.className = "cm-widgetBuffer";
dom.setAttribute("aria-hidden", "true");
this.setDOM(dom);
}
}
getSide() {
return this.side;
}
domAtPos(pos) {
return this.side > 0 ? DOMPos$1.before(this.dom) : DOMPos$1.after(this.dom);
}
localPosFromDOM() {
return 0;
}
domBoundsAround() {
return null;
}
coordsAt(pos) {
return this.dom.getBoundingClientRect();
}
get overrideDOMText() {
return Text.empty;
}
get isHidden() {
return true;
}
};
TextView$1.prototype.children = WidgetView$1.prototype.children = WidgetBufferView$1.prototype.children = noChildren$1;
noAttrs$1 = /* @__PURE__ */Object.create(null);
LineView$1 = class LineView$1 extends ContentView$1 {
constructor() {
super(...arguments);
this.children = [];
this.length = 0;
this.prevAttrs = void 0;
this.attrs = null;
this.breakAfter = 0;
}
merge(from, to, source, hasStart, openStart, openEnd) {
if (source) {
if (!(source instanceof LineView$1)) return false;
if (!this.dom) source.transferDOM(this);
}
if (hasStart) this.setDeco(source ? source.attrs : null);
mergeChildrenInto$1(this, from, to, source ? source.children.slice() : [], openStart, openEnd);
return true;
}
split(at) {
let end = new LineView$1();
end.breakAfter = this.breakAfter;
if (this.length == 0) return end;
let {
i: i$1,
off
} = this.childPos(at);
if (off) {
end.append(this.children[i$1].split(off), 0);
this.children[i$1].merge(off, this.children[i$1].length, null, false, 0, 0);
i$1++;
}
for (let j = i$1; j < this.children.length; j++) end.append(this.children[j], 0);
while (i$1 > 0 && this.children[i$1 - 1].length == 0) this.children[--i$1].destroy();
this.children.length = i$1;
this.markDirty();
this.length = at;
return end;
}
transferDOM(other) {
if (!this.dom) return;
this.markDirty();
other.setDOM(this.dom);
other.prevAttrs = this.prevAttrs === void 0 ? this.attrs : this.prevAttrs;
this.prevAttrs = void 0;
this.dom = null;
}
setDeco(attrs) {
if (!attrsEq$1(this.attrs, attrs)) {
if (this.dom) {
this.prevAttrs = this.attrs;
this.markDirty();
}
this.attrs = attrs;
}
}
append(child, openStart) {
joinInlineInto$1(this, child, openStart);
}
addLineDeco(deco) {
let attrs = deco.spec.attributes,
cls = deco.spec.class;
if (attrs) this.attrs = combineAttrs$1(attrs, this.attrs || {});
if (cls) this.attrs = combineAttrs$1({
class: cls
}, this.attrs || {});
}
domAtPos(pos) {
return inlineDOMAtPos$1(this, pos);
}
reuseDOM(node) {
if (node.nodeName == "DIV") {
this.setDOM(node);
this.flags |= 6;
}
}
sync(view, track) {
var _a$2;
if (!this.dom) {
this.setDOM(document.createElement("div"));
this.dom.className = "cm-line";
this.prevAttrs = this.attrs ? null : void 0;
} else if (this.flags & 4) {
clearAttributes$1(this.dom);
this.dom.className = "cm-line";
this.prevAttrs = this.attrs ? null : void 0;
}
if (this.prevAttrs !== void 0) {
updateAttrs$1(this.dom, this.prevAttrs, this.attrs);
this.dom.classList.add("cm-line");
this.prevAttrs = void 0;
}
super.sync(view, track);
let last = this.dom.lastChild;
while (last && ContentView$1.get(last) instanceof MarkView$1) last = last.lastChild;
if (!last || !this.length || last.nodeName != "BR" && ((_a$2 = ContentView$1.get(last)) === null || _a$2 === void 0 ? void 0 : _a$2.isEditable) == false && (!browser$1.ios || !this.children.some(ch => ch instanceof TextView$1))) {
let hack = document.createElement("BR");
hack.cmIgnore = true;
this.dom.appendChild(hack);
}
}
measureTextSize() {
if (this.children.length == 0 || this.length > 20) return null;
let totalWidth = 0,
textHeight;
for (let child of this.children) {
if (!(child instanceof TextView$1) || /[^ -~]/.test(child.text)) return null;
let rects = clientRectsFor$1(child.dom);
if (rects.length != 1) return null;
totalWidth += rects[0].width;
textHeight = rects[0].height;
}
return !totalWidth ? null : {
lineHeight: this.dom.getBoundingClientRect().height,
charWidth: totalWidth / this.length,
textHeight
};
}
coordsAt(pos, side) {
let rect = coordsInChildren$1(this, pos, side);
if (!this.children.length && rect && this.parent) {
let {
heightOracle
} = this.parent.view.viewState,
height = rect.bottom - rect.top;
if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {
let dist$2 = (height - heightOracle.textHeight) / 2;
return {
top: rect.top + dist$2,
bottom: rect.bottom - dist$2,
left: rect.left,
right: rect.left
};
}
}
return rect;
}
become(_other) {
return false;
}
covers() {
return true;
}
static find(docView, pos) {
for (let i$1 = 0, off = 0; i$1 < docView.children.length; i$1++) {
let block = docView.children[i$1],
end = off + block.length;
if (end >= pos) {
if (block instanceof LineView$1) return block;
if (end > pos) break;
}
off = end + block.breakAfter;
}
return null;
}
};
BlockWidgetView$1 = class BlockWidgetView$1 extends ContentView$1 {
constructor(widget, length, deco) {
super();
this.widget = widget;
this.length = length;
this.deco = deco;
this.breakAfter = 0;
this.prevWidget = null;
}
merge(from, to, source, _takeDeco, openStart, openEnd) {
if (source && (!(source instanceof BlockWidgetView$1) || !this.widget.compare(source.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) return false;
this.length = from + (source ? source.length : 0) + (this.length - to);
return true;
}
domAtPos(pos) {
return pos == 0 ? DOMPos$1.before(this.dom) : DOMPos$1.after(this.dom, pos == this.length);
}
split(at) {
let len = this.length - at;
this.length = at;
let end = new BlockWidgetView$1(this.widget, len, this.deco);
end.breakAfter = this.breakAfter;
return end;
}
get children() {
return noChildren$1;
}
sync(view) {
if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
if (this.dom && this.prevWidget) this.prevWidget.destroy(this.dom);
this.prevWidget = null;
this.setDOM(this.widget.toDOM(view));
if (!this.widget.editable) this.dom.contentEditable = "false";
}
}
get overrideDOMText() {
return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
}
domBoundsAround() {
return null;
}
become(other) {
if (other instanceof BlockWidgetView$1 && other.widget.constructor == this.widget.constructor) {
if (!other.widget.compare(this.widget)) this.markDirty(true);
if (this.dom && !this.prevWidget) this.prevWidget = this.widget;
this.widget = other.widget;
this.length = other.length;
this.deco = other.deco;
this.breakAfter = other.breakAfter;
return true;
}
return false;
}
ignoreMutation() {
return true;
}
ignoreEvent(event) {
return this.widget.ignoreEvent(event);
}
get isEditable() {
return false;
}
get isWidget() {
return true;
}
coordsAt(pos, side) {
return this.widget.coordsAt(this.dom, pos, side);
}
destroy() {
super.destroy();
if (this.dom) this.widget.destroy(this.dom);
}
covers(side) {
let {
startSide,
endSide
} = this.deco;
return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;
}
};
/**
Widgets added to the content are described by subclasses of this
class. Using a description object like that makes it possible to
delay creating of the DOM structure for a widget until it is
needed, and to avoid redrawing widgets even if the decorations
that define them are recreated.
*/
WidgetType$1 = class {
/**
Compare this instance to another instance of the same type.
(TypeScript can't express this, but only instances of the same
specific class will be passed to this method.) This is used to
avoid redrawing widgets when they are replaced by a new
decoration of the same type. The default implementation just
returns `false`, which will cause new instances of the widget to
always be redrawn.
*/
eq(widget) {
return false;
}
/**
Update a DOM element created by a widget of the same type (but
different, non-`eq` content) to reflect this widget. May return
true to indicate that it could update, false to indicate it
couldn't (in which case the widget will be redrawn). The default
implementation just returns false.
*/
updateDOM(dom, view) {
return false;
}
/**
@internal
*/
compare(other) {
return this == other || this.constructor == other.constructor && this.eq(other);
}
/**
The estimated height this widget will have, to be used when
estimating the height of content that hasn't been drawn. May
return -1 to indicate you don't know. The default implementation
returns -1.
*/
get estimatedHeight() {
return -1;
}
/**
For inline widgets that are displayed inline (as opposed to
`inline-block`) and introduce line breaks (through `<br>` tags
or textual newlines), this must indicate the amount of line
breaks they introduce. Defaults to 0.
*/
get lineBreaks() {
return 0;
}
/**
Can be used to configure which kinds of events inside the widget
should be ignored by the editor. The default is to ignore all
events.
*/
ignoreEvent(event) {
return true;
}
/**
Override the way screen coordinates for positions at/in the
widget are found. `pos` will be the offset into the widget, and
`side` the side of the position that is being queried—less than
zero for before, greater than zero for after, and zero for
directly at that position.
*/
coordsAt(dom, pos, side) {
return null;
}
/**
@internal
*/
get isHidden() {
return false;
}
/**
@internal
*/
get editable() {
return false;
}
/**
This is called when the an instance of the widget is removed
from the editor view.
*/
destroy(dom) {}
};
/**
The different types of blocks that can occur in an editor view.
*/
BlockType$1 = /* @__PURE__ */function (BlockType$2) {
/**
A line of text.
*/
BlockType$2[BlockType$2["Text"] = 0] = "Text";
/**
A block widget associated with the position after it.
*/
BlockType$2[BlockType$2["WidgetBefore"] = 1] = "WidgetBefore";
/**
A block widget associated with the position before it.
*/
BlockType$2[BlockType$2["WidgetAfter"] = 2] = "WidgetAfter";
/**
A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.
*/
BlockType$2[BlockType$2["WidgetRange"] = 3] = "WidgetRange";
return BlockType$2;
}(BlockType$1 || (BlockType$1 = {}));
/**
A decoration provides information on how to draw or style a piece
of content. You'll usually use it wrapped in a
[`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.
@nonabstract
*/
_export("Ot", Decoration$1 = class extends RangeValue {
constructor(startSide, endSide, widget, spec) {
super();
this.startSide = startSide;
this.endSide = endSide;
this.widget = widget;
this.spec = spec;
}
/**
@internal
*/
get heightRelevant() {
return false;
}
/**
Create a mark decoration, which influences the styling of the
content in its range. Nested mark decorations will cause nested
DOM elements to be created. Nesting order is determined by
precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
the higher-precedence decorations creating the inner DOM nodes.
Such elements are split on line boundaries and on the boundaries
of lower-precedence decorations.
*/
static mark(spec) {
return new MarkDecoration$1(spec);
}
/**
Create a widget decoration, which displays a DOM element at the
given position.
*/
static widget(spec) {
let side = Math.max(-1e4, Math.min(1e4, spec.side || 0)),
block = !!spec.block;
side += block && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8;
return new PointDecoration$1(spec, side, side, block, spec.widget || null, false);
}
/**
Create a replace decoration which replaces the given range with
a widget, or simply hides it.
*/
static replace(spec) {
let block = !!spec.block,
startSide,
endSide;
if (spec.isBlockGap) {
startSide = -5e8;
endSide = 4e8;
} else {
let {
start,
end
} = getInclusive$1(spec, block);
startSide = (start ? block ? -3e8 : -1 : 5e8) - 1;
endSide = (end ? block ? 2e8 : 1 : -6e8) + 1;
}
return new PointDecoration$1(spec, startSide, endSide, block, spec.widget || null, true);
}
/**
Create a line decoration, which can add DOM attributes to the
line starting at the given position.
*/
static line(spec) {
return new LineDecoration$1(spec);
}
/**
Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
decorated range or ranges. If the ranges aren't already sorted,
pass `true` for `sort` to make the library sort them for you.
*/
static set(of, sort = false) {
return RangeSet$1.of(of, sort);
}
/**
@internal
*/
hasHeight() {
return this.widget ? this.widget.estimatedHeight > -1 : false;
}
});
/**
The empty set of decorations.
*/
Decoration$1.none = RangeSet$1.empty;
MarkDecoration$1 = class MarkDecoration$1 extends Decoration$1 {
constructor(spec) {
let {
start,
end
} = getInclusive$1(spec);
super(start ? -1 : 5e8, end ? 1 : -6e8, null, spec);
this.tagName = spec.tagName || "span";
this.class = spec.class || "";
this.attrs = spec.attributes || null;
}
eq(other) {
var _a$2, _b;
return this == other || other instanceof MarkDecoration$1 && this.tagName == other.tagName && (this.class || ((_a$2 = this.attrs) === null || _a$2 === void 0 ? void 0 : _a$2.class)) == (other.class || ((_b = other.attrs) === null || _b === void 0 ? void 0 : _b.class)) && attrsEq$1(this.attrs, other.attrs, "class");
}
range(from, to = from) {
if (from >= to) throw new RangeError("Mark decorations may not be empty");
return super.range(from, to);
}
};
MarkDecoration$1.prototype.point = false;
LineDecoration$1 = class LineDecoration$1 extends Decoration$1 {
constructor(spec) {
super(-2e8, -2e8, null, spec);
}
eq(other) {
return other instanceof LineDecoration$1 && this.spec.class == other.spec.class && attrsEq$1(this.spec.attributes, other.spec.attributes);
}
range(from, to = from) {
if (to != from) throw new RangeError("Line decoration ranges must be zero-length");
return super.range(from, to);
}
};
LineDecoration$1.prototype.mapMode = MapMode.TrackBefore;
LineDecoration$1.prototype.point = true;
PointDecoration$1 = class PointDecoration$1 extends Decoration$1 {
constructor(spec, startSide, endSide, block, widget, isReplace) {
super(startSide, endSide, widget, spec);
this.block = block;
this.isReplace = isReplace;
this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
}
get type() {
return this.startSide != this.endSide ? BlockType$1.WidgetRange : this.startSide <= 0 ? BlockType$1.WidgetBefore : BlockType$1.WidgetAfter;
}
get heightRelevant() {
return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
}
eq(other) {
return other instanceof PointDecoration$1 && widgetsEq$1(this.widget, other.widget) && this.block == other.block && this.startSide == other.startSide && this.endSide == other.endSide;
}
range(from, to = from) {
if (this.isReplace && (from > to || from == to && this.startSide > 0 && this.endSide <= 0)) throw new RangeError("Invalid range for replacement decoration");
if (!this.isReplace && to != from) throw new RangeError("Widget decorations can only have zero-length ranges");
return super.range(from, to);
}
};
PointDecoration$1.prototype.point = true;
ContentBuilder$1 = class ContentBuilder$1 {
constructor(doc$2, pos, end, disallowBlockEffectsFor) {
this.doc = doc$2;
this.pos = pos;
this.end = end;
this.disallowBlockEffectsFor = disallowBlockEffectsFor;
this.content = [];
this.curLine = null;
this.breakAtStart = 0;
this.pendingBuffer = 0;
this.bufferMarks = [];
this.atCursorPos = true;
this.openStart = -1;
this.openEnd = -1;
this.text = "";
this.textOff = 0;
this.cursor = doc$2.iter();
this.skip = pos;
}
posCovered() {
if (this.content.length == 0) return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
let last = this.content[this.content.length - 1];
return !(last.breakAfter || last instanceof BlockWidgetView$1 && last.deco.endSide < 0);
}
getLine() {
if (!this.curLine) {
this.content.push(this.curLine = new LineView$1());
this.atCursorPos = true;
}
return this.curLine;
}
flushBuffer(active = this.bufferMarks) {
if (this.pendingBuffer) {
this.curLine.append(wrapMarks$1(new WidgetBufferView$1(-1), active), active.length);
this.pendingBuffer = 0;
}
}
addBlockWidget(view) {
this.flushBuffer();
this.curLine = null;
this.content.push(view);
}
finish(openEnd) {
if (this.pendingBuffer && openEnd <= this.bufferMarks.length) this.flushBuffer();else this.pendingBuffer = 0;
if (!this.posCovered() && !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView$1)) this.getLine();
}
buildText(length, active, openStart) {
while (length > 0) {
if (this.textOff == this.text.length) {
let {
value,
lineBreak,
done
} = this.cursor.next(this.skip);
this.skip = 0;
if (done) throw new Error("Ran out of text content when drawing inline views");
if (lineBreak) {
if (!this.posCovered()) this.getLine();
if (this.content.length) this.content[this.content.length - 1].breakAfter = 1;else this.breakAtStart = 1;
this.flushBuffer();
this.curLine = null;
this.atCursorPos = true;
length--;
continue;
} else {
this.text = value;
this.textOff = 0;
}
}
let take = Math.min(this.text.length - this.textOff, length, 512);
this.flushBuffer(active.slice(active.length - openStart));
this.getLine().append(wrapMarks$1(new TextView$1(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
this.atCursorPos = true;
this.textOff += take;
length -= take;
openStart = 0;
}
}
span(from, to, active, openStart) {
this.buildText(to - from, active, openStart);
this.pos = to;
if (this.openStart < 0) this.openStart = openStart;
}
point(from, to, deco, active, openStart, index) {
if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration$1) {
if (deco.block) throw new RangeError("Block decorations may not be specified via plugins");
if (to > this.doc.lineAt(this.pos).to) throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
}
let len = to - from;
if (deco instanceof PointDecoration$1) {
if (deco.block) {
if (deco.startSide > 0 && !this.posCovered()) this.getLine();
this.addBlockWidget(new BlockWidgetView$1(deco.widget || NullWidget$1.block, len, deco));
} else {
let view = WidgetView$1.create(deco.widget || NullWidget$1.inline, len, len ? 0 : deco.startSide);
let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0);
let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);
let line = this.getLine();
if (this.pendingBuffer == 2 && !cursorBefore && !view.isEditable) this.pendingBuffer = 0;
this.flushBuffer(active);
if (cursorBefore) {
line.append(wrapMarks$1(new WidgetBufferView$1(1), active), openStart);
openStart = active.length + Math.max(0, openStart - active.length);
}
line.append(wrapMarks$1(view, active), openStart);
this.atCursorPos = cursorAfter;
this.pendingBuffer = !cursorAfter ? 0 : from < to || openStart > active.length ? 1 : 2;
if (this.pendingBuffer) this.bufferMarks = active.slice();
}
} else if (this.doc.lineAt(this.pos).from == this.pos) this.getLine().addLineDeco(deco);
if (len) {
if (this.textOff + len <= this.text.length) this.textOff += len;else {
this.skip += len - (this.text.length - this.textOff);
this.text = "";
this.textOff = 0;
}
this.pos = to;
}
if (this.openStart < 0) this.openStart = openStart;
}
static build(text, from, to, decorations$2, dynamicDecorationMap) {
let builder = new ContentBuilder$1(text, from, to, dynamicDecorationMap);
builder.openEnd = RangeSet$1.spans(decorations$2, from, to, builder);
if (builder.openStart < 0) builder.openStart = builder.openEnd;
builder.finish(builder.openEnd);
return builder;
}
};
NullWidget$1 = class extends WidgetType$1 {
constructor(tag) {
super();
this.tag = tag;
}
eq(other) {
return other.tag == this.tag;
}
toDOM() {
return document.createElement(this.tag);
}
updateDOM(elt) {
return elt.nodeName.toLowerCase() == this.tag;
}
get isHidden() {
return true;
}
};
NullWidget$1.inline = /* @__PURE__ */new NullWidget$1("span");
NullWidget$1.block = /* @__PURE__ */new NullWidget$1("div");
/**
Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
*/
Direction$1 = /* @__PURE__ */function (Direction$2) {
/**
Left-to-right.
*/
Direction$2[Direction$2["LTR"] = 0] = "LTR";
/**
Right-to-left.
*/
Direction$2[Direction$2["RTL"] = 1] = "RTL";
return Direction$2;
}(Direction$1 || (Direction$1 = {}));
LTR$1 = Direction$1.LTR, RTL$1 = Direction$1.RTL;
LowTypes$1 = /* @__PURE__ */dec$1("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
ArabicTypes$1 = /* @__PURE__ */dec$1("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
Brackets$1 = /* @__PURE__ */Object.create(null), BracketStack$1 = [];
for (let p of ["()", "[]", "{}"]) {
let l = /* @__PURE__ */p.charCodeAt(0),
r = /* @__PURE__ */p.charCodeAt(1);
Brackets$1[l] = r;
Brackets$1[r] = -l;
}
BidiRE$1 = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
/**
Represents a contiguous range of text that has a single direction
(as in left-to-right or right-to-left).
*/
BidiSpan$1 = class {
/**
The direction of this span.
*/
get dir() {
return this.level % 2 ? RTL$1 : LTR$1;
}
/**
@internal
*/
constructor(from, to, level) {
this.from = from;
this.to = to;
this.level = level;
}
/**
@internal
*/
side(end, dir) {
return this.dir == dir == end ? this.to : this.from;
}
/**
@internal
*/
forward(forward, dir) {
return forward == (this.dir == dir);
}
/**
@internal
*/
static find(order, index, level, assoc) {
let maybe = -1;
for (let i$1 = 0; i$1 < order.length; i$1++) {
let span = order[i$1];
if (span.from <= index && span.to >= index) {
if (span.level == level) return i$1;
if (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index : span.to > index : order[maybe].level > span.level)) maybe = i$1;
}
}
if (maybe < 0) throw new RangeError("Index out of range");
return maybe;
}
};
types$1 = [];
movedOver$1 = "";
clickAddsSelectionRange$1 = /* @__PURE__ */Facet$1.define();
dragMovesSelection$1$1 = /* @__PURE__ */Facet$1.define();
mouseSelectionStyle$1 = /* @__PURE__ */Facet$1.define();
exceptionSink$1 = /* @__PURE__ */Facet$1.define();
updateListener$1 = /* @__PURE__ */Facet$1.define();
inputHandler$2 = /* @__PURE__ */Facet$1.define();
focusChangeEffect$1 = /* @__PURE__ */Facet$1.define();
perLineTextDirection$1 = /* @__PURE__ */Facet$1.define({
combine: values => values.some(x => x)
});
nativeSelectionHidden$1 = /* @__PURE__ */Facet$1.define({
combine: values => values.some(x => x)
});
scrollHandler = /* @__PURE__ */Facet$1.define();
ScrollTarget$1 = class ScrollTarget$1 {
constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
this.range = range;
this.y = y;
this.x = x;
this.yMargin = yMargin;
this.xMargin = xMargin;
this.isSnapshot = isSnapshot;
}
map(changes) {
return changes.empty ? this : new ScrollTarget$1(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
}
clip(state) {
return this.range.to <= state.doc.length ? this : new ScrollTarget$1(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
}
};
scrollIntoView$2 = /* @__PURE__ */StateEffect$1.define({
map: (t$1, ch) => t$1.map(ch)
});
editable$1 = /* @__PURE__ */Facet$1.define({
combine: values => values.length ? values[0] : true
});
nextPluginID$1 = 0;
viewPlugin$1 = /* @__PURE__ */Facet$1.define();
/**
View plugins associate stateful values with a view. They can
influence the way the content is drawn, and are notified of things
that happen in the view.
*/
_export("At", ViewPlugin$1 = class ViewPlugin$1 {
constructor(id$1, create, domEventHandlers, domEventObservers, buildExtensions) {
this.id = id$1;
this.create = create;
this.domEventHandlers = domEventHandlers;
this.domEventObservers = domEventObservers;
this.extension = buildExtensions(this);
}
/**
Define a plugin from a constructor function that creates the
plugin's value, given an editor view.
*/
static define(create, spec) {
const {
eventHandlers,
eventObservers,
provide,
decorations: deco
} = spec || {};
return new ViewPlugin$1(nextPluginID$1++, create, eventHandlers, eventObservers, plugin => {
let ext = [viewPlugin$1.of(plugin)];
if (deco) ext.push(decorations$1.of(view => {
let pluginInst = view.plugin(plugin);
return pluginInst ? deco(pluginInst) : Decoration$1.none;
}));
if (provide) ext.push(provide(plugin));
return ext;
});
}
/**
Create a plugin for a class whose constructor takes a single
editor view as argument.
*/
static fromClass(cls, spec) {
return ViewPlugin$1.define(view => new cls(view), spec);
}
});
PluginInstance$1 = class {
constructor(spec) {
this.spec = spec;
this.mustUpdate = null;
this.value = null;
}
update(view) {
if (!this.value) {
if (this.spec) try {
this.value = this.spec.create(view);
} catch (e) {
logException$1(view.state, e, "CodeMirror plugin crashed");
this.deactivate();
}
} else if (this.mustUpdate) {
let update = this.mustUpdate;
this.mustUpdate = null;
if (this.value.update) try {
this.value.update(update);
} catch (e) {
logException$1(update.state, e, "CodeMirror plugin crashed");
if (this.value.destroy) try {
this.value.destroy();
} catch (_) {}
this.deactivate();
}
}
return this;
}
destroy(view) {
var _a$2;
if ((_a$2 = this.value) === null || _a$2 === void 0 ? void 0 : _a$2.destroy) try {
this.value.destroy();
} catch (e) {
logException$1(view.state, e, "CodeMirror plugin crashed");
}
}
deactivate() {
this.spec = this.value = null;
}
};
editorAttributes$1 = /* @__PURE__ */Facet$1.define();
contentAttributes$1 = /* @__PURE__ */Facet$1.define();
decorations$1 = /* @__PURE__ */Facet$1.define();
outerDecorations = /* @__PURE__ */Facet$1.define();
atomicRanges$1 = /* @__PURE__ */Facet$1.define();
bidiIsolatedRanges$1 = /* @__PURE__ */Facet$1.define();
scrollMargins$1 = /* @__PURE__ */Facet$1.define();
styleModule$1 = /* @__PURE__ */Facet$1.define();
ChangedRange$1 = class ChangedRange$1 {
constructor(fromA, toA, fromB, toB) {
this.fromA = fromA;
this.toA = toA;
this.fromB = fromB;
this.toB = toB;
}
join(other) {
return new ChangedRange$1(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));
}
addToSet(set) {
let i$1 = set.length,
me = this;
for (; i$1 > 0; i$1--) {
let range = set[i$1 - 1];
if (range.fromA > me.toA) continue;
if (range.toA < me.fromA) break;
me = me.join(range);
set.splice(i$1 - 1, 1);
}
set.splice(i$1, 0, me);
return set;
}
static extendWithRanges(diff, ranges) {
if (ranges.length == 0) return diff;
let result = [];
for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {
let next = dI == diff.length ? null : diff[dI],
off = posA - posB;
let end = next ? next.fromB : 1e9;
while (rI < ranges.length && ranges[rI] < end) {
let from = ranges[rI],
to = ranges[rI + 1];
let fromB = Math.max(posB, from),
toB = Math.min(end, to);
if (fromB <= toB) new ChangedRange$1(fromB + off, toB + off, fromB, toB).addToSet(result);
if (to > end) break;else rI += 2;
}
if (!next) return result;
new ChangedRange$1(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);
posA = next.toA;
posB = next.toB;
}
}
};
/**
View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this
class, which describe what happened, whenever the view is updated.
*/
ViewUpdate$1 = class ViewUpdate$1 {
constructor(view, state, transactions) {
this.view = view;
this.state = state;
this.transactions = transactions;
/**
@internal
*/
this.flags = 0;
this.startState = view.state;
this.changes = ChangeSet.empty(this.startState.doc.length);
for (let tr of transactions) this.changes = this.changes.compose(tr.changes);
let changedRanges = [];
this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange$1(fromA, toA, fromB, toB)));
this.changedRanges = changedRanges;
}
/**
@internal
*/
static create(view, state, transactions) {
return new ViewUpdate$1(view, state, transactions);
}
/**
Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
[visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
update.
*/
get viewportChanged() {
return (this.flags & 4) > 0;
}
/**
Indicates whether the height of a block element in the editor
changed in this update.
*/
get heightChanged() {
return (this.flags & 2) > 0;
}
/**
Returns true when the document was modified or the size of the
editor, or elements within the editor, changed.
*/
get geometryChanged() {
return this.docChanged || (this.flags & 10) > 0;
}
/**
True when this update indicates a focus change.
*/
get focusChanged() {
return (this.flags & 1) > 0;
}
/**
Whether the document changed in this update.
*/
get docChanged() {
return !this.changes.empty;
}
/**
Whether the selection was explicitly set in this update.
*/
get selectionSet() {
return this.transactions.some(tr => tr.selection);
}
/**
@internal
*/
get empty() {
return this.flags == 0 && this.transactions.length == 0;
}
};
DocView$1 = class extends ContentView$1 {
get length() {
return this.view.state.doc.length;
}
constructor(view) {
super();
this.view = view;
this.decorations = [];
this.dynamicDecorationMap = [];
this.domChanged = null;
this.hasComposition = null;
this.markedForComposition = /* @__PURE__ */new Set();
this.lastCompositionAfterCursor = false;
this.minWidth = 0;
this.minWidthFrom = 0;
this.minWidthTo = 0;
this.impreciseAnchor = null;
this.impreciseHead = null;
this.forceSelection = false;
this.lastUpdate = Date.now();
this.setDOM(view.contentDOM);
this.children = [new LineView$1()];
this.children[0].setParent(this);
this.updateDeco();
this.updateInner([new ChangedRange$1(0, 0, 0, view.state.doc.length)], 0, null);
}
update(update) {
var _a$2;
let changedRanges = update.changedRanges;
if (this.minWidth > 0 && changedRanges.length) if (!changedRanges.every(({
fromA,
toA
}) => toA < this.minWidthFrom || fromA > this.minWidthTo)) this.minWidth = this.minWidthFrom = this.minWidthTo = 0;else {
this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
}
let readCompositionAt = -1;
if (this.view.inputState.composing >= 0) {
if ((_a$2 = this.domChanged) === null || _a$2 === void 0 ? void 0 : _a$2.newSel) readCompositionAt = this.domChanged.newSel.head;else if (!touchesComposition$1(update.changes, this.hasComposition) && !update.selectionSet) readCompositionAt = update.state.selection.main.head;
}
let composition = readCompositionAt > -1 ? findCompositionRange$1(this.view, update.changes, readCompositionAt) : null;
this.domChanged = null;
if (this.hasComposition) {
this.markedForComposition.clear();
let {
from,
to
} = this.hasComposition;
changedRanges = new ChangedRange$1(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1)).addToSet(changedRanges.slice());
}
this.hasComposition = composition ? {
from: composition.range.fromB,
to: composition.range.toB
} : null;
if ((browser$1.ie || browser$1.chrome) && !composition && update && update.state.doc.lines != update.startState.doc.lines) this.forceSelection = true;
let prevDeco = this.decorations;
let decoDiff = findChangedDeco$1(prevDeco, this.updateDeco(), update.changes);
changedRanges = ChangedRange$1.extendWithRanges(changedRanges, decoDiff);
if (!(this.flags & 7) && changedRanges.length == 0) return false;else {
this.updateInner(changedRanges, update.startState.doc.length, composition);
if (update.transactions.length) this.lastUpdate = Date.now();
return true;
}
}
updateInner(changes, oldLength, composition) {
this.view.viewState.mustMeasureContent = true;
this.updateChildren(changes, oldLength, composition);
let {
observer
} = this.view;
observer.ignore(() => {
this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
let track = browser$1.chrome || browser$1.ios ? {
node: observer.selectionRange.focusNode,
written: false
} : void 0;
this.sync(this.view, track);
this.flags &= -8;
if (track && (track.written || observer.selectionRange.focusNode != track.node)) this.forceSelection = true;
this.dom.style.height = "";
});
this.markedForComposition.forEach(cView => cView.flags &= -9);
let gaps = [];
if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) {
for (let child of this.children) if (child instanceof BlockWidgetView$1 && child.widget instanceof BlockGapWidget$1) gaps.push(child.dom);
}
observer.updateGaps(gaps);
}
updateChildren(changes, oldLength, composition) {
let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;
let cursor = this.childCursor(oldLength);
for (let i$1 = ranges.length - 1;; i$1--) {
let next = i$1 >= 0 ? ranges[i$1] : null;
if (!next) break;
let {
fromA,
toA,
fromB,
toB
} = next,
content$1,
breakAtStart,
openStart,
openEnd;
if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {
let before = ContentBuilder$1.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);
let after = ContentBuilder$1.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);
breakAtStart = before.breakAtStart;
openStart = before.openStart;
openEnd = after.openEnd;
let compLine = this.compositionView(composition);
if (after.breakAtStart) compLine.breakAfter = 1;else if (after.content.length && compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {
compLine.breakAfter = after.content[0].breakAfter;
after.content.shift();
}
if (before.content.length && compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) before.content.pop();
content$1 = before.content.concat(compLine).concat(after.content);
} else ({
content: content$1,
breakAtStart,
openStart,
openEnd
} = ContentBuilder$1.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));
let {
i: toI,
off: toOff
} = cursor.findPos(toA, 1);
let {
i: fromI,
off: fromOff
} = cursor.findPos(fromA, -1);
replaceRange$1(this, fromI, fromOff, toI, toOff, content$1, breakAtStart, openStart, openEnd);
}
if (composition) this.fixCompositionDOM(composition);
}
compositionView(composition) {
let cur$1 = new TextView$1(composition.text.nodeValue);
cur$1.flags |= 8;
for (let {
deco
} of composition.marks) cur$1 = new MarkView$1(deco, [cur$1], cur$1.length);
let line = new LineView$1();
line.append(cur$1, 0);
return line;
}
fixCompositionDOM(composition) {
let fix = (dom, cView$1) => {
cView$1.flags |= 8 | (cView$1.children.some(c => c.flags & 7) ? 1 : 0);
this.markedForComposition.add(cView$1);
let prev = ContentView$1.get(dom);
if (prev && prev != cView$1) prev.dom = null;
cView$1.setDOM(dom);
};
let pos = this.childPos(composition.range.fromB, 1);
let cView = this.children[pos.i];
fix(composition.line, cView);
for (let i$1 = composition.marks.length - 1; i$1 >= -1; i$1--) {
pos = cView.childPos(pos.off, 1);
cView = cView.children[pos.i];
fix(i$1 >= 0 ? composition.marks[i$1].node : composition.text, cView);
}
}
updateSelection(mustRead = false, fromPointer = false) {
if (mustRead || !this.view.observer.selectionRange.focusNode) this.view.observer.readSelectionRange();
let activeElt = this.view.root.activeElement,
focused = activeElt == this.dom;
let selectionNotFocus = !focused && hasSelection$1(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));
if (!(focused || fromPointer || selectionNotFocus)) return;
let force = this.forceSelection;
this.forceSelection = false;
let main = this.view.state.selection.main;
let anchor = this.moveToLine(this.domAtPos(main.anchor));
let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));
if (browser$1.gecko && main.empty && !this.hasComposition && betweenUneditable$1(anchor)) {
let dummy = document.createTextNode("");
this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
anchor = head = new DOMPos$1(dummy, 0);
force = true;
}
let domSel = this.view.observer.selectionRange;
if (force || !domSel.focusNode || (!isEquivalentPosition$1(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || !isEquivalentPosition$1(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) && !this.suppressWidgetCursorChange(domSel, main)) {
this.view.observer.ignore(() => {
if (browser$1.android && browser$1.chrome && this.dom.contains(domSel.focusNode) && inUneditable$1(domSel.focusNode, this.dom)) {
this.dom.blur();
this.dom.focus({
preventScroll: true
});
}
let rawSel = getSelection$1(this.view.root);
if (!rawSel) ;else if (main.empty) {
if (browser$1.gecko) {
let nextTo = nextToUneditable$1(anchor.node, anchor.offset);
if (nextTo && nextTo != 3) {
let text = (nextTo == 1 ? textNodeBefore : textNodeAfter)(anchor.node, anchor.offset);
if (text) anchor = new DOMPos$1(text.node, text.offset);
}
}
rawSel.collapse(anchor.node, anchor.offset);
if (main.bidiLevel != null && rawSel.caretBidiLevel !== void 0) rawSel.caretBidiLevel = main.bidiLevel;
} else if (rawSel.extend) {
rawSel.collapse(anchor.node, anchor.offset);
try {
rawSel.extend(head.node, head.offset);
} catch (_) {}
} else {
let range = document.createRange();
if (main.anchor > main.head) [anchor, head] = [head, anchor];
range.setEnd(head.node, head.offset);
range.setStart(anchor.node, anchor.offset);
rawSel.removeAllRanges();
rawSel.addRange(range);
}
if (selectionNotFocus && this.view.root.activeElement == this.dom) {
this.dom.blur();
if (activeElt) activeElt.focus();
}
});
this.view.observer.setSelectionRange(anchor, head);
}
this.impreciseAnchor = anchor.precise ? null : new DOMPos$1(domSel.anchorNode, domSel.anchorOffset);
this.impreciseHead = head.precise ? null : new DOMPos$1(domSel.focusNode, domSel.focusOffset);
}
suppressWidgetCursorChange(sel, cursor) {
return this.hasComposition && cursor.empty && isEquivalentPosition$1(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset) && this.posFromDOM(sel.focusNode, sel.focusOffset) == cursor.head;
}
enforceCursorAssoc() {
if (this.hasComposition) return;
let {
view
} = this,
cursor = view.state.selection.main;
let sel = getSelection$1(view.root);
let {
anchorNode,
anchorOffset
} = view.observer.selectionRange;
if (!sel || !cursor.empty || !cursor.assoc || !sel.modify) return;
let line = LineView$1.find(this, cursor.head);
if (!line) return;
let lineStart = line.posAtStart;
if (cursor.head == lineStart || cursor.head == lineStart + line.length) return;
let before = this.coordsAt(cursor.head, -1),
after = this.coordsAt(cursor.head, 1);
if (!before || !after || before.bottom > after.top) return;
let dom = this.domAtPos(cursor.head + cursor.assoc);
sel.collapse(dom.node, dom.offset);
sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
view.observer.readSelectionRange();
let newRange = view.observer.selectionRange;
if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from) sel.collapse(anchorNode, anchorOffset);
}
moveToLine(pos) {
let dom = this.dom,
newPos;
if (pos.node != dom) return pos;
for (let i$1 = pos.offset; !newPos && i$1 < dom.childNodes.length; i$1++) {
let view = ContentView$1.get(dom.childNodes[i$1]);
if (view instanceof LineView$1) newPos = view.domAtPos(0);
}
for (let i$1 = pos.offset - 1; !newPos && i$1 >= 0; i$1--) {
let view = ContentView$1.get(dom.childNodes[i$1]);
if (view instanceof LineView$1) newPos = view.domAtPos(view.length);
}
return newPos ? new DOMPos$1(newPos.node, newPos.offset, true) : pos;
}
nearest(dom) {
for (let cur$1 = dom; cur$1;) {
let domView = ContentView$1.get(cur$1);
if (domView && domView.rootView == this) return domView;
cur$1 = cur$1.parentNode;
}
return null;
}
posFromDOM(node, offset) {
let view = this.nearest(node);
if (!view) throw new RangeError("Trying to find position for a DOM position outside of the document");
return view.localPosFromDOM(node, offset) + view.posAtStart;
}
domAtPos(pos) {
let {
i: i$1,
off
} = this.childCursor().findPos(pos, -1);
for (; i$1 < this.children.length - 1;) {
let child = this.children[i$1];
if (off < child.length || child instanceof LineView$1) break;
i$1++;
off = 0;
}
return this.children[i$1].domAtPos(off);
}
coordsAt(pos, side) {
let best = null,
bestPos = 0;
for (let off = this.length, i$1 = this.children.length - 1; i$1 >= 0; i$1--) {
let child = this.children[i$1],
end = off - child.breakAfter,
start = end - child.length;
if (end < pos) break;
if (start <= pos && (start < pos || child.covers(-1)) && (end > pos || child.covers(1)) && (!best || child instanceof LineView$1 && !(best instanceof LineView$1 && side >= 0))) {
best = child;
bestPos = start;
}
off = start;
}
return best ? best.coordsAt(pos - bestPos, side) : null;
}
coordsForChar(pos) {
let {
i: i$1,
off
} = this.childPos(pos, 1),
child = this.children[i$1];
if (!(child instanceof LineView$1)) return null;
while (child.children.length) {
let {
i: i$2,
off: childOff
} = child.childPos(off, 1);
for (;; i$2++) {
if (i$2 == child.children.length) return null;
if ((child = child.children[i$2]).length) break;
}
off = childOff;
}
if (!(child instanceof TextView$1)) return null;
let end = findClusterBreak(child.text, off);
if (end == off) return null;
let rects = textRange$1(child.dom, off, end).getClientRects();
for (let i$2 = 0; i$2 < rects.length; i$2++) {
let rect = rects[i$2];
if (i$2 == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right) return rect;
}
return null;
}
measureVisibleLineHeights(viewport) {
let result = [],
{
from,
to
} = viewport;
let contentWidth = this.view.contentDOM.clientWidth;
let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
let widest = -1,
ltr = this.view.textDirection == Direction$1.LTR;
for (let pos = 0, i$1 = 0; i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (end > to) break;
if (pos >= from) {
let childRect = child.dom.getBoundingClientRect();
result.push(childRect.height);
if (isWider) {
let last = child.dom.lastChild;
let rects = last ? clientRectsFor$1(last) : [];
if (rects.length) {
let rect = rects[rects.length - 1];
let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
if (width > widest) {
widest = width;
this.minWidth = contentWidth;
this.minWidthFrom = pos;
this.minWidthTo = end;
}
}
}
}
pos = end + child.breakAfter;
}
return result;
}
textDirectionAt(pos) {
let {
i: i$1
} = this.childPos(pos, 1);
return getComputedStyle(this.children[i$1].dom).direction == "rtl" ? Direction$1.RTL : Direction$1.LTR;
}
measureTextSize() {
for (let child of this.children) if (child instanceof LineView$1) {
let measure = child.measureTextSize();
if (measure) return measure;
}
let dummy = document.createElement("div"),
lineHeight,
charWidth,
textHeight;
dummy.className = "cm-line";
dummy.style.width = "99999px";
dummy.style.position = "absolute";
dummy.textContent = "abc def ghi jkl mno pqr stu";
this.view.observer.ignore(() => {
this.dom.appendChild(dummy);
let rect = clientRectsFor$1(dummy.firstChild)[0];
lineHeight = dummy.getBoundingClientRect().height;
charWidth = rect ? rect.width / 27 : 7;
textHeight = rect ? rect.height : lineHeight;
dummy.remove();
});
return {
lineHeight,
charWidth,
textHeight
};
}
childCursor(pos = this.length) {
let i$1 = this.children.length;
if (i$1) pos -= this.children[--i$1].length;
return new ChildCursor$1(this.children, pos, i$1);
}
computeBlockGapDeco() {
let deco = [],
vs = this.view.viewState;
for (let pos = 0, i$1 = 0;; i$1++) {
let next = i$1 == vs.viewports.length ? null : vs.viewports[i$1];
let end = next ? next.from - 1 : this.length;
if (end > pos) {
let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
deco.push(Decoration$1.replace({
widget: new BlockGapWidget$1(height),
block: true,
inclusive: true,
isBlockGap: true
}).range(pos, end));
}
if (!next) break;
pos = next.to + 1;
}
return Decoration$1.set(deco);
}
updateDeco() {
let i$1 = 0;
let allDeco = this.view.state.facet(decorations$1).map(d => {
return (this.dynamicDecorationMap[i$1++] = typeof d == "function") ? d(this.view) : d;
});
let dynamicOuter = false,
outerDeco = this.view.state.facet(outerDecorations).map((d, i$2) => {
let dynamic = typeof d == "function";
if (dynamic) dynamicOuter = true;
return dynamic ? d(this.view) : d;
});
if (outerDeco.length) {
this.dynamicDecorationMap[i$1++] = dynamicOuter;
allDeco.push(RangeSet$1.join(outerDeco));
}
this.decorations = [...allDeco, this.computeBlockGapDeco(), this.view.viewState.lineGapDeco];
while (i$1 < this.decorations.length) this.dynamicDecorationMap[i$1++] = false;
return this.decorations;
}
scrollIntoView(target) {
if (target.isSnapshot) {
let ref$1 = this.view.viewState.lineBlockAt(target.range.head);
this.view.scrollDOM.scrollTop = ref$1.top - target.yMargin;
this.view.scrollDOM.scrollLeft = target.xMargin;
return;
}
for (let handler of this.view.state.facet(scrollHandler)) try {
if (handler(this.view, target.range, target)) return true;
} catch (e) {
logException$1(this.view.state, e, "scroll handler");
}
let {
range
} = target;
let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1),
other;
if (!rect) return;
if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) rect = {
left: Math.min(rect.left, other.left),
top: Math.min(rect.top, other.top),
right: Math.max(rect.right, other.right),
bottom: Math.max(rect.bottom, other.bottom)
};
let margins = getScrollMargins$1(this.view);
let targetRect = {
left: rect.left - margins.left,
top: rect.top - margins.top,
right: rect.right + margins.right,
bottom: rect.bottom + margins.bottom
};
let {
offsetWidth,
offsetHeight
} = this.view.scrollDOM;
scrollRectIntoView$1(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction$1.LTR);
}
};
BlockGapWidget$1 = class extends WidgetType$1 {
constructor(height) {
super();
this.height = height;
}
toDOM() {
let elt = document.createElement("div");
elt.className = "cm-gap";
this.updateDOM(elt);
return elt;
}
eq(other) {
return other.height == this.height;
}
updateDOM(elt) {
elt.style.height = this.height + "px";
return true;
}
get editable() {
return true;
}
get estimatedHeight() {
return this.height;
}
ignoreEvent() {
return false;
}
};
DecorationComparator$1$1 = class DecorationComparator$3 {
constructor() {
this.changes = [];
}
compareRange(from, to) {
addRange$1(from, to, this.changes);
}
comparePoint(from, to) {
addRange$1(from, to, this.changes);
}
};
InputState$1 = class {
setSelectionOrigin(origin) {
this.lastSelectionOrigin = origin;
this.lastSelectionTime = Date.now();
}
constructor(view) {
this.view = view;
this.lastKeyCode = 0;
this.lastKeyTime = 0;
this.lastTouchTime = 0;
this.lastFocusTime = 0;
this.lastScrollTop = 0;
this.lastScrollLeft = 0;
this.pendingIOSKey = void 0;
this.lastSelectionOrigin = null;
this.lastSelectionTime = 0;
this.lastEscPress = 0;
this.lastContextMenu = 0;
this.scrollHandlers = [];
this.handlers = Object.create(null);
this.composing = -1;
this.compositionFirstChange = null;
this.compositionEndedAt = 0;
this.compositionPendingKey = false;
this.compositionPendingChange = false;
this.mouseSelection = null;
this.draggedContent = null;
this.handleEvent = this.handleEvent.bind(this);
this.notifiedFocused = view.hasFocus;
if (browser$1.safari) view.contentDOM.addEventListener("input", () => null);
if (browser$1.gecko) firefoxCopyCutHack$1(view.contentDOM.ownerDocument);
}
handleEvent(event) {
if (!eventBelongsToEditor$1(this.view, event) || this.ignoreDuringComposition(event)) return;
if (event.type == "keydown" && this.keydown(event)) return;
this.runHandlers(event.type, event);
}
runHandlers(type, event) {
let handlers$2 = this.handlers[type];
if (handlers$2) {
for (let observer of handlers$2.observers) observer(this.view, event);
for (let handler of handlers$2.handlers) {
if (event.defaultPrevented) break;
if (handler(this.view, event)) {
event.preventDefault();
break;
}
}
}
}
ensureHandlers(plugins) {
let handlers$2 = computeHandlers$1(plugins),
prev = this.handlers,
dom = this.view.contentDOM;
for (let type in handlers$2) if (type != "scroll") {
let passive = !handlers$2[type].handlers.length;
let exists = prev[type];
if (exists && passive != !exists.handlers.length) {
dom.removeEventListener(type, this.handleEvent);
exists = null;
}
if (!exists) dom.addEventListener(type, this.handleEvent, {
passive
});
}
for (let type in prev) if (type != "scroll" && !handlers$2[type]) dom.removeEventListener(type, this.handleEvent);
this.handlers = handlers$2;
}
keydown(event) {
this.lastKeyCode = event.keyCode;
this.lastKeyTime = Date.now();
if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2e3) return true;
if (event.keyCode != 27 && modifierCodes$1.indexOf(event.keyCode) < 0) this.view.inputState.lastEscPress = 0;
if (browser$1.android && browser$1.chrome && !event.synthetic && (event.keyCode == 13 || event.keyCode == 8)) {
this.view.observer.delayAndroidKey(event.key, event.keyCode);
return true;
}
let pending;
if (browser$1.ios && !event.synthetic && !event.altKey && !event.metaKey && ((pending = PendingKeys$1.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys$1.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
this.pendingIOSKey = pending || event;
setTimeout(() => this.flushIOSKey(), 250);
return true;
}
if (event.keyCode != 229) this.view.observer.forceFlush();
return false;
}
flushIOSKey(change) {
let key = this.pendingIOSKey;
if (!key) return false;
if (key.key == "Enter" && change && change.from < change.to && /^\S+$/.test(change.insert.toString())) return false;
this.pendingIOSKey = void 0;
return dispatchKey$1(this.view.contentDOM, key.key, key.keyCode, key instanceof KeyboardEvent ? key : void 0);
}
ignoreDuringComposition(event) {
if (!/^key/.test(event.type)) return false;
if (this.composing > 0) return true;
if (browser$1.safari && !browser$1.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
this.compositionPendingKey = false;
return true;
}
return false;
}
startMouseSelection(mouseSelection) {
if (this.mouseSelection) this.mouseSelection.destroy();
this.mouseSelection = mouseSelection;
}
update(update) {
if (this.mouseSelection) this.mouseSelection.update(update);
if (this.draggedContent && update.docChanged) this.draggedContent = this.draggedContent.map(update.changes);
if (update.transactions.length) this.lastKeyCode = this.lastSelectionTime = 0;
}
destroy() {
if (this.mouseSelection) this.mouseSelection.destroy();
}
};
PendingKeys$1 = [{
key: "Backspace",
keyCode: 8,
inputType: "deleteContentBackward"
}, {
key: "Enter",
keyCode: 13,
inputType: "insertParagraph"
}, {
key: "Enter",
keyCode: 13,
inputType: "insertLineBreak"
}, {
key: "Delete",
keyCode: 46,
inputType: "deleteContentForward"
}];
EmacsyPendingKeys$1 = "dthko";
modifierCodes$1 = [16, 17, 18, 20, 91, 92, 224, 225];
dragScrollMargin$1 = 6;
MouseSelection$1 = class {
constructor(view, startEvent, style, mustSelect) {
this.view = view;
this.startEvent = startEvent;
this.style = style;
this.mustSelect = mustSelect;
this.scrollSpeed = {
x: 0,
y: 0
};
this.scrolling = -1;
this.lastEvent = startEvent;
this.scrollParent = scrollableParent$1(view.contentDOM);
this.atoms = view.state.facet(atomicRanges$1).map(f => f(view));
let doc$2 = view.contentDOM.ownerDocument;
doc$2.addEventListener("mousemove", this.move = this.move.bind(this));
doc$2.addEventListener("mouseup", this.up = this.up.bind(this));
this.extend = startEvent.shiftKey;
this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange$1(view, startEvent);
this.dragging = isInPrimarySelection$1(view, startEvent) && getClickType$1(startEvent) == 1 ? null : false;
}
start(event) {
if (this.dragging === false) this.select(event);
}
move(event) {
var _a$2;
if (event.buttons == 0) return this.destroy();
if (this.dragging || this.dragging == null && dist$1(this.startEvent, event) < 10) return;
this.select(this.lastEvent = event);
let sx = 0,
sy = 0;
let rect = ((_a$2 = this.scrollParent) === null || _a$2 === void 0 ? void 0 : _a$2.getBoundingClientRect()) || {
left: 0,
top: 0,
right: this.view.win.innerWidth,
bottom: this.view.win.innerHeight
};
let margins = getScrollMargins$1(this.view);
if (event.clientX - margins.left <= rect.left + dragScrollMargin$1) sx = -dragScrollSpeed$1(rect.left - event.clientX);else if (event.clientX + margins.right >= rect.right - dragScrollMargin$1) sx = dragScrollSpeed$1(event.clientX - rect.right);
if (event.clientY - margins.top <= rect.top + dragScrollMargin$1) sy = -dragScrollSpeed$1(rect.top - event.clientY);else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin$1) sy = dragScrollSpeed$1(event.clientY - rect.bottom);
this.setScrollSpeed(sx, sy);
}
up(event) {
if (this.dragging == null) this.select(this.lastEvent);
if (!this.dragging) event.preventDefault();
this.destroy();
}
destroy() {
this.setScrollSpeed(0, 0);
let doc$2 = this.view.contentDOM.ownerDocument;
doc$2.removeEventListener("mousemove", this.move);
doc$2.removeEventListener("mouseup", this.up);
this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
}
setScrollSpeed(sx, sy) {
this.scrollSpeed = {
x: sx,
y: sy
};
if (sx || sy) {
if (this.scrolling < 0) this.scrolling = setInterval(() => this.scroll(), 50);
} else if (this.scrolling > -1) {
clearInterval(this.scrolling);
this.scrolling = -1;
}
}
scroll() {
if (this.scrollParent) {
this.scrollParent.scrollLeft += this.scrollSpeed.x;
this.scrollParent.scrollTop += this.scrollSpeed.y;
} else this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y);
if (this.dragging === false) this.select(this.lastEvent);
}
skipAtoms(sel) {
let ranges = null;
for (let i$1 = 0; i$1 < sel.ranges.length; i$1++) {
let range = sel.ranges[i$1],
updated = null;
if (range.empty) {
let pos = skipAtomicRanges$1(this.atoms, range.from, 0);
if (pos != range.from) updated = EditorSelection.cursor(pos, -1);
} else {
let from = skipAtomicRanges$1(this.atoms, range.from, -1);
let to = skipAtomicRanges$1(this.atoms, range.to, 1);
if (from != range.from || to != range.to) updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
}
if (updated) {
if (!ranges) ranges = sel.ranges.slice();
ranges[i$1] = updated;
}
}
return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
}
select(event) {
let {
view
} = this,
selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));
if (this.mustSelect || !selection.eq(view.state.selection, this.dragging === false)) this.view.dispatch({
selection,
userEvent: "select.pointer"
});
this.mustSelect = false;
}
update(update) {
if (this.style.update(update)) setTimeout(() => this.select(this.lastEvent), 20);
}
};
handlers$1 = /* @__PURE__ */Object.create(null);
observers$1 = /* @__PURE__ */Object.create(null);
brokenClipboardAPI$1 = browser$1.ie && browser$1.ie_version < 15 || browser$1.ios && browser$1.webkit_version < 604;
observers$1.scroll = view => {
view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
};
handlers$1.keydown = (view, event) => {
view.inputState.setSelectionOrigin("select");
if (event.keyCode == 27) view.inputState.lastEscPress = Date.now();
return false;
};
observers$1.touchstart = (view, e) => {
view.inputState.lastTouchTime = Date.now();
view.inputState.setSelectionOrigin("select.pointer");
};
observers$1.touchmove = view => {
view.inputState.setSelectionOrigin("select.pointer");
};
handlers$1.mousedown = (view, event) => {
view.observer.flush();
if (view.inputState.lastTouchTime > Date.now() - 2e3) return false;
let style = null;
for (let makeStyle of view.state.facet(mouseSelectionStyle$1)) {
style = makeStyle(view, event);
if (style) break;
}
if (!style && event.button == 0) style = basicMouseSelection$1(view, event);
if (style) {
let mustFocus = !view.hasFocus;
view.inputState.startMouseSelection(new MouseSelection$1(view, event, style, mustFocus));
if (mustFocus) view.observer.ignore(() => focusPreventScroll$1(view.contentDOM));
let mouseSel = view.inputState.mouseSelection;
if (mouseSel) {
mouseSel.start(event);
return mouseSel.dragging === false;
}
}
return false;
};
insideY$1 = (y, rect) => y >= rect.top && y <= rect.bottom;
inside$1 = (x, y, rect) => insideY$1(y, rect) && x >= rect.left && x <= rect.right;
BadMouseDetail$1 = browser$1.ie && browser$1.ie_version <= 11;
lastMouseDown$1 = null, lastMouseDownCount$1 = 0, lastMouseDownTime$1 = 0;
handlers$1.dragstart = (view, event) => {
let {
selection: {
main: range
}
} = view.state;
if (event.target.draggable) {
let cView = view.docView.nearest(event.target);
if (cView && cView.isWidget) {
let from = cView.posAtStart,
to = from + cView.length;
if (from >= range.to || to <= range.from) range = EditorSelection.range(from, to);
}
}
let {
inputState
} = view;
if (inputState.mouseSelection) inputState.mouseSelection.dragging = true;
inputState.draggedContent = range;
if (event.dataTransfer) {
event.dataTransfer.setData("Text", view.state.sliceDoc(range.from, range.to));
event.dataTransfer.effectAllowed = "copyMove";
}
return false;
};
handlers$1.dragend = view => {
view.inputState.draggedContent = null;
return false;
};
handlers$1.drop = (view, event) => {
if (!event.dataTransfer) return false;
if (view.state.readOnly) return true;
let files = event.dataTransfer.files;
if (files && files.length) {
let text = Array(files.length),
read$1 = 0;
let finishFile = () => {
if (++read$1 == files.length) dropText$1(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);
};
for (let i$1 = 0; i$1 < files.length; i$1++) {
let reader = new FileReader();
reader.onerror = finishFile;
reader.onload = () => {
if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) text[i$1] = reader.result;
finishFile();
};
reader.readAsText(files[i$1]);
}
return true;
} else {
let text = event.dataTransfer.getData("Text");
if (text) {
dropText$1(view, event, text, true);
return true;
}
}
return false;
};
handlers$1.paste = (view, event) => {
if (view.state.readOnly) return true;
view.observer.flush();
let data = brokenClipboardAPI$1 ? null : event.clipboardData;
if (data) {
doPaste$1(view, data.getData("text/plain") || data.getData("text/uri-list"));
return true;
} else {
capturePaste$1(view);
return false;
}
};
lastLinewiseCopy$1 = null;
handlers$1.copy = handlers$1.cut = (view, event) => {
let {
text,
ranges,
linewise
} = copiedRange$1(view.state);
if (!text && !linewise) return false;
lastLinewiseCopy$1 = linewise ? text : null;
if (event.type == "cut" && !view.state.readOnly) view.dispatch({
changes: ranges,
scrollIntoView: true,
userEvent: "delete.cut"
});
let data = brokenClipboardAPI$1 ? null : event.clipboardData;
if (data) {
data.clearData();
data.setData("text/plain", text);
return true;
} else {
captureCopy$1(view, text);
return false;
}
};
isFocusChange$1 = /* @__PURE__ */Annotation.define();
observers$1.focus = view => {
view.inputState.lastFocusTime = Date.now();
if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
}
updateForFocusChange$1(view);
};
observers$1.blur = view => {
view.observer.clearSelectionRange();
updateForFocusChange$1(view);
};
observers$1.compositionstart = observers$1.compositionupdate = view => {
if (view.inputState.compositionFirstChange == null) view.inputState.compositionFirstChange = true;
if (view.inputState.composing < 0) view.inputState.composing = 0;
};
observers$1.compositionend = view => {
view.inputState.composing = -1;
view.inputState.compositionEndedAt = Date.now();
view.inputState.compositionPendingKey = true;
view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
view.inputState.compositionFirstChange = null;
if (browser$1.chrome && browser$1.android) view.observer.flushSoon();else if (view.inputState.compositionPendingChange) Promise.resolve().then(() => view.observer.flush());else setTimeout(() => {
if (view.inputState.composing < 0 && view.docView.hasComposition) view.update([]);
}, 50);
};
observers$1.contextmenu = view => {
view.inputState.lastContextMenu = Date.now();
};
handlers$1.beforeinput = (view, event) => {
var _a$2;
let pending;
if (browser$1.chrome && browser$1.android && (pending = PendingKeys$1.find(key => key.inputType == event.inputType))) {
view.observer.delayAndroidKey(pending.key, pending.keyCode);
if (pending.key == "Backspace" || pending.key == "Delete") {
let startViewHeight = ((_a$2 = window.visualViewport) === null || _a$2 === void 0 ? void 0 : _a$2.height) || 0;
setTimeout(() => {
var _a$3;
if ((((_a$3 = window.visualViewport) === null || _a$3 === void 0 ? void 0 : _a$3.height) || 0) > startViewHeight + 10 && view.hasFocus) {
view.contentDOM.blur();
view.focus();
}
}, 100);
}
}
if (browser$1.ios && event.inputType == "deleteContentForward") view.observer.flushSoon();
if (browser$1.safari && event.inputType == "insertText" && view.inputState.composing >= 0) setTimeout(() => observers$1.compositionend(view, event), 20);
return false;
};
appliedFirefoxHack$1 = /* @__PURE__ */new Set();
wrappingWhiteSpace$1 = ["pre-wrap", "normal", "pre-line", "break-spaces"];
HeightOracle$1 = class {
constructor(lineWrapping) {
this.lineWrapping = lineWrapping;
this.doc = Text.empty;
this.heightSamples = {};
this.lineHeight = 14;
this.charWidth = 7;
this.textHeight = 14;
this.lineLength = 30;
this.heightChanged = false;
}
heightForGap(from, to) {
let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
if (this.lineWrapping) lines += Math.max(0, Math.ceil((to - from - lines * this.lineLength * .5) / this.lineLength));
return this.lineHeight * lines;
}
heightForLine(length) {
if (!this.lineWrapping) return this.lineHeight;
return (1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)))) * this.lineHeight;
}
setDoc(doc$2) {
this.doc = doc$2;
return this;
}
mustRefreshForWrapping(whiteSpace) {
return wrappingWhiteSpace$1.indexOf(whiteSpace) > -1 != this.lineWrapping;
}
mustRefreshForHeights(lineHeights) {
let newHeight = false;
for (let i$1 = 0; i$1 < lineHeights.length; i$1++) {
let h = lineHeights[i$1];
if (h < 0) i$1++;else if (!this.heightSamples[Math.floor(h * 10)]) {
newHeight = true;
this.heightSamples[Math.floor(h * 10)] = true;
}
}
return newHeight;
}
refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
let lineWrapping = wrappingWhiteSpace$1.indexOf(whiteSpace) > -1;
let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
this.lineWrapping = lineWrapping;
this.lineHeight = lineHeight;
this.charWidth = charWidth;
this.textHeight = textHeight;
this.lineLength = lineLength;
if (changed) {
this.heightSamples = {};
for (let i$1 = 0; i$1 < knownHeights.length; i$1++) {
let h = knownHeights[i$1];
if (h < 0) i$1++;else this.heightSamples[Math.floor(h * 10)] = true;
}
}
return changed;
}
};
MeasuredHeights$1 = class {
constructor(from, heights) {
this.from = from;
this.heights = heights;
this.index = 0;
}
get more() {
return this.index < this.heights.length;
}
};
/**
Record used to represent information about a block-level element
in the editor view.
*/
BlockInfo$1 = class BlockInfo$1 {
/**
@internal
*/
constructor(from, length, top$1, height, _content) {
this.from = from;
this.length = length;
this.top = top$1;
this.height = height;
this._content = _content;
}
/**
The type of element this is. When querying lines, this may be
an array of all the blocks that make up the line.
*/
get type() {
return typeof this._content == "number" ? BlockType$1.Text : Array.isArray(this._content) ? this._content : this._content.type;
}
/**
The end of the element as a document position.
*/
get to() {
return this.from + this.length;
}
/**
The bottom position of the element.
*/
get bottom() {
return this.top + this.height;
}
/**
If this is a widget block, this will return the widget
associated with it.
*/
get widget() {
return this._content instanceof PointDecoration$1 ? this._content.widget : null;
}
/**
If this is a textblock, this holds the number of line breaks
that appear in widgets inside the block.
*/
get widgetLineBreaks() {
return typeof this._content == "number" ? this._content : 0;
}
/**
@internal
*/
join(other) {
let content$1 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]);
return new BlockInfo$1(this.from, this.length + other.length, this.top, this.height + other.height, content$1);
}
};
QueryType$2 = /* @__PURE__ */function (QueryType$3) {
QueryType$3[QueryType$3["ByPos"] = 0] = "ByPos";
QueryType$3[QueryType$3["ByHeight"] = 1] = "ByHeight";
QueryType$3[QueryType$3["ByPosNoHeight"] = 2] = "ByPosNoHeight";
return QueryType$3;
}(QueryType$2 || (QueryType$2 = {}));
Epsilon$1 = .001;
HeightMap$1 = class HeightMap$1 {
constructor(length, height, flags = 2) {
this.length = length;
this.height = height;
this.flags = flags;
}
get outdated() {
return (this.flags & 2) > 0;
}
set outdated(value) {
this.flags = (value ? 2 : 0) | this.flags & -3;
}
setHeight(oracle, height) {
if (this.height != height) {
if (Math.abs(this.height - height) > Epsilon$1) oracle.heightChanged = true;
this.height = height;
}
}
replace(_from, _to, nodes) {
return HeightMap$1.of(nodes);
}
decomposeLeft(_to, result) {
result.push(this);
}
decomposeRight(_from, result) {
result.push(this);
}
applyChanges(decorations$2, oldDoc, oracle, changes) {
let me = this,
doc$2 = oracle.doc;
for (let i$1 = changes.length - 1; i$1 >= 0; i$1--) {
let {
fromA,
toA,
fromB,
toB
} = changes[i$1];
let start = me.lineAt(fromA, QueryType$2.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
let end = start.to >= toA ? start : me.lineAt(toA, QueryType$2.ByPosNoHeight, oracle, 0, 0);
toB += end.to - toA;
toA = end.to;
while (i$1 > 0 && start.from <= changes[i$1 - 1].toA) {
fromA = changes[i$1 - 1].fromA;
fromB = changes[i$1 - 1].fromB;
i$1--;
if (fromA < start.from) start = me.lineAt(fromA, QueryType$2.ByPosNoHeight, oracle, 0, 0);
}
fromB += start.from - fromA;
fromA = start.from;
let nodes = NodeBuilder$1.build(oracle.setDoc(doc$2), decorations$2, fromB, toB);
me = me.replace(fromA, toA, nodes);
}
return me.updateHeight(oracle, 0);
}
static empty() {
return new HeightMapText$1(0, 0);
}
static of(nodes) {
if (nodes.length == 1) return nodes[0];
let i$1 = 0,
j = nodes.length,
before = 0,
after = 0;
for (;;) if (i$1 == j) {
if (before > after * 2) {
let split = nodes[i$1 - 1];
if (split.break) nodes.splice(--i$1, 1, split.left, null, split.right);else nodes.splice(--i$1, 1, split.left, split.right);
j += 1 + split.break;
before -= split.size;
} else if (after > before * 2) {
let split = nodes[j];
if (split.break) nodes.splice(j, 1, split.left, null, split.right);else nodes.splice(j, 1, split.left, split.right);
j += 2 + split.break;
after -= split.size;
} else break;
} else if (before < after) {
let next = nodes[i$1++];
if (next) before += next.size;
} else {
let next = nodes[--j];
if (next) after += next.size;
}
let brk = 0;
if (nodes[i$1 - 1] == null) {
brk = 1;
i$1--;
} else if (nodes[i$1] == null) {
brk = 1;
j++;
}
return new HeightMapBranch$1(HeightMap$1.of(nodes.slice(0, i$1)), brk, HeightMap$1.of(nodes.slice(j)));
}
};
HeightMap$1.prototype.size = 1;
HeightMapBlock$1 = class extends HeightMap$1 {
constructor(length, height, deco) {
super(length, height);
this.deco = deco;
}
blockAt(_height, _oracle, top$1, offset) {
return new BlockInfo$1(offset, this.length, top$1, this.height, this.deco || 0);
}
lineAt(_value, _type, oracle, top$1, offset) {
return this.blockAt(0, oracle, top$1, offset);
}
forEachLine(from, to, oracle, top$1, offset, f) {
if (from <= offset + this.length && to >= offset) f(this.blockAt(0, oracle, top$1, offset));
}
updateHeight(oracle, offset = 0, _force = false, measured) {
if (measured && measured.from <= offset && measured.more) this.setHeight(oracle, measured.heights[measured.index++]);
this.outdated = false;
return this;
}
toString() {
return `block(${this.length})`;
}
};
HeightMapText$1 = class HeightMapText$1 extends HeightMapBlock$1 {
constructor(length, height) {
super(length, height, null);
this.collapsed = 0;
this.widgetHeight = 0;
this.breaks = 0;
}
blockAt(_height, _oracle, top$1, offset) {
return new BlockInfo$1(offset, this.length, top$1, this.height, this.breaks);
}
replace(_from, _to, nodes) {
let node = nodes[0];
if (nodes.length == 1 && (node instanceof HeightMapText$1 || node instanceof HeightMapGap$1 && node.flags & 4) && Math.abs(this.length - node.length) < 10) {
if (node instanceof HeightMapGap$1) node = new HeightMapText$1(node.length, this.height);else node.height = this.height;
if (!this.outdated) node.outdated = false;
return node;
} else return HeightMap$1.of(nodes);
}
updateHeight(oracle, offset = 0, force = false, measured) {
if (measured && measured.from <= offset && measured.more) this.setHeight(oracle, measured.heights[measured.index++]);else if (force || this.outdated) this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) + this.breaks * oracle.lineHeight);
this.outdated = false;
return this;
}
toString() {
return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
}
};
HeightMapGap$1 = class HeightMapGap$1 extends HeightMap$1 {
constructor(length) {
super(length, 0);
}
heightMetrics(oracle, offset) {
let firstLine = oracle.doc.lineAt(offset).number,
lastLine = oracle.doc.lineAt(offset + this.length).number;
let lines = lastLine - firstLine + 1;
let perLine,
perChar = 0;
if (oracle.lineWrapping) {
let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
perLine = totalPerLine / lines;
if (this.length > lines + 1) perChar = (this.height - totalPerLine) / (this.length - lines - 1);
} else perLine = this.height / lines;
return {
firstLine,
lastLine,
perLine,
perChar
};
}
blockAt(height, oracle, top$1, offset) {
let {
firstLine,
lastLine,
perLine,
perChar
} = this.heightMetrics(oracle, offset);
if (oracle.lineWrapping) {
let guess = offset + (height < oracle.lineHeight ? 0 : Math.round(Math.max(0, Math.min(1, (height - top$1) / this.height)) * this.length));
let line = oracle.doc.lineAt(guess),
lineHeight = perLine + line.length * perChar;
let lineTop = Math.max(top$1, height - lineHeight / 2);
return new BlockInfo$1(line.from, line.length, lineTop, lineHeight, 0);
} else {
let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top$1) / perLine)));
let {
from,
length
} = oracle.doc.line(firstLine + line);
return new BlockInfo$1(from, length, top$1 + perLine * line, perLine, 0);
}
}
lineAt(value, type, oracle, top$1, offset) {
if (type == QueryType$2.ByHeight) return this.blockAt(value, oracle, top$1, offset);
if (type == QueryType$2.ByPosNoHeight) {
let {
from,
to
} = oracle.doc.lineAt(value);
return new BlockInfo$1(from, to - from, 0, 0, 0);
}
let {
firstLine,
perLine,
perChar
} = this.heightMetrics(oracle, offset);
let line = oracle.doc.lineAt(value),
lineHeight = perLine + line.length * perChar;
let linesAbove = line.number - firstLine;
let lineTop = top$1 + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
return new BlockInfo$1(line.from, line.length, Math.max(top$1, Math.min(lineTop, top$1 + this.height - lineHeight)), lineHeight, 0);
}
forEachLine(from, to, oracle, top$1, offset, f) {
from = Math.max(from, offset);
to = Math.min(to, offset + this.length);
let {
firstLine,
perLine,
perChar
} = this.heightMetrics(oracle, offset);
for (let pos = from, lineTop = top$1; pos <= to;) {
let line = oracle.doc.lineAt(pos);
if (pos == from) {
let linesAbove = line.number - firstLine;
lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
}
let lineHeight = perLine + perChar * line.length;
f(new BlockInfo$1(line.from, line.length, lineTop, lineHeight, 0));
lineTop += lineHeight;
pos = line.to + 1;
}
}
replace(from, to, nodes) {
let after = this.length - to;
if (after > 0) {
let last = nodes[nodes.length - 1];
if (last instanceof HeightMapGap$1) nodes[nodes.length - 1] = new HeightMapGap$1(last.length + after);else nodes.push(null, new HeightMapGap$1(after - 1));
}
if (from > 0) {
let first = nodes[0];
if (first instanceof HeightMapGap$1) nodes[0] = new HeightMapGap$1(from + first.length);else nodes.unshift(new HeightMapGap$1(from - 1), null);
}
return HeightMap$1.of(nodes);
}
decomposeLeft(to, result) {
result.push(new HeightMapGap$1(to - 1), null);
}
decomposeRight(from, result) {
result.push(null, new HeightMapGap$1(this.length - from - 1));
}
updateHeight(oracle, offset = 0, force = false, measured) {
let end = offset + this.length;
if (measured && measured.from <= offset + this.length && measured.more) {
let nodes = [],
pos = Math.max(offset, measured.from),
singleHeight = -1;
if (measured.from > offset) nodes.push(new HeightMapGap$1(measured.from - offset - 1).updateHeight(oracle, offset));
while (pos <= end && measured.more) {
let len = oracle.doc.lineAt(pos).length;
if (nodes.length) nodes.push(null);
let height = measured.heights[measured.index++];
if (singleHeight == -1) singleHeight = height;else if (Math.abs(height - singleHeight) >= Epsilon$1) singleHeight = -2;
let line = new HeightMapText$1(len, height);
line.outdated = false;
nodes.push(line);
pos += len + 1;
}
if (pos <= end) nodes.push(null, new HeightMapGap$1(end - pos).updateHeight(oracle, pos));
let result = HeightMap$1.of(nodes);
if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon$1 || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon$1) oracle.heightChanged = true;
return result;
} else if (force || this.outdated) {
this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));
this.outdated = false;
}
return this;
}
toString() {
return `gap(${this.length})`;
}
};
HeightMapBranch$1 = class extends HeightMap$1 {
constructor(left, brk, right) {
super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 : 0));
this.left = left;
this.right = right;
this.size = left.size + right.size;
}
get break() {
return this.flags & 1;
}
blockAt(height, oracle, top$1, offset) {
let mid = top$1 + this.left.height;
return height < mid ? this.left.blockAt(height, oracle, top$1, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
}
lineAt(value, type, oracle, top$1, offset) {
let rightTop = top$1 + this.left.height,
rightOffset = offset + this.left.length + this.break;
let left = type == QueryType$2.ByHeight ? value < rightTop : value < rightOffset;
let base$1 = left ? this.left.lineAt(value, type, oracle, top$1, offset) : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
if (this.break || (left ? base$1.to < rightOffset : base$1.from > rightOffset)) return base$1;
let subQuery = type == QueryType$2.ByPosNoHeight ? QueryType$2.ByPosNoHeight : QueryType$2.ByPos;
if (left) return base$1.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));else return this.left.lineAt(rightOffset, subQuery, oracle, top$1, offset).join(base$1);
}
forEachLine(from, to, oracle, top$1, offset, f) {
let rightTop = top$1 + this.left.height,
rightOffset = offset + this.left.length + this.break;
if (this.break) {
if (from < rightOffset) this.left.forEachLine(from, to, oracle, top$1, offset, f);
if (to >= rightOffset) this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
} else {
let mid = this.lineAt(rightOffset, QueryType$2.ByPos, oracle, top$1, offset);
if (from < mid.from) this.left.forEachLine(from, mid.from - 1, oracle, top$1, offset, f);
if (mid.to >= from && mid.from <= to) f(mid);
if (to > mid.to) this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
}
}
replace(from, to, nodes) {
let rightStart = this.left.length + this.break;
if (to < rightStart) return this.balanced(this.left.replace(from, to, nodes), this.right);
if (from > this.left.length) return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
let result = [];
if (from > 0) this.decomposeLeft(from, result);
let left = result.length;
for (let node of nodes) result.push(node);
if (from > 0) mergeGaps$1(result, left - 1);
if (to < this.length) {
let right = result.length;
this.decomposeRight(to, result);
mergeGaps$1(result, right);
}
return HeightMap$1.of(result);
}
decomposeLeft(to, result) {
let left = this.left.length;
if (to <= left) return this.left.decomposeLeft(to, result);
result.push(this.left);
if (this.break) {
left++;
if (to >= left) result.push(null);
}
if (to > left) this.right.decomposeLeft(to - left, result);
}
decomposeRight(from, result) {
let left = this.left.length,
right = left + this.break;
if (from >= right) return this.right.decomposeRight(from - right, result);
if (from < left) this.left.decomposeRight(from, result);
if (this.break && from < right) result.push(null);
result.push(this.right);
}
balanced(left, right) {
if (left.size > 2 * right.size || right.size > 2 * left.size) return HeightMap$1.of(this.break ? [left, null, right] : [left, right]);
this.left = left;
this.right = right;
this.height = left.height + right.height;
this.outdated = left.outdated || right.outdated;
this.size = left.size + right.size;
this.length = left.length + this.break + right.length;
return this;
}
updateHeight(oracle, offset = 0, force = false, measured) {
let {
left,
right
} = this,
rightStart = offset + left.length + this.break,
rebalance = null;
if (measured && measured.from <= offset + left.length && measured.more) rebalance = left = left.updateHeight(oracle, offset, force, measured);else left.updateHeight(oracle, offset, force);
if (measured && measured.from <= rightStart + right.length && measured.more) rebalance = right = right.updateHeight(oracle, rightStart, force, measured);else right.updateHeight(oracle, rightStart, force);
if (rebalance) return this.balanced(left, right);
this.height = this.left.height + this.right.height;
this.outdated = false;
return this;
}
toString() {
return this.left + (this.break ? " " : "-") + this.right;
}
};
relevantWidgetHeight$1 = 5;
NodeBuilder$1 = class NodeBuilder$1 {
constructor(pos, oracle) {
this.pos = pos;
this.oracle = oracle;
this.nodes = [];
this.lineStart = -1;
this.lineEnd = -1;
this.covering = null;
this.writtenTo = pos;
}
get isCovered() {
return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
}
span(_from, to) {
if (this.lineStart > -1) {
let end = Math.min(to, this.lineEnd),
last = this.nodes[this.nodes.length - 1];
if (last instanceof HeightMapText$1) last.length += end - this.pos;else if (end > this.pos || !this.isCovered) this.nodes.push(new HeightMapText$1(end - this.pos, -1));
this.writtenTo = end;
if (to > end) {
this.nodes.push(null);
this.writtenTo++;
this.lineStart = -1;
}
}
this.pos = to;
}
point(from, to, deco) {
if (from < to || deco.heightRelevant) {
let height = deco.widget ? deco.widget.estimatedHeight : 0;
let breaks = deco.widget ? deco.widget.lineBreaks : 0;
if (height < 0) height = this.oracle.lineHeight;
let len = to - from;
if (deco.block) this.addBlock(new HeightMapBlock$1(len, height, deco));else if (len || breaks || height >= relevantWidgetHeight$1) this.addLineDeco(height, breaks, len);
} else if (to > from) this.span(from, to);
if (this.lineEnd > -1 && this.lineEnd < this.pos) this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
}
enterLine() {
if (this.lineStart > -1) return;
let {
from,
to
} = this.oracle.doc.lineAt(this.pos);
this.lineStart = from;
this.lineEnd = to;
if (this.writtenTo < from) {
if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) this.nodes.push(this.blankContent(this.writtenTo, from - 1));
this.nodes.push(null);
}
if (this.pos > from) this.nodes.push(new HeightMapText$1(this.pos - from, -1));
this.writtenTo = this.pos;
}
blankContent(from, to) {
let gap = new HeightMapGap$1(to - from);
if (this.oracle.doc.lineAt(from).to == to) gap.flags |= 4;
return gap;
}
ensureLine() {
this.enterLine();
let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
if (last instanceof HeightMapText$1) return last;
let line = new HeightMapText$1(0, -1);
this.nodes.push(line);
return line;
}
addBlock(block) {
this.enterLine();
let deco = block.deco;
if (deco && deco.startSide > 0 && !this.isCovered) this.ensureLine();
this.nodes.push(block);
this.writtenTo = this.pos = this.pos + block.length;
if (deco && deco.endSide > 0) this.covering = block;
}
addLineDeco(height, breaks, length) {
let line = this.ensureLine();
line.length += length;
line.collapsed += length;
line.widgetHeight = Math.max(line.widgetHeight, height);
line.breaks += breaks;
this.writtenTo = this.pos = this.pos + length;
}
finish(from) {
let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
if (this.lineStart > -1 && !(last instanceof HeightMapText$1) && !this.isCovered) this.nodes.push(new HeightMapText$1(0, -1));else if (this.writtenTo < this.pos || last == null) this.nodes.push(this.blankContent(this.writtenTo, this.pos));
let pos = from;
for (let node of this.nodes) {
if (node instanceof HeightMapText$1) node.updateHeight(this.oracle, pos);
pos += node ? node.length : 1;
}
return this.nodes;
}
static build(oracle, decorations$2, from, to) {
let builder = new NodeBuilder$1(from, oracle);
RangeSet$1.spans(decorations$2, from, to, builder, 0);
return builder.finish(from);
}
};
DecorationComparator$2 = class {
constructor() {
this.changes = [];
}
compareRange() {}
comparePoint(from, to, a, b) {
if (from < to || a && a.heightRelevant || b && b.heightRelevant) addRange$1(from, to, this.changes, 5);
}
};
LineGap$1 = class {
constructor(from, to, size) {
this.from = from;
this.to = to;
this.size = size;
}
static same(a, b) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) {
let gA = a[i$1],
gB = b[i$1];
if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) return false;
}
return true;
}
draw(viewState, wrapping) {
return Decoration$1.replace({
widget: new LineGapWidget$1(this.size * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
}).range(this.from, this.to);
}
};
LineGapWidget$1 = class extends WidgetType$1 {
constructor(size, vertical) {
super();
this.size = size;
this.vertical = vertical;
}
eq(other) {
return other.size == this.size && other.vertical == this.vertical;
}
toDOM() {
let elt = document.createElement("div");
if (this.vertical) elt.style.height = this.size + "px";else {
elt.style.width = this.size + "px";
elt.style.height = "2px";
elt.style.display = "inline-block";
}
return elt;
}
get estimatedHeight() {
return this.vertical ? this.size : -1;
}
};
ViewState$1 = class {
constructor(state) {
this.state = state;
this.pixelViewport = {
left: 0,
right: window.innerWidth,
top: 0,
bottom: 0
};
this.inView = true;
this.paddingTop = 0;
this.paddingBottom = 0;
this.contentDOMWidth = 0;
this.contentDOMHeight = 0;
this.editorHeight = 0;
this.editorWidth = 0;
this.scrollTop = 0;
this.scrolledToBottom = false;
this.scaleX = 1;
this.scaleY = 1;
this.scrollAnchorPos = 0;
this.scrollAnchorHeight = -1;
this.scaler = IdScaler$1;
this.scrollTarget = null;
this.printing = false;
this.mustMeasureContent = true;
this.defaultTextDirection = Direction$1.LTR;
this.visibleRanges = [];
this.mustEnforceCursorAssoc = false;
this.heightOracle = new HeightOracle$1(state.facet(contentAttributes$1).some(v => typeof v != "function" && v.class == "cm-lineWrapping"));
this.stateDeco = state.facet(decorations$1).filter(d => typeof d != "function");
this.heightMap = HeightMap$1.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange$1(0, 0, 0, state.doc.length)]);
this.viewport = this.getViewport(0, null);
this.updateViewportLines();
this.updateForViewport();
this.lineGaps = this.ensureLineGaps([]);
this.lineGapDeco = Decoration$1.set(this.lineGaps.map(gap => gap.draw(this, false)));
this.computeVisibleRanges();
}
updateForViewport() {
let viewports = [this.viewport],
{
main
} = this.state.selection;
for (let i$1 = 0; i$1 <= 1; i$1++) {
let pos = i$1 ? main.head : main.anchor;
if (!viewports.some(({
from,
to
}) => pos >= from && pos <= to)) {
let {
from,
to
} = this.lineBlockAt(pos);
viewports.push(new Viewport$1(from, to));
}
}
this.viewports = viewports.sort((a, b) => a.from - b.from);
this.scaler = this.heightMap.height <= 7e6 ? IdScaler$1 : new BigScaler$1(this.heightOracle, this.heightMap, this.viewports);
}
updateViewportLines() {
this.viewportLines = [];
this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {
this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock$1(block, this.scaler));
});
}
update(update, scrollTarget = null) {
this.state = update.state;
let prevDeco = this.stateDeco;
this.stateDeco = this.state.facet(decorations$1).filter(d => typeof d != "function");
let contentChanges = update.changedRanges;
let heightChanges = ChangedRange$1.extendWithRanges(contentChanges, heightRelevantDecoChanges$1(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
let prevHeight = this.heightMap.height;
let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
if (this.heightMap.height != prevHeight) update.flags |= 2;
if (scrollAnchor) {
this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);
this.scrollAnchorHeight = scrollAnchor.top;
} else {
this.scrollAnchorPos = -1;
this.scrollAnchorHeight = this.heightMap.height;
}
let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || !this.viewportIsAppropriate(viewport)) viewport = this.getViewport(0, scrollTarget);
let updateLines = !update.changes.empty || update.flags & 2 || viewport.from != this.viewport.from || viewport.to != this.viewport.to;
this.viewport = viewport;
this.updateForViewport();
if (updateLines) this.updateViewportLines();
if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
update.flags |= this.computeVisibleRanges();
if (scrollTarget) this.scrollTarget = scrollTarget;
if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && update.state.selection.main.empty && update.state.selection.main.assoc && !update.state.facet(nativeSelectionHidden$1)) this.mustEnforceCursorAssoc = true;
}
measure(view) {
let dom = view.contentDOM,
style = window.getComputedStyle(dom);
let oracle = this.heightOracle;
let whiteSpace = style.whiteSpace;
this.defaultTextDirection = style.direction == "rtl" ? Direction$1.RTL : Direction$1.LTR;
let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
let domRect = dom.getBoundingClientRect();
let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
this.contentDOMHeight = domRect.height;
this.mustMeasureContent = false;
let result = 0,
bias = 0;
if (domRect.width && domRect.height) {
let {
scaleX,
scaleY
} = getScale$1(dom, domRect);
if (scaleX > .005 && Math.abs(this.scaleX - scaleX) > .005 || scaleY > .005 && Math.abs(this.scaleY - scaleY) > .005) {
this.scaleX = scaleX;
this.scaleY = scaleY;
result |= 8;
refresh = measureContent = true;
}
}
let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
this.paddingTop = paddingTop;
this.paddingBottom = paddingBottom;
result |= 10;
}
if (this.editorWidth != view.scrollDOM.clientWidth) {
if (oracle.lineWrapping) measureContent = true;
this.editorWidth = view.scrollDOM.clientWidth;
result |= 8;
}
let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
if (this.scrollTop != scrollTop) {
this.scrollAnchorHeight = -1;
this.scrollTop = scrollTop;
}
this.scrolledToBottom = isScrolledToBottom$1(view.scrollDOM);
let pixelViewport = (this.printing ? fullPixelRange$1 : visiblePixelRange$1)(dom, this.paddingTop);
let dTop = pixelViewport.top - this.pixelViewport.top,
dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
this.pixelViewport = pixelViewport;
let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
if (inView != this.inView) {
this.inView = inView;
if (inView) measureContent = true;
}
if (!this.inView && !this.scrollTarget) return 0;
let contentWidth = domRect.width;
if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
this.contentDOMWidth = domRect.width;
this.editorHeight = view.scrollDOM.clientHeight;
result |= 8;
}
if (measureContent) {
let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
if (oracle.mustRefreshForHeights(lineHeights)) refresh = true;
if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
let {
lineHeight,
charWidth,
textHeight
} = view.docView.measureTextSize();
refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);
if (refresh) {
view.docView.minWidth = 0;
result |= 8;
}
}
if (dTop > 0 && dBottom > 0) bias = Math.max(dTop, dBottom);else if (dTop < 0 && dBottom < 0) bias = Math.min(dTop, dBottom);
oracle.heightChanged = false;
for (let vp of this.viewports) {
let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
this.heightMap = (refresh ? HeightMap$1.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange$1(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights$1(vp.from, heights));
}
if (oracle.heightChanged) result |= 2;
}
let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to);
if (viewportChange) this.viewport = this.getViewport(bias, this.scrollTarget);
this.updateForViewport();
if (result & 2 || viewportChange) this.updateViewportLines();
if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
result |= this.computeVisibleRanges();
if (this.mustEnforceCursorAssoc) {
this.mustEnforceCursorAssoc = false;
view.docView.enforceCursorAssoc();
}
return result;
}
get visibleTop() {
return this.scaler.fromDOM(this.pixelViewport.top);
}
get visibleBottom() {
return this.scaler.fromDOM(this.pixelViewport.bottom);
}
getViewport(bias, scrollTarget) {
let marginTop = .5 - Math.max(-.5, Math.min(.5, bias / 1e3 / 2));
let map = this.heightMap,
oracle = this.heightOracle;
let {
visibleTop,
visibleBottom
} = this;
let viewport = new Viewport$1(map.lineAt(visibleTop - marginTop * 1e3, QueryType$2.ByHeight, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1e3, QueryType$2.ByHeight, oracle, 0, 0).to);
if (scrollTarget) {
let {
head
} = scrollTarget.range;
if (head < viewport.from || head > viewport.to) {
let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
let block = map.lineAt(head, QueryType$2.ByPos, oracle, 0, 0),
topPos;
if (scrollTarget.y == "center") topPos = (block.top + block.bottom) / 2 - viewHeight / 2;else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) topPos = block.top;else topPos = block.bottom - viewHeight;
viewport = new Viewport$1(map.lineAt(topPos - 1e3 / 2, QueryType$2.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1e3 / 2, QueryType$2.ByHeight, oracle, 0, 0).to);
}
}
return viewport;
}
mapViewport(viewport, changes) {
let from = changes.mapPos(viewport.from, -1),
to = changes.mapPos(viewport.to, 1);
return new Viewport$1(this.heightMap.lineAt(from, QueryType$2.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType$2.ByPos, this.heightOracle, 0, 0).to);
}
viewportIsAppropriate({
from,
to
}, bias = 0) {
if (!this.inView) return true;
let {
top: top$1
} = this.heightMap.lineAt(from, QueryType$2.ByPos, this.heightOracle, 0, 0);
let {
bottom
} = this.heightMap.lineAt(to, QueryType$2.ByPos, this.heightOracle, 0, 0);
let {
visibleTop,
visibleBottom
} = this;
return (from == 0 || top$1 <= visibleTop - Math.max(10, Math.min(-bias, 250))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(bias, 250))) && top$1 > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3;
}
mapLineGaps(gaps, changes) {
if (!gaps.length || changes.empty) return gaps;
let mapped = [];
for (let gap of gaps) if (!changes.touchesRange(gap.from, gap.to)) mapped.push(new LineGap$1(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));
return mapped;
}
ensureLineGaps(current, mayMeasure) {
let wrapping = this.heightOracle.lineWrapping;
let margin = wrapping ? 1e4 : 2e3,
halfMargin = margin >> 1,
doubleMargin = margin << 1;
if (this.defaultTextDirection != Direction$1.LTR && !wrapping) return [];
let gaps = [];
let addGap = (from, to, line, structure) => {
if (to - from < halfMargin) return;
let sel = this.state.selection.main,
avoid = [sel.from];
if (!sel.empty) avoid.push(sel.to);
for (let pos of avoid) if (pos > from && pos < to) {
addGap(from, pos - 10, line, structure);
addGap(pos + 10, to, line, structure);
return;
}
let gap = find$1(current, gap$1 => gap$1.from >= line.from && gap$1.to <= line.to && Math.abs(gap$1.from - from) < halfMargin && Math.abs(gap$1.to - to) < halfMargin && !avoid.some(pos => gap$1.from < pos && gap$1.to > pos));
if (!gap) {
if (to < line.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {
let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
if (lineStart > from) to = lineStart;
}
gap = new LineGap$1(from, to, this.gapSize(line, from, to, structure));
}
gaps.push(gap);
};
for (let line of this.viewportLines) {
if (line.length < doubleMargin) continue;
let structure = lineStructure$1(line.from, line.to, this.stateDeco);
if (structure.total < doubleMargin) continue;
let target = this.scrollTarget ? this.scrollTarget.range.head : null;
let viewFrom, viewTo;
if (wrapping) {
let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight;
let top$1, bot;
if (target != null) {
let targetFrac = findFraction$1(structure, target);
let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
top$1 = targetFrac - spaceFrac;
bot = targetFrac + spaceFrac;
} else {
top$1 = (this.visibleTop - line.top - marginHeight) / line.height;
bot = (this.visibleBottom - line.top + marginHeight) / line.height;
}
viewFrom = findPosition$1(structure, top$1);
viewTo = findPosition$1(structure, bot);
} else {
let totalWidth = structure.total * this.heightOracle.charWidth;
let marginWidth = margin * this.heightOracle.charWidth;
let left, right;
if (target != null) {
let targetFrac = findFraction$1(structure, target);
let spaceFrac = ((this.pixelViewport.right - this.pixelViewport.left) / 2 + marginWidth) / totalWidth;
left = targetFrac - spaceFrac;
right = targetFrac + spaceFrac;
} else {
left = (this.pixelViewport.left - marginWidth) / totalWidth;
right = (this.pixelViewport.right + marginWidth) / totalWidth;
}
viewFrom = findPosition$1(structure, left);
viewTo = findPosition$1(structure, right);
}
if (viewFrom > line.from) addGap(line.from, viewFrom, line, structure);
if (viewTo < line.to) addGap(viewTo, line.to, line, structure);
}
return gaps;
}
gapSize(line, from, to, structure) {
let fraction = findFraction$1(structure, to) - findFraction$1(structure, from);
if (this.heightOracle.lineWrapping) return line.height * fraction;else return structure.total * this.heightOracle.charWidth * fraction;
}
updateLineGaps(gaps) {
if (!LineGap$1.same(gaps, this.lineGaps)) {
this.lineGaps = gaps;
this.lineGapDeco = Decoration$1.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));
}
}
computeVisibleRanges() {
let deco = this.stateDeco;
if (this.lineGaps.length) deco = deco.concat(this.lineGapDeco);
let ranges = [];
RangeSet$1.spans(deco, this.viewport.from, this.viewport.to, {
span(from, to) {
ranges.push({
from,
to
});
},
point() {}
}, 20);
let changed = ranges.length != this.visibleRanges.length || this.visibleRanges.some((r, i$1) => r.from != ranges[i$1].from || r.to != ranges[i$1].to);
this.visibleRanges = ranges;
return changed ? 4 : 0;
}
lineBlockAt(pos) {
return pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos) || scaleBlock$1(this.heightMap.lineAt(pos, QueryType$2.ByPos, this.heightOracle, 0, 0), this.scaler);
}
lineBlockAtHeight(height) {
return scaleBlock$1(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType$2.ByHeight, this.heightOracle, 0, 0), this.scaler);
}
scrollAnchorAt(scrollTop) {
let block = this.lineBlockAtHeight(scrollTop + 8);
return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
}
elementAtHeight(height) {
return scaleBlock$1(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
}
get docHeight() {
return this.scaler.toDOM(this.heightMap.height);
}
get contentHeight() {
return this.docHeight + this.paddingTop + this.paddingBottom;
}
};
Viewport$1 = class {
constructor(from, to) {
this.from = from;
this.to = to;
}
};
IdScaler$1 = {
toDOM(n) {
return n;
},
fromDOM(n) {
return n;
},
scale: 1
};
BigScaler$1 = class {
constructor(oracle, heightMap, viewports) {
let vpHeight = 0,
base$1 = 0,
domBase = 0;
this.viewports = viewports.map(({
from,
to
}) => {
let top$1 = heightMap.lineAt(from, QueryType$2.ByPos, oracle, 0, 0).top;
let bottom = heightMap.lineAt(to, QueryType$2.ByPos, oracle, 0, 0).bottom;
vpHeight += bottom - top$1;
return {
from,
to,
top: top$1,
bottom,
domTop: 0,
domBottom: 0
};
});
this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight);
for (let obj of this.viewports) {
obj.domTop = domBase + (obj.top - base$1) * this.scale;
domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
base$1 = obj.bottom;
}
}
toDOM(n) {
for (let i$1 = 0, base$1 = 0, domBase = 0;; i$1++) {
let vp = i$1 < this.viewports.length ? this.viewports[i$1] : null;
if (!vp || n < vp.top) return domBase + (n - base$1) * this.scale;
if (n <= vp.bottom) return vp.domTop + (n - vp.top);
base$1 = vp.bottom;
domBase = vp.domBottom;
}
}
fromDOM(n) {
for (let i$1 = 0, base$1 = 0, domBase = 0;; i$1++) {
let vp = i$1 < this.viewports.length ? this.viewports[i$1] : null;
if (!vp || n < vp.domTop) return base$1 + (n - domBase) / this.scale;
if (n <= vp.domBottom) return vp.top + (n - vp.domTop);
base$1 = vp.bottom;
domBase = vp.domBottom;
}
}
};
theme$1 = /* @__PURE__ */Facet$1.define({
combine: strs => strs.join(" ")
});
darkTheme$1 = /* @__PURE__ */Facet$1.define({
combine: values => values.indexOf(true) > -1
});
baseThemeID$1 = /* @__PURE__ */StyleModule.newName(), baseLightID$1 = /* @__PURE__ */StyleModule.newName(), baseDarkID$1 = /* @__PURE__ */StyleModule.newName();
lightDarkIDs$1 = {
"&light": "." + baseLightID$1,
"&dark": "." + baseDarkID$1
};
baseTheme$1$6 = /* @__PURE__ */buildTheme$1("." + baseThemeID$1, {
"&": {
position: "relative !important",
boxSizing: "border-box",
"&.cm-focused": {
outline: "1px dotted #212121"
},
display: "flex !important",
flexDirection: "column"
},
".cm-scroller": {
display: "flex !important",
alignItems: "flex-start !important",
fontFamily: "monospace",
lineHeight: 1.4,
height: "100%",
overflowX: "auto",
position: "relative",
zIndex: 0
},
".cm-content": {
margin: 0,
flexGrow: 2,
flexShrink: 0,
display: "block",
whiteSpace: "pre",
wordWrap: "normal",
boxSizing: "border-box",
minHeight: "100%",
padding: "4px 0",
outline: "none",
"&[contenteditable=true]": {
WebkitUserModify: "read-write-plaintext-only"
}
},
".cm-lineWrapping": {
whiteSpace_fallback: "pre-wrap",
whiteSpace: "break-spaces",
wordBreak: "break-word",
overflowWrap: "anywhere",
flexShrink: 1
},
"&light .cm-content": {
caretColor: "black"
},
"&dark .cm-content": {
caretColor: "white"
},
".cm-line": {
display: "block",
padding: "0 2px 0 6px"
},
".cm-layer": {
position: "absolute",
left: 0,
top: 0,
contain: "size style",
"& > *": {
position: "absolute"
}
},
"&light .cm-selectionBackground": {
background: "#d9d9d9"
},
"&dark .cm-selectionBackground": {
background: "#222"
},
"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
background: "#d7d4f0"
},
"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
background: "#233"
},
".cm-cursorLayer": {
pointerEvents: "none"
},
"&.cm-focused > .cm-scroller > .cm-cursorLayer": {
animation: "steps(1) cm-blink 1.2s infinite"
},
"@keyframes cm-blink": {
"0%": {},
"50%": {
opacity: 0
},
"100%": {}
},
"@keyframes cm-blink2": {
"0%": {},
"50%": {
opacity: 0
},
"100%": {}
},
".cm-cursor, .cm-dropCursor": {
borderLeft: "1.2px solid black",
marginLeft: "-0.6px",
pointerEvents: "none"
},
".cm-cursor": {
display: "none"
},
"&dark .cm-cursor": {
borderLeftColor: "#444"
},
".cm-dropCursor": {
position: "absolute"
},
"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
display: "block"
},
".cm-iso": {
unicodeBidi: "isolate"
},
".cm-announced": {
position: "fixed",
top: "-10000px"
},
"@media print": {
".cm-announced": {
display: "none"
}
},
"&light .cm-activeLine": {
backgroundColor: "#cceeff44"
},
"&dark .cm-activeLine": {
backgroundColor: "#99eeff33"
},
"&light .cm-specialChar": {
color: "red"
},
"&dark .cm-specialChar": {
color: "#f78"
},
".cm-gutters": {
flexShrink: 0,
display: "flex",
height: "100%",
boxSizing: "border-box",
insetInlineStart: 0,
zIndex: 200
},
"&light .cm-gutters": {
backgroundColor: "#f5f5f5",
color: "#6c6c6c",
borderRight: "1px solid #ddd"
},
"&dark .cm-gutters": {
backgroundColor: "#333338",
color: "#ccc"
},
".cm-gutter": {
display: "flex !important",
flexDirection: "column",
flexShrink: 0,
boxSizing: "border-box",
minHeight: "100%",
overflow: "hidden"
},
".cm-gutterElement": {
boxSizing: "border-box"
},
".cm-lineNumbers .cm-gutterElement": {
padding: "0 3px 0 5px",
minWidth: "20px",
textAlign: "right",
whiteSpace: "nowrap"
},
"&light .cm-activeLineGutter": {
backgroundColor: "#e2f2ff"
},
"&dark .cm-activeLineGutter": {
backgroundColor: "#222227"
},
".cm-panels": {
boxSizing: "border-box",
position: "sticky",
left: 0,
right: 0
},
"&light .cm-panels": {
backgroundColor: "#f5f5f5",
color: "black"
},
"&light .cm-panels-top": {
borderBottom: "1px solid #ddd"
},
"&light .cm-panels-bottom": {
borderTop: "1px solid #ddd"
},
"&dark .cm-panels": {
backgroundColor: "#333338",
color: "white"
},
".cm-tab": {
display: "inline-block",
overflow: "hidden",
verticalAlign: "bottom"
},
".cm-widgetBuffer": {
verticalAlign: "text-top",
height: "1em",
width: 0,
display: "inline"
},
".cm-placeholder": {
color: "#888",
display: "inline-block",
verticalAlign: "top"
},
".cm-highlightSpace:before": {
content: "attr(data-display)",
position: "absolute",
pointerEvents: "none",
color: "#888"
},
".cm-highlightTab": {
backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,
backgroundSize: "auto 100%",
backgroundPosition: "right 90%",
backgroundRepeat: "no-repeat"
},
".cm-trailingSpace": {
backgroundColor: "#ff332255"
},
".cm-button": {
verticalAlign: "middle",
color: "inherit",
fontSize: "70%",
padding: ".2em 1em",
borderRadius: "1px"
},
"&light .cm-button": {
backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
border: "1px solid #888",
"&:active": {
backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
}
},
"&dark .cm-button": {
backgroundImage: "linear-gradient(#393939, #111)",
border: "1px solid #888",
"&:active": {
backgroundImage: "linear-gradient(#111, #333)"
}
},
".cm-textfield": {
verticalAlign: "middle",
color: "inherit",
fontSize: "70%",
border: "1px solid silver",
padding: ".2em .5em"
},
"&light .cm-textfield": {
backgroundColor: "white"
},
"&dark .cm-textfield": {
border: "1px solid #555",
backgroundColor: "inherit"
}
}, lightDarkIDs$1);
LineBreakPlaceholder$1 = "";
DOMReader$1 = class {
constructor(points, state) {
this.points = points;
this.text = "";
this.lineSeparator = state.facet(EditorState.lineSeparator);
}
append(text) {
this.text += text;
}
lineBreak() {
this.text += LineBreakPlaceholder$1;
}
readRange(start, end) {
if (!start) return this;
let parent = start.parentNode;
for (let cur$1 = start;;) {
this.findPointBefore(parent, cur$1);
let oldLen = this.text.length;
this.readNode(cur$1);
let next = cur$1.nextSibling;
if (next == end) break;
let view = ContentView$1.get(cur$1),
nextView = ContentView$1.get(next);
if (view && nextView ? view.breakAfter : (view ? view.breakAfter : isBlockElement$1(cur$1)) || isBlockElement$1(next) && (cur$1.nodeName != "BR" || cur$1.cmIgnore) && this.text.length > oldLen) this.lineBreak();
cur$1 = next;
}
this.findPointBefore(parent, end);
return this;
}
readTextNode(node) {
let text = node.nodeValue;
for (let point of this.points) if (point.node == node) point.pos = this.text.length + Math.min(point.offset, text.length);
for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) {
let nextBreak = -1,
breakSize = 1,
m;
if (this.lineSeparator) {
nextBreak = text.indexOf(this.lineSeparator, off);
breakSize = this.lineSeparator.length;
} else if (m = re.exec(text)) {
nextBreak = m.index;
breakSize = m[0].length;
}
this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));
if (nextBreak < 0) break;
this.lineBreak();
if (breakSize > 1) {
for (let point of this.points) if (point.node == node && point.pos > this.text.length) point.pos -= breakSize - 1;
}
off = nextBreak + breakSize;
}
}
readNode(node) {
if (node.cmIgnore) return;
let view = ContentView$1.get(node);
let fromView = view && view.overrideDOMText;
if (fromView != null) {
this.findPointInside(node, fromView.length);
for (let i$1 = fromView.iter(); !i$1.next().done;) if (i$1.lineBreak) this.lineBreak();else this.append(i$1.value);
} else if (node.nodeType == 3) this.readTextNode(node);else if (node.nodeName == "BR") {
if (node.nextSibling) this.lineBreak();
} else if (node.nodeType == 1) this.readRange(node.firstChild, null);
}
findPointBefore(node, next) {
for (let point of this.points) if (point.node == node && node.childNodes[point.offset] == next) point.pos = this.text.length;
}
findPointInside(node, length) {
for (let point of this.points) if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) point.pos = this.text.length + (isAtEnd$1(node, point.node, point.offset) ? length : 0);
}
};
DOMPoint$1 = class {
constructor(node, offset) {
this.node = node;
this.offset = offset;
this.pos = -1;
}
};
DOMChange$1 = class {
constructor(view, start, end, typeOver) {
this.typeOver = typeOver;
this.bounds = null;
this.text = "";
let {
impreciseHead: iHead,
impreciseAnchor: iAnchor
} = view.docView;
if (view.state.readOnly && start > -1) this.newSel = null;else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {
let selPoints = iHead || iAnchor ? [] : selectionPoints$1(view);
let reader = new DOMReader$1(selPoints, view.state);
reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
this.text = reader.text;
this.newSel = selectionFromPoints$1(selPoints, this.bounds.from);
} else {
let domSel = view.observer.selectionRange;
let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains$1(view.contentDOM, domSel.focusNode) ? view.state.selection.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains$1(view.contentDOM, domSel.anchorNode) ? view.state.selection.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
let vp = view.viewport;
if ((browser$1.ios || browser$1.chrome) && view.state.selection.main.empty && head != anchor && (vp.from > 0 || vp.to < view.state.doc.length)) {
let from = Math.min(head, anchor),
to = Math.max(head, anchor);
let offFrom = vp.from - from,
offTo = vp.to - to;
if ((offFrom == 0 || offFrom == 1 || from == 0) && (offTo == 0 || offTo == -1 || to == view.state.doc.length)) {
head = 0;
anchor = view.state.doc.length;
}
}
this.newSel = EditorSelection.single(anchor, head);
}
}
};
observeOptions$1 = {
childList: true,
characterData: true,
subtree: true,
attributes: true,
characterDataOldValue: true
};
useCharData$1 = browser$1.ie && browser$1.ie_version <= 11;
DOMObserver$1 = class {
constructor(view) {
this.view = view;
this.active = false;
this.selectionRange = new DOMSelectionState$1();
this.selectionChanged = false;
this.delayedFlush = -1;
this.resizeTimeout = -1;
this.queue = [];
this.delayedAndroidKey = null;
this.flushingAndroidKey = -1;
this.lastChange = 0;
this.scrollTargets = [];
this.intersection = null;
this.resizeScroll = null;
this.intersecting = false;
this.gapIntersection = null;
this.gaps = [];
this.printQuery = null;
this.parentCheck = -1;
this.dom = view.contentDOM;
this.observer = new MutationObserver(mutations => {
for (let mut of mutations) this.queue.push(mut);
if ((browser$1.ie && browser$1.ie_version <= 11 || browser$1.ios && view.composing) && mutations.some(m => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) this.flushSoon();else this.flush();
});
if (useCharData$1) this.onCharData = event => {
this.queue.push({
target: event.target,
type: "characterData",
oldValue: event.prevValue
});
this.flushSoon();
};
this.onSelectionChange = this.onSelectionChange.bind(this);
this.onResize = this.onResize.bind(this);
this.onPrint = this.onPrint.bind(this);
this.onScroll = this.onScroll.bind(this);
if (window.matchMedia) this.printQuery = window.matchMedia("print");
if (typeof ResizeObserver == "function") {
this.resizeScroll = new ResizeObserver(() => {
var _a$2;
if (((_a$2 = this.view.docView) === null || _a$2 === void 0 ? void 0 : _a$2.lastUpdate) < Date.now() - 75) this.onResize();
});
this.resizeScroll.observe(view.scrollDOM);
}
this.addWindowListeners(this.win = view.win);
this.start();
if (typeof IntersectionObserver == "function") {
this.intersection = new IntersectionObserver(entries => {
if (this.parentCheck < 0) this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3);
if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 != this.intersecting) {
this.intersecting = !this.intersecting;
if (this.intersecting != this.view.inView) this.onScrollChanged(document.createEvent("Event"));
}
}, {
threshold: [0, .001]
});
this.intersection.observe(this.dom);
this.gapIntersection = new IntersectionObserver(entries => {
if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) this.onScrollChanged(document.createEvent("Event"));
}, {});
}
this.listenForScroll();
this.readSelectionRange();
}
onScrollChanged(e) {
this.view.inputState.runHandlers("scroll", e);
if (this.intersecting) this.view.measure();
}
onScroll(e) {
if (this.intersecting) this.flush(false);
this.onScrollChanged(e);
}
onResize() {
if (this.resizeTimeout < 0) this.resizeTimeout = setTimeout(() => {
this.resizeTimeout = -1;
this.view.requestMeasure();
}, 50);
}
onPrint(event) {
if (event.type == "change" && !event.matches) return;
this.view.viewState.printing = true;
this.view.measure();
setTimeout(() => {
this.view.viewState.printing = false;
this.view.requestMeasure();
}, 500);
}
updateGaps(gaps) {
if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i$1) => g != gaps[i$1]))) {
this.gapIntersection.disconnect();
for (let gap of gaps) this.gapIntersection.observe(gap);
this.gaps = gaps;
}
}
onSelectionChange(event) {
let wasChanged = this.selectionChanged;
if (!this.readSelectionRange() || this.delayedAndroidKey) return;
let {
view
} = this,
sel = this.selectionRange;
if (view.state.facet(editable$1) ? view.root.activeElement != this.dom : !hasSelection$1(view.dom, sel)) return;
let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);
if (context && context.ignoreEvent(event)) {
if (!wasChanged) this.selectionChanged = false;
return;
}
if ((browser$1.ie && browser$1.ie_version <= 11 || browser$1.android && browser$1.chrome) && !view.state.selection.main.empty && sel.focusNode && isEquivalentPosition$1(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) this.flushSoon();else this.flush(false);
}
readSelectionRange() {
let {
view
} = this;
let selection = getSelection$1(view.root);
if (!selection) return false;
let range = browser$1.safari && view.root.nodeType == 11 && deepActiveElement$1(this.dom.ownerDocument) == this.dom && safariSelectionRangeHack$1(this.view, selection) || selection;
if (!range || this.selectionRange.eq(range)) return false;
let local = hasSelection$1(this.dom, range);
if (local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart$1(this.dom, range)) {
this.view.inputState.lastFocusTime = 0;
view.docView.updateSelection();
return false;
}
this.selectionRange.setRange(range);
if (local) this.selectionChanged = true;
return true;
}
setSelectionRange(anchor, head) {
this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
this.selectionChanged = false;
}
clearSelectionRange() {
this.selectionRange.set(null, 0, null, 0);
}
listenForScroll() {
this.parentCheck = -1;
let i$1 = 0,
changed = null;
for (let dom = this.dom; dom;) if (dom.nodeType == 1) {
if (!changed && i$1 < this.scrollTargets.length && this.scrollTargets[i$1] == dom) i$1++;else if (!changed) changed = this.scrollTargets.slice(0, i$1);
if (changed) changed.push(dom);
dom = dom.assignedSlot || dom.parentNode;
} else if (dom.nodeType == 11) dom = dom.host;else break;
if (i$1 < this.scrollTargets.length && !changed) changed = this.scrollTargets.slice(0, i$1);
if (changed) {
for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll);
for (let dom of this.scrollTargets = changed) dom.addEventListener("scroll", this.onScroll);
}
}
ignore(f) {
if (!this.active) return f();
try {
this.stop();
return f();
} finally {
this.start();
this.clear();
}
}
start() {
if (this.active) return;
this.observer.observe(this.dom, observeOptions$1);
if (useCharData$1) this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
this.active = true;
}
stop() {
if (!this.active) return;
this.active = false;
this.observer.disconnect();
if (useCharData$1) this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
}
clear() {
this.processRecords();
this.queue.length = 0;
this.selectionChanged = false;
}
delayAndroidKey(key, keyCode) {
var _a$2;
if (!this.delayedAndroidKey) {
let flush = () => {
let key$1 = this.delayedAndroidKey;
if (key$1) {
this.clearDelayedAndroidKey();
this.view.inputState.lastKeyCode = key$1.keyCode;
this.view.inputState.lastKeyTime = Date.now();
if (!this.flush() && key$1.force) dispatchKey$1(this.dom, key$1.key, key$1.keyCode);
}
};
this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
}
if (!this.delayedAndroidKey || key == "Enter") this.delayedAndroidKey = {
key,
keyCode,
force: this.lastChange < Date.now() - 50 || !!((_a$2 = this.delayedAndroidKey) === null || _a$2 === void 0 ? void 0 : _a$2.force)
};
}
clearDelayedAndroidKey() {
this.win.cancelAnimationFrame(this.flushingAndroidKey);
this.delayedAndroidKey = null;
this.flushingAndroidKey = -1;
}
flushSoon() {
if (this.delayedFlush < 0) this.delayedFlush = this.view.win.requestAnimationFrame(() => {
this.delayedFlush = -1;
this.flush();
});
}
forceFlush() {
if (this.delayedFlush >= 0) {
this.view.win.cancelAnimationFrame(this.delayedFlush);
this.delayedFlush = -1;
}
this.flush();
}
pendingRecords() {
for (let mut of this.observer.takeRecords()) this.queue.push(mut);
return this.queue;
}
processRecords() {
let records = this.pendingRecords();
if (records.length) this.queue = [];
let from = -1,
to = -1,
typeOver = false;
for (let record of records) {
let range = this.readMutation(record);
if (!range) continue;
if (range.typeOver) typeOver = true;
if (from == -1) ({
from,
to
} = range);else {
from = Math.min(range.from, from);
to = Math.max(range.to, to);
}
}
return {
from,
to,
typeOver
};
}
readChange() {
let {
from,
to,
typeOver
} = this.processRecords();
let newSel = this.selectionChanged && hasSelection$1(this.dom, this.selectionRange);
if (from < 0 && !newSel) return null;
if (from > -1) this.lastChange = Date.now();
this.view.inputState.lastFocusTime = 0;
this.selectionChanged = false;
let change = new DOMChange$1(this.view, from, to, typeOver);
this.view.docView.domChanged = {
newSel: change.newSel ? change.newSel.main : null
};
return change;
}
flush(readSelection = true) {
if (this.delayedFlush >= 0 || this.delayedAndroidKey) return false;
if (readSelection) this.readSelectionRange();
let domChange = this.readChange();
if (!domChange) {
this.view.requestMeasure();
return false;
}
let startState = this.view.state;
let handled = applyDOMChange$1(this.view, domChange);
if (this.view.state == startState) this.view.update([]);
return handled;
}
readMutation(rec) {
let cView = this.view.docView.nearest(rec.target);
if (!cView || cView.ignoreMutation(rec)) return null;
cView.markDirty(rec.type == "attributes");
if (rec.type == "attributes") cView.flags |= 4;
if (rec.type == "childList") {
let childBefore = findChild$1(cView, rec.previousSibling || rec.target.previousSibling, -1);
let childAfter = findChild$1(cView, rec.nextSibling || rec.target.nextSibling, 1);
return {
from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd,
typeOver: false
};
} else if (rec.type == "characterData") return {
from: cView.posAtStart,
to: cView.posAtEnd,
typeOver: rec.target.nodeValue == rec.oldValue
};else return null;
}
setWindow(win) {
if (win != this.win) {
this.removeWindowListeners(this.win);
this.win = win;
this.addWindowListeners(this.win);
}
}
addWindowListeners(win) {
win.addEventListener("resize", this.onResize);
if (this.printQuery) this.printQuery.addEventListener("change", this.onPrint);else win.addEventListener("beforeprint", this.onPrint);
win.addEventListener("scroll", this.onScroll);
win.document.addEventListener("selectionchange", this.onSelectionChange);
}
removeWindowListeners(win) {
win.removeEventListener("scroll", this.onScroll);
win.removeEventListener("resize", this.onResize);
if (this.printQuery) this.printQuery.removeEventListener("change", this.onPrint);else win.removeEventListener("beforeprint", this.onPrint);
win.document.removeEventListener("selectionchange", this.onSelectionChange);
}
destroy() {
var _a$2, _b, _c;
this.stop();
(_a$2 = this.intersection) === null || _a$2 === void 0 || _a$2.disconnect();
(_b = this.gapIntersection) === null || _b === void 0 || _b.disconnect();
(_c = this.resizeScroll) === null || _c === void 0 || _c.disconnect();
for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll);
this.removeWindowListeners(this.win);
clearTimeout(this.parentCheck);
clearTimeout(this.resizeTimeout);
this.win.cancelAnimationFrame(this.delayedFlush);
this.win.cancelAnimationFrame(this.flushingAndroidKey);
}
};
_export("kt", EditorView = class EditorView {
/**
The current editor state.
*/
get state() {
return this.viewState.state;
}
/**
To be able to display large documents without consuming too much
memory or overloading the browser, CodeMirror only draws the
code that is visible (plus a margin around it) to the DOM. This
property tells you the extent of the current drawn viewport, in
document positions.
*/
get viewport() {
return this.viewState.viewport;
}
/**
When there are, for example, large collapsed ranges in the
viewport, its size can be a lot bigger than the actual visible
content. Thus, if you are doing something like styling the
content in the viewport, it is preferable to only do so for
these ranges, which are the subset of the viewport that is
actually drawn.
*/
get visibleRanges() {
return this.viewState.visibleRanges;
}
/**
Returns false when the editor is entirely scrolled out of view
or otherwise hidden.
*/
get inView() {
return this.viewState.inView;
}
/**
Indicates whether the user is currently composing text via
[IME](https://en.wikipedia.org/wiki/Input_method), and at least
one change has been made in the current composition.
*/
get composing() {
return this.inputState.composing > 0;
}
/**
Indicates whether the user is currently in composing state. Note
that on some platforms, like Android, this will be the case a
lot, since just putting the cursor on a word starts a
composition there.
*/
get compositionStarted() {
return this.inputState.composing >= 0;
}
/**
The document or shadow root that the view lives in.
*/
get root() {
return this._root;
}
/**
@internal
*/
get win() {
return this.dom.ownerDocument.defaultView || window;
}
/**
Construct a new view. You'll want to either provide a `parent`
option, or put `view.dom` into your document after creating a
view, so that the user can see the editor.
*/
constructor(config$1 = {}) {
this.plugins = [];
this.pluginMap = /* @__PURE__ */new Map();
this.editorAttrs = {};
this.contentAttrs = {};
this.bidiCache = [];
this.destroyed = false;
/**
@internal
*/
this.updateState = 2;
/**
@internal
*/
this.measureScheduled = -1;
/**
@internal
*/
this.measureRequests = [];
this.contentDOM = document.createElement("div");
this.scrollDOM = document.createElement("div");
this.scrollDOM.tabIndex = -1;
this.scrollDOM.className = "cm-scroller";
this.scrollDOM.appendChild(this.contentDOM);
this.announceDOM = document.createElement("div");
this.announceDOM.className = "cm-announced";
this.announceDOM.setAttribute("aria-live", "polite");
this.dom = document.createElement("div");
this.dom.appendChild(this.announceDOM);
this.dom.appendChild(this.scrollDOM);
if (config$1.parent) config$1.parent.appendChild(this.dom);
let {
dispatch
} = config$1;
this.dispatchTransactions = config$1.dispatchTransactions || dispatch && (trs => trs.forEach(tr => dispatch(tr, this))) || (trs => this.update(trs));
this.dispatch = this.dispatch.bind(this);
this._root = config$1.root || getRoot$1(config$1.parent) || document;
this.viewState = new ViewState$1(config$1.state || EditorState.create(config$1));
if (config$1.scrollTo && config$1.scrollTo.is(scrollIntoView$2)) this.viewState.scrollTarget = config$1.scrollTo.value.clip(this.viewState.state);
this.plugins = this.state.facet(viewPlugin$1).map(spec => new PluginInstance$1(spec));
for (let plugin of this.plugins) plugin.update(this);
this.observer = new DOMObserver$1(this);
this.inputState = new InputState$1(this);
this.inputState.ensureHandlers(this.plugins);
this.docView = new DocView$1(this);
this.mountStyles();
this.updateAttrs();
this.updateState = 0;
this.requestMeasure();
}
dispatch(...input) {
let trs = input.length == 1 && input[0] instanceof Transaction ? input : input.length == 1 && Array.isArray(input[0]) ? input[0] : [this.state.update(...input)];
this.dispatchTransactions(trs, this);
}
/**
Update the view for the given array of transactions. This will
update the visible document and selection to match the state
produced by the transactions, and notify view plugins of the
change. You should usually call
[`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
as a primitive.
*/
update(transactions) {
if (this.updateState != 0) throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
let redrawn = false,
attrsChanged = false,
update;
let state = this.state;
for (let tr of transactions) {
if (tr.startState != state) throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
state = tr.state;
}
if (this.destroyed) {
this.viewState.state = state;
return;
}
let focus = this.hasFocus,
focusFlag = 0,
dispatchFocus = null;
if (transactions.some(tr => tr.annotation(isFocusChange$1))) {
this.inputState.notifiedFocused = focus;
focusFlag = 1;
} else if (focus != this.inputState.notifiedFocused) {
this.inputState.notifiedFocused = focus;
dispatchFocus = focusChangeTransaction$1(state, focus);
if (!dispatchFocus) focusFlag = 1;
}
let pendingKey = this.observer.delayedAndroidKey,
domChange = null;
if (pendingKey) {
this.observer.clearDelayedAndroidKey();
domChange = this.observer.readChange();
if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection)) domChange = null;
} else this.observer.clear();
if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) return this.setState(state);
update = ViewUpdate$1.create(this, state, transactions);
update.flags |= focusFlag;
let scrollTarget = this.viewState.scrollTarget;
try {
this.updateState = 2;
for (let tr of transactions) {
if (scrollTarget) scrollTarget = scrollTarget.map(tr.changes);
if (tr.scrollIntoView) {
let {
main
} = tr.state.selection;
scrollTarget = new ScrollTarget$1(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
}
for (let e of tr.effects) if (e.is(scrollIntoView$2)) scrollTarget = e.value.clip(this.state);
}
this.viewState.update(update, scrollTarget);
this.bidiCache = CachedOrder$1.update(this.bidiCache, update.changes);
if (!update.empty) {
this.updatePlugins(update);
this.inputState.update(update);
}
redrawn = this.docView.update(update);
if (this.state.facet(styleModule$1) != this.styleModules) this.mountStyles();
attrsChanged = this.updateAttrs();
this.showAnnouncements(transactions);
this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer")));
} finally {
this.updateState = 0;
}
if (update.startState.facet(theme$1) != update.state.facet(theme$1)) this.viewState.mustMeasureContent = true;
if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) this.requestMeasure();
if (redrawn) this.docViewUpdate();
if (!update.empty) for (let listener of this.state.facet(updateListener$1)) try {
listener(update);
} catch (e) {
logException$1(this.state, e, "update listener");
}
if (dispatchFocus || domChange) Promise.resolve().then(() => {
if (dispatchFocus && this.state == dispatchFocus.startState) this.dispatch(dispatchFocus);
if (domChange) {
if (!applyDOMChange$1(this, domChange) && pendingKey.force) dispatchKey$1(this.contentDOM, pendingKey.key, pendingKey.keyCode);
}
});
}
/**
Reset the view to the given state. (This will cause the entire
document to be redrawn and all view plugins to be reinitialized,
so you should probably only use it when the new state isn't
derived from the old state. Otherwise, use
[`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
*/
setState(newState) {
if (this.updateState != 0) throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
if (this.destroyed) {
this.viewState.state = newState;
return;
}
this.updateState = 2;
let hadFocus = this.hasFocus;
try {
for (let plugin of this.plugins) plugin.destroy(this);
this.viewState = new ViewState$1(newState);
this.plugins = newState.facet(viewPlugin$1).map(spec => new PluginInstance$1(spec));
this.pluginMap.clear();
for (let plugin of this.plugins) plugin.update(this);
this.docView.destroy();
this.docView = new DocView$1(this);
this.inputState.ensureHandlers(this.plugins);
this.mountStyles();
this.updateAttrs();
this.bidiCache = [];
} finally {
this.updateState = 0;
}
if (hadFocus) this.focus();
this.requestMeasure();
}
updatePlugins(update) {
let prevSpecs = update.startState.facet(viewPlugin$1),
specs = update.state.facet(viewPlugin$1);
if (prevSpecs != specs) {
let newPlugins = [];
for (let spec of specs) {
let found = prevSpecs.indexOf(spec);
if (found < 0) newPlugins.push(new PluginInstance$1(spec));else {
let plugin = this.plugins[found];
plugin.mustUpdate = update;
newPlugins.push(plugin);
}
}
for (let plugin of this.plugins) if (plugin.mustUpdate != update) plugin.destroy(this);
this.plugins = newPlugins;
this.pluginMap.clear();
} else for (let p of this.plugins) p.mustUpdate = update;
for (let i$1 = 0; i$1 < this.plugins.length; i$1++) this.plugins[i$1].update(this);
if (prevSpecs != specs) this.inputState.ensureHandlers(this.plugins);
}
docViewUpdate() {
for (let plugin of this.plugins) {
let val = plugin.value;
if (val && val.docViewUpdate) try {
val.docViewUpdate(this);
} catch (e) {
logException$1(this.state, e, "doc view update listener");
}
}
}
/**
@internal
*/
measure(flush = true) {
if (this.destroyed) return;
if (this.measureScheduled > -1) this.win.cancelAnimationFrame(this.measureScheduled);
if (this.observer.delayedAndroidKey) {
this.measureScheduled = -1;
this.requestMeasure();
return;
}
this.measureScheduled = 0;
if (flush) this.observer.forceFlush();
let updated = null;
let sDOM = this.scrollDOM,
scrollTop = sDOM.scrollTop * this.scaleY;
let {
scrollAnchorPos,
scrollAnchorHeight
} = this.viewState;
if (Math.abs(scrollTop - this.viewState.scrollTop) > 1) scrollAnchorHeight = -1;
this.viewState.scrollAnchorHeight = -1;
try {
for (let i$1 = 0;; i$1++) {
if (scrollAnchorHeight < 0) if (isScrolledToBottom$1(sDOM)) {
scrollAnchorPos = -1;
scrollAnchorHeight = this.viewState.heightMap.height;
} else {
let block = this.viewState.scrollAnchorAt(scrollTop);
scrollAnchorPos = block.from;
scrollAnchorHeight = block.top;
}
this.updateState = 1;
let changed = this.viewState.measure(this);
if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) break;
if (i$1 > 5) {
console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize");
break;
}
let measuring = [];
if (!(changed & 4)) [this.measureRequests, measuring] = [measuring, this.measureRequests];
let measured = measuring.map(m => {
try {
return m.read(this);
} catch (e) {
logException$1(this.state, e);
return BadMeasure$1;
}
});
let update = ViewUpdate$1.create(this, this.state, []),
redrawn = false;
update.flags |= changed;
if (!updated) updated = update;else updated.flags |= changed;
this.updateState = 2;
if (!update.empty) {
this.updatePlugins(update);
this.inputState.update(update);
this.updateAttrs();
redrawn = this.docView.update(update);
if (redrawn) this.docViewUpdate();
}
for (let i$2 = 0; i$2 < measuring.length; i$2++) if (measured[i$2] != BadMeasure$1) try {
let m = measuring[i$2];
if (m.write) m.write(measured[i$2], this);
} catch (e) {
logException$1(this.state, e);
}
if (redrawn) this.docView.updateSelection(true);
if (!update.viewportChanged && this.measureRequests.length == 0) {
if (this.viewState.editorHeight) if (this.viewState.scrollTarget) {
this.docView.scrollIntoView(this.viewState.scrollTarget);
this.viewState.scrollTarget = null;
scrollAnchorHeight = -1;
continue;
} else {
let diff = (scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top) - scrollAnchorHeight;
if (diff > 1 || diff < -1) {
scrollTop = scrollTop + diff;
sDOM.scrollTop = scrollTop / this.scaleY;
scrollAnchorHeight = -1;
continue;
}
}
break;
}
}
} finally {
this.updateState = 0;
this.measureScheduled = -1;
}
if (updated && !updated.empty) for (let listener of this.state.facet(updateListener$1)) listener(updated);
}
/**
Get the CSS classes for the currently active editor themes.
*/
get themeClasses() {
return baseThemeID$1 + " " + (this.state.facet(darkTheme$1) ? baseDarkID$1 : baseLightID$1) + " " + this.state.facet(theme$1);
}
updateAttrs() {
let editorAttrs = attrsFromFacet$1(this, editorAttributes$1, {
class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
});
let contentAttrs = {
spellcheck: "false",
autocorrect: "off",
autocapitalize: "off",
translate: "no",
contenteditable: !this.state.facet(editable$1) ? "false" : "true",
class: "cm-content",
style: `${browser$1.tabSize}: ${this.state.tabSize}`,
role: "textbox",
"aria-multiline": "true"
};
if (this.state.readOnly) contentAttrs["aria-readonly"] = "true";
attrsFromFacet$1(this, contentAttributes$1, contentAttrs);
let changed = this.observer.ignore(() => {
let changedContent = updateAttrs$1(this.contentDOM, this.contentAttrs, contentAttrs);
let changedEditor = updateAttrs$1(this.dom, this.editorAttrs, editorAttrs);
return changedContent || changedEditor;
});
this.editorAttrs = editorAttrs;
this.contentAttrs = contentAttrs;
return changed;
}
showAnnouncements(trs) {
let first = true;
for (let tr of trs) for (let effect of tr.effects) if (effect.is(EditorView.announce)) {
if (first) this.announceDOM.textContent = "";
first = false;
let div = this.announceDOM.appendChild(document.createElement("div"));
div.textContent = effect.value;
}
}
mountStyles() {
this.styleModules = this.state.facet(styleModule$1);
let nonce = this.state.facet(EditorView.cspNonce);
StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1$6).reverse(), nonce ? {
nonce
} : void 0);
}
readMeasured() {
if (this.updateState == 2) throw new Error("Reading the editor layout isn't allowed during an update");
if (this.updateState == 0 && this.measureScheduled > -1) this.measure(false);
}
/**
Schedule a layout measurement, optionally providing callbacks to
do custom DOM measuring followed by a DOM write phase. Using
this is preferable reading DOM layout directly from, for
example, an event handler, because it'll make sure measuring and
drawing done by other components is synchronized, avoiding
unnecessary DOM layout computations.
*/
requestMeasure(request) {
if (this.measureScheduled < 0) this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
if (request) {
if (this.measureRequests.indexOf(request) > -1) return;
if (request.key != null) {
for (let i$1 = 0; i$1 < this.measureRequests.length; i$1++) if (this.measureRequests[i$1].key === request.key) {
this.measureRequests[i$1] = request;
return;
}
}
this.measureRequests.push(request);
}
}
/**
Get the value of a specific plugin, if present. Note that
plugins that crash can be dropped from a view, so even when you
know you registered a given plugin, it is recommended to check
the return value of this method.
*/
plugin(plugin) {
let known = this.pluginMap.get(plugin);
if (known === void 0 || known && known.spec != plugin) this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null);
return known && known.update(this).value;
}
/**
The top position of the document, in screen coordinates. This
may be negative when the editor is scrolled down. Points
directly to the top of the first line, not above the padding.
*/
get documentTop() {
return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
}
/**
Reports the padding above and below the document.
*/
get documentPadding() {
return {
top: this.viewState.paddingTop,
bottom: this.viewState.paddingBottom
};
}
/**
If the editor is transformed with CSS, this provides the scale
along the X axis. Otherwise, it will just be 1. Note that
transforms other than translation and scaling are not supported.
*/
get scaleX() {
return this.viewState.scaleX;
}
/**
Provide the CSS transformed scale along the Y axis.
*/
get scaleY() {
return this.viewState.scaleY;
}
/**
Find the text line or block widget at the given vertical
position (which is interpreted as relative to the [top of the
document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
*/
elementAtHeight(height) {
this.readMeasured();
return this.viewState.elementAtHeight(height);
}
/**
Find the line block (see
[`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given
height, again interpreted relative to the [top of the
document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
*/
lineBlockAtHeight(height) {
this.readMeasured();
return this.viewState.lineBlockAtHeight(height);
}
/**
Get the extent and vertical position of all [line
blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
are relative to the [top of the
document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
*/
get viewportLineBlocks() {
return this.viewState.viewportLines;
}
/**
Find the line block around the given document position. A line
block is a range delimited on both sides by either a
non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the
start/end of the document. It will usually just hold a line of
text, but may be broken into multiple textblocks by block
widgets.
*/
lineBlockAt(pos) {
return this.viewState.lineBlockAt(pos);
}
/**
The editor's total content height.
*/
get contentHeight() {
return this.viewState.contentHeight;
}
/**
Move a cursor position by [grapheme
cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
the motion is away from the line start, or towards it. In
bidirectional text, the line is traversed in visual order, using
the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
When the start position was the last one on the line, the
returned position will be across the line break. If there is no
further line, the original position is returned.
By default, this method moves over a single cluster. The
optional `by` argument can be used to move across more. It will
be called with the first cluster as argument, and should return
a predicate that determines, for each subsequent cluster,
whether it should also be moved over.
*/
moveByChar(start, forward, by) {
return skipAtoms$1(this, start, moveByChar$1(this, start, forward, by));
}
/**
Move a cursor position across the next group of either
[letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
non-whitespace characters.
*/
moveByGroup(start, forward) {
return skipAtoms$1(this, start, moveByChar$1(this, start, forward, initial => byGroup$1(this, start.head, initial)));
}
/**
Get the cursor position visually at the start or end of a line.
Note that this may differ from the _logical_ position at its
start or end (which is simply at `line.from`/`line.to`) if text
at the start or end goes against the line's base text direction.
*/
visualLineSide(line, end) {
let order = this.bidiSpans(line),
dir = this.textDirectionAt(line.from);
let span = order[end ? order.length - 1 : 0];
return EditorSelection.cursor(span.side(end, dir) + line.from, span.forward(!end, dir) ? 1 : -1);
}
/**
Move to the next line boundary in the given direction. If
`includeWrap` is true, line wrapping is on, and there is a
further wrap point on the current line, the wrap point will be
returned. Otherwise this function will return the start or end
of the line.
*/
moveToLineBoundary(start, forward, includeWrap = true) {
return moveToLineBoundary$1(this, start, forward, includeWrap);
}
/**
Move a cursor position vertically. When `distance` isn't given,
it defaults to moving to the next line (including wrapped
lines). Otherwise, `distance` should provide a positive distance
in pixels.
When `start` has a
[`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
motion will use that as a target horizontal position. Otherwise,
the cursor's own horizontal position is used. The returned
cursor will have its goal column set to whichever column was
used.
*/
moveVertically(start, forward, distance) {
return skipAtoms$1(this, start, moveVertically$1(this, start, forward, distance));
}
/**
Find the DOM parent node and offset (child offset if `node` is
an element, character offset when it is a text node) at the
given document position.
Note that for positions that aren't currently in
`visibleRanges`, the resulting DOM position isn't necessarily
meaningful (it may just point before or after a placeholder
element).
*/
domAtPos(pos) {
return this.docView.domAtPos(pos);
}
/**
Find the document position at the given DOM node. Can be useful
for associating positions with DOM events. Will raise an error
when `node` isn't part of the editor content.
*/
posAtDOM(node, offset = 0) {
return this.docView.posFromDOM(node, offset);
}
posAtCoords(coords, precise = true) {
this.readMeasured();
return posAtCoords$1(this, coords, precise);
}
/**
Get the screen coordinates at the given document position.
`side` determines whether the coordinates are based on the
element before (-1) or after (1) the position (if no element is
available on the given side, the method will transparently use
another strategy to get reasonable coordinates).
*/
coordsAtPos(pos, side = 1) {
this.readMeasured();
let rect = this.docView.coordsAt(pos, side);
if (!rect || rect.left == rect.right) return rect;
let line = this.state.doc.lineAt(pos),
order = this.bidiSpans(line);
let span = order[BidiSpan$1.find(order, pos - line.from, -1, side)];
return flattenRect$1(rect, span.dir == Direction$1.LTR == side > 0);
}
/**
Return the rectangle around a given character. If `pos` does not
point in front of a character that is in the viewport and
rendered (i.e. not replaced, not a line break), this will return
null. For space characters that are a line wrap point, this will
return the position before the line break.
*/
coordsForChar(pos) {
this.readMeasured();
return this.docView.coordsForChar(pos);
}
/**
The default width of a character in the editor. May not
accurately reflect the width of all characters (given variable
width fonts or styling of invididual ranges).
*/
get defaultCharacterWidth() {
return this.viewState.heightOracle.charWidth;
}
/**
The default height of a line in the editor. May not be accurate
for all lines.
*/
get defaultLineHeight() {
return this.viewState.heightOracle.lineHeight;
}
/**
The text direction
([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
CSS property) of the editor's content element.
*/
get textDirection() {
return this.viewState.defaultTextDirection;
}
/**
Find the text direction of the block at the given position, as
assigned by CSS. If
[`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
isn't enabled, or the given position is outside of the viewport,
this will always return the same as
[`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
this may trigger a DOM layout.
*/
textDirectionAt(pos) {
if (!this.state.facet(perLineTextDirection$1) || pos < this.viewport.from || pos > this.viewport.to) return this.textDirection;
this.readMeasured();
return this.docView.textDirectionAt(pos);
}
/**
Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
(as determined by the
[`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
CSS property of its content element).
*/
get lineWrapping() {
return this.viewState.heightOracle.lineWrapping;
}
/**
Returns the bidirectional text structure of the given line
(which should be in the current document) as an array of span
objects. The order of these spans matches the [text
direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
left-to-right, the leftmost spans come first, otherwise the
rightmost spans come first.
*/
bidiSpans(line) {
if (line.length > MaxBidiLine$1) return trivialOrder$1(line.length);
let dir = this.textDirectionAt(line.from),
isolates;
for (let entry of this.bidiCache) if (entry.from == line.from && entry.dir == dir && (entry.fresh || isolatesEq$1(entry.isolates, isolates = getIsolatedRanges$1(this, line)))) return entry.order;
if (!isolates) isolates = getIsolatedRanges$1(this, line);
let order = computeOrder$1(line.text, dir, isolates);
this.bidiCache.push(new CachedOrder$1(line.from, line.to, dir, isolates, true, order));
return order;
}
/**
Check whether the editor has focus.
*/
get hasFocus() {
var _a$2;
return (this.dom.ownerDocument.hasFocus() || browser$1.safari && ((_a$2 = this.inputState) === null || _a$2 === void 0 ? void 0 : _a$2.lastContextMenu) > Date.now() - 3e4) && this.root.activeElement == this.contentDOM;
}
/**
Put focus on the editor.
*/
focus() {
this.observer.ignore(() => {
focusPreventScroll$1(this.contentDOM);
this.docView.updateSelection();
});
}
/**
Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
necessary when moving the editor's existing DOM to a new window or shadow root.
*/
setRoot(root) {
if (this._root != root) {
this._root = root;
this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);
this.mountStyles();
}
}
/**
Clean up this editor view, removing its element from the
document, unregistering event handlers, and notifying
plugins. The view instance can no longer be used after
calling this.
*/
destroy() {
for (let plugin of this.plugins) plugin.destroy(this);
this.plugins = [];
this.inputState.destroy();
this.docView.destroy();
this.dom.remove();
this.observer.destroy();
if (this.measureScheduled > -1) this.win.cancelAnimationFrame(this.measureScheduled);
this.destroyed = true;
}
/**
Returns an effect that can be
[added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
cause it to scroll the given position or range into view.
*/
static scrollIntoView(pos, options = {}) {
return scrollIntoView$2.of(new ScrollTarget$1(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));
}
/**
Return an effect that resets the editor to its current (at the
time this method was called) scroll position. Note that this
only affects the editor's own scrollable element, not parents.
See also
[`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
The effect should be used with a document identical to the one
it was created for. Failing to do so is not an error, but may
not scroll to the expected position. You can
[map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
*/
scrollSnapshot() {
let {
scrollTop,
scrollLeft
} = this.scrollDOM;
let ref$1 = this.viewState.scrollAnchorAt(scrollTop);
return scrollIntoView$2.of(new ScrollTarget$1(EditorSelection.cursor(ref$1.from), "start", "start", ref$1.top - scrollTop, scrollLeft, true));
}
/**
Returns an extension that can be used to add DOM event handlers.
The value should be an object mapping event names to handler
functions. For any given event, such functions are ordered by
extension precedence, and the first handler to return true will
be assumed to have handled that event, and no other handlers or
built-in behavior will be activated for it. These are registered
on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
for `scroll` handlers, which will be called any time the
editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
its parent nodes is scrolled.
*/
static domEventHandlers(handlers$2) {
return ViewPlugin$1.define(() => ({}), {
eventHandlers: handlers$2
});
}
/**
Create an extension that registers DOM event observers. Contrary
to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
observers can't be prevented from running by a higher-precedence
handler returning true. They also don't prevent other handlers
and observers from running when they return true, and should not
call `preventDefault`.
*/
static domEventObservers(observers$2) {
return ViewPlugin$1.define(() => ({}), {
eventObservers: observers$2
});
}
/**
Create a theme extension. The first argument can be a
[`style-mod`](https://github.com/marijnh/style-mod#documentation)
style spec providing the styles for the theme. These will be
prefixed with a generated class for the style.
Because the selectors will be prefixed with a scope class, rule
that directly match the editor's [wrapper
element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
added—need to be explicitly differentiated by adding an `&` to
the selector for that element—for example
`&.cm-focused`.
When `dark` is set to true, the theme will be marked as dark,
which will cause the `&dark` rules from [base
themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
`&light` when a light theme is active).
*/
static theme(spec, options) {
let prefix = StyleModule.newName();
let result = [theme$1.of(prefix), styleModule$1.of(buildTheme$1(`.${prefix}`, spec))];
if (options && options.dark) result.push(darkTheme$1.of(true));
return result;
}
/**
Create an extension that adds styles to the base theme. Like
with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
place of the editor wrapper element when directly targeting
that. You can also use `&dark` or `&light` instead to only
target editors with a dark or light theme.
*/
static baseTheme(spec) {
return Prec.lowest(styleModule$1.of(buildTheme$1("." + baseThemeID$1, spec, lightDarkIDs$1)));
}
/**
Retrieve an editor view instance from the view's DOM
representation.
*/
static findFromDOM(dom) {
var _a$2;
let content$1 = dom.querySelector(".cm-content");
let cView = content$1 && ContentView$1.get(content$1) || ContentView$1.get(dom);
return ((_a$2 = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a$2 === void 0 ? void 0 : _a$2.view) || null;
}
});
/**
Facet to add a [style
module](https://github.com/marijnh/style-mod#documentation) to
an editor view. The view will ensure that the module is
mounted in its [document
root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).
*/
EditorView.styleModule = styleModule$1;
/**
An input handler can override the way changes to the editable
DOM content are handled. Handlers are passed the document
positions between which the change was found, and the new
content. When one returns true, no further input handlers are
called and the default behavior is prevented.
The `insert` argument can be used to get the default transaction
that would be applied for this input. This can be useful when
dispatching the custom behavior as a separate transaction.
*/
EditorView.inputHandler = inputHandler$2;
/**
Scroll handlers can override how things are scrolled into view.
If they return `true`, no further handling happens for the
scrolling. If they return false, the default scroll behavior is
applied. Scroll handlers should never initiate editor updates.
*/
EditorView.scrollHandler = scrollHandler;
/**
This facet can be used to provide functions that create effects
to be dispatched when the editor's focus state changes.
*/
EditorView.focusChangeEffect = focusChangeEffect$1;
/**
By default, the editor assumes all its content has the same
[text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`
value to make it read the text direction of every (rendered)
line separately.
*/
EditorView.perLineTextDirection = perLineTextDirection$1;
/**
Allows you to provide a function that should be called when the
library catches an exception from an extension (mostly from view
plugins, but may be used by other extensions to route exceptions
from user-code-provided callbacks). This is mostly useful for
debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).
*/
EditorView.exceptionSink = exceptionSink$1;
/**
A facet that can be used to register a function to be called
every time the view updates.
*/
EditorView.updateListener = updateListener$1;
/**
Facet that controls whether the editor content DOM is editable.
When its highest-precedence value is `false`, the element will
not have its `contenteditable` attribute set. (Note that this
doesn't affect API calls that change the editor content, even
when those are bound to keys or buttons. See the
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)
*/
EditorView.editable = editable$1;
/**
Allows you to influence the way mouse selection happens. The
functions in this facet will be called for a `mousedown` event
on the editor, and can return an object that overrides the way a
selection is computed from that mouse click or drag.
*/
EditorView.mouseSelectionStyle = mouseSelectionStyle$1;
/**
Facet used to configure whether a given selection drag event
should move or copy the selection. The given predicate will be
called with the `mousedown` event, and can return `true` when
the drag should move the content.
*/
EditorView.dragMovesSelection = dragMovesSelection$1$1;
/**
Facet used to configure whether a given selecting click adds a
new range to the existing selection or replaces it entirely. The
default behavior is to check `event.metaKey` on macOS, and
`event.ctrlKey` elsewhere.
*/
EditorView.clickAddsSelectionRange = clickAddsSelectionRange$1;
/**
A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)
are shown in the view. Decorations can be provided in two
ways—directly, or via a function that takes an editor view.
Only decoration sets provided directly are allowed to influence
the editor's vertical layout structure. The ones provided as
functions are called _after_ the new viewport has been computed,
and thus **must not** introduce block widgets or replacing
decorations that cover line breaks.
If you want decorated ranges to behave like atomic units for
cursor motion and deletion purposes, also provide the range set
containing the decorations to
[`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).
*/
EditorView.decorations = decorations$1;
/**
Facet that works much like
[`decorations`](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), but puts its
inputs at the very bottom of the precedence stack, meaning mark
decorations provided here will only be split by other, partially
overlapping \`outerDecorations\` ranges, and wrap around all
regular decorations. Use this for mark elements that should, as
much as possible, remain in one piece.
*/
EditorView.outerDecorations = outerDecorations;
/**
Used to provide ranges that should be treated as atoms as far as
cursor motion is concerned. This causes methods like
[`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and
[`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the
commands built on top of them) to skip across such regions when
a selection endpoint would enter them. This does _not_ prevent
direct programmatic [selection
updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such
regions.
*/
EditorView.atomicRanges = atomicRanges$1;
/**
When range decorations add a `unicode-bidi: isolate` style, they
should also include a
[`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property
in their decoration spec, and be exposed through this facet, so
that the editor can compute the proper text order. (Other values
for `unicode-bidi`, except of course `normal`, are not
supported.)
*/
EditorView.bidiIsolatedRanges = bidiIsolatedRanges$1;
/**
Facet that allows extensions to provide additional scroll
margins (space around the sides of the scrolling element that
should be considered invisible). This can be useful when the
plugin introduces elements that cover part of that element (for
example a horizontally fixed gutter).
*/
EditorView.scrollMargins = scrollMargins$1;
/**
This facet records whether a dark theme is active. The extension
returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically
includes an instance of this when the `dark` option is set to
true.
*/
EditorView.darkTheme = darkTheme$1;
/**
Provides a Content Security Policy nonce to use when creating
the style sheets for the editor. Holds the empty string when no
nonce has been provided.
*/
EditorView.cspNonce = /* @__PURE__ */Facet$1.define({
combine: values => values.length ? values[0] : ""
});
/**
Facet that provides additional DOM attributes for the editor's
editable DOM element.
*/
EditorView.contentAttributes = contentAttributes$1;
/**
Facet that provides DOM attributes for the editor's outer
element.
*/
EditorView.editorAttributes = editorAttributes$1;
/**
An extension that enables line wrapping in the editor (by
setting CSS `white-space` to `pre-wrap` in the content).
*/
EditorView.lineWrapping = /* @__PURE__ */EditorView.contentAttributes.of({
"class": "cm-lineWrapping"
});
/**
State effect used to include screen reader announcements in a
transaction. These will be added to the DOM in a visually hidden
element with `aria-live="polite"` set, and should be used to
describe effects that are visually obvious but may not be
noticed by screen reader users (such as moving to the next
search match).
*/
EditorView.announce = /* @__PURE__ */StateEffect$1.define();
MaxBidiLine$1 = 4096;
BadMeasure$1 = {};
CachedOrder$1 = class CachedOrder$1 {
constructor(from, to, dir, isolates, fresh, order) {
this.from = from;
this.to = to;
this.dir = dir;
this.isolates = isolates;
this.fresh = fresh;
this.order = order;
}
static update(cache$1, changes) {
if (changes.empty && !cache$1.some(c => c.fresh)) return cache$1;
let result = [],
lastDir = cache$1.length ? cache$1[cache$1.length - 1].dir : Direction$1.LTR;
for (let i$1 = Math.max(0, cache$1.length - 10); i$1 < cache$1.length; i$1++) {
let entry = cache$1[i$1];
if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) result.push(new CachedOrder$1(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
}
return result;
}
};
currentPlatform$1 = browser$1.mac ? "mac" : browser$1.windows ? "win" : browser$1.linux ? "linux" : "key";
handleKeyEvents = /* @__PURE__ */Prec.default(/* @__PURE__ */EditorView.domEventHandlers({
keydown(event, view) {
return runHandlers(getKeymap(view.state), event, view, "editor");
}
}));
/**
Facet used for registering keymaps.
You can add multiple keymaps to an editor. Their priorities
determine their precedence (the ones specified early or with high
priority get checked first). When a handler has returned `true`
for a given key, no further handlers are called.
*/
_export("Lt", keymap = /* @__PURE__ */Facet$1.define({
enables: handleKeyEvents
}));
Keymaps = /* @__PURE__ */new WeakMap();
storedPrefix = null;
PrefixTimeout = 4e3;
RectangleMarker = class RectangleMarker {
/**
Create a marker with the given class and dimensions. If `width`
is null, the DOM element will get no width style.
*/
constructor(className, left, top$1, width, height) {
this.className = className;
this.left = left;
this.top = top$1;
this.width = width;
this.height = height;
}
draw() {
let elt = document.createElement("div");
elt.className = this.className;
this.adjust(elt);
return elt;
}
update(elt, prev) {
if (prev.className != this.className) return false;
this.adjust(elt);
return true;
}
adjust(elt) {
elt.style.left = this.left + "px";
elt.style.top = this.top + "px";
if (this.width != null) elt.style.width = this.width + "px";
elt.style.height = this.height + "px";
}
eq(p) {
return this.left == p.left && this.top == p.top && this.width == p.width && this.height == p.height && this.className == p.className;
}
/**
Create a set of rectangles for the given selection range,
assigning them theclass`className`. Will create a single
rectangle for empty ranges, and a set of selection-style
rectangles covering the range's content (in a bidi-aware
way) for non-empty ones.
*/
static forRange(view, className, range) {
if (range.empty) {
let pos = view.coordsAtPos(range.head, range.assoc || 1);
if (!pos) return [];
let base$1 = getBase(view);
return [new RectangleMarker(className, pos.left - base$1.left, pos.top - base$1.top, null, pos.bottom - pos.top)];
} else return rectanglesForRange(view, className, range);
}
};
LayerView = class {
constructor(view, layer$1) {
this.view = view;
this.layer = layer$1;
this.drawn = [];
this.scaleX = 1;
this.scaleY = 1;
this.measureReq = {
read: this.measure.bind(this),
write: this.draw.bind(this)
};
this.dom = view.scrollDOM.appendChild(document.createElement("div"));
this.dom.classList.add("cm-layer");
if (layer$1.above) this.dom.classList.add("cm-layer-above");
if (layer$1.class) this.dom.classList.add(layer$1.class);
this.scale();
this.dom.setAttribute("aria-hidden", "true");
this.setOrder(view.state);
view.requestMeasure(this.measureReq);
if (layer$1.mount) layer$1.mount(this.dom, view);
}
update(update) {
if (update.startState.facet(layerOrder) != update.state.facet(layerOrder)) this.setOrder(update.state);
if (this.layer.update(update, this.dom) || update.geometryChanged) {
this.scale();
update.view.requestMeasure(this.measureReq);
}
}
docViewUpdate(view) {
if (this.layer.updateOnDocViewUpdate !== false) view.requestMeasure(this.measureReq);
}
setOrder(state) {
let pos = 0,
order = state.facet(layerOrder);
while (pos < order.length && order[pos] != this.layer) pos++;
this.dom.style.zIndex = String((this.layer.above ? 150 : -1) - pos);
}
measure() {
return this.layer.markers(this.view);
}
scale() {
let {
scaleX,
scaleY
} = this.view;
if (scaleX != this.scaleX || scaleY != this.scaleY) {
this.scaleX = scaleX;
this.scaleY = scaleY;
this.dom.style.transform = `scale(${1 / scaleX}, ${1 / scaleY})`;
}
}
draw(markers) {
if (markers.length != this.drawn.length || markers.some((p, i$1) => !sameMarker(p, this.drawn[i$1]))) {
let old = this.dom.firstChild,
oldI = 0;
for (let marker of markers) if (marker.update && old && marker.constructor && this.drawn[oldI].constructor && marker.update(old, this.drawn[oldI])) {
old = old.nextSibling;
oldI++;
} else this.dom.insertBefore(marker.draw(), old);
while (old) {
let next = old.nextSibling;
old.remove();
old = next;
}
this.drawn = markers;
}
}
destroy() {
if (this.layer.destroy) this.layer.destroy(this.dom, this.view);
this.dom.remove();
}
};
layerOrder = /* @__PURE__ */Facet$1.define();
CanHidePrimary$1 = !browser$1.ios;
selectionConfig = /* @__PURE__ */Facet$1.define({
combine(configs) {
return combineConfig$1(configs, {
cursorBlinkRate: 1200,
drawRangeCursor: true
}, {
cursorBlinkRate: (a, b) => Math.min(a, b),
drawRangeCursor: (a, b) => a || b
});
}
});
cursorLayer = /* @__PURE__ */layer({
above: true,
markers(view) {
let {
state
} = view,
conf = state.facet(selectionConfig);
let cursors = [];
for (let r of state.selection.ranges) {
let prim = r == state.selection.main;
if (r.empty ? !prim || CanHidePrimary$1 : conf.drawRangeCursor) {
let className = prim ? "cm-cursor cm-cursor-primary" : "cm-cursor cm-cursor-secondary";
let cursor = r.empty ? r : EditorSelection.cursor(r.head, r.head > r.anchor ? -1 : 1);
for (let piece of RectangleMarker.forRange(view, className, cursor)) cursors.push(piece);
}
}
return cursors;
},
update(update, dom) {
if (update.transactions.some(tr => tr.selection)) dom.style.animationName = dom.style.animationName == "cm-blink" ? "cm-blink2" : "cm-blink";
let confChange = configChanged(update);
if (confChange) setBlinkRate(update.state, dom);
return update.docChanged || update.selectionSet || confChange;
},
mount(dom, view) {
setBlinkRate(view.state, dom);
},
class: "cm-cursorLayer"
});
selectionLayer = /* @__PURE__ */layer({
above: false,
markers(view) {
return view.state.selection.ranges.map(r => r.empty ? [] : RectangleMarker.forRange(view, "cm-selectionBackground", r)).reduce((a, b) => a.concat(b));
},
update(update, dom) {
return update.docChanged || update.selectionSet || update.viewportChanged || configChanged(update);
},
class: "cm-selectionLayer"
});
themeSpec$1 = {
".cm-line": {
"& ::selection": {
backgroundColor: "transparent !important"
},
"&::selection": {
backgroundColor: "transparent !important"
}
}
};
if (CanHidePrimary$1) {
themeSpec$1[".cm-line"].caretColor = "transparent !important";
themeSpec$1[".cm-content"] = {
caretColor: "transparent !important"
};
}
hideNativeSelection = /* @__PURE__ */Prec.highest(/* @__PURE__ */EditorView.theme(themeSpec$1));
setDropCursorPos$1 = /* @__PURE__ */StateEffect$1.define({
map(pos, mapping) {
return pos == null ? null : mapping.mapPos(pos);
}
});
dropCursorPos$1 = /* @__PURE__ */StateField$1.define({
create() {
return null;
},
update(pos, tr) {
if (pos != null) pos = tr.changes.mapPos(pos);
return tr.effects.reduce((pos$1, e) => e.is(setDropCursorPos$1) ? e.value : pos$1, pos);
}
});
drawDropCursor$1 = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.view = view;
this.cursor = null;
this.measureReq = {
read: this.readPos.bind(this),
write: this.drawCursor.bind(this)
};
}
update(update) {
var _a$2;
let cursorPos = update.state.field(dropCursorPos$1);
if (cursorPos == null) {
if (this.cursor != null) {
(_a$2 = this.cursor) === null || _a$2 === void 0 || _a$2.remove();
this.cursor = null;
}
} else {
if (!this.cursor) {
this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
this.cursor.className = "cm-dropCursor";
}
if (update.startState.field(dropCursorPos$1) != cursorPos || update.docChanged || update.geometryChanged) this.view.requestMeasure(this.measureReq);
}
}
readPos() {
let {
view
} = this;
let pos = view.state.field(dropCursorPos$1);
let rect = pos != null && view.coordsAtPos(pos);
if (!rect) return null;
let outer = view.scrollDOM.getBoundingClientRect();
return {
left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
height: rect.bottom - rect.top
};
}
drawCursor(pos) {
if (this.cursor) {
let {
scaleX,
scaleY
} = this.view;
if (pos) {
this.cursor.style.left = pos.left / scaleX + "px";
this.cursor.style.top = pos.top / scaleY + "px";
this.cursor.style.height = pos.height / scaleY + "px";
} else this.cursor.style.left = "-100000px";
}
}
destroy() {
if (this.cursor) this.cursor.remove();
}
setDropPos(pos) {
if (this.view.state.field(dropCursorPos$1) != pos) this.view.dispatch({
effects: setDropCursorPos$1.of(pos)
});
}
}, {
eventObservers: {
dragover(event) {
this.setDropPos(this.view.posAtCoords({
x: event.clientX,
y: event.clientY
}));
},
dragleave(event) {
if (event.target == this.view.contentDOM || !this.view.contentDOM.contains(event.relatedTarget)) this.setDropPos(null);
},
dragend() {
this.setDropPos(null);
},
drop() {
this.setDropPos(null);
}
}
});
MatchDecorator = class {
/**
Create a decorator.
*/
constructor(config$1) {
const {
regexp,
decoration,
decorate,
boundary,
maxLength = 1e3
} = config$1;
if (!regexp.global) throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");
this.regexp = regexp;
if (decorate) this.addMatch = (match, view, from, add$1) => decorate(add$1, from, from + match[0].length, match, view);else if (typeof decoration == "function") this.addMatch = (match, view, from, add$1) => {
let deco = decoration(match, view, from);
if (deco) add$1(from, from + match[0].length, deco);
};else if (decoration) this.addMatch = (match, _view, from, add$1) => add$1(from, from + match[0].length, decoration);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");
this.boundary = boundary;
this.maxLength = maxLength;
}
/**
Compute the full set of decorations for matches in the given
view's viewport. You'll want to call this when initializing your
plugin.
*/
createDeco(view) {
let build = new RangeSetBuilder$1(),
add$1 = build.add.bind(build);
for (let {
from,
to
} of matchRanges(view, this.maxLength)) iterMatches(view.state.doc, this.regexp, from, to, (from$1, m) => this.addMatch(m, view, from$1, add$1));
return build.finish();
}
/**
Update a set of decorations for a view update. `deco` _must_ be
the set of decorations produced by _this_ `MatchDecorator` for
the view state before the update.
*/
updateDeco(update, deco) {
let changeFrom = 1e9,
changeTo = -1;
if (update.docChanged) update.changes.iterChanges((_f, _t, from, to) => {
if (to > update.view.viewport.from && from < update.view.viewport.to) {
changeFrom = Math.min(from, changeFrom);
changeTo = Math.max(to, changeTo);
}
});
if (update.viewportChanged || changeTo - changeFrom > 1e3) return this.createDeco(update.view);
if (changeTo > -1) return this.updateRange(update.view, deco.map(update.changes), changeFrom, changeTo);
return deco;
}
updateRange(view, deco, updateFrom, updateTo) {
for (let r of view.visibleRanges) {
let from = Math.max(r.from, updateFrom),
to = Math.min(r.to, updateTo);
if (to > from) {
let fromLine = view.state.doc.lineAt(from),
toLine = fromLine.to < to ? view.state.doc.lineAt(to) : fromLine;
let start = Math.max(r.from, fromLine.from),
end = Math.min(r.to, toLine.to);
if (this.boundary) {
for (; from > fromLine.from; from--) if (this.boundary.test(fromLine.text[from - 1 - fromLine.from])) {
start = from;
break;
}
for (; to < toLine.to; to++) if (this.boundary.test(toLine.text[to - toLine.from])) {
end = to;
break;
}
}
let ranges = [],
m;
let add$1 = (from$1, to$1, deco$1) => ranges.push(deco$1.range(from$1, to$1));
if (fromLine == toLine) {
this.regexp.lastIndex = start - fromLine.from;
while ((m = this.regexp.exec(fromLine.text)) && m.index < end - fromLine.from) this.addMatch(m, view, m.index + fromLine.from, add$1);
} else iterMatches(view.state.doc, this.regexp, start, end, (from$1, m$1) => this.addMatch(m$1, view, from$1, add$1));
deco = deco.update({
filterFrom: start,
filterTo: end,
filter: (from$1, to$1) => from$1 < start || to$1 > end,
add: ranges
});
}
}
return deco;
}
};
UnicodeRegexpSupport$1 = /x/.unicode != null ? "gu" : "g";
Specials = /* @__PURE__ */new RegExp("[\0-\b\n--\u2028\u2029-]", UnicodeRegexpSupport$1);
Names = {
0: "null",
7: "bell",
8: "backspace",
10: "newline",
11: "vertical tab",
13: "carriage return",
27: "escape",
8203: "zero width space",
8204: "zero width non-joiner",
8205: "zero width joiner",
8206: "left-to-right mark",
8207: "right-to-left mark",
8232: "line separator",
8237: "left-to-right override",
8238: "right-to-left override",
8294: "left-to-right isolate",
8295: "right-to-left isolate",
8297: "pop directional isolate",
8233: "paragraph separator",
65279: "zero width no-break space",
65532: "object replacement"
};
_supportsTabSize = null;
specialCharConfig = /* @__PURE__ */Facet$1.define({
combine(configs) {
let config$1 = combineConfig$1(configs, {
render: null,
specialChars: Specials,
addSpecialChars: null
});
if (config$1.replaceTabs = !supportsTabSize()) config$1.specialChars = new RegExp(" |" + config$1.specialChars.source, UnicodeRegexpSupport$1);
if (config$1.addSpecialChars) config$1.specialChars = new RegExp(config$1.specialChars.source + "|" + config$1.addSpecialChars.source, UnicodeRegexpSupport$1);
return config$1;
}
});
_plugin = null;
DefaultPlaceholder = "•";
SpecialCharWidget = class extends WidgetType$1 {
constructor(options, code$1) {
super();
this.options = options;
this.code = code$1;
}
eq(other) {
return other.code == this.code;
}
toDOM(view) {
let ph = placeholder$1(this.code);
let desc = view.state.phrase("Control character") + " " + (Names[this.code] || "0x" + this.code.toString(16));
let custom = this.options.render && this.options.render(this.code, desc, ph);
if (custom) return custom;
let span = document.createElement("span");
span.textContent = ph;
span.title = desc;
span.setAttribute("aria-label", desc);
span.className = "cm-specialChar";
return span;
}
ignoreEvent() {
return false;
}
};
TabWidget = class extends WidgetType$1 {
constructor(width) {
super();
this.width = width;
}
eq(other) {
return other.width == this.width;
}
toDOM() {
let span = document.createElement("span");
span.textContent = " ";
span.className = "cm-tab";
span.style.width = this.width + "px";
return span;
}
ignoreEvent() {
return false;
}
};
lineDeco = /* @__PURE__ */Decoration$1.line({
class: "cm-activeLine"
});
activeLineHighlighter = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.decorations = this.getDeco(view);
}
update(update) {
if (update.docChanged || update.selectionSet) this.decorations = this.getDeco(update.view);
}
getDeco(view) {
let lastLineStart = -1,
deco = [];
for (let r of view.state.selection.ranges) {
let line = view.lineBlockAt(r.head);
if (line.from > lastLineStart) {
deco.push(lineDeco.range(line.from));
lastLineStart = line.from;
}
}
return Decoration$1.set(deco);
}
}, {
decorations: v => v.decorations
});
Outside = "-10000px";
TooltipViewManager = class {
constructor(view, facet, createTooltipView, removeTooltipView) {
this.facet = facet;
this.createTooltipView = createTooltipView;
this.removeTooltipView = removeTooltipView;
this.input = view.state.facet(facet);
this.tooltips = this.input.filter(t$1 => t$1);
let prev = null;
this.tooltipViews = this.tooltips.map(t$1 => prev = createTooltipView(t$1, prev));
}
update(update, above) {
var _a$2;
let input = update.state.facet(this.facet);
let tooltips$1 = input.filter(x => x);
if (input === this.input) {
for (let t$1 of this.tooltipViews) if (t$1.update) t$1.update(update);
return false;
}
let tooltipViews = [],
newAbove = above ? [] : null;
for (let i$1 = 0; i$1 < tooltips$1.length; i$1++) {
let tip = tooltips$1[i$1],
known = -1;
if (!tip) continue;
for (let i$2 = 0; i$2 < this.tooltips.length; i$2++) {
let other = this.tooltips[i$2];
if (other && other.create == tip.create) known = i$2;
}
if (known < 0) {
tooltipViews[i$1] = this.createTooltipView(tip, i$1 ? tooltipViews[i$1 - 1] : null);
if (newAbove) newAbove[i$1] = !!tip.above;
} else {
let tooltipView = tooltipViews[i$1] = this.tooltipViews[known];
if (newAbove) newAbove[i$1] = above[known];
if (tooltipView.update) tooltipView.update(update);
}
}
for (let t$1 of this.tooltipViews) if (tooltipViews.indexOf(t$1) < 0) {
this.removeTooltipView(t$1);
(_a$2 = t$1.destroy) === null || _a$2 === void 0 || _a$2.call(t$1);
}
if (above) {
newAbove.forEach((val, i$1) => above[i$1] = val);
above.length = newAbove.length;
}
this.input = input;
this.tooltips = tooltips$1;
this.tooltipViews = tooltipViews;
return true;
}
};
tooltipConfig = /* @__PURE__ */Facet$1.define({
combine: values => {
var _a$2, _b, _c;
return {
position: browser$1.ios ? "absolute" : ((_a$2 = values.find(conf => conf.position)) === null || _a$2 === void 0 ? void 0 : _a$2.position) || "fixed",
parent: ((_b = values.find(conf => conf.parent)) === null || _b === void 0 ? void 0 : _b.parent) || null,
tooltipSpace: ((_c = values.find(conf => conf.tooltipSpace)) === null || _c === void 0 ? void 0 : _c.tooltipSpace) || windowSpace
};
}
});
knownHeight = /* @__PURE__ */new WeakMap();
tooltipPlugin = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.view = view;
this.above = [];
this.inView = true;
this.madeAbsolute = false;
this.lastTransaction = 0;
this.measureTimeout = -1;
let config$1 = view.state.facet(tooltipConfig);
this.position = config$1.position;
this.parent = config$1.parent;
this.classes = view.themeClasses;
this.createContainer();
this.measureReq = {
read: this.readMeasure.bind(this),
write: this.writeMeasure.bind(this),
key: this
};
this.resizeObserver = typeof ResizeObserver == "function" ? new ResizeObserver(() => this.measureSoon()) : null;
this.manager = new TooltipViewManager(view, showTooltip, (t$1, p) => this.createTooltip(t$1, p), t$1 => {
if (this.resizeObserver) this.resizeObserver.unobserve(t$1.dom);
t$1.dom.remove();
});
this.above = this.manager.tooltips.map(t$1 => !!t$1.above);
this.intersectionObserver = typeof IntersectionObserver == "function" ? new IntersectionObserver(entries => {
if (Date.now() > this.lastTransaction - 50 && entries.length > 0 && entries[entries.length - 1].intersectionRatio < 1) this.measureSoon();
}, {
threshold: [1]
}) : null;
this.observeIntersection();
view.win.addEventListener("resize", this.measureSoon = this.measureSoon.bind(this));
this.maybeMeasure();
}
createContainer() {
if (this.parent) {
this.container = document.createElement("div");
this.container.style.position = "relative";
this.container.className = this.view.themeClasses;
this.parent.appendChild(this.container);
} else this.container = this.view.dom;
}
observeIntersection() {
if (this.intersectionObserver) {
this.intersectionObserver.disconnect();
for (let tooltip of this.manager.tooltipViews) this.intersectionObserver.observe(tooltip.dom);
}
}
measureSoon() {
if (this.measureTimeout < 0) this.measureTimeout = setTimeout(() => {
this.measureTimeout = -1;
this.maybeMeasure();
}, 50);
}
update(update) {
if (update.transactions.length) this.lastTransaction = Date.now();
let updated = this.manager.update(update, this.above);
if (updated) this.observeIntersection();
let shouldMeasure = updated || update.geometryChanged;
let newConfig = update.state.facet(tooltipConfig);
if (newConfig.position != this.position && !this.madeAbsolute) {
this.position = newConfig.position;
for (let t$1 of this.manager.tooltipViews) t$1.dom.style.position = this.position;
shouldMeasure = true;
}
if (newConfig.parent != this.parent) {
if (this.parent) this.container.remove();
this.parent = newConfig.parent;
this.createContainer();
for (let t$1 of this.manager.tooltipViews) this.container.appendChild(t$1.dom);
shouldMeasure = true;
} else if (this.parent && this.view.themeClasses != this.classes) this.classes = this.container.className = this.view.themeClasses;
if (shouldMeasure) this.maybeMeasure();
}
createTooltip(tooltip, prev) {
let tooltipView = tooltip.create(this.view);
let before = prev ? prev.dom : null;
tooltipView.dom.classList.add("cm-tooltip");
if (tooltip.arrow && !tooltipView.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")) {
let arrow = document.createElement("div");
arrow.className = "cm-tooltip-arrow";
tooltipView.dom.appendChild(arrow);
}
tooltipView.dom.style.position = this.position;
tooltipView.dom.style.top = Outside;
tooltipView.dom.style.left = "0px";
this.container.insertBefore(tooltipView.dom, before);
if (tooltipView.mount) tooltipView.mount(this.view);
if (this.resizeObserver) this.resizeObserver.observe(tooltipView.dom);
return tooltipView;
}
destroy() {
var _a$2, _b, _c;
this.view.win.removeEventListener("resize", this.measureSoon);
for (let tooltipView of this.manager.tooltipViews) {
tooltipView.dom.remove();
(_a$2 = tooltipView.destroy) === null || _a$2 === void 0 || _a$2.call(tooltipView);
}
if (this.parent) this.container.remove();
(_b = this.resizeObserver) === null || _b === void 0 || _b.disconnect();
(_c = this.intersectionObserver) === null || _c === void 0 || _c.disconnect();
clearTimeout(this.measureTimeout);
}
readMeasure() {
let editor = this.view.dom.getBoundingClientRect();
let scaleX = 1,
scaleY = 1,
makeAbsolute = false;
if (this.position == "fixed" && this.manager.tooltipViews.length) {
let {
dom
} = this.manager.tooltipViews[0];
if (browser$1.gecko) makeAbsolute = dom.offsetParent != this.container.ownerDocument.body;else if (dom.style.top == Outside && dom.style.left == "0px") {
let rect = dom.getBoundingClientRect();
makeAbsolute = Math.abs(rect.top + 1e4) > 1 || Math.abs(rect.left) > 1;
}
}
if (makeAbsolute || this.position == "absolute") if (this.parent) {
let rect = this.parent.getBoundingClientRect();
if (rect.width && rect.height) {
scaleX = rect.width / this.parent.offsetWidth;
scaleY = rect.height / this.parent.offsetHeight;
}
} else ({
scaleX,
scaleY
} = this.view.viewState);
return {
editor,
parent: this.parent ? this.container.getBoundingClientRect() : editor,
pos: this.manager.tooltips.map((t$1, i$1) => {
let tv = this.manager.tooltipViews[i$1];
return tv.getCoords ? tv.getCoords(t$1.pos) : this.view.coordsAtPos(t$1.pos);
}),
size: this.manager.tooltipViews.map(({
dom
}) => dom.getBoundingClientRect()),
space: this.view.state.facet(tooltipConfig).tooltipSpace(this.view),
scaleX,
scaleY,
makeAbsolute
};
}
writeMeasure(measured) {
var _a$2;
if (measured.makeAbsolute) {
this.madeAbsolute = true;
this.position = "absolute";
for (let t$1 of this.manager.tooltipViews) t$1.dom.style.position = "absolute";
}
let {
editor,
space: space$1,
scaleX,
scaleY
} = measured;
let others = [];
for (let i$1 = 0; i$1 < this.manager.tooltips.length; i$1++) {
let tooltip = this.manager.tooltips[i$1],
tView = this.manager.tooltipViews[i$1],
{
dom
} = tView;
let pos = measured.pos[i$1],
size = measured.size[i$1];
if (!pos || pos.bottom <= Math.max(editor.top, space$1.top) || pos.top >= Math.min(editor.bottom, space$1.bottom) || pos.right < Math.max(editor.left, space$1.left) - .1 || pos.left > Math.min(editor.right, space$1.right) + .1) {
dom.style.top = Outside;
continue;
}
let arrow = tooltip.arrow ? tView.dom.querySelector(".cm-tooltip-arrow") : null;
let arrowHeight = arrow ? 7 : 0;
let width = size.right - size.left,
height = (_a$2 = knownHeight.get(tView)) !== null && _a$2 !== void 0 ? _a$2 : size.bottom - size.top;
let offset = tView.offset || noOffset,
ltr = this.view.textDirection == Direction$1.LTR;
let left = size.width > space$1.right - space$1.left ? ltr ? space$1.left : space$1.right - size.width : ltr ? Math.min(pos.left - (arrow ? 14 : 0) + offset.x, space$1.right - width) : Math.max(space$1.left, pos.left - width + (arrow ? 14 : 0) - offset.x);
let above = this.above[i$1];
if (!tooltip.strictSide && (above ? pos.top - (size.bottom - size.top) - offset.y < space$1.top : pos.bottom + (size.bottom - size.top) + offset.y > space$1.bottom) && above == space$1.bottom - pos.bottom > pos.top - space$1.top) above = this.above[i$1] = !above;
let spaceVert = (above ? pos.top - space$1.top : space$1.bottom - pos.bottom) - arrowHeight;
if (spaceVert < height && tView.resize !== false) {
if (spaceVert < this.view.defaultLineHeight) {
dom.style.top = Outside;
continue;
}
knownHeight.set(tView, height);
dom.style.height = (height = spaceVert) / scaleY + "px";
} else if (dom.style.height) dom.style.height = "";
let top$1 = above ? pos.top - height - arrowHeight - offset.y : pos.bottom + arrowHeight + offset.y;
let right = left + width;
if (tView.overlap !== true) {
for (let r of others) if (r.left < right && r.right > left && r.top < top$1 + height && r.bottom > top$1) top$1 = above ? r.top - height - 2 - arrowHeight : r.bottom + arrowHeight + 2;
}
if (this.position == "absolute") {
dom.style.top = (top$1 - measured.parent.top) / scaleY + "px";
dom.style.left = (left - measured.parent.left) / scaleX + "px";
} else {
dom.style.top = top$1 / scaleY + "px";
dom.style.left = left / scaleX + "px";
}
if (arrow) {
let arrowLeft = pos.left + (ltr ? offset.x : -offset.x) - (left + 14 - 7);
arrow.style.left = arrowLeft / scaleX + "px";
}
if (tView.overlap !== true) others.push({
left,
top: top$1,
right,
bottom: top$1 + height
});
dom.classList.toggle("cm-tooltip-above", above);
dom.classList.toggle("cm-tooltip-below", !above);
if (tView.positioned) tView.positioned(measured.space);
}
}
maybeMeasure() {
if (this.manager.tooltips.length) {
if (this.view.inView) this.view.requestMeasure(this.measureReq);
if (this.inView != this.view.inView) {
this.inView = this.view.inView;
if (!this.inView) for (let tv of this.manager.tooltipViews) tv.dom.style.top = Outside;
}
}
}
}, {
eventObservers: {
scroll() {
this.maybeMeasure();
}
}
});
baseTheme$4 = /* @__PURE__ */EditorView.baseTheme({
".cm-tooltip": {
zIndex: 100,
boxSizing: "border-box"
},
"&light .cm-tooltip": {
border: "1px solid #bbb",
backgroundColor: "#f5f5f5"
},
"&light .cm-tooltip-section:not(:first-child)": {
borderTop: "1px solid #bbb"
},
"&dark .cm-tooltip": {
backgroundColor: "#333338",
color: "white"
},
".cm-tooltip-arrow": {
height: `7px`,
width: `14px`,
position: "absolute",
zIndex: -1,
overflow: "hidden",
"&:before, &:after": {
content: "''",
position: "absolute",
width: 0,
height: 0,
borderLeft: `7px solid transparent`,
borderRight: `7px solid transparent`
},
".cm-tooltip-above &": {
bottom: `-7px`,
"&:before": {
borderTop: `7px solid #bbb`
},
"&:after": {
borderTop: `7px solid #f5f5f5`,
bottom: "1px"
}
},
".cm-tooltip-below &": {
top: `-7px`,
"&:before": {
borderBottom: `7px solid #bbb`
},
"&:after": {
borderBottom: `7px solid #f5f5f5`,
top: "1px"
}
}
},
"&dark .cm-tooltip .cm-tooltip-arrow": {
"&:before": {
borderTopColor: "#333338",
borderBottomColor: "#333338"
},
"&:after": {
borderTopColor: "transparent",
borderBottomColor: "transparent"
}
}
});
noOffset = {
x: 0,
y: 0
};
/**
Facet to which an extension can add a value to show a tooltip.
*/
_export("zt", showTooltip = /* @__PURE__ */Facet$1.define({
enables: [tooltipPlugin, baseTheme$4]
}));
showHoverTooltip = /* @__PURE__ */Facet$1.define({
combine: inputs => inputs.reduce((a, i$1) => a.concat(i$1), [])
});
HoverTooltipHost = class HoverTooltipHost {
static create(view) {
return new HoverTooltipHost(view);
}
constructor(view) {
this.view = view;
this.mounted = false;
this.dom = document.createElement("div");
this.dom.classList.add("cm-tooltip-hover");
this.manager = new TooltipViewManager(view, showHoverTooltip, (t$1, p) => this.createHostedView(t$1, p), t$1 => t$1.dom.remove());
}
createHostedView(tooltip, prev) {
let hostedView = tooltip.create(this.view);
hostedView.dom.classList.add("cm-tooltip-section");
this.dom.insertBefore(hostedView.dom, prev ? prev.dom.nextSibling : this.dom.firstChild);
if (this.mounted && hostedView.mount) hostedView.mount(this.view);
return hostedView;
}
mount(view) {
for (let hostedView of this.manager.tooltipViews) if (hostedView.mount) hostedView.mount(view);
this.mounted = true;
}
positioned(space$1) {
for (let hostedView of this.manager.tooltipViews) if (hostedView.positioned) hostedView.positioned(space$1);
}
update(update) {
this.manager.update(update);
}
destroy() {
var _a$2;
for (let t$1 of this.manager.tooltipViews) (_a$2 = t$1.destroy) === null || _a$2 === void 0 || _a$2.call(t$1);
}
passProp(name$1) {
let value = void 0;
for (let view of this.manager.tooltipViews) {
let given = view[name$1];
if (given !== void 0) {
if (value === void 0) value = given;else if (value !== given) return void 0;
}
}
return value;
}
get offset() {
return this.passProp("offset");
}
get getCoords() {
return this.passProp("getCoords");
}
get overlap() {
return this.passProp("overlap");
}
get resize() {
return this.passProp("resize");
}
};
showHoverTooltipHost = /* @__PURE__ */showTooltip.compute([showHoverTooltip], state => {
let tooltips$1 = state.facet(showHoverTooltip);
if (tooltips$1.length === 0) return null;
return {
pos: Math.min(...tooltips$1.map(t$1 => t$1.pos)),
end: Math.max(...tooltips$1.map(t$1 => {
var _a$2;
return (_a$2 = t$1.end) !== null && _a$2 !== void 0 ? _a$2 : t$1.pos;
})),
create: HoverTooltipHost.create,
above: tooltips$1[0].above,
arrow: tooltips$1.some(t$1 => t$1.arrow)
};
});
HoverPlugin = class {
constructor(view, source, field, setHover, hoverTime) {
this.view = view;
this.source = source;
this.field = field;
this.setHover = setHover;
this.hoverTime = hoverTime;
this.hoverTimeout = -1;
this.restartTimeout = -1;
this.pending = null;
this.lastMove = {
x: 0,
y: 0,
target: view.dom,
time: 0
};
this.checkHover = this.checkHover.bind(this);
view.dom.addEventListener("mouseleave", this.mouseleave = this.mouseleave.bind(this));
view.dom.addEventListener("mousemove", this.mousemove = this.mousemove.bind(this));
}
update() {
if (this.pending) {
this.pending = null;
clearTimeout(this.restartTimeout);
this.restartTimeout = setTimeout(() => this.startHover(), 20);
}
}
get active() {
return this.view.state.field(this.field);
}
checkHover() {
this.hoverTimeout = -1;
if (this.active.length) return;
let hovered = Date.now() - this.lastMove.time;
if (hovered < this.hoverTime) this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime - hovered);else this.startHover();
}
startHover() {
clearTimeout(this.restartTimeout);
let {
view,
lastMove
} = this;
let desc = view.docView.nearest(lastMove.target);
if (!desc) return;
let pos,
side = 1;
if (desc instanceof WidgetView$1) pos = desc.posAtStart;else {
pos = view.posAtCoords(lastMove);
if (pos == null) return;
let posCoords = view.coordsAtPos(pos);
if (!posCoords || lastMove.y < posCoords.top || lastMove.y > posCoords.bottom || lastMove.x < posCoords.left - view.defaultCharacterWidth || lastMove.x > posCoords.right + view.defaultCharacterWidth) return;
let bidi = view.bidiSpans(view.state.doc.lineAt(pos)).find(s => s.from <= pos && s.to >= pos);
let rtl = bidi && bidi.dir == Direction$1.RTL ? -1 : 1;
side = lastMove.x < posCoords.left ? -rtl : rtl;
}
let open = this.source(view, pos, side);
if (open === null || open === void 0 ? void 0 : open.then) {
let pending = this.pending = {
pos
};
open.then(result => {
if (this.pending == pending) {
this.pending = null;
if (result && !(Array.isArray(result) && !result.length)) view.dispatch({
effects: this.setHover.of(Array.isArray(result) ? result : [result])
});
}
}, e => logException$1(view.state, e, "hover tooltip"));
} else if (open && !(Array.isArray(open) && !open.length)) view.dispatch({
effects: this.setHover.of(Array.isArray(open) ? open : [open])
});
}
get tooltip() {
let plugin = this.view.plugin(tooltipPlugin);
let index = plugin ? plugin.manager.tooltips.findIndex(t$1 => t$1.create == HoverTooltipHost.create) : -1;
return index > -1 ? plugin.manager.tooltipViews[index] : null;
}
mousemove(event) {
var _a$2, _b;
this.lastMove = {
x: event.clientX,
y: event.clientY,
target: event.target,
time: Date.now()
};
if (this.hoverTimeout < 0) this.hoverTimeout = setTimeout(this.checkHover, this.hoverTime);
let {
active,
tooltip
} = this;
if (active.length && tooltip && !isInTooltip(tooltip.dom, event) || this.pending) {
let {
pos
} = active[0] || this.pending,
end = (_b = (_a$2 = active[0]) === null || _a$2 === void 0 ? void 0 : _a$2.end) !== null && _b !== void 0 ? _b : pos;
if (pos == end ? this.view.posAtCoords(this.lastMove) != pos : !isOverRange(this.view, pos, end, event.clientX, event.clientY)) {
this.view.dispatch({
effects: this.setHover.of([])
});
this.pending = null;
}
}
}
mouseleave(event) {
clearTimeout(this.hoverTimeout);
this.hoverTimeout = -1;
let {
active
} = this;
if (active.length) {
let {
tooltip
} = this;
if (!(tooltip && tooltip.dom.contains(event.relatedTarget))) this.view.dispatch({
effects: this.setHover.of([])
});else this.watchTooltipLeave(tooltip.dom);
}
}
watchTooltipLeave(tooltip) {
let watch$1 = event => {
tooltip.removeEventListener("mouseleave", watch$1);
if (this.active.length && !this.view.dom.contains(event.relatedTarget)) this.view.dispatch({
effects: this.setHover.of([])
});
};
tooltip.addEventListener("mouseleave", watch$1);
}
destroy() {
clearTimeout(this.hoverTimeout);
this.view.dom.removeEventListener("mouseleave", this.mouseleave);
this.view.dom.removeEventListener("mousemove", this.mousemove);
}
};
tooltipMargin = 4;
closeHoverTooltipEffect = /* @__PURE__ */StateEffect$1.define();
panelConfig = /* @__PURE__ */Facet$1.define({
combine(configs) {
let topContainer, bottomContainer;
for (let c of configs) {
topContainer = topContainer || c.topContainer;
bottomContainer = bottomContainer || c.bottomContainer;
}
return {
topContainer,
bottomContainer
};
}
});
panelPlugin = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.input = view.state.facet(showPanel);
this.specs = this.input.filter(s => s);
this.panels = this.specs.map(spec => spec(view));
let conf = view.state.facet(panelConfig);
this.top = new PanelGroup(view, true, conf.topContainer);
this.bottom = new PanelGroup(view, false, conf.bottomContainer);
this.top.sync(this.panels.filter(p => p.top));
this.bottom.sync(this.panels.filter(p => !p.top));
for (let p of this.panels) {
p.dom.classList.add("cm-panel");
if (p.mount) p.mount();
}
}
update(update) {
let conf = update.state.facet(panelConfig);
if (this.top.container != conf.topContainer) {
this.top.sync([]);
this.top = new PanelGroup(update.view, true, conf.topContainer);
}
if (this.bottom.container != conf.bottomContainer) {
this.bottom.sync([]);
this.bottom = new PanelGroup(update.view, false, conf.bottomContainer);
}
this.top.syncClasses();
this.bottom.syncClasses();
let input = update.state.facet(showPanel);
if (input != this.input) {
let specs = input.filter(x => x);
let panels = [],
top$1 = [],
bottom = [],
mount = [];
for (let spec of specs) {
let known = this.specs.indexOf(spec),
panel;
if (known < 0) {
panel = spec(update.view);
mount.push(panel);
} else {
panel = this.panels[known];
if (panel.update) panel.update(update);
}
panels.push(panel);
(panel.top ? top$1 : bottom).push(panel);
}
this.specs = specs;
this.panels = panels;
this.top.sync(top$1);
this.bottom.sync(bottom);
for (let p of mount) {
p.dom.classList.add("cm-panel");
if (p.mount) p.mount();
}
} else for (let p of this.panels) if (p.update) p.update(update);
}
destroy() {
this.top.sync([]);
this.bottom.sync([]);
}
}, {
provide: plugin => EditorView.scrollMargins.of(view => {
let value = view.plugin(plugin);
return value && {
top: value.top.scrollMargin(),
bottom: value.bottom.scrollMargin()
};
})
});
PanelGroup = class {
constructor(view, top$1, container$1) {
this.view = view;
this.top = top$1;
this.container = container$1;
this.dom = void 0;
this.classes = "";
this.panels = [];
this.syncClasses();
}
sync(panels) {
for (let p of this.panels) if (p.destroy && panels.indexOf(p) < 0) p.destroy();
this.panels = panels;
this.syncDOM();
}
syncDOM() {
if (this.panels.length == 0) {
if (this.dom) {
this.dom.remove();
this.dom = void 0;
}
return;
}
if (!this.dom) {
this.dom = document.createElement("div");
this.dom.className = this.top ? "cm-panels cm-panels-top" : "cm-panels cm-panels-bottom";
this.dom.style[this.top ? "top" : "bottom"] = "0";
let parent = this.container || this.view.dom;
parent.insertBefore(this.dom, this.top ? parent.firstChild : null);
}
let curDOM = this.dom.firstChild;
for (let panel of this.panels) if (panel.dom.parentNode == this.dom) {
while (curDOM != panel.dom) curDOM = rm(curDOM);
curDOM = curDOM.nextSibling;
} else this.dom.insertBefore(panel.dom, curDOM);
while (curDOM) curDOM = rm(curDOM);
}
scrollMargin() {
return !this.dom || this.container ? 0 : Math.max(0, this.top ? this.dom.getBoundingClientRect().bottom - Math.max(0, this.view.scrollDOM.getBoundingClientRect().top) : Math.min(innerHeight, this.view.scrollDOM.getBoundingClientRect().bottom) - this.dom.getBoundingClientRect().top);
}
syncClasses() {
if (!this.container || this.classes == this.view.themeClasses) return;
for (let cls of this.classes.split(" ")) if (cls) this.container.classList.remove(cls);
for (let cls of (this.classes = this.view.themeClasses).split(" ")) if (cls) this.container.classList.add(cls);
}
};
showPanel = /* @__PURE__ */Facet$1.define({
enables: panelPlugin
});
/**
A gutter marker represents a bit of information attached to a line
in a specific gutter. Your own custom markers have to extend this
class.
*/
GutterMarker$1 = class extends RangeValue {
/**
@internal
*/
compare(other) {
return this == other || this.constructor == other.constructor && this.eq(other);
}
/**
Compare this marker to another marker of the same type.
*/
eq(other) {
return false;
}
/**
Called if the marker has a `toDOM` method and its representation
was removed from a gutter.
*/
destroy(dom) {}
};
GutterMarker$1.prototype.elementClass = "";
GutterMarker$1.prototype.toDOM = void 0;
GutterMarker$1.prototype.mapMode = MapMode.TrackBefore;
GutterMarker$1.prototype.startSide = GutterMarker$1.prototype.endSide = -1;
GutterMarker$1.prototype.point = true;
/**
Facet used to add a class to all gutter elements for a given line.
Markers given to this facet should _only_ define an
[`elementclass`](https://codemirror.net/6/docs/ref/#view.GutterMarker.elementClass), not a
[`toDOM`](https://codemirror.net/6/docs/ref/#view.GutterMarker.toDOM) (or the marker will appear
in all gutters for the line).
*/
gutterLineClass = /* @__PURE__ */Facet$1.define();
defaults$1 = {
class: "",
renderEmptyElements: false,
elementStyle: "",
markers: () => RangeSet$1.empty,
lineMarker: () => null,
widgetMarker: () => null,
lineMarkerChange: null,
initialSpacer: null,
updateSpacer: null,
domEventHandlers: {}
};
activeGutters = /* @__PURE__ */Facet$1.define();
unfixGutters = /* @__PURE__ */Facet$1.define({
combine: values => values.some(x => x)
});
gutterView = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.view = view;
this.prevViewport = view.viewport;
this.dom = document.createElement("div");
this.dom.className = "cm-gutters";
this.dom.setAttribute("aria-hidden", "true");
this.dom.style.minHeight = this.view.contentHeight / this.view.scaleY + "px";
this.gutters = view.state.facet(activeGutters).map(conf => new SingleGutterView(view, conf));
for (let gutter$2 of this.gutters) this.dom.appendChild(gutter$2.dom);
this.fixed = !view.state.facet(unfixGutters);
if (this.fixed) this.dom.style.position = "sticky";
this.syncGutters(false);
view.scrollDOM.insertBefore(this.dom, view.contentDOM);
}
update(update) {
if (this.updateGutters(update)) {
let vpA = this.prevViewport,
vpB = update.view.viewport;
let vpOverlap = Math.min(vpA.to, vpB.to) - Math.max(vpA.from, vpB.from);
this.syncGutters(vpOverlap < (vpB.to - vpB.from) * .8);
}
if (update.geometryChanged) this.dom.style.minHeight = this.view.contentHeight / this.view.scaleY + "px";
if (this.view.state.facet(unfixGutters) != !this.fixed) {
this.fixed = !this.fixed;
this.dom.style.position = this.fixed ? "sticky" : "";
}
this.prevViewport = update.view.viewport;
}
syncGutters(detach) {
let after = this.dom.nextSibling;
if (detach) this.dom.remove();
let lineClasses = RangeSet$1.iter(this.view.state.facet(gutterLineClass), this.view.viewport.from);
let classSet = [];
let contexts = this.gutters.map(gutter$2 => new UpdateContext(gutter$2, this.view.viewport, -this.view.documentPadding.top));
for (let line of this.view.viewportLineBlocks) {
if (classSet.length) classSet = [];
if (Array.isArray(line.type)) {
let first = true;
for (let b of line.type) if (b.type == BlockType$1.Text && first) {
advanceCursor(lineClasses, classSet, b.from);
for (let cx of contexts) cx.line(this.view, b, classSet);
first = false;
} else if (b.widget) for (let cx of contexts) cx.widget(this.view, b);
} else if (line.type == BlockType$1.Text) {
advanceCursor(lineClasses, classSet, line.from);
for (let cx of contexts) cx.line(this.view, line, classSet);
} else if (line.widget) for (let cx of contexts) cx.widget(this.view, line);
}
for (let cx of contexts) cx.finish();
if (detach) this.view.scrollDOM.insertBefore(this.dom, after);
}
updateGutters(update) {
let prev = update.startState.facet(activeGutters),
cur$1 = update.state.facet(activeGutters);
let change = update.docChanged || update.heightChanged || update.viewportChanged || !RangeSet$1.eq(update.startState.facet(gutterLineClass), update.state.facet(gutterLineClass), update.view.viewport.from, update.view.viewport.to);
if (prev == cur$1) {
for (let gutter$2 of this.gutters) if (gutter$2.update(update)) change = true;
} else {
change = true;
let gutters$1 = [];
for (let conf of cur$1) {
let known = prev.indexOf(conf);
if (known < 0) gutters$1.push(new SingleGutterView(this.view, conf));else {
this.gutters[known].update(update);
gutters$1.push(this.gutters[known]);
}
}
for (let g of this.gutters) {
g.dom.remove();
if (gutters$1.indexOf(g) < 0) g.destroy();
}
for (let g of gutters$1) this.dom.appendChild(g.dom);
this.gutters = gutters$1;
}
return change;
}
destroy() {
for (let view of this.gutters) view.destroy();
this.dom.remove();
}
}, {
provide: plugin => EditorView.scrollMargins.of(view => {
let value = view.plugin(plugin);
if (!value || value.gutters.length == 0 || !value.fixed) return null;
return view.textDirection == Direction$1.LTR ? {
left: value.dom.offsetWidth * view.scaleX
} : {
right: value.dom.offsetWidth * view.scaleX
};
})
});
UpdateContext = class {
constructor(gutter$2, viewport, height) {
this.gutter = gutter$2;
this.height = height;
this.i = 0;
this.cursor = RangeSet$1.iter(gutter$2.markers, viewport.from);
}
addElement(view, block, markers) {
let {
gutter: gutter$2
} = this,
above = (block.top - this.height) / view.scaleY,
height = block.height / view.scaleY;
if (this.i == gutter$2.elements.length) {
let newElt = new GutterElement(view, height, above, markers);
gutter$2.elements.push(newElt);
gutter$2.dom.appendChild(newElt.dom);
} else gutter$2.elements[this.i].update(view, height, above, markers);
this.height = block.bottom;
this.i++;
}
line(view, line, extraMarkers) {
let localMarkers = [];
advanceCursor(this.cursor, localMarkers, line.from);
if (extraMarkers.length) localMarkers = localMarkers.concat(extraMarkers);
let forLine = this.gutter.config.lineMarker(view, line, localMarkers);
if (forLine) localMarkers.unshift(forLine);
let gutter$2 = this.gutter;
if (localMarkers.length == 0 && !gutter$2.config.renderEmptyElements) return;
this.addElement(view, line, localMarkers);
}
widget(view, block) {
let marker = this.gutter.config.widgetMarker(view, block.widget, block);
if (marker) this.addElement(view, block, [marker]);
}
finish() {
let gutter$2 = this.gutter;
while (gutter$2.elements.length > this.i) {
let last = gutter$2.elements.pop();
gutter$2.dom.removeChild(last.dom);
last.destroy();
}
}
};
SingleGutterView = class {
constructor(view, config$1) {
this.view = view;
this.config = config$1;
this.elements = [];
this.spacer = null;
this.dom = document.createElement("div");
this.dom.className = "cm-gutter" + (this.config.class ? " " + this.config.class : "");
for (let prop in config$1.domEventHandlers) this.dom.addEventListener(prop, event => {
let target = event.target,
y;
if (target != this.dom && this.dom.contains(target)) {
while (target.parentNode != this.dom) target = target.parentNode;
let rect = target.getBoundingClientRect();
y = (rect.top + rect.bottom) / 2;
} else y = event.clientY;
let line = view.lineBlockAtHeight(y - view.documentTop);
if (config$1.domEventHandlers[prop](view, line, event)) event.preventDefault();
});
this.markers = asArray$1(config$1.markers(view));
if (config$1.initialSpacer) {
this.spacer = new GutterElement(view, 0, 0, [config$1.initialSpacer(view)]);
this.dom.appendChild(this.spacer.dom);
this.spacer.dom.style.cssText += "visibility: hidden; pointer-events: none";
}
}
update(update) {
let prevMarkers = this.markers;
this.markers = asArray$1(this.config.markers(update.view));
if (this.spacer && this.config.updateSpacer) {
let updated = this.config.updateSpacer(this.spacer.markers[0], update);
if (updated != this.spacer.markers[0]) this.spacer.update(update.view, 0, 0, [updated]);
}
let vp = update.view.viewport;
return !RangeSet$1.eq(this.markers, prevMarkers, vp.from, vp.to) || (this.config.lineMarkerChange ? this.config.lineMarkerChange(update) : false);
}
destroy() {
for (let elt of this.elements) elt.destroy();
}
};
GutterElement = class {
constructor(view, height, above, markers) {
this.height = -1;
this.above = 0;
this.markers = [];
this.dom = document.createElement("div");
this.dom.className = "cm-gutterElement";
this.update(view, height, above, markers);
}
update(view, height, above, markers) {
if (this.height != height) {
this.height = height;
this.dom.style.height = height + "px";
}
if (this.above != above) this.dom.style.marginTop = (this.above = above) ? above + "px" : "";
if (!sameMarkers(this.markers, markers)) this.setMarkers(view, markers);
}
setMarkers(view, markers) {
let cls = "cm-gutterElement",
domPos = this.dom.firstChild;
for (let iNew = 0, iOld = 0;;) {
let skipTo = iOld,
marker = iNew < markers.length ? markers[iNew++] : null,
matched = false;
if (marker) {
let c = marker.elementClass;
if (c) cls += " " + c;
for (let i$1 = iOld; i$1 < this.markers.length; i$1++) if (this.markers[i$1].compare(marker)) {
skipTo = i$1;
matched = true;
break;
}
} else skipTo = this.markers.length;
while (iOld < skipTo) {
let next = this.markers[iOld++];
if (next.toDOM) {
next.destroy(domPos);
let after = domPos.nextSibling;
domPos.remove();
domPos = after;
}
}
if (!marker) break;
if (marker.toDOM) if (matched) domPos = domPos.nextSibling;else this.dom.insertBefore(marker.toDOM(view), domPos);
if (matched) iOld++;
}
this.dom.className = cls;
this.markers = markers;
}
destroy() {
this.setMarkers(null, []);
}
};
lineNumberMarkers = /* @__PURE__ */Facet$1.define();
lineNumberConfig = /* @__PURE__ */Facet$1.define({
combine(values) {
return combineConfig$1(values, {
formatNumber: String,
domEventHandlers: {}
}, {
domEventHandlers(a, b) {
let result = Object.assign({}, a);
for (let event in b) {
let exists = result[event],
add$1 = b[event];
result[event] = exists ? (view, line, event$1) => exists(view, line, event$1) || add$1(view, line, event$1) : add$1;
}
return result;
}
});
}
});
NumberMarker = class extends GutterMarker$1 {
constructor(number$1) {
super();
this.number = number$1;
}
eq(other) {
return this.number == other.number;
}
toDOM() {
return document.createTextNode(this.number);
}
};
lineNumberGutter = /* @__PURE__ */activeGutters.compute([lineNumberConfig], state => ({
class: "cm-lineNumbers",
renderEmptyElements: false,
markers(view) {
return view.state.facet(lineNumberMarkers);
},
lineMarker(view, line, others) {
if (others.some(m => m.toDOM)) return null;
return new NumberMarker(formatNumber(view, view.state.doc.lineAt(line.from).number));
},
widgetMarker: () => null,
lineMarkerChange: update => update.startState.facet(lineNumberConfig) != update.state.facet(lineNumberConfig),
initialSpacer(view) {
return new NumberMarker(formatNumber(view, maxLineNumber(view.state.doc.lines)));
},
updateSpacer(spacer, update) {
let max = formatNumber(update.view, maxLineNumber(update.view.state.doc.lines));
return max == spacer.number ? spacer : new NumberMarker(max);
},
domEventHandlers: state.facet(lineNumberConfig).domEventHandlers
}));
activeLineGutterMarker = /* @__PURE__ */new class extends GutterMarker$1 {
constructor() {
super(...arguments);
this.elementClass = "cm-activeLineGutter";
}
}();
activeLineGutterHighlighter = /* @__PURE__ */gutterLineClass.compute(["selection"], state => {
let marks$1 = [],
last = -1;
for (let range of state.selection.ranges) {
let linePos = state.doc.lineAt(range.head).from;
if (linePos > last) {
last = linePos;
marks$1.push(activeLineGutterMarker.range(linePos));
}
}
return RangeSet$1.of(marks$1);
});
DefaultBufferLength = 1024;
nextPropID = 0;
Range$1 = class {
constructor(from, to) {
this.from = from;
this.to = to;
}
};
/**
Each [node type](#common.NodeType) or [individual tree](#common.Tree)
can have metadata associated with it in props. Instances of this
class represent prop names.
*/
NodeProp = class {
/**
Create a new node prop type.
*/
constructor(config$1 = {}) {
this.id = nextPropID++;
this.perNode = !!config$1.perNode;
this.deserialize = config$1.deserialize || (() => {
throw new Error("This node type doesn't define a deserialize function");
});
}
/**
This is meant to be used with
[`NodeSet.extend`](#common.NodeSet.extend) or
[`LRParser.configure`](#lr.ParserConfig.props) to compute
prop values for each node type in the set. Takes a [match
object](#common.NodeType^match) or function that returns undefined
if the node type doesn't get this prop, and the prop's value if
it does.
*/
add(match) {
if (this.perNode) throw new RangeError("Can't add per-node props to node types");
if (typeof match != "function") match = NodeType.match(match);
return type => {
let result = match(type);
return result === void 0 ? null : [this, result];
};
}
};
/**
Prop that is used to describe matching delimiters. For opening
delimiters, this holds an array of node names (written as a
space-separated string when declaring this prop in a grammar)
for the node types of closing delimiters that match it.
*/
NodeProp.closedBy = new NodeProp({
deserialize: str => str.split(" ")
});
/**
The inverse of [`closedBy`](#common.NodeProp^closedBy). This is
attached to closing delimiters, holding an array of node names
of types of matching opening delimiters.
*/
NodeProp.openedBy = new NodeProp({
deserialize: str => str.split(" ")
});
/**
Used to assign node types to groups (for example, all node
types that represent an expression could be tagged with an
`"Expression"` group).
*/
NodeProp.group = new NodeProp({
deserialize: str => str.split(" ")
});
/**
Attached to nodes to indicate these should be
[displayed](https://codemirror.net/docs/ref/#language.syntaxTree)
in a bidirectional text isolate, so that direction-neutral
characters on their sides don't incorrectly get associated with
surrounding text. You'll generally want to set this for nodes
that contain arbitrary text, like strings and comments, and for
nodes that appear _inside_ arbitrary text, like HTML tags. When
not given a value, in a grammar declaration, defaults to
`"auto"`.
*/
NodeProp.isolate = new NodeProp({
deserialize: value => {
if (value && value != "rtl" && value != "ltr" && value != "auto") throw new RangeError("Invalid value for isolate: " + value);
return value || "auto";
}
});
/**
The hash of the [context](#lr.ContextTracker.constructor)
that the node was parsed in, if any. Used to limit reuse of
contextual nodes.
*/
NodeProp.contextHash = new NodeProp({
perNode: true
});
/**
The distance beyond the end of the node that the tokenizer
looked ahead for any of the tokens inside the node. (The LR
parser only stores this when it is larger than 25, for
efficiency reasons.)
*/
NodeProp.lookAhead = new NodeProp({
perNode: true
});
/**
This per-node prop is used to replace a given node, or part of a
node, with another tree. This is useful to include trees from
different languages in mixed-language parsers.
*/
NodeProp.mounted = new NodeProp({
perNode: true
});
/**
A mounted tree, which can be [stored](#common.NodeProp^mounted) on
a tree node to indicate that parts of its content are
represented by another tree.
*/
MountedTree = class {
constructor(tree, overlay, parser$3) {
this.tree = tree;
this.overlay = overlay;
this.parser = parser$3;
}
/**
@internal
*/
static get(tree) {
return tree && tree.props && tree.props[NodeProp.mounted.id];
}
};
noProps = Object.create(null);
/**
Each node in a syntax tree has a node type associated with it.
*/
NodeType = class NodeType {
/**
@internal
*/
constructor(name$1, props, id$1, flags = 0) {
this.name = name$1;
this.props = props;
this.id = id$1;
this.flags = flags;
}
/**
Define a node type.
*/
static define(spec) {
let props = spec.props && spec.props.length ? Object.create(null) : noProps;
let flags = (spec.top ? 1 : 0) | (spec.skipped ? 2 : 0) | (spec.error ? 4 : 0) | (spec.name == null ? 8 : 0);
let type = new NodeType(spec.name || "", props, spec.id, flags);
if (spec.props) for (let src of spec.props) {
if (!Array.isArray(src)) src = src(type);
if (src) {
if (src[0].perNode) throw new RangeError("Can't store a per-node prop on a node type");
props[src[0].id] = src[1];
}
}
return type;
}
/**
Retrieves a node prop for this type. Will return `undefined` if
the prop isn't present on this node.
*/
prop(prop) {
return this.props[prop.id];
}
/**
True when this is the top node of a grammar.
*/
get isTop() {
return (this.flags & 1) > 0;
}
/**
True when this node is produced by a skip rule.
*/
get isSkipped() {
return (this.flags & 2) > 0;
}
/**
Indicates whether this is an error node.
*/
get isError() {
return (this.flags & 4) > 0;
}
/**
When true, this node type doesn't correspond to a user-declared
named node, for example because it is used to cache repetition.
*/
get isAnonymous() {
return (this.flags & 8) > 0;
}
/**
Returns true when this node's name or one of its
[groups](#common.NodeProp^group) matches the given string.
*/
is(name$1) {
if (typeof name$1 == "string") {
if (this.name == name$1) return true;
let group = this.prop(NodeProp.group);
return group ? group.indexOf(name$1) > -1 : false;
}
return this.id == name$1;
}
/**
Create a function from node types to arbitrary values by
specifying an object whose property names are node or
[group](#common.NodeProp^group) names. Often useful with
[`NodeProp.add`](#common.NodeProp.add). You can put multiple
names, separated by spaces, in a single property name to map
multiple node names to a single value.
*/
static match(map) {
let direct = Object.create(null);
for (let prop in map) for (let name$1 of prop.split(" ")) direct[name$1] = map[prop];
return node => {
for (let groups = node.prop(NodeProp.group), i$1 = -1; i$1 < (groups ? groups.length : 0); i$1++) {
let found = direct[i$1 < 0 ? node.name : groups[i$1]];
if (found) return found;
}
};
}
};
/**
An empty dummy node type to use when no actual type is available.
*/
NodeType.none = new NodeType("", Object.create(null), 0, 8);
/**
A node set holds a collection of node types. It is used to
compactly represent trees by storing their type ids, rather than a
full pointer to the type object, in a numeric array. Each parser
[has](#lr.LRParser.nodeSet) a node set, and [tree
buffers](#common.TreeBuffer) can only store collections of nodes
from the same set. A set can have a maximum of 2**16 (65536) node
types in it, so that the ids fit into 16-bit typed array slots.
*/
NodeSet = class NodeSet {
/**
Create a set with the given types. The `id` property of each
type should correspond to its position within the array.
*/
constructor(types$2) {
this.types = types$2;
for (let i$1 = 0; i$1 < types$2.length; i$1++) if (types$2[i$1].id != i$1) throw new RangeError("Node type ids should correspond to array positions when creating a node set");
}
/**
Create a copy of this set with some node properties added. The
arguments to this method can be created with
[`NodeProp.add`](#common.NodeProp.add).
*/
extend(...props) {
let newTypes = [];
for (let type of this.types) {
let newProps = null;
for (let source of props) {
let add$1 = source(type);
if (add$1) {
if (!newProps) newProps = Object.assign({}, type.props);
newProps[add$1[0].id] = add$1[1];
}
}
newTypes.push(newProps ? new NodeType(type.name, newProps, type.id, type.flags) : type);
}
return new NodeSet(newTypes);
}
};
CachedNode = /* @__PURE__ */new WeakMap(), CachedInnerNode = /* @__PURE__ */new WeakMap();
/**
Options that control iteration. Can be combined with the `|`
operator to enable multiple ones.
*/
(function (IterMode$1) {
/**
When enabled, iteration will only visit [`Tree`](#common.Tree)
objects, not nodes packed into
[`TreeBuffer`](#common.TreeBuffer)s.
*/
IterMode$1[IterMode$1["ExcludeBuffers"] = 1] = "ExcludeBuffers";
/**
Enable this to make iteration include anonymous nodes (such as
the nodes that wrap repeated grammar constructs into a balanced
tree).
*/
IterMode$1[IterMode$1["IncludeAnonymous"] = 2] = "IncludeAnonymous";
/**
By default, regular [mounted](#common.NodeProp^mounted) nodes
replace their base node in iteration. Enable this to ignore them
instead.
*/
IterMode$1[IterMode$1["IgnoreMounts"] = 4] = "IgnoreMounts";
/**
This option only applies in
[`enter`](#common.SyntaxNode.enter)-style methods. It tells the
library to not enter mounted overlays if one covers the given
position.
*/
IterMode$1[IterMode$1["IgnoreOverlays"] = 8] = "IgnoreOverlays";
})(IterMode || _export("Tt", IterMode = {}));
/**
A piece of syntax tree. There are two ways to approach these
trees: the way they are actually stored in memory, and the
convenient way.
Syntax trees are stored as a tree of `Tree` and `TreeBuffer`
objects. By packing detail information into `TreeBuffer` leaf
nodes, the representation is made a lot more memory-efficient.
However, when you want to actually work with tree nodes, this
representation is very awkward, so most client code will want to
use the [`TreeCursor`](#common.TreeCursor) or
[`SyntaxNode`](#common.SyntaxNode) interface instead, which provides
a view on some part of this data structure, and can be used to
move around to adjacent nodes.
*/
Tree = class Tree {
/**
Construct a new tree. See also [`Tree.build`](#common.Tree^build).
*/
constructor(type, children, positions, length, props) {
this.type = type;
this.children = children;
this.positions = positions;
this.length = length;
/**
@internal
*/
this.props = null;
if (props && props.length) {
this.props = Object.create(null);
for (let [prop, value] of props) this.props[typeof prop == "number" ? prop : prop.id] = value;
}
}
/**
@internal
*/
toString() {
let mounted = MountedTree.get(this);
if (mounted && !mounted.overlay) return mounted.tree.toString();
let children = "";
for (let ch of this.children) {
let str = ch.toString();
if (str) {
if (children) children += ",";
children += str;
}
}
return !this.type.name ? children : (/\W/.test(this.type.name) && !this.type.isError ? JSON.stringify(this.type.name) : this.type.name) + (children.length ? "(" + children + ")" : "");
}
/**
Get a [tree cursor](#common.TreeCursor) positioned at the top of
the tree. Mode can be used to [control](#common.IterMode) which
nodes the cursor visits.
*/
cursor(mode = 0) {
return new TreeCursor(this.topNode, mode);
}
/**
Get a [tree cursor](#common.TreeCursor) pointing into this tree
at the given position and side (see
[`moveTo`](#common.TreeCursor.moveTo).
*/
cursorAt(pos, side = 0, mode = 0) {
let cursor = new TreeCursor(CachedNode.get(this) || this.topNode);
cursor.moveTo(pos, side);
CachedNode.set(this, cursor._tree);
return cursor;
}
/**
Get a [syntax node](#common.SyntaxNode) object for the top of the
tree.
*/
get topNode() {
return new TreeNode(this, 0, 0, null);
}
/**
Get the [syntax node](#common.SyntaxNode) at the given position.
If `side` is -1, this will move into nodes that end at the
position. If 1, it'll move into nodes that start at the
position. With 0, it'll only enter nodes that cover the position
from both sides.
Note that this will not enter
[overlays](#common.MountedTree.overlay), and you often want
[`resolveInner`](#common.Tree.resolveInner) instead.
*/
resolve(pos, side = 0) {
let node = resolveNode(CachedNode.get(this) || this.topNode, pos, side, false);
CachedNode.set(this, node);
return node;
}
/**
Like [`resolve`](#common.Tree.resolve), but will enter
[overlaid](#common.MountedTree.overlay) nodes, producing a syntax node
pointing into the innermost overlaid tree at the given position
(with parent links going through all parent structure, including
the host trees).
*/
resolveInner(pos, side = 0) {
let node = resolveNode(CachedInnerNode.get(this) || this.topNode, pos, side, true);
CachedInnerNode.set(this, node);
return node;
}
/**
In some situations, it can be useful to iterate through all
nodes around a position, including those in overlays that don't
directly cover the position. This method gives you an iterator
that will produce all nodes, from small to big, around the given
position.
*/
resolveStack(pos, side = 0) {
return stackIterator(this, pos, side);
}
/**
Iterate over the tree and its children, calling `enter` for any
node that touches the `from`/`to` region (if given) before
running over such a node's children, and `leave` (if given) when
leaving the node. When `enter` returns `false`, that node will
not have its children iterated over (or `leave` called).
*/
iterate(spec) {
let {
enter,
leave,
from = 0,
to = this.length
} = spec;
let mode = spec.mode || 0,
anon = (mode & IterMode.IncludeAnonymous) > 0;
for (let c = this.cursor(mode | IterMode.IncludeAnonymous);;) {
let entered = false;
if (c.from <= to && c.to >= from && (!anon && c.type.isAnonymous || enter(c) !== false)) {
if (c.firstChild()) continue;
entered = true;
}
for (;;) {
if (entered && leave && (anon || !c.type.isAnonymous)) leave(c);
if (c.nextSibling()) break;
if (!c.parent()) return;
entered = true;
}
}
}
/**
Get the value of the given [node prop](#common.NodeProp) for this
node. Works with both per-node and per-type props.
*/
prop(prop) {
return !prop.perNode ? this.type.prop(prop) : this.props ? this.props[prop.id] : void 0;
}
/**
Returns the node's [per-node props](#common.NodeProp.perNode) in a
format that can be passed to the [`Tree`](#common.Tree)
constructor.
*/
get propValues() {
let result = [];
if (this.props) for (let id$1 in this.props) result.push([+id$1, this.props[id$1]]);
return result;
}
/**
Balance the direct children of this tree, producing a copy of
which may have children grouped into subtrees with type
[`NodeType.none`](#common.NodeType^none).
*/
balance(config$1 = {}) {
return this.children.length <= 8 ? this : balanceRange(NodeType.none, this.children, this.positions, 0, this.children.length, 0, this.length, (children, positions, length) => new Tree(this.type, children, positions, length, this.propValues), config$1.makeTree || ((children, positions, length) => new Tree(NodeType.none, children, positions, length)));
}
/**
Build a tree from a postfix-ordered buffer of node information,
or a cursor over such a buffer.
*/
static build(data) {
return buildTree(data);
}
};
/**
The empty tree
*/
Tree.empty = new Tree(NodeType.none, [], [], 0);
FlatBufferCursor = class FlatBufferCursor {
constructor(buffer, index) {
this.buffer = buffer;
this.index = index;
}
get id() {
return this.buffer[this.index - 4];
}
get start() {
return this.buffer[this.index - 3];
}
get end() {
return this.buffer[this.index - 2];
}
get size() {
return this.buffer[this.index - 1];
}
get pos() {
return this.index;
}
next() {
this.index -= 4;
}
fork() {
return new FlatBufferCursor(this.buffer, this.index);
}
};
/**
Tree buffers contain (type, start, end, endIndex) quads for each
node. In such a buffer, nodes are stored in prefix order (parents
before children, with the endIndex of the parent indicating which
children belong to it).
*/
TreeBuffer = class TreeBuffer {
/**
Create a tree buffer.
*/
constructor(buffer, length, set) {
this.buffer = buffer;
this.length = length;
this.set = set;
}
/**
@internal
*/
get type() {
return NodeType.none;
}
/**
@internal
*/
toString() {
let result = [];
for (let index = 0; index < this.buffer.length;) {
result.push(this.childString(index));
index = this.buffer[index + 3];
}
return result.join(",");
}
/**
@internal
*/
childString(index) {
let id$1 = this.buffer[index],
endIndex = this.buffer[index + 3];
let type = this.set.types[id$1],
result = type.name;
if (/\W/.test(result) && !type.isError) result = JSON.stringify(result);
index += 4;
if (endIndex == index) return result;
let children = [];
while (index < endIndex) {
children.push(this.childString(index));
index = this.buffer[index + 3];
}
return result + "(" + children.join(",") + ")";
}
/**
@internal
*/
findChild(startIndex, endIndex, dir, pos, side) {
let {
buffer
} = this,
pick = -1;
for (let i$1 = startIndex; i$1 != endIndex; i$1 = buffer[i$1 + 3]) if (checkSide(side, pos, buffer[i$1 + 1], buffer[i$1 + 2])) {
pick = i$1;
if (dir > 0) break;
}
return pick;
}
/**
@internal
*/
slice(startI, endI, from) {
let b = this.buffer;
let copy = new Uint16Array(endI - startI),
len = 0;
for (let i$1 = startI, j = 0; i$1 < endI;) {
copy[j++] = b[i$1++];
copy[j++] = b[i$1++] - from;
let to = copy[j++] = b[i$1++] - from;
copy[j++] = b[i$1++] - startI;
len = Math.max(len, to);
}
return new TreeBuffer(copy, len, this.set);
}
};
BaseNode = class {
cursor(mode = 0) {
return new TreeCursor(this, mode);
}
getChild(type, before = null, after = null) {
let r = getChildren(this, type, before, after);
return r.length ? r[0] : null;
}
getChildren(type, before = null, after = null) {
return getChildren(this, type, before, after);
}
resolve(pos, side = 0) {
return resolveNode(this, pos, side, false);
}
resolveInner(pos, side = 0) {
return resolveNode(this, pos, side, true);
}
matchContext(context) {
return matchNodeContext(this, context);
}
enterUnfinishedNodesBefore(pos) {
let scan = this.childBefore(pos),
node = this;
while (scan) {
let last = scan.lastChild;
if (!last || last.to != scan.to) break;
if (last.type.isError && last.from == last.to) {
node = scan;
scan = last.prevSibling;
} else scan = last;
}
return node;
}
get node() {
return this;
}
get next() {
return this.parent;
}
};
TreeNode = class TreeNode extends BaseNode {
constructor(_tree, from, index, _parent) {
super();
this._tree = _tree;
this.from = from;
this.index = index;
this._parent = _parent;
}
get type() {
return this._tree.type;
}
get name() {
return this._tree.type.name;
}
get to() {
return this.from + this._tree.length;
}
nextChild(i$1, dir, pos, side, mode = 0) {
for (let parent = this;;) {
for (let {
children,
positions
} = parent._tree, e = dir > 0 ? children.length : -1; i$1 != e; i$1 += dir) {
let next = children[i$1],
start = positions[i$1] + parent.from;
if (!checkSide(side, pos, start, start + next.length)) continue;
if (next instanceof TreeBuffer) {
if (mode & IterMode.ExcludeBuffers) continue;
let index = next.findChild(0, next.buffer.length, dir, pos - start, side);
if (index > -1) return new BufferNode(new BufferContext(parent, next, i$1, start), null, index);
} else if (mode & IterMode.IncludeAnonymous || !next.type.isAnonymous || hasChild(next)) {
let mounted;
if (!(mode & IterMode.IgnoreMounts) && (mounted = MountedTree.get(next)) && !mounted.overlay) return new TreeNode(mounted.tree, start, i$1, parent);
let inner = new TreeNode(next, start, i$1, parent);
return mode & IterMode.IncludeAnonymous || !inner.type.isAnonymous ? inner : inner.nextChild(dir < 0 ? next.children.length - 1 : 0, dir, pos, side);
}
}
if (mode & IterMode.IncludeAnonymous || !parent.type.isAnonymous) return null;
if (parent.index >= 0) i$1 = parent.index + dir;else i$1 = dir < 0 ? -1 : parent._parent._tree.children.length;
parent = parent._parent;
if (!parent) return null;
}
}
get firstChild() {
return this.nextChild(0, 1, 0, 4);
}
get lastChild() {
return this.nextChild(this._tree.children.length - 1, -1, 0, 4);
}
childAfter(pos) {
return this.nextChild(0, 1, pos, 2);
}
childBefore(pos) {
return this.nextChild(this._tree.children.length - 1, -1, pos, -2);
}
enter(pos, side, mode = 0) {
let mounted;
if (!(mode & IterMode.IgnoreOverlays) && (mounted = MountedTree.get(this._tree)) && mounted.overlay) {
let rPos = pos - this.from;
for (let {
from,
to
} of mounted.overlay) if ((side > 0 ? from <= rPos : from < rPos) && (side < 0 ? to >= rPos : to > rPos)) return new TreeNode(mounted.tree, mounted.overlay[0].from + this.from, -1, this);
}
return this.nextChild(0, 1, pos, side, mode);
}
nextSignificantParent() {
let val = this;
while (val.type.isAnonymous && val._parent) val = val._parent;
return val;
}
get parent() {
return this._parent ? this._parent.nextSignificantParent() : null;
}
get nextSibling() {
return this._parent && this.index >= 0 ? this._parent.nextChild(this.index + 1, 1, 0, 4) : null;
}
get prevSibling() {
return this._parent && this.index >= 0 ? this._parent.nextChild(this.index - 1, -1, 0, 4) : null;
}
get tree() {
return this._tree;
}
toTree() {
return this._tree;
}
/**
@internal
*/
toString() {
return this._tree.toString();
}
};
BufferContext = class {
constructor(parent, buffer, index, start) {
this.parent = parent;
this.buffer = buffer;
this.index = index;
this.start = start;
}
};
BufferNode = class BufferNode extends BaseNode {
get name() {
return this.type.name;
}
get from() {
return this.context.start + this.context.buffer.buffer[this.index + 1];
}
get to() {
return this.context.start + this.context.buffer.buffer[this.index + 2];
}
constructor(context, _parent, index) {
super();
this.context = context;
this._parent = _parent;
this.index = index;
this.type = context.buffer.set.types[context.buffer.buffer[index]];
}
child(dir, pos, side) {
let {
buffer
} = this.context;
let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.context.start, side);
return index < 0 ? null : new BufferNode(this.context, this, index);
}
get firstChild() {
return this.child(1, 0, 4);
}
get lastChild() {
return this.child(-1, 0, 4);
}
childAfter(pos) {
return this.child(1, pos, 2);
}
childBefore(pos) {
return this.child(-1, pos, -2);
}
enter(pos, side, mode = 0) {
if (mode & IterMode.ExcludeBuffers) return null;
let {
buffer
} = this.context;
let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], side > 0 ? 1 : -1, pos - this.context.start, side);
return index < 0 ? null : new BufferNode(this.context, this, index);
}
get parent() {
return this._parent || this.context.parent.nextSignificantParent();
}
externalSibling(dir) {
return this._parent ? null : this.context.parent.nextChild(this.context.index + dir, dir, 0, 4);
}
get nextSibling() {
let {
buffer
} = this.context;
let after = buffer.buffer[this.index + 3];
if (after < (this._parent ? buffer.buffer[this._parent.index + 3] : buffer.buffer.length)) return new BufferNode(this.context, this._parent, after);
return this.externalSibling(1);
}
get prevSibling() {
let {
buffer
} = this.context;
let parentStart = this._parent ? this._parent.index + 4 : 0;
if (this.index == parentStart) return this.externalSibling(-1);
return new BufferNode(this.context, this._parent, buffer.findChild(parentStart, this.index, -1, 0, 4));
}
get tree() {
return null;
}
toTree() {
let children = [],
positions = [];
let {
buffer
} = this.context;
let startI = this.index + 4,
endI = buffer.buffer[this.index + 3];
if (endI > startI) {
let from = buffer.buffer[this.index + 1];
children.push(buffer.slice(startI, endI, from));
positions.push(0);
}
return new Tree(this.type, children, positions, this.to - this.from);
}
/**
@internal
*/
toString() {
return this.context.buffer.childString(this.index);
}
};
StackIterator = class {
constructor(heads, node) {
this.heads = heads;
this.node = node;
}
get next() {
return iterStack(this.heads);
}
};
TreeCursor = class {
/**
Shorthand for `.type.name`.
*/
get name() {
return this.type.name;
}
/**
@internal
*/
constructor(node, mode = 0) {
this.mode = mode;
/**
@internal
*/
this.buffer = null;
this.stack = [];
/**
@internal
*/
this.index = 0;
this.bufferNode = null;
if (node instanceof TreeNode) this.yieldNode(node);else {
this._tree = node.context.parent;
this.buffer = node.context;
for (let n = node._parent; n; n = n._parent) this.stack.unshift(n.index);
this.bufferNode = node;
this.yieldBuf(node.index);
}
}
yieldNode(node) {
if (!node) return false;
this._tree = node;
this.type = node.type;
this.from = node.from;
this.to = node.to;
return true;
}
yieldBuf(index, type) {
this.index = index;
let {
start,
buffer
} = this.buffer;
this.type = type || buffer.set.types[buffer.buffer[index]];
this.from = start + buffer.buffer[index + 1];
this.to = start + buffer.buffer[index + 2];
return true;
}
/**
@internal
*/
yield(node) {
if (!node) return false;
if (node instanceof TreeNode) {
this.buffer = null;
return this.yieldNode(node);
}
this.buffer = node.context;
return this.yieldBuf(node.index, node.type);
}
/**
@internal
*/
toString() {
return this.buffer ? this.buffer.buffer.childString(this.index) : this._tree.toString();
}
/**
@internal
*/
enterChild(dir, pos, side) {
if (!this.buffer) return this.yield(this._tree.nextChild(dir < 0 ? this._tree._tree.children.length - 1 : 0, dir, pos, side, this.mode));
let {
buffer
} = this.buffer;
let index = buffer.findChild(this.index + 4, buffer.buffer[this.index + 3], dir, pos - this.buffer.start, side);
if (index < 0) return false;
this.stack.push(this.index);
return this.yieldBuf(index);
}
/**
Move the cursor to this node's first child. When this returns
false, the node has no child, and the cursor has not been moved.
*/
firstChild() {
return this.enterChild(1, 0, 4);
}
/**
Move the cursor to this node's last child.
*/
lastChild() {
return this.enterChild(-1, 0, 4);
}
/**
Move the cursor to the first child that ends after `pos`.
*/
childAfter(pos) {
return this.enterChild(1, pos, 2);
}
/**
Move to the last child that starts before `pos`.
*/
childBefore(pos) {
return this.enterChild(-1, pos, -2);
}
/**
Move the cursor to the child around `pos`. If side is -1 the
child may end at that position, when 1 it may start there. This
will also enter [overlaid](#common.MountedTree.overlay)
[mounted](#common.NodeProp^mounted) trees unless `overlays` is
set to false.
*/
enter(pos, side, mode = this.mode) {
if (!this.buffer) return this.yield(this._tree.enter(pos, side, mode));
return mode & IterMode.ExcludeBuffers ? false : this.enterChild(1, pos, side);
}
/**
Move to the node's parent node, if this isn't the top node.
*/
parent() {
if (!this.buffer) return this.yieldNode(this.mode & IterMode.IncludeAnonymous ? this._tree._parent : this._tree.parent);
if (this.stack.length) return this.yieldBuf(this.stack.pop());
let parent = this.mode & IterMode.IncludeAnonymous ? this.buffer.parent : this.buffer.parent.nextSignificantParent();
this.buffer = null;
return this.yieldNode(parent);
}
/**
@internal
*/
sibling(dir) {
if (!this.buffer) return !this._tree._parent ? false : this.yield(this._tree.index < 0 ? null : this._tree._parent.nextChild(this._tree.index + dir, dir, 0, 4, this.mode));
let {
buffer
} = this.buffer,
d = this.stack.length - 1;
if (dir < 0) {
let parentStart = d < 0 ? 0 : this.stack[d] + 4;
if (this.index != parentStart) return this.yieldBuf(buffer.findChild(parentStart, this.index, -1, 0, 4));
} else {
let after = buffer.buffer[this.index + 3];
if (after < (d < 0 ? buffer.buffer.length : buffer.buffer[this.stack[d] + 3])) return this.yieldBuf(after);
}
return d < 0 ? this.yield(this.buffer.parent.nextChild(this.buffer.index + dir, dir, 0, 4, this.mode)) : false;
}
/**
Move to this node's next sibling, if any.
*/
nextSibling() {
return this.sibling(1);
}
/**
Move to this node's previous sibling, if any.
*/
prevSibling() {
return this.sibling(-1);
}
atLastNode(dir) {
let index,
parent,
{
buffer
} = this;
if (buffer) {
if (dir > 0) {
if (this.index < buffer.buffer.buffer.length) return false;
} else for (let i$1 = 0; i$1 < this.index; i$1++) if (buffer.buffer.buffer[i$1 + 3] < this.index) return false;
({
index,
parent
} = buffer);
} else ({
index,
_parent: parent
} = this._tree);
for (; parent; {
index,
_parent: parent
} = parent) if (index > -1) for (let i$1 = index + dir, e = dir < 0 ? -1 : parent._tree.children.length; i$1 != e; i$1 += dir) {
let child = parent._tree.children[i$1];
if (this.mode & IterMode.IncludeAnonymous || child instanceof TreeBuffer || !child.type.isAnonymous || hasChild(child)) return false;
}
return true;
}
move(dir, enter) {
if (enter && this.enterChild(dir, 0, 4)) return true;
for (;;) {
if (this.sibling(dir)) return true;
if (this.atLastNode(dir) || !this.parent()) return false;
}
}
/**
Move to the next node in a
[pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR)
traversal, going from a node to its first child or, if the
current node is empty or `enter` is false, its next sibling or
the next sibling of the first parent node that has one.
*/
next(enter = true) {
return this.move(1, enter);
}
/**
Move to the next node in a last-to-first pre-order traveral. A
node is followed by its last child or, if it has none, its
previous sibling or the previous sibling of the first parent
node that has one.
*/
prev(enter = true) {
return this.move(-1, enter);
}
/**
Move the cursor to the innermost node that covers `pos`. If
`side` is -1, it will enter nodes that end at `pos`. If it is 1,
it will enter nodes that start at `pos`.
*/
moveTo(pos, side = 0) {
while (this.from == this.to || (side < 1 ? this.from >= pos : this.from > pos) || (side > -1 ? this.to <= pos : this.to < pos)) if (!this.parent()) break;
while (this.enterChild(1, pos, side));
return this;
}
/**
Get a [syntax node](#common.SyntaxNode) at the cursor's current
position.
*/
get node() {
if (!this.buffer) return this._tree;
let cache$1 = this.bufferNode,
result = null,
depth = 0;
if (cache$1 && cache$1.context == this.buffer) scan: for (let index = this.index, d = this.stack.length; d >= 0;) {
for (let c = cache$1; c; c = c._parent) if (c.index == index) {
if (index == this.index) return c;
result = c;
depth = d + 1;
break scan;
}
index = this.stack[--d];
}
for (let i$1 = depth; i$1 < this.stack.length; i$1++) result = new BufferNode(this.buffer, result, this.stack[i$1]);
return this.bufferNode = new BufferNode(this.buffer, result, this.index);
}
/**
Get the [tree](#common.Tree) that represents the current node, if
any. Will return null when the node is in a [tree
buffer](#common.TreeBuffer).
*/
get tree() {
return this.buffer ? null : this._tree._tree;
}
/**
Iterate over the current node and all its descendants, calling
`enter` when entering a node and `leave`, if given, when leaving
one. When `enter` returns `false`, any children of that node are
skipped, and `leave` isn't called for it.
*/
iterate(enter, leave) {
for (let depth = 0;;) {
let mustLeave = false;
if (this.type.isAnonymous || enter(this) !== false) {
if (this.firstChild()) {
depth++;
continue;
}
if (!this.type.isAnonymous) mustLeave = true;
}
for (;;) {
if (mustLeave && leave) leave(this);
mustLeave = this.type.isAnonymous;
if (this.nextSibling()) break;
if (!depth) return;
this.parent();
depth--;
mustLeave = true;
}
}
}
/**
Test whether the current node matches a given context—a sequence
of direct parent node names. Empty strings in the context array
are treated as wildcards.
*/
matchContext(context) {
if (!this.buffer) return matchNodeContext(this.node, context);
let {
buffer
} = this.buffer,
{
types: types$2
} = buffer.set;
for (let i$1 = context.length - 1, d = this.stack.length - 1; i$1 >= 0; d--) {
if (d < 0) return matchNodeContext(this.node, context, i$1);
let type = types$2[buffer.buffer[this.stack[d]]];
if (!type.isAnonymous) {
if (context[i$1] && context[i$1] != type.name) return false;
i$1--;
}
}
return true;
}
};
nodeSizeCache = /* @__PURE__ */new WeakMap();
_export("Et", NodeWeakMap = class {
constructor() {
this.map = /* @__PURE__ */new WeakMap();
}
setBuffer(buffer, index, value) {
let inner = this.map.get(buffer);
if (!inner) this.map.set(buffer, inner = /* @__PURE__ */new Map());
inner.set(index, value);
}
getBuffer(buffer, index) {
let inner = this.map.get(buffer);
return inner && inner.get(index);
}
/**
Set the value for this syntax node.
*/
set(node, value) {
if (node instanceof BufferNode) this.setBuffer(node.context.buffer, node.index, value);else if (node instanceof TreeNode) this.map.set(node.tree, value);
}
/**
Retrieve value for this syntax node, if it exists in the map.
*/
get(node) {
return node instanceof BufferNode ? this.getBuffer(node.context.buffer, node.index) : node instanceof TreeNode ? this.map.get(node.tree) : void 0;
}
/**
Set the value for the node that a cursor currently points to.
*/
cursorSet(cursor, value) {
if (cursor.buffer) this.setBuffer(cursor.buffer.buffer, cursor.index, value);else this.map.set(cursor.tree, value);
}
/**
Retrieve the value for the node that a cursor currently points
to.
*/
cursorGet(cursor) {
return cursor.buffer ? this.getBuffer(cursor.buffer.buffer, cursor.index) : this.map.get(cursor.tree);
}
});
/**
Tree fragments are used during [incremental
parsing](#common.Parser.startParse) to track parts of old trees
that can be reused in a new parse. An array of fragments is used
to track regions of an old tree whose nodes might be reused in new
parses. Use the static
[`applyChanges`](#common.TreeFragment^applyChanges) method to
update fragments for document changes.
*/
TreeFragment = class TreeFragment {
/**
Construct a tree fragment. You'll usually want to use
[`addTree`](#common.TreeFragment^addTree) and
[`applyChanges`](#common.TreeFragment^applyChanges) instead of
calling this directly.
*/
constructor(from, to, tree, offset, openStart = false, openEnd = false) {
this.from = from;
this.to = to;
this.tree = tree;
this.offset = offset;
this.open = (openStart ? 1 : 0) | (openEnd ? 2 : 0);
}
/**
Whether the start of the fragment represents the start of a
parse, or the end of a change. (In the second case, it may not
be safe to reuse some nodes at the start, depending on the
parsing algorithm.)
*/
get openStart() {
return (this.open & 1) > 0;
}
/**
Whether the end of the fragment represents the end of a
full-document parse, or the start of a change.
*/
get openEnd() {
return (this.open & 2) > 0;
}
/**
Create a set of fragments from a freshly parsed tree, or update
an existing set of fragments by replacing the ones that overlap
with a tree with content from the new tree. When `partial` is
true, the parse is treated as incomplete, and the resulting
fragment has [`openEnd`](#common.TreeFragment.openEnd) set to
true.
*/
static addTree(tree, fragments = [], partial = false) {
let result = [new TreeFragment(0, tree.length, tree, 0, false, partial)];
for (let f of fragments) if (f.to > tree.length) result.push(f);
return result;
}
/**
Apply a set of edits to an array of fragments, removing or
splitting fragments as necessary to remove edited ranges, and
adjusting offsets for fragments that moved.
*/
static applyChanges(fragments, changes, minGap = 128) {
if (!changes.length) return fragments;
let result = [];
let fI = 1,
nextF = fragments.length ? fragments[0] : null;
for (let cI = 0, pos = 0, off = 0;; cI++) {
let nextC = cI < changes.length ? changes[cI] : null;
let nextPos = nextC ? nextC.fromA : 1e9;
if (nextPos - pos >= minGap) while (nextF && nextF.from < nextPos) {
let cut = nextF;
if (pos >= cut.from || nextPos <= cut.to || off) {
let fFrom = Math.max(cut.from, pos) - off,
fTo = Math.min(cut.to, nextPos) - off;
cut = fFrom >= fTo ? null : new TreeFragment(fFrom, fTo, cut.tree, cut.offset + off, cI > 0, !!nextC);
}
if (cut) result.push(cut);
if (nextF.to > nextPos) break;
nextF = fI < fragments.length ? fragments[fI++] : null;
}
if (!nextC) break;
pos = nextC.toA;
off = nextC.toA - nextC.toB;
}
return result;
}
};
/**
A superclass that parsers should extend.
*/
Parser = class {
/**
Start a parse, returning a [partial parse](#common.PartialParse)
object. [`fragments`](#common.TreeFragment) can be passed in to
make the parse incremental.
By default, the entire input is parsed. You can pass `ranges`,
which should be a sorted array of non-empty, non-overlapping
ranges, to parse only those ranges. The tree returned in that
case will start at `ranges[0].from`.
*/
startParse(input, fragments, ranges) {
if (typeof input == "string") input = new StringInput(input);
ranges = !ranges ? [new Range$1(0, input.length)] : ranges.length ? ranges.map(r => new Range$1(r.from, r.to)) : [new Range$1(0, 0)];
return this.createParse(input, fragments || [], ranges);
}
/**
Run a full parse, returning the resulting tree.
*/
parse(input, fragments, ranges) {
let parse = this.startParse(input, fragments, ranges);
for (;;) {
let done = parse.advance();
if (done) return done;
}
}
};
StringInput = class {
constructor(string$1) {
this.string = string$1;
}
get length() {
return this.string.length;
}
chunk(from) {
return this.string.slice(from);
}
get lineChunks() {
return false;
}
read(from, to) {
return this.string.slice(from, to);
}
};
InnerParse = class {
constructor(parser$3, parse, overlay, target, from) {
this.parser = parser$3;
this.parse = parse;
this.overlay = overlay;
this.target = target;
this.from = from;
}
};
ActiveOverlay = class {
constructor(parser$3, predicate, mounts, index, start, target, prev) {
this.parser = parser$3;
this.predicate = predicate;
this.mounts = mounts;
this.index = index;
this.start = start;
this.target = target;
this.prev = prev;
this.depth = 0;
this.ranges = [];
}
};
stoppedInner = new NodeProp({
perNode: true
});
MixedParse = class {
constructor(base$1, nest, input, fragments, ranges) {
this.nest = nest;
this.input = input;
this.fragments = fragments;
this.ranges = ranges;
this.inner = [];
this.innerDone = 0;
this.baseTree = null;
this.stoppedAt = null;
this.baseParse = base$1;
}
advance() {
if (this.baseParse) {
let done$1 = this.baseParse.advance();
if (!done$1) return null;
this.baseParse = null;
this.baseTree = done$1;
this.startInner();
if (this.stoppedAt != null) for (let inner$1 of this.inner) inner$1.parse.stopAt(this.stoppedAt);
}
if (this.innerDone == this.inner.length) {
let result = this.baseTree;
if (this.stoppedAt != null) result = new Tree(result.type, result.children, result.positions, result.length, result.propValues.concat([[stoppedInner, this.stoppedAt]]));
return result;
}
let inner = this.inner[this.innerDone],
done = inner.parse.advance();
if (done) {
this.innerDone++;
let props = Object.assign(Object.create(null), inner.target.props);
props[NodeProp.mounted.id] = new MountedTree(done, inner.overlay, inner.parser);
inner.target.props = props;
}
return null;
}
get parsedPos() {
if (this.baseParse) return 0;
let pos = this.input.length;
for (let i$1 = this.innerDone; i$1 < this.inner.length; i$1++) if (this.inner[i$1].from < pos) pos = Math.min(pos, this.inner[i$1].parse.parsedPos);
return pos;
}
stopAt(pos) {
this.stoppedAt = pos;
if (this.baseParse) this.baseParse.stopAt(pos);else for (let i$1 = this.innerDone; i$1 < this.inner.length; i$1++) this.inner[i$1].parse.stopAt(pos);
}
startInner() {
let fragmentCursor = new FragmentCursor$1(this.fragments);
let overlay = null;
let covered = null;
let cursor = new TreeCursor(new TreeNode(this.baseTree, this.ranges[0].from, 0, null), IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
scan: for (let nest, isCovered;;) {
let enter = true,
range;
if (this.stoppedAt != null && cursor.from >= this.stoppedAt) enter = false;else if (fragmentCursor.hasNode(cursor)) {
if (overlay) {
let match = overlay.mounts.find(m => m.frag.from <= cursor.from && m.frag.to >= cursor.to && m.mount.overlay);
if (match) for (let r of match.mount.overlay) {
let from = r.from + match.pos,
to = r.to + match.pos;
if (from >= cursor.from && to <= cursor.to && !overlay.ranges.some(r$1 => r$1.from < to && r$1.to > from)) overlay.ranges.push({
from,
to
});
}
}
enter = false;
} else if (covered && (isCovered = checkCover(covered.ranges, cursor.from, cursor.to))) enter = isCovered != 2;else if (!cursor.type.isAnonymous && (nest = this.nest(cursor, this.input)) && (cursor.from < cursor.to || !nest.overlay)) {
if (!cursor.tree) materialize(cursor);
let oldMounts = fragmentCursor.findMounts(cursor.from, nest.parser);
if (typeof nest.overlay == "function") overlay = new ActiveOverlay(nest.parser, nest.overlay, oldMounts, this.inner.length, cursor.from, cursor.tree, overlay);else {
let ranges = punchRanges(this.ranges, nest.overlay || (cursor.from < cursor.to ? [new Range$1(cursor.from, cursor.to)] : []));
if (ranges.length) checkRanges(ranges);
if (ranges.length || !nest.overlay) this.inner.push(new InnerParse(nest.parser, ranges.length ? nest.parser.startParse(this.input, enterFragments(oldMounts, ranges), ranges) : nest.parser.startParse(""), nest.overlay ? nest.overlay.map(r => new Range$1(r.from - cursor.from, r.to - cursor.from)) : null, cursor.tree, ranges.length ? ranges[0].from : cursor.from));
if (!nest.overlay) enter = false;else if (ranges.length) covered = {
ranges,
depth: 0,
prev: covered
};
}
} else if (overlay && (range = overlay.predicate(cursor))) {
if (range === true) range = new Range$1(cursor.from, cursor.to);
if (range.from < range.to) overlay.ranges.push(range);
}
if (enter && cursor.firstChild()) {
if (overlay) overlay.depth++;
if (covered) covered.depth++;
} else for (;;) {
if (cursor.nextSibling()) break;
if (!cursor.parent()) break scan;
if (overlay && ! --overlay.depth) {
let ranges = punchRanges(this.ranges, overlay.ranges);
if (ranges.length) {
checkRanges(ranges);
this.inner.splice(overlay.index, 0, new InnerParse(overlay.parser, overlay.parser.startParse(this.input, enterFragments(overlay.mounts, ranges), ranges), overlay.ranges.map(r => new Range$1(r.from - overlay.start, r.to - overlay.start)), overlay.target, ranges[0].from));
}
overlay = overlay.prev;
}
if (covered && ! --covered.depth) covered = covered.prev;
}
}
}
};
StructureCursor = class {
constructor(root, offset) {
this.offset = offset;
this.done = false;
this.cursor = root.cursor(IterMode.IncludeAnonymous | IterMode.IgnoreMounts);
}
moveTo(pos) {
let {
cursor
} = this,
p = pos - this.offset;
while (!this.done && cursor.from < p) if (cursor.to >= pos && cursor.enter(p, 1, IterMode.IgnoreOverlays | IterMode.ExcludeBuffers)) ;else if (!cursor.next(false)) this.done = true;
}
hasNode(cursor) {
this.moveTo(cursor.from);
if (!this.done && this.cursor.from + this.offset == cursor.from && this.cursor.tree) for (let tree = this.cursor.tree;;) {
if (tree == cursor.tree) return true;
if (tree.children.length && tree.positions[0] == 0 && tree.children[0] instanceof Tree) tree = tree.children[0];else break;
}
return false;
}
};
FragmentCursor$1 = class {
constructor(fragments) {
var _a$2;
this.fragments = fragments;
this.curTo = 0;
this.fragI = 0;
if (fragments.length) {
let first = this.curFrag = fragments[0];
this.curTo = (_a$2 = first.tree.prop(stoppedInner)) !== null && _a$2 !== void 0 ? _a$2 : first.to;
this.inner = new StructureCursor(first.tree, -first.offset);
} else this.curFrag = this.inner = null;
}
hasNode(node) {
while (this.curFrag && node.from >= this.curTo) this.nextFrag();
return this.curFrag && this.curFrag.from <= node.from && this.curTo >= node.to && this.inner.hasNode(node);
}
nextFrag() {
var _a$2;
this.fragI++;
if (this.fragI == this.fragments.length) this.curFrag = this.inner = null;else {
let frag = this.curFrag = this.fragments[this.fragI];
this.curTo = (_a$2 = frag.tree.prop(stoppedInner)) !== null && _a$2 !== void 0 ? _a$2 : frag.to;
this.inner = new StructureCursor(frag.tree, -frag.offset);
}
}
findMounts(pos, parser$3) {
var _a$2;
let result = [];
if (this.inner) {
this.inner.cursor.moveTo(pos, 1);
for (let pos$1 = this.inner.cursor.node; pos$1; pos$1 = pos$1.parent) {
let mount = (_a$2 = pos$1.tree) === null || _a$2 === void 0 ? void 0 : _a$2.prop(NodeProp.mounted);
if (mount && mount.parser == parser$3) for (let i$1 = this.fragI; i$1 < this.fragments.length; i$1++) {
let frag = this.fragments[i$1];
if (frag.from >= pos$1.to) break;
if (frag.tree == this.curFrag.tree) result.push({
frag,
pos: pos$1.from - frag.offset,
mount
});
}
}
}
return result;
}
};
nextTagID = 0;
Tag = class Tag {
constructor(set, base$1, modified) {
this.set = set;
this.base = base$1;
this.modified = modified;
this.id = nextTagID++;
}
static define(parent) {
if (parent === null || parent === void 0 ? void 0 : parent.base) throw new Error("Can not derive from a modified tag");
let tag = new Tag([], null, []);
tag.set.push(tag);
if (parent) for (let t$1 of parent.set) tag.set.push(t$1);
return tag;
}
static defineModifier() {
let mod = new Modifier();
return tag => {
if (tag.modified.indexOf(mod) > -1) return tag;
return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
};
}
};
nextModifierID = 0;
Modifier = class Modifier {
constructor() {
this.instances = [];
this.id = nextModifierID++;
}
static get(base$1, mods) {
if (!mods.length) return base$1;
let exists = mods[0].instances.find(t$1 => t$1.base == base$1 && sameArray$1(mods, t$1.modified));
if (exists) return exists;
let set = [],
tag = new Tag(set, base$1, mods);
for (let m of mods) m.instances.push(tag);
let configs = permute(mods);
for (let parent of base$1.set) for (let config$1 of configs) set.push(Modifier.get(parent, config$1));
return tag;
}
};
ruleNodeProp = new NodeProp();
Rule = class {
constructor(tags$1, mode, context, next) {
this.tags = tags$1;
this.mode = mode;
this.context = context;
this.next = next;
}
get opaque() {
return this.mode == 0;
}
get inherit() {
return this.mode == 1;
}
sort(other) {
if (!other || other.depth < this.depth) {
this.next = other;
return this;
}
other.next = this.sort(other.next);
return other;
}
get depth() {
return this.context ? this.context.length : 0;
}
};
Rule.empty = new Rule([], 2, null);
HighlightBuilder = class {
constructor(at, highlighters, span) {
this.at = at;
this.highlighters = highlighters;
this.span = span;
this.class = "";
}
startSpan(at, cls) {
if (cls != this.class) {
this.flush(at);
if (at > this.at) this.at = at;
this.class = cls;
}
}
flush(to) {
if (to > this.at && this.class) this.span(this.at, to, this.class);
}
highlightRange(cursor, from, to, inheritedClass, highlighters) {
let {
type,
from: start,
to: end
} = cursor;
if (start >= to || end <= from) return;
if (type.isTop) highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
let cls = inheritedClass;
let rule = getStyleTags(cursor) || Rule.empty;
let tagCls = highlightTags(highlighters, rule.tags);
if (tagCls) {
if (cls) cls += " ";
cls += tagCls;
if (rule.mode == 1) inheritedClass += (inheritedClass ? " " : "") + tagCls;
}
this.startSpan(cursor.from, cls);
if (rule.opaque) return;
let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
if (mounted && mounted.overlay) {
let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
let hasChild$1 = cursor.firstChild();
for (let i$1 = 0, pos = start;; i$1++) {
let next = i$1 < mounted.overlay.length ? mounted.overlay[i$1] : null;
let nextPos = next ? next.from + start : end;
let rangeFrom = Math.max(from, pos),
rangeTo = Math.min(to, nextPos);
if (rangeFrom < rangeTo && hasChild$1) while (cursor.from < rangeTo) {
this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
this.startSpan(Math.min(to, cursor.to), cls);
if (cursor.to >= nextPos || !cursor.nextSibling()) break;
}
if (!next || nextPos > to) break;
pos = next.to + start;
if (pos > from) {
this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters);
this.startSpan(pos, cls);
}
}
if (hasChild$1) cursor.parent();
} else if (cursor.firstChild()) {
do {
if (cursor.to <= from) continue;
if (cursor.from >= to) break;
this.highlightRange(cursor, from, to, inheritedClass, highlighters);
this.startSpan(Math.min(to, cursor.to), cls);
} while (cursor.nextSibling());
cursor.parent();
}
}
};
t = Tag.define;
comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
_export("wt", tags = {
comment,
lineComment: t(comment),
blockComment: t(comment),
docComment: t(comment),
name,
variableName: t(name),
typeName,
tagName: t(typeName),
propertyName,
attributeName: t(propertyName),
className: t(name),
labelName: t(name),
namespace: t(name),
macroName: t(name),
literal,
string,
docString: t(string),
character: t(string),
attributeValue: t(string),
number,
integer: t(number),
float: t(number),
bool: t(literal),
regexp: t(literal),
escape: t(literal),
color: t(literal),
url: t(literal),
keyword,
self: t(keyword),
null: t(keyword),
atom: t(keyword),
unit: t(keyword),
modifier: t(keyword),
operatorKeyword: t(keyword),
controlKeyword: t(keyword),
definitionKeyword: t(keyword),
moduleKeyword: t(keyword),
operator,
derefOperator: t(operator),
arithmeticOperator: t(operator),
logicOperator: t(operator),
bitwiseOperator: t(operator),
compareOperator: t(operator),
updateOperator: t(operator),
definitionOperator: t(operator),
typeOperator: t(operator),
controlOperator: t(operator),
punctuation,
separator: t(punctuation),
bracket,
angleBracket: t(bracket),
squareBracket: t(bracket),
paren: t(bracket),
brace: t(bracket),
content,
heading,
heading1: t(heading),
heading2: t(heading),
heading3: t(heading),
heading4: t(heading),
heading5: t(heading),
heading6: t(heading),
contentSeparator: t(content),
list: t(content),
quote: t(content),
emphasis: t(content),
strong: t(content),
link: t(content),
monospace: t(content),
strikethrough: t(content),
inserted: t(),
deleted: t(),
changed: t(),
invalid: t(),
meta,
documentMeta: t(meta),
annotation: t(meta),
processingInstruction: t(meta),
definition: Tag.defineModifier(),
constant: Tag.defineModifier(),
function: Tag.defineModifier(),
standard: Tag.defineModifier(),
local: Tag.defineModifier(),
special: Tag.defineModifier()
});
classHighlighter = tagHighlighter([{
tag: tags.link,
class: "tok-link"
}, {
tag: tags.heading,
class: "tok-heading"
}, {
tag: tags.emphasis,
class: "tok-emphasis"
}, {
tag: tags.strong,
class: "tok-strong"
}, {
tag: tags.keyword,
class: "tok-keyword"
}, {
tag: tags.atom,
class: "tok-atom"
}, {
tag: tags.bool,
class: "tok-bool"
}, {
tag: tags.url,
class: "tok-url"
}, {
tag: tags.labelName,
class: "tok-labelName"
}, {
tag: tags.inserted,
class: "tok-inserted"
}, {
tag: tags.deleted,
class: "tok-deleted"
}, {
tag: tags.literal,
class: "tok-literal"
}, {
tag: tags.string,
class: "tok-string"
}, {
tag: tags.number,
class: "tok-number"
}, {
tag: [tags.regexp, tags.escape, tags.special(tags.string)],
class: "tok-string2"
}, {
tag: tags.variableName,
class: "tok-variableName"
}, {
tag: tags.local(tags.variableName),
class: "tok-variableName tok-local"
}, {
tag: tags.definition(tags.variableName),
class: "tok-variableName tok-definition"
}, {
tag: tags.special(tags.variableName),
class: "tok-variableName2"
}, {
tag: tags.definition(tags.propertyName),
class: "tok-propertyName tok-definition"
}, {
tag: tags.typeName,
class: "tok-typeName"
}, {
tag: tags.namespace,
class: "tok-namespace"
}, {
tag: tags.className,
class: "tok-className"
}, {
tag: tags.macroName,
class: "tok-macroName"
}, {
tag: tags.propertyName,
class: "tok-propertyName"
}, {
tag: tags.operator,
class: "tok-operator"
}, {
tag: tags.comment,
class: "tok-comment"
}, {
tag: tags.meta,
class: "tok-meta"
}, {
tag: tags.invalid,
class: "tok-invalid"
}, {
tag: tags.punctuation,
class: "tok-punctuation"
}]); //#endregion
//#region ../../../node_modules/.pnpm/@codemirror+language@6.10.1/node_modules/@codemirror/language/dist/index.js
/**
Node prop stored in a parser's top syntax node to provide the
facet that stores language-specific data for that language.
*/
languageDataProp$1 = /* @__PURE__ */new NodeProp();
sublanguageProp$1 = /* @__PURE__ */new NodeProp();
/**
A language object manages parsing and per-language
[metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
managed as a [Lezer](https://lezer.codemirror.net) tree. The class
can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
for stream parsers.
*/
Language$1 = class {
/**
Construct a language object. If you need to invoke this
directly, first define a data facet with
[`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
to the language's outer syntax node.
*/
constructor(data, parser$3, extraExtensions = [], name$1 = "") {
this.data = data;
this.name = name$1;
if (!EditorState.prototype.hasOwnProperty("tree")) Object.defineProperty(EditorState.prototype, "tree", {
get() {
return syntaxTree$1(this);
}
});
this.parser = parser$3;
this.extension = [language$1.of(this), EditorState.languageData.of((state, pos, side) => {
let top$1 = topNodeAt$1(state, pos, side),
data$1 = top$1.type.prop(languageDataProp$1);
if (!data$1) return [];
let base$1 = state.facet(data$1),
sub = top$1.type.prop(sublanguageProp$1);
if (sub) {
let innerNode = top$1.resolve(pos - top$1.from, side);
for (let sublang of sub) if (sublang.test(innerNode, state)) {
let data$2 = state.facet(sublang.facet);
return sublang.type == "replace" ? data$2 : data$2.concat(base$1);
}
}
return base$1;
})].concat(extraExtensions);
}
/**
Query whether this language is active at the given position.
*/
isActiveAt(state, pos, side = -1) {
return topNodeAt$1(state, pos, side).type.prop(languageDataProp$1) == this.data;
}
/**
Find the document regions that were parsed using this language.
The returned regions will _include_ any nested languages rooted
in this language, when those exist.
*/
findRegions(state) {
let lang = state.facet(language$1);
if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) return [{
from: 0,
to: state.doc.length
}];
if (!lang || !lang.allowsNesting) return [];
let result = [];
let explore = (tree, from) => {
if (tree.prop(languageDataProp$1) == this.data) {
result.push({
from,
to: from + tree.length
});
return;
}
let mount = tree.prop(NodeProp.mounted);
if (mount) {
if (mount.tree.prop(languageDataProp$1) == this.data) {
if (mount.overlay) for (let r of mount.overlay) result.push({
from: r.from + from,
to: r.to + from
});else result.push({
from,
to: from + tree.length
});
return;
} else if (mount.overlay) {
let size = result.length;
explore(mount.tree, mount.overlay[0].from + from);
if (result.length > size) return;
}
}
for (let i$1 = 0; i$1 < tree.children.length; i$1++) {
let ch = tree.children[i$1];
if (ch instanceof Tree) explore(ch, tree.positions[i$1] + from);
}
};
explore(syntaxTree$1(state), 0);
return result;
}
/**
Indicates whether this language allows nested languages. The
default implementation returns true.
*/
get allowsNesting() {
return true;
}
};
/**
@internal
*/
Language$1.setState = /* @__PURE__ */StateEffect$1.define();
_export("ct", LRLanguage = class LRLanguage extends Language$1 {
constructor(data, parser$3, name$1) {
super(data, parser$3, [], name$1);
this.parser = parser$3;
}
/**
Define a language from a parser.
*/
static define(spec) {
let data = defineLanguageFacet$1(spec.languageData);
return new LRLanguage(data, spec.parser.configure({
props: [languageDataProp$1.add(type => type.isTop ? data : void 0)]
}), spec.name);
}
/**
Create a new instance of this language with a reconfigured
version of its parser and optionally a new name.
*/
configure(options, name$1) {
return new LRLanguage(this.data, this.parser.configure(options), name$1 || this.name);
}
get allowsNesting() {
return this.parser.hasWrappers();
}
});
DocInput$1 = class {
/**
Create an input object for the given document.
*/
constructor(doc$2) {
this.doc = doc$2;
this.cursorPos = 0;
this.string = "";
this.cursor = doc$2.iter();
}
get length() {
return this.doc.length;
}
syncTo(pos) {
this.string = this.cursor.next(pos - this.cursorPos).value;
this.cursorPos = pos + this.string.length;
return this.cursorPos - this.string.length;
}
chunk(pos) {
this.syncTo(pos);
return this.string;
}
get lineChunks() {
return true;
}
read(from, to) {
let stringStart = this.cursorPos - this.string.length;
if (from < stringStart || to >= this.cursorPos) return this.doc.sliceString(from, to);else return this.string.slice(from - stringStart, to - stringStart);
}
};
currentContext$1 = null;
/**
A parse context provided to parsers working on the editor content.
*/
ParseContext$1 = class ParseContext$1 {
constructor(parser$3, state, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) {
this.parser = parser$3;
this.state = state;
this.fragments = fragments;
this.tree = tree;
this.treeLen = treeLen;
this.viewport = viewport;
this.skipped = skipped;
this.scheduleOn = scheduleOn;
this.parse = null;
/**
@internal
*/
this.tempSkipped = [];
}
/**
@internal
*/
static create(parser$3, state, viewport) {
return new ParseContext$1(parser$3, state, [], Tree.empty, 0, viewport, [], null);
}
startParse() {
return this.parser.startParse(new DocInput$1(this.state.doc), this.fragments);
}
/**
@internal
*/
work(until, upto) {
if (upto != null && upto >= this.state.doc.length) upto = void 0;
if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
this.takeTree();
return true;
}
return this.withContext(() => {
var _a$2;
if (typeof until == "number") {
let endTime = Date.now() + until;
until = () => Date.now() > endTime;
}
if (!this.parse) this.parse = this.startParse();
if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length) this.parse.stopAt(upto);
for (;;) {
let done = this.parse.advance();
if (done) {
this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
this.treeLen = (_a$2 = this.parse.stoppedAt) !== null && _a$2 !== void 0 ? _a$2 : this.state.doc.length;
this.tree = done;
this.parse = null;
if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) this.parse = this.startParse();else return true;
}
if (until()) return false;
}
});
}
/**
@internal
*/
takeTree() {
let pos, tree;
if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) this.parse.stopAt(pos);
this.withContext(() => {
while (!(tree = this.parse.advance()));
});
this.treeLen = pos;
this.tree = tree;
this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
this.parse = null;
}
}
withContext(f) {
let prev = currentContext$1;
currentContext$1 = this;
try {
return f();
} finally {
currentContext$1 = prev;
}
}
withoutTempSkipped(fragments) {
for (let r; r = this.tempSkipped.pop();) fragments = cutFragments$1(fragments, r.from, r.to);
return fragments;
}
/**
@internal
*/
changes(changes, newState) {
let {
fragments,
tree,
treeLen,
viewport,
skipped
} = this;
this.takeTree();
if (!changes.empty) {
let ranges = [];
changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({
fromA,
toA,
fromB,
toB
}));
fragments = TreeFragment.applyChanges(fragments, ranges);
tree = Tree.empty;
treeLen = 0;
viewport = {
from: changes.mapPos(viewport.from, -1),
to: changes.mapPos(viewport.to, 1)
};
if (this.skipped.length) {
skipped = [];
for (let r of this.skipped) {
let from = changes.mapPos(r.from, 1),
to = changes.mapPos(r.to, -1);
if (from < to) skipped.push({
from,
to
});
}
}
}
return new ParseContext$1(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
}
/**
@internal
*/
updateViewport(viewport) {
if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) return false;
this.viewport = viewport;
let startLen = this.skipped.length;
for (let i$1 = 0; i$1 < this.skipped.length; i$1++) {
let {
from,
to
} = this.skipped[i$1];
if (from < viewport.to && to > viewport.from) {
this.fragments = cutFragments$1(this.fragments, from, to);
this.skipped.splice(i$1--, 1);
}
}
if (this.skipped.length >= startLen) return false;
this.reset();
return true;
}
/**
@internal
*/
reset() {
if (this.parse) {
this.takeTree();
this.parse = null;
}
}
/**
Notify the parse scheduler that the given region was skipped
because it wasn't in view, and the parse should be restarted
when it comes into view.
*/
skipUntilInView(from, to) {
this.skipped.push({
from,
to
});
}
/**
Returns a parser intended to be used as placeholder when
asynchronously loading a nested parser. It'll skip its input and
mark it as not-really-parsed, so that the next update will parse
it again.
When `until` is given, a reparse will be scheduled when that
promise resolves.
*/
static getSkippingParser(until) {
return new class extends Parser {
createParse(input, fragments, ranges) {
let from = ranges[0].from,
to = ranges[ranges.length - 1].to;
return {
parsedPos: from,
advance() {
let cx = currentContext$1;
if (cx) {
for (let r of ranges) cx.tempSkipped.push(r);
if (until) cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
}
this.parsedPos = to;
return new Tree(NodeType.none, [], [], to - from);
},
stoppedAt: null,
stopAt() {}
};
}
}();
}
/**
@internal
*/
isDone(upto) {
upto = Math.min(upto, this.state.doc.length);
let frags = this.fragments;
return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
}
/**
Get the context for the current parse, or `null` if no editor
parse is in progress.
*/
static get() {
return currentContext$1;
}
};
LanguageState$1 = class LanguageState$1 {
constructor(context) {
this.context = context;
this.tree = context.tree;
}
apply(tr) {
if (!tr.docChanged && this.tree == this.context.tree) return this;
let newCx = this.context.changes(tr.changes, tr.state);
let upto = this.context.treeLen == tr.startState.doc.length ? void 0 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
if (!newCx.work(20, upto)) newCx.takeTree();
return new LanguageState$1(newCx);
}
static init(state) {
let vpTo = Math.min(3e3, state.doc.length);
let parseState = ParseContext$1.create(state.facet(language$1).parser, state, {
from: 0,
to: vpTo
});
if (!parseState.work(20, vpTo)) parseState.takeTree();
return new LanguageState$1(parseState);
}
};
Language$1.state = /* @__PURE__ */StateField$1.define({
create: LanguageState$1.init,
update(value, tr) {
for (let e of tr.effects) if (e.is(Language$1.setState)) return e.value;
if (tr.startState.facet(language$1) != tr.state.facet(language$1)) return LanguageState$1.init(tr.state);
return value.apply(tr);
}
});
requestIdle$1 = callback => {
let timeout = setTimeout(() => callback(), 500);
return () => clearTimeout(timeout);
};
if (typeof requestIdleCallback != "undefined") requestIdle$1 = callback => {
let idle = -1,
timeout = setTimeout(() => {
idle = requestIdleCallback(callback, {
timeout: 400
});
}, 100);
return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
};
isInputPending$1 = typeof navigator != "undefined" && ((_a$1 = navigator.scheduling) === null || _a$1 === void 0 ? void 0 : _a$1.isInputPending) ? () => navigator.scheduling.isInputPending() : null;
parseWorker$1 = /* @__PURE__ */ViewPlugin$1.fromClass(class ParseWorker {
constructor(view) {
this.view = view;
this.working = null;
this.workScheduled = 0;
this.chunkEnd = -1;
this.chunkBudget = -1;
this.work = this.work.bind(this);
this.scheduleWork();
}
update(update) {
let cx = this.view.state.field(Language$1.state).context;
if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) this.scheduleWork();
if (update.docChanged || update.selectionSet) {
if (this.view.hasFocus) this.chunkBudget += 50;
this.scheduleWork();
}
this.checkAsyncSchedule(cx);
}
scheduleWork() {
if (this.working) return;
let {
state
} = this.view,
field = state.field(Language$1.state);
if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) this.working = requestIdle$1(this.work);
}
work(deadline) {
this.working = null;
let now = Date.now();
if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) {
this.chunkEnd = now + 3e4;
this.chunkBudget = 3e3;
}
if (this.chunkBudget <= 0) return;
let {
state,
viewport: {
to: vpTo
}
} = this.view,
field = state.field(Language$1.state);
if (field.tree == field.context.tree && field.context.isDone(vpTo + 1e5)) return;
let endTime = Date.now() + Math.min(this.chunkBudget, 100, deadline && !isInputPending$1 ? Math.max(25, deadline.timeRemaining() - 5) : 1e9);
let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1e3;
let done = field.context.work(() => {
return isInputPending$1 && isInputPending$1() || Date.now() > endTime;
}, vpTo + (viewportFirst ? 0 : 1e5));
this.chunkBudget -= Date.now() - now;
if (done || this.chunkBudget <= 0) {
field.context.takeTree();
this.view.dispatch({
effects: Language$1.setState.of(new LanguageState$1(field.context))
});
}
if (this.chunkBudget > 0 && !(done && !viewportFirst)) this.scheduleWork();
this.checkAsyncSchedule(field.context);
}
checkAsyncSchedule(cx) {
if (cx.scheduleOn) {
this.workScheduled++;
cx.scheduleOn.then(() => this.scheduleWork()).catch(err => logException$1(this.view.state, err)).then(() => this.workScheduled--);
cx.scheduleOn = null;
}
}
destroy() {
if (this.working) this.working();
}
isWorking() {
return !!(this.working || this.workScheduled > 0);
}
}, {
eventHandlers: {
focus() {
this.scheduleWork();
}
}
});
/**
The facet used to associate a language with an editor state. Used
by `Language` object's `extension` property (so you don't need to
manually wrap your languages in this). Can be used to access the
current language on a state.
*/
language$1 = /* @__PURE__ */Facet$1.define({
combine(languages) {
return languages.length ? languages[0] : null;
},
enables: language$2 => [Language$1.state, parseWorker$1, EditorView.contentAttributes.compute([language$2], state => {
let lang = state.facet(language$2);
return lang && lang.name ? {
"data-language": lang.name
} : {};
})]
});
/**
This class bundles a [language](https://codemirror.net/6/docs/ref/#language.Language) with an
optional set of supporting extensions. Language packages are
encouraged to export a function that optionally takes a
configuration object and returns a `LanguageSupport` instance, as
the main way for client code to use the package.
*/
_export("lt", LanguageSupport = class {
/**
Create a language support object.
*/
constructor(language$2, support = []) {
this.language = language$2;
this.support = support;
this.extension = [language$2, support];
}
});
/**
Facet that defines a way to provide a function that computes the
appropriate indentation depth, as a column number (see
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)), at the start of a given
line. A return value of `null` indicates no indentation can be
determined, and the line should inherit the indentation of the one
above it. A return value of `undefined` defers to the next indent
service.
*/
indentService = /* @__PURE__ */Facet$1.define();
/**
Facet for overriding the unit by which indentation happens. Should
be a string consisting either entirely of the same whitespace
character. When not set, this defaults to 2 spaces.
*/
indentUnit = /* @__PURE__ */Facet$1.define({
combine: values => {
if (!values.length) return " ";
let unit = values[0];
if (!unit || /\S/.test(unit) || Array.from(unit).some(e => e != unit[0])) throw new Error("Invalid indent unit: " + JSON.stringify(values[0]));
return unit;
}
});
IndentContext = class {
/**
Create an indent context.
*/
constructor(state, options = {}) {
this.state = state;
this.options = options;
this.unit = getIndentUnit(state);
}
/**
Get a description of the line at the given position, taking
[simulated line
breaks](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
into account. If there is such a break at `pos`, the `bias`
argument determines whether the part of the line line before or
after the break is used.
*/
lineAt(pos, bias = 1) {
let line = this.state.doc.lineAt(pos);
let {
simulateBreak,
simulateDoubleBreak
} = this.options;
if (simulateBreak != null && simulateBreak >= line.from && simulateBreak <= line.to) if (simulateDoubleBreak && simulateBreak == pos) return {
text: "",
from: pos
};else if (bias < 0 ? simulateBreak < pos : simulateBreak <= pos) return {
text: line.text.slice(simulateBreak - line.from),
from: simulateBreak
};else return {
text: line.text.slice(0, simulateBreak - line.from),
from: line.from
};
return line;
}
/**
Get the text directly after `pos`, either the entire line
or the next 100 characters, whichever is shorter.
*/
textAfterPos(pos, bias = 1) {
if (this.options.simulateDoubleBreak && pos == this.options.simulateBreak) return "";
let {
text,
from
} = this.lineAt(pos, bias);
return text.slice(pos - from, Math.min(text.length, pos + 100 - from));
}
/**
Find the column for the given position.
*/
column(pos, bias = 1) {
let {
text,
from
} = this.lineAt(pos, bias);
let result = this.countColumn(text, pos - from);
let override = this.options.overrideIndentation ? this.options.overrideIndentation(from) : -1;
if (override > -1) result += override - this.countColumn(text, text.search(/\S|$/));
return result;
}
/**
Find the column position (taking tabs into account) of the given
position in the given string.
*/
countColumn(line, pos = line.length) {
return countColumn$1(line, this.state.tabSize, pos);
}
/**
Find the indentation column of the line at the given point.
*/
lineIndent(pos, bias = 1) {
let {
text,
from
} = this.lineAt(pos, bias);
let override = this.options.overrideIndentation;
if (override) {
let overriden = override(from);
if (overriden > -1) return overriden;
}
return this.countColumn(text, text.search(/\S|$/));
}
/**
Returns the [simulated line
break](https://codemirror.net/6/docs/ref/#language.IndentContext.constructor^options.simulateBreak)
for this context, if any.
*/
get simulatedBreak() {
return this.options.simulateBreak || null;
}
};
/**
A syntax tree node prop used to associate indentation strategies
with node types. Such a strategy is a function from an indentation
context to a column number (see also
[`indentString`](https://codemirror.net/6/docs/ref/#language.indentString)) or null, where null
indicates that no definitive indentation can be determined.
*/
_export("yt", indentNodeProp = /* @__PURE__ */new NodeProp());
TreeIndentContext = class TreeIndentContext extends IndentContext {
constructor(base$1, pos, context) {
super(base$1.state, base$1.options);
this.base = base$1;
this.pos = pos;
this.context = context;
}
/**
The syntax tree node to which the indentation strategy
applies.
*/
get node() {
return this.context.node;
}
/**
@internal
*/
static create(base$1, pos, context) {
return new TreeIndentContext(base$1, pos, context);
}
/**
Get the text directly after `this.pos`, either the entire line
or the next 100 characters, whichever is shorter.
*/
get textAfter() {
return this.textAfterPos(this.pos);
}
/**
Get the indentation at the reference line for `this.node`, which
is the line on which it starts, unless there is a node that is
_not_ a parent of this node covering the start of that line. If
so, the line at the start of that node is tried, again skipping
on if it is covered by another such node.
*/
get baseIndent() {
return this.baseIndentFor(this.node);
}
/**
Get the indentation for the reference line of the given node
(see [`baseIndent`](https://codemirror.net/6/docs/ref/#language.TreeIndentContext.baseIndent)).
*/
baseIndentFor(node) {
let line = this.state.doc.lineAt(node.from);
for (;;) {
let atBreak = node.resolve(line.from);
while (atBreak.parent && atBreak.parent.from == atBreak.from) atBreak = atBreak.parent;
if (isParent(atBreak, node)) break;
line = this.state.doc.lineAt(atBreak.from);
}
return this.lineIndent(line.from);
}
/**
Continue looking for indentations in the node's parent nodes,
and return the result of that.
*/
continue() {
return indentFor(this.context.next, this.base, this.pos);
}
};
flatIndent = context => context.baseIndent;
DontIndentBeyond = 200;
foldService = /* @__PURE__ */Facet$1.define();
/**
This node prop is used to associate folding information with
syntax node types. Given a syntax node, it should check whether
that tree is foldable and return the range that can be collapsed
when it is.
*/
_export("gt", foldNodeProp = /* @__PURE__ */new NodeProp());
foldEffect = /* @__PURE__ */StateEffect$1.define({
map: mapRange
});
/**
State effect that unfolds the given range (if it was folded).
*/
unfoldEffect = /* @__PURE__ */StateEffect$1.define({
map: mapRange
});
_export("_t", foldState = /* @__PURE__ */StateField$1.define({
create() {
return Decoration$1.none;
},
update(folded, tr) {
folded = folded.map(tr.changes);
for (let e of tr.effects) if (e.is(foldEffect) && !foldExists(folded, e.value.from, e.value.to)) {
let {
preparePlaceholder
} = tr.state.facet(foldConfig);
let widget = !preparePlaceholder ? foldWidget : Decoration$1.replace({
widget: new PreparedFoldWidget(preparePlaceholder(tr.state, e.value))
});
folded = folded.update({
add: [widget.range(e.value.from, e.value.to)]
});
} else if (e.is(unfoldEffect)) folded = folded.update({
filter: (from, to) => e.value.from != from || e.value.to != to,
filterFrom: e.value.from,
filterTo: e.value.to
});
if (tr.selection) {
let onSelection = false,
{
head
} = tr.selection.main;
folded.between(head, head, (a, b) => {
if (a < head && b > head) onSelection = true;
});
if (onSelection) folded = folded.update({
filterFrom: head,
filterTo: head,
filter: (a, b) => b <= head || a >= head
});
}
return folded;
},
provide: f => EditorView.decorations.from(f),
toJSON(folded, state) {
let ranges = [];
folded.between(0, state.doc.length, (from, to) => {
ranges.push(from, to);
});
return ranges;
},
fromJSON(value) {
if (!Array.isArray(value) || value.length % 2) throw new RangeError("Invalid JSON for fold state");
let ranges = [];
for (let i$1 = 0; i$1 < value.length;) {
let from = value[i$1++],
to = value[i$1++];
if (typeof from != "number" || typeof to != "number") throw new RangeError("Invalid JSON for fold state");
ranges.push(foldWidget.range(from, to));
}
return Decoration$1.set(ranges, true);
}
}));
foldCode = view => {
for (let line of selectedLines(view)) {
let range = foldable(view.state, line.from, line.to);
if (range) {
view.dispatch({
effects: maybeEnable(view.state, [foldEffect.of(range), announceFold(view, range)])
});
return true;
}
}
return false;
};
/**
Unfold folded ranges on selected lines.
*/
unfoldCode = view => {
if (!view.state.field(foldState, false)) return false;
let effects = [];
for (let line of selectedLines(view)) {
let folded = findFold(view.state, line.from, line.to);
if (folded) effects.push(unfoldEffect.of(folded), announceFold(view, folded, false));
}
if (effects.length) view.dispatch({
effects
});
return effects.length > 0;
};
foldAll = view => {
let {
state
} = view,
effects = [];
for (let pos = 0; pos < state.doc.length;) {
let line = view.lineBlockAt(pos),
range = foldable(state, line.from, line.to);
if (range) effects.push(foldEffect.of(range));
pos = (range ? view.lineBlockAt(range.to) : line).to + 1;
}
if (effects.length) view.dispatch({
effects: maybeEnable(view.state, effects)
});
return !!effects.length;
};
/**
Unfold all folded code.
*/
unfoldAll = view => {
let field = view.state.field(foldState, false);
if (!field || !field.size) return false;
let effects = [];
field.between(0, view.state.doc.length, (from, to) => {
effects.push(unfoldEffect.of({
from,
to
}));
});
view.dispatch({
effects
});
return true;
};
defaultConfig = {
placeholderDOM: null,
preparePlaceholder: null,
placeholderText: "…"
};
foldConfig = /* @__PURE__ */Facet$1.define({
combine(values) {
return combineConfig$1(values, defaultConfig);
}
});
foldWidget = /* @__PURE__ */Decoration$1.replace({
widget: /* @__PURE__ */new class extends WidgetType$1 {
toDOM(view) {
return widgetToDOM(view, null);
}
}()
});
PreparedFoldWidget = class extends WidgetType$1 {
constructor(value) {
super();
this.value = value;
}
eq(other) {
return this.value == other.value;
}
toDOM(view) {
return widgetToDOM(view, this.value);
}
};
foldGutterDefaults = {
openText: "⌄",
closedText: "›",
markerDOM: null,
domEventHandlers: {},
foldingChanged: () => false
};
FoldMarker = class extends GutterMarker$1 {
constructor(config$1, open) {
super();
this.config = config$1;
this.open = open;
}
eq(other) {
return this.config == other.config && this.open == other.open;
}
toDOM(view) {
if (this.config.markerDOM) return this.config.markerDOM(this.open);
let span = document.createElement("span");
span.textContent = this.open ? this.config.openText : this.config.closedText;
span.title = view.state.phrase(this.open ? "Fold line" : "Unfold line");
return span;
}
};
baseTheme$1$4 = /* @__PURE__ */EditorView.baseTheme({
".cm-foldPlaceholder": {
backgroundColor: "#eee",
border: "1px solid #ddd",
color: "#888",
borderRadius: ".2em",
margin: "0 1px",
padding: "0 1px",
cursor: "pointer"
},
".cm-foldGutter span": {
padding: "0 1px",
cursor: "pointer"
}
});
/**
A highlight style associates CSS styles with higlighting
[tags](https://lezer.codemirror.net/docs/ref#highlight.Tag).
*/
_export("st", HighlightStyle = class HighlightStyle {
constructor(specs, options) {
this.specs = specs;
let modSpec;
function def(spec) {
let cls = StyleModule.newName();
(modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
return cls;
}
const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : void 0;
const scopeOpt = options.scope;
this.scope = scopeOpt instanceof Language$1 ? type => type.prop(languageDataProp$1) == scopeOpt.data : scopeOpt ? type => type == scopeOpt : void 0;
this.style = tagHighlighter(specs.map(style => ({
tag: style.tag,
class: style.class || def(Object.assign({}, style, {
tag: null
}))
})), {
all
}).style;
this.module = modSpec ? new StyleModule(modSpec) : null;
this.themeType = options.themeType;
}
/**
Create a highlighter style that associates the given styles to
the given tags. The specs must be objects that hold a style tag
or array of tags in their `tag` property, and either a single
`class` property providing a static CSS class (for highlighter
that rely on external styling), or a
[`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
set of CSS properties (which define the styling for those tags).
The CSS rules created for a highlighter will be emitted in the
order of the spec's properties. That means that for elements that
have multiple tags associated with them, styles defined further
down in the list will have a higher CSS precedence than styles
defined earlier.
*/
static define(specs, options) {
return new HighlightStyle(specs, options || {});
}
});
highlighterFacet = /* @__PURE__ */Facet$1.define();
fallbackHighlighter = /* @__PURE__ */Facet$1.define({
combine(values) {
return values.length ? [values[0]] : null;
}
});
TreeHighlighter = class {
constructor(view) {
this.markCache = Object.create(null);
this.tree = syntaxTree$1(view.state);
this.decorations = this.buildDeco(view, getHighlighters(view.state));
this.decoratedTo = view.viewport.to;
}
update(update) {
let tree = syntaxTree$1(update.state),
highlighters = getHighlighters(update.state);
let styleChange = highlighters != getHighlighters(update.startState);
let {
viewport
} = update.view,
decoratedToMapped = update.changes.mapPos(this.decoratedTo, 1);
if (tree.length < viewport.to && !styleChange && tree.type == this.tree.type && decoratedToMapped >= viewport.to) {
this.decorations = this.decorations.map(update.changes);
this.decoratedTo = decoratedToMapped;
} else if (tree != this.tree || update.viewportChanged || styleChange) {
this.tree = tree;
this.decorations = this.buildDeco(update.view, highlighters);
this.decoratedTo = viewport.to;
}
}
buildDeco(view, highlighters) {
if (!highlighters || !this.tree.length) return Decoration$1.none;
let builder = new RangeSetBuilder$1();
for (let {
from,
to
} of view.visibleRanges) highlightTree(this.tree, highlighters, (from$1, to$1, style) => {
builder.add(from$1, to$1, this.markCache[style] || (this.markCache[style] = Decoration$1.mark({
class: style
})));
}, from, to);
return builder.finish();
}
};
treeHighlighter = /* @__PURE__ */Prec.high(/* @__PURE__ */ViewPlugin$1.fromClass(TreeHighlighter, {
decorations: v => v.decorations
}));
/**
A default highlight style (works well with light themes).
*/
defaultHighlightStyle$1 = /* @__PURE__ */HighlightStyle.define([{
tag: tags.meta,
color: "#404740"
}, {
tag: tags.link,
textDecoration: "underline"
}, {
tag: tags.heading,
textDecoration: "underline",
fontWeight: "bold"
}, {
tag: tags.emphasis,
fontStyle: "italic"
}, {
tag: tags.strong,
fontWeight: "bold"
}, {
tag: tags.strikethrough,
textDecoration: "line-through"
}, {
tag: tags.keyword,
color: "#708"
}, {
tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
color: "#219"
}, {
tag: [tags.literal, tags.inserted],
color: "#164"
}, {
tag: [tags.string, tags.deleted],
color: "#a11"
}, {
tag: [tags.regexp, tags.escape, /* @__PURE__ */tags.special(tags.string)],
color: "#e40"
}, {
tag: /* @__PURE__ */tags.definition(tags.variableName),
color: "#00f"
}, {
tag: /* @__PURE__ */tags.local(tags.variableName),
color: "#30a"
}, {
tag: [tags.typeName, tags.namespace],
color: "#085"
}, {
tag: tags.className,
color: "#167"
}, {
tag: [/* @__PURE__ */tags.special(tags.variableName), tags.macroName],
color: "#256"
}, {
tag: /* @__PURE__ */tags.definition(tags.propertyName),
color: "#00c"
}, {
tag: tags.comment,
color: "#940"
}, {
tag: tags.invalid,
color: "#f00"
}]);
baseTheme$5 = /* @__PURE__ */EditorView.baseTheme({
"&.cm-focused .cm-matchingBracket": {
backgroundColor: "#328c8252"
},
"&.cm-focused .cm-nonmatchingBracket": {
backgroundColor: "#bb555544"
}
});
DefaultScanDist = 1e4, DefaultBrackets = "()[]{}";
bracketMatchingConfig = /* @__PURE__ */Facet$1.define({
combine(configs) {
return combineConfig$1(configs, {
afterCursor: true,
brackets: DefaultBrackets,
maxScanDistance: DefaultScanDist,
renderMatch: defaultRenderMatch
});
}
});
matchingMark = /* @__PURE__ */Decoration$1.mark({
class: "cm-matchingBracket"
}), nonmatchingMark = /* @__PURE__ */Decoration$1.mark({
class: "cm-nonmatchingBracket"
});
bracketMatchingUnique = [/* @__PURE__ */StateField$1.define({
create() {
return Decoration$1.none;
},
update(deco, tr) {
if (!tr.docChanged && !tr.selection) return deco;
let decorations$2 = [];
let config$1 = tr.state.facet(bracketMatchingConfig);
for (let range of tr.state.selection.ranges) {
if (!range.empty) continue;
let match = matchBrackets(tr.state, range.head, -1, config$1) || range.head > 0 && matchBrackets(tr.state, range.head - 1, 1, config$1) || config$1.afterCursor && (matchBrackets(tr.state, range.head, 1, config$1) || range.head < tr.state.doc.length && matchBrackets(tr.state, range.head + 1, -1, config$1));
if (match) decorations$2 = decorations$2.concat(config$1.renderMatch(match, tr.state));
}
return Decoration$1.set(decorations$2, true);
},
provide: f => EditorView.decorations.from(f)
}), baseTheme$5];
bracketMatchingHandle = /* @__PURE__ */new NodeProp();
noTokens$1 = /* @__PURE__ */Object.create(null);
typeArray$1 = [NodeType.none];
warned$1 = [];
byTag$1 = /* @__PURE__ */Object.create(null);
defaultTable$1 = /* @__PURE__ */Object.create(null);
for (let [legacyName, name$1] of [["variable", "variableName"], ["variable-2", "variableName.special"], ["string-2", "string.special"], ["def", "variableName.definition"], ["tag", "tagName"], ["attribute", "attributeName"], ["type", "typeName"], ["builtin", "variableName.standard"], ["qualifier", "modifier"], ["error", "invalid"], ["header", "heading"], ["property", "propertyName"]]) defaultTable$1[legacyName] = /* @__PURE__ */createTokenType$1(noTokens$1, name$1);
marks = {
rtl: /* @__PURE__ */Decoration$1.mark({
class: "cm-iso",
inclusive: true,
attributes: {
dir: "rtl"
},
bidiIsolate: Direction$1.RTL
}),
ltr: /* @__PURE__ */Decoration$1.mark({
class: "cm-iso",
inclusive: true,
attributes: {
dir: "ltr"
},
bidiIsolate: Direction$1.LTR
}),
auto: /* @__PURE__ */Decoration$1.mark({
class: "cm-iso",
inclusive: true,
attributes: {
dir: "auto"
},
bidiIsolate: null
})
}; //#endregion
//#region ../../../node_modules/.pnpm/@codemirror+commands@6.5.0/node_modules/@codemirror/commands/dist/index.js
/**
Comment or uncomment the current selection. Will use line comments
if available, otherwise falling back to block comments.
*/
toggleComment = target => {
let {
state
} = target,
line = state.doc.lineAt(state.selection.main.from),
config$1 = getConfig(target.state, line.from);
return config$1.line ? toggleLineComment(target) : config$1.block ? toggleBlockCommentByLine(target) : false;
};
toggleLineComment = /* @__PURE__ */command(changeLineComment, 0);
/**
Comment the current selection using line comments.
*/
lineComment = /* @__PURE__ */command(changeLineComment, 1);
/**
Uncomment the current selection using line comments.
*/
lineUncomment = /* @__PURE__ */command(changeLineComment, 2);
/**
Comment or uncomment the current selection using block comments.
The block comment syntax is taken from the
[`commentTokens`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt).
*/
toggleBlockComment = /* @__PURE__ */command(changeBlockComment, 0);
/**
Comment or uncomment the lines around the current selection using
block comments.
*/
toggleBlockCommentByLine = /* @__PURE__ */command((o, s) => changeBlockComment(o, s, selectedLineRanges(s)), 0);
SearchMargin = 50;
fromHistory = /* @__PURE__ */Annotation.define();
/**
Transaction annotation that will prevent that transaction from
being combined with other transactions in the undo history. Given
`"before"`, it'll prevent merging with previous transactions. With
`"after"`, subsequent transactions won't be combined with this
one. With `"full"`, the transaction is isolated on both sides.
*/
isolateHistory = /* @__PURE__ */Annotation.define();
/**
This facet provides a way to register functions that, given a
transaction, provide a set of effects that the history should
store when inverting the transaction. This can be used to
integrate some kinds of effects in the history, so that they can
be undone (and redone again).
*/
invertedEffects = /* @__PURE__ */Facet$1.define();
historyConfig = /* @__PURE__ */Facet$1.define({
combine(configs) {
return combineConfig$1(configs, {
minDepth: 100,
newGroupDelay: 500,
joinToEvent: (_t, isAdjacent$1) => isAdjacent$1
}, {
minDepth: Math.max,
newGroupDelay: Math.min,
joinToEvent: (a, b) => (tr, adj) => a(tr, adj) || b(tr, adj)
});
}
});
historyField_ = /* @__PURE__ */StateField$1.define({
create() {
return HistoryState.empty;
},
update(state, tr) {
let config$1 = tr.state.facet(historyConfig);
let fromHist = tr.annotation(fromHistory);
if (fromHist) {
let item = HistEvent.fromTransaction(tr, fromHist.selection),
from = fromHist.side;
let other = from == 0 ? state.undone : state.done;
if (item) other = updateBranch(other, other.length, config$1.minDepth, item);else other = addSelection(other, tr.startState.selection);
return new HistoryState(from == 0 ? fromHist.rest : other, from == 0 ? other : fromHist.rest);
}
let isolate = tr.annotation(isolateHistory);
if (isolate == "full" || isolate == "before") state = state.isolate();
if (tr.annotation(Transaction.addToHistory) === false) return !tr.changes.empty ? state.addMapping(tr.changes.desc) : state;
let event = HistEvent.fromTransaction(tr);
let time = tr.annotation(Transaction.time),
userEvent = tr.annotation(Transaction.userEvent);
if (event) state = state.addChanges(event, time, userEvent, config$1, tr);else if (tr.selection) state = state.addSelection(tr.startState.selection, time, userEvent, config$1.newGroupDelay);
if (isolate == "full" || isolate == "after") state = state.isolate();
return state;
},
toJSON(value) {
return {
done: value.done.map(e => e.toJSON()),
undone: value.undone.map(e => e.toJSON())
};
},
fromJSON(json$1) {
return new HistoryState(json$1.done.map(HistEvent.fromJSON), json$1.undone.map(HistEvent.fromJSON));
}
});
_export("ot", historyField = historyField_);
undo = /* @__PURE__ */cmd(0, false);
/**
Redo a group of history events. Returns false if no group was
available.
*/
redo = /* @__PURE__ */cmd(1, false);
/**
Undo a change or selection change.
*/
undoSelection = /* @__PURE__ */cmd(0, true);
HistEvent = class HistEvent {
constructor(changes, effects, mapped, startSelection, selectionsAfter) {
this.changes = changes;
this.effects = effects;
this.mapped = mapped;
this.startSelection = startSelection;
this.selectionsAfter = selectionsAfter;
}
setSelAfter(after) {
return new HistEvent(this.changes, this.effects, this.mapped, this.startSelection, after);
}
toJSON() {
var _a$2, _b, _c;
return {
changes: (_a$2 = this.changes) === null || _a$2 === void 0 ? void 0 : _a$2.toJSON(),
mapped: (_b = this.mapped) === null || _b === void 0 ? void 0 : _b.toJSON(),
startSelection: (_c = this.startSelection) === null || _c === void 0 ? void 0 : _c.toJSON(),
selectionsAfter: this.selectionsAfter.map(s => s.toJSON())
};
}
static fromJSON(json$1) {
return new HistEvent(json$1.changes && ChangeSet.fromJSON(json$1.changes), [], json$1.mapped && ChangeDesc$1.fromJSON(json$1.mapped), json$1.startSelection && EditorSelection.fromJSON(json$1.startSelection), json$1.selectionsAfter.map(EditorSelection.fromJSON));
}
static fromTransaction(tr, selection) {
let effects = none$2;
for (let invert of tr.startState.facet(invertedEffects)) {
let result = invert(tr);
if (result.length) effects = effects.concat(result);
}
if (!effects.length && tr.changes.empty) return null;
return new HistEvent(tr.changes.invert(tr.startState.doc), effects, void 0, selection || tr.startState.selection, none$2);
}
static selection(selections) {
return new HistEvent(void 0, none$2, void 0, void 0, selections);
}
};
none$2 = [];
MaxSelectionsPerEvent = 200;
joinableUserEvent = /^(input\.type|delete)($|\.)/;
HistoryState = class HistoryState {
constructor(done, undone, prevTime = 0, prevUserEvent = void 0) {
this.done = done;
this.undone = undone;
this.prevTime = prevTime;
this.prevUserEvent = prevUserEvent;
}
isolate() {
return this.prevTime ? new HistoryState(this.done, this.undone) : this;
}
addChanges(event, time, userEvent, config$1, tr) {
let done = this.done,
lastEvent = done[done.length - 1];
if (lastEvent && lastEvent.changes && !lastEvent.changes.empty && event.changes && (!userEvent || joinableUserEvent.test(userEvent)) && (!lastEvent.selectionsAfter.length && time - this.prevTime < config$1.newGroupDelay && config$1.joinToEvent(tr, isAdjacent(lastEvent.changes, event.changes)) || userEvent == "input.type.compose")) done = updateBranch(done, done.length - 1, config$1.minDepth, new HistEvent(event.changes.compose(lastEvent.changes), conc(event.effects, lastEvent.effects), lastEvent.mapped, lastEvent.startSelection, none$2));else done = updateBranch(done, done.length, config$1.minDepth, event);
return new HistoryState(done, none$2, time, userEvent);
}
addSelection(selection, time, userEvent, newGroupDelay) {
let last = this.done.length ? this.done[this.done.length - 1].selectionsAfter : none$2;
if (last.length > 0 && time - this.prevTime < newGroupDelay && userEvent == this.prevUserEvent && userEvent && /^select($|\.)/.test(userEvent) && eqSelectionShape(last[last.length - 1], selection)) return this;
return new HistoryState(addSelection(this.done, selection), this.undone, time, userEvent);
}
addMapping(mapping) {
return new HistoryState(addMappingToBranch(this.done, mapping), addMappingToBranch(this.undone, mapping), this.prevTime, this.prevUserEvent);
}
pop(side, state, onlySelection) {
let branch = side == 0 ? this.done : this.undone;
if (branch.length == 0) return null;
let event = branch[branch.length - 1],
selection = event.selectionsAfter[0] || state.selection;
if (onlySelection && event.selectionsAfter.length) return state.update({
selection: event.selectionsAfter[event.selectionsAfter.length - 1],
annotations: fromHistory.of({
side,
rest: popSelection(branch),
selection
}),
userEvent: side == 0 ? "select.undo" : "select.redo",
scrollIntoView: true
});else if (!event.changes) return null;else {
let rest = branch.length == 1 ? none$2 : branch.slice(0, branch.length - 1);
if (event.mapped) rest = addMappingToBranch(rest, event.mapped);
return state.update({
changes: event.changes,
selection: event.startSelection,
effects: event.effects,
annotations: fromHistory.of({
side,
rest,
selection
}),
filter: false,
userEvent: side == 0 ? "undo" : "redo",
scrollIntoView: true
});
}
}
};
HistoryState.empty = /* @__PURE__ */new HistoryState(none$2, none$2);
cursorCharLeft = view => cursorByChar(view, !ltrAtCursor(view));
/**
Move the selection one character to the right.
*/
cursorCharRight = view => cursorByChar(view, ltrAtCursor(view));
cursorGroupLeft = view => cursorByGroup(view, !ltrAtCursor(view));
/**
Move the selection one group to the right.
*/
cursorGroupRight = view => cursorByGroup(view, ltrAtCursor(view));
segmenter = typeof Intl != "undefined" && Intl.Segmenter ? /* @__PURE__ */new Intl.Segmenter(void 0, {
granularity: "word"
}) : null;
cursorLineUp = view => cursorByLine(view, false);
/**
Move the selection one line down.
*/
cursorLineDown = view => cursorByLine(view, true);
cursorPageUp = view => cursorByPage(view, false);
/**
Move the selection one page down.
*/
cursorPageDown = view => cursorByPage(view, true);
cursorLineBoundaryForward = view => moveSel(view, range => moveByLineBoundary(view, range, true));
/**
Move the selection to previous line wrap point, or failing that to
the start of the line. If the line is indented, and the cursor
isn't already at the end of the indentation, this will move to the
end of the indentation instead of the start of the line.
*/
cursorLineBoundaryBackward = view => moveSel(view, range => moveByLineBoundary(view, range, false));
/**
Move the selection to the start of the line.
*/
cursorLineStart = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from, 1));
/**
Move the selection to the end of the line.
*/
cursorLineEnd = view => moveSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to, -1));
cursorMatchingBracket = ({
state,
dispatch
}) => toMatchingBracket(state, dispatch, false);
selectCharLeft = view => selectByChar(view, !ltrAtCursor(view));
/**
Move the selection head one character to the right.
*/
selectCharRight = view => selectByChar(view, ltrAtCursor(view));
selectGroupLeft = view => selectByGroup(view, !ltrAtCursor(view));
/**
Move the selection head one group to the right.
*/
selectGroupRight = view => selectByGroup(view, ltrAtCursor(view));
selectLineUp = view => selectByLine(view, false);
/**
Move the selection head one line down.
*/
selectLineDown = view => selectByLine(view, true);
selectPageUp = view => selectByPage(view, false);
/**
Move the selection head one page down.
*/
selectPageDown = view => selectByPage(view, true);
/**
Move the selection head to the next line boundary.
*/
selectLineBoundaryForward = view => extendSel(view, range => moveByLineBoundary(view, range, true));
/**
Move the selection head to the previous line boundary.
*/
selectLineBoundaryBackward = view => extendSel(view, range => moveByLineBoundary(view, range, false));
/**
Move the selection head to the start of the line.
*/
selectLineStart = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).from));
/**
Move the selection head to the end of the line.
*/
selectLineEnd = view => extendSel(view, range => EditorSelection.cursor(view.lineBlockAt(range.head).to));
/**
Move the selection to the start of the document.
*/
cursorDocStart = ({
state,
dispatch
}) => {
dispatch(setSel(state, {
anchor: 0
}));
return true;
};
/**
Move the selection to the end of the document.
*/
cursorDocEnd = ({
state,
dispatch
}) => {
dispatch(setSel(state, {
anchor: state.doc.length
}));
return true;
};
/**
Move the selection head to the start of the document.
*/
selectDocStart = ({
state,
dispatch
}) => {
dispatch(setSel(state, {
anchor: state.selection.main.anchor,
head: 0
}));
return true;
};
/**
Move the selection head to the end of the document.
*/
selectDocEnd = ({
state,
dispatch
}) => {
dispatch(setSel(state, {
anchor: state.selection.main.anchor,
head: state.doc.length
}));
return true;
};
/**
Select the entire document.
*/
selectAll = ({
state,
dispatch
}) => {
dispatch(state.update({
selection: {
anchor: 0,
head: state.doc.length
},
userEvent: "select"
}));
return true;
};
/**
Expand the selection to cover entire lines.
*/
selectLine = ({
state,
dispatch
}) => {
let ranges = selectedLineBlocks(state).map(({
from,
to
}) => EditorSelection.range(from, Math.min(to + 1, state.doc.length)));
dispatch(state.update({
selection: EditorSelection.create(ranges),
userEvent: "select"
}));
return true;
};
deleteByChar = (target, forward, byIndentUnit) => deleteBy(target, range => {
let pos = range.from,
{
state
} = target,
line = state.doc.lineAt(pos),
before,
targetPos;
if (byIndentUnit && !forward && pos > line.from && pos < line.from + 200 && !/[^ \t]/.test(before = line.text.slice(0, pos - line.from))) {
if (before[before.length - 1] == " ") return pos - 1;
let drop = countColumn$1(before, state.tabSize) % getIndentUnit(state) || getIndentUnit(state);
for (let i$1 = 0; i$1 < drop && before[before.length - 1 - i$1] == " "; i$1++) pos--;
targetPos = pos;
} else {
targetPos = findClusterBreak(line.text, pos - line.from, forward, forward) + line.from;
if (targetPos == pos && line.number != (forward ? state.doc.lines : 1)) targetPos += forward ? 1 : -1;else if (!forward && /[\ufe00-\ufe0f]/.test(line.text.slice(targetPos - line.from, pos - line.from))) targetPos = findClusterBreak(line.text, targetPos - line.from, false, false) + line.from;
}
return targetPos;
});
/**
Delete the selection, or, for cursor selections, the character or
indentation unit before the cursor.
*/
deleteCharBackward = view => deleteByChar(view, false, true);
/**
Delete the selection or the character after the cursor.
*/
deleteCharForward = view => deleteByChar(view, true, false);
deleteByGroup = (target, forward) => deleteBy(target, range => {
let pos = range.head,
{
state
} = target,
line = state.doc.lineAt(pos);
let categorize = state.charCategorizer(pos);
for (let cat = null;;) {
if (pos == (forward ? line.to : line.from)) {
if (pos == range.head && line.number != (forward ? state.doc.lines : 1)) pos += forward ? 1 : -1;
break;
}
let next = findClusterBreak(line.text, pos - line.from, forward) + line.from;
let nextChar$1 = line.text.slice(Math.min(pos, next) - line.from, Math.max(pos, next) - line.from);
let nextCat = categorize(nextChar$1);
if (cat != null && nextCat != cat) break;
if (nextChar$1 != " " || pos != range.head) cat = nextCat;
pos = next;
}
return pos;
});
/**
Delete the selection or backward until the end of the next
[group](https://codemirror.net/6/docs/ref/#view.EditorView.moveByGroup), only skipping groups of
whitespace when they consist of a single space.
*/
deleteGroupBackward = target => deleteByGroup(target, false);
/**
Delete the selection or forward until the end of the next group.
*/
deleteGroupForward = target => deleteByGroup(target, true);
/**
Delete the selection, or, if it is a cursor selection, delete to
the end of the line. If the cursor is directly at the end of the
line, delete the line break after it.
*/
deleteToLineEnd = view => deleteBy(view, range => {
let lineEnd = view.lineBlockAt(range.head).to;
return range.head < lineEnd ? lineEnd : Math.min(view.state.doc.length, range.head + 1);
});
/**
Delete the selection, or, if it is a cursor selection, delete to
the start of the line. If the cursor is directly at the start of the
line, delete the line break before it.
*/
deleteToLineStart = view => deleteBy(view, range => {
let lineStart = view.lineBlockAt(range.head).from;
return range.head > lineStart ? lineStart : Math.max(0, range.head - 1);
});
/**
Replace each selection range with a line break, leaving the cursor
on the line before the break.
*/
splitLine = ({
state,
dispatch
}) => {
if (state.readOnly) return false;
let changes = state.changeByRange(range => {
return {
changes: {
from: range.from,
to: range.to,
insert: Text.of(["", ""])
},
range: EditorSelection.cursor(range.from)
};
});
dispatch(state.update(changes, {
scrollIntoView: true,
userEvent: "input"
}));
return true;
};
/**
Flip the characters before and after the cursor(s).
*/
transposeChars = ({
state,
dispatch
}) => {
if (state.readOnly) return false;
let changes = state.changeByRange(range => {
if (!range.empty || range.from == 0 || range.from == state.doc.length) return {
range
};
let pos = range.from,
line = state.doc.lineAt(pos);
let from = pos == line.from ? pos - 1 : findClusterBreak(line.text, pos - line.from, false) + line.from;
let to = pos == line.to ? pos + 1 : findClusterBreak(line.text, pos - line.from, true) + line.from;
return {
changes: {
from,
to,
insert: state.doc.slice(pos, to).append(state.doc.slice(from, pos))
},
range: EditorSelection.cursor(to)
};
});
if (changes.changes.empty) return false;
dispatch(state.update(changes, {
scrollIntoView: true,
userEvent: "move.character"
}));
return true;
};
moveLineUp = ({
state,
dispatch
}) => moveLine(state, dispatch, false);
/**
Move the selected lines down one line.
*/
moveLineDown = ({
state,
dispatch
}) => moveLine(state, dispatch, true);
copyLineUp = ({
state,
dispatch
}) => copyLine(state, dispatch, false);
/**
Create a copy of the selected lines. Keep the selection in the bottom copy.
*/
copyLineDown = ({
state,
dispatch
}) => copyLine(state, dispatch, true);
/**
Delete selected lines.
*/
deleteLine = view => {
if (view.state.readOnly) return false;
let {
state
} = view,
changes = state.changes(selectedLineBlocks(state).map(({
from,
to
}) => {
if (from > 0) from--;else if (to < state.doc.length) to++;
return {
from,
to
};
}));
let selection = updateSel(state.selection, range => {
let dist$2 = void 0;
if (view.lineWrapping) {
let block = view.lineBlockAt(range.head),
pos = view.coordsAtPos(range.head, range.assoc || 1);
if (pos) dist$2 = block.bottom + view.documentTop - pos.bottom + view.defaultLineHeight / 2;
}
return view.moveVertically(range, true, dist$2);
}).map(changes);
view.dispatch({
changes,
selection,
scrollIntoView: true,
userEvent: "delete.line"
});
return true;
};
insertNewlineAndIndent = /* @__PURE__ */newlineAndIndent(false);
indentMore = ({
state,
dispatch
}) => {
if (state.readOnly) return false;
dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
changes.push({
from: line.from,
insert: state.facet(indentUnit)
});
}), {
userEvent: "input.indent"
}));
return true;
};
/**
Remove a [unit](https://codemirror.net/6/docs/ref/#language.indentUnit) of indentation from all
selected lines.
*/
indentLess = ({
state,
dispatch
}) => {
if (state.readOnly) return false;
dispatch(state.update(changeBySelectedLine(state, (line, changes) => {
let space$1 = /^\s*/.exec(line.text)[0];
if (!space$1) return;
let col = countColumn$1(space$1, state.tabSize),
keep = 0;
let insert$2 = indentString(state, Math.max(0, col - getIndentUnit(state)));
while (keep < space$1.length && keep < insert$2.length && space$1.charCodeAt(keep) == insert$2.charCodeAt(keep)) keep++;
changes.push({
from: line.from + keep,
to: line.from + space$1.length,
insert: insert$2.slice(keep)
});
}), {
userEvent: "delete.dedent"
}));
return true;
}; //#endregion
//#region ../../../node_modules/.pnpm/@codemirror+autocomplete@6.16.0_@codemirror+language@6.10.1_@codemirror+state@6.4.1_@co_04cea374553a6c4341e0cc5f5f6a6a66/node_modules/@codemirror/autocomplete/dist/index.js
/**
An instance of this is passed to completion source functions.
*/
_export("q", CompletionContext = class {
/**
Create a new completion context. (Mostly useful for testing
completion sources—in the editor, the extension will create
these for you.)
*/
constructor(state, pos, explicit) {
this.state = state;
this.pos = pos;
this.explicit = explicit;
/**
@internal
*/
this.abortListeners = [];
}
/**
Get the extent, content, and (if there is a token) type of the
token before `this.pos`.
*/
tokenBefore(types$2) {
let token = syntaxTree$1(this.state).resolveInner(this.pos, -1);
while (token && types$2.indexOf(token.name) < 0) token = token.parent;
return token ? {
from: token.from,
to: this.pos,
text: this.state.sliceDoc(token.from, this.pos),
type: token.type
} : null;
}
/**
Get the match of the given expression directly before the
cursor.
*/
matchBefore(expr) {
let line = this.state.doc.lineAt(this.pos);
let start = Math.max(line.from, this.pos - 250);
let str = line.text.slice(start - line.from, this.pos - line.from);
let found = str.search(ensureAnchor(expr, false));
return found < 0 ? null : {
from: start + found,
to: this.pos,
text: str.slice(found)
};
}
/**
Yields true when the query has been aborted. Can be useful in
asynchronous queries to avoid doing work that will be ignored.
*/
get aborted() {
return this.abortListeners == null;
}
/**
Allows you to register abort handlers, which will be called when
the query is
[aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
*/
addEventListener(type, listener) {
if (type == "abort" && this.abortListeners) this.abortListeners.push(listener);
}
});
Option = class {
constructor(completion, source, match, score$1) {
this.completion = completion;
this.source = source;
this.match = match;
this.score = score$1;
}
};
_export("nt", pickedCompletion = /* @__PURE__ */Annotation.define());
SourceCache = /* @__PURE__ */new WeakMap();
startCompletionEffect = /* @__PURE__ */StateEffect$1.define();
closeCompletionEffect = /* @__PURE__ */StateEffect$1.define();
FuzzyMatcher = class {
constructor(pattern) {
this.pattern = pattern;
this.chars = [];
this.folded = [];
this.any = [];
this.precise = [];
this.byWord = [];
this.score = 0;
this.matched = [];
for (let p = 0; p < pattern.length;) {
let char = codePointAt(pattern, p),
size = codePointSize(char);
this.chars.push(char);
let part = pattern.slice(p, p + size),
upper = part.toUpperCase();
this.folded.push(codePointAt(upper == part ? part.toLowerCase() : upper, 0));
p += size;
}
this.astral = pattern.length != this.chars.length;
}
ret(score$1, matched) {
this.score = score$1;
this.matched = matched;
return this;
}
match(word) {
if (this.pattern.length == 0) return this.ret(-100, []);
if (word.length < this.pattern.length) return null;
let {
chars,
folded,
any,
precise,
byWord
} = this;
if (chars.length == 1) {
let first = codePointAt(word, 0),
firstSize = codePointSize(first);
let score$1 = firstSize == word.length ? 0 : -100;
if (first == chars[0]) ;else if (first == folded[0]) score$1 += -200;else return null;
return this.ret(score$1, [0, firstSize]);
}
let direct = word.indexOf(this.pattern);
if (direct == 0) return this.ret(word.length == this.pattern.length ? 0 : -100, [0, this.pattern.length]);
let len = chars.length,
anyTo = 0;
if (direct < 0) {
for (let i$1 = 0, e = Math.min(word.length, 200); i$1 < e && anyTo < len;) {
let next = codePointAt(word, i$1);
if (next == chars[anyTo] || next == folded[anyTo]) any[anyTo++] = i$1;
i$1 += codePointSize(next);
}
if (anyTo < len) return null;
}
let preciseTo = 0;
let byWordTo = 0,
byWordFolded = false;
let adjacentTo = 0,
adjacentStart = -1,
adjacentEnd = -1;
let hasLower = /[a-z]/.test(word),
wordAdjacent = true;
for (let i$1 = 0, e = Math.min(word.length, 200), prevType = 0; i$1 < e && byWordTo < len;) {
let next = codePointAt(word, i$1);
if (direct < 0) {
if (preciseTo < len && next == chars[preciseTo]) precise[preciseTo++] = i$1;
if (adjacentTo < len) if (next == chars[adjacentTo] || next == folded[adjacentTo]) {
if (adjacentTo == 0) adjacentStart = i$1;
adjacentEnd = i$1 + 1;
adjacentTo++;
} else adjacentTo = 0;
}
let ch,
type = next < 255 ? next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 : next >= 65 && next <= 90 ? 1 : 0 : (ch = fromCodePoint(next)) != ch.toLowerCase() ? 1 : ch != ch.toUpperCase() ? 2 : 0;
if (!i$1 || type == 1 && hasLower || prevType == 0 && type != 0) {
if (chars[byWordTo] == next || folded[byWordTo] == next && (byWordFolded = true)) byWord[byWordTo++] = i$1;else if (byWord.length) wordAdjacent = false;
}
prevType = type;
i$1 += codePointSize(next);
}
if (byWordTo == len && byWord[0] == 0 && wordAdjacent) return this.result(-100 + (byWordFolded ? -200 : 0), byWord, word);
if (adjacentTo == len && adjacentStart == 0) return this.ret(-200 - word.length + (adjacentEnd == word.length ? 0 : -100), [0, adjacentEnd]);
if (direct > -1) return this.ret(-700 - word.length, [direct, direct + this.pattern.length]);
if (adjacentTo == len) return this.ret(-900 - word.length, [adjacentStart, adjacentEnd]);
if (byWordTo == len) return this.result(-100 + (byWordFolded ? -200 : 0) + -700 + (wordAdjacent ? 0 : -1100), byWord, word);
return chars.length == 2 ? null : this.result((any[0] ? -700 : 0) + -200 + -1100, any, word);
}
result(score$1, positions, word) {
let result = [],
i$1 = 0;
for (let pos of positions) {
let to = pos + (this.astral ? codePointSize(codePointAt(word, pos)) : 1);
if (i$1 && result[i$1 - 1] == pos) result[i$1 - 1] = to;else {
result[i$1++] = pos;
result[i$1++] = to;
}
}
return this.ret(score$1 - word.length, result);
}
};
StrictMatcher = class {
constructor(pattern) {
this.pattern = pattern;
this.matched = [];
this.score = 0;
this.folded = pattern.toLowerCase();
}
match(word) {
if (word.length < this.pattern.length) return null;
let start = word.slice(0, this.pattern.length);
let match = start == this.pattern ? 0 : start.toLowerCase() == this.folded ? -200 : null;
if (match == null) return null;
this.matched = [0, start.length];
this.score = match + (word.length == this.pattern.length ? 0 : -100);
return this;
}
};
completionConfig = /* @__PURE__ */Facet$1.define({
combine(configs) {
return combineConfig$1(configs, {
activateOnTyping: true,
activateOnCompletion: () => false,
activateOnTypingDelay: 100,
selectOnOpen: true,
override: null,
closeOnBlur: true,
maxRenderedOptions: 100,
defaultKeymap: true,
tooltipClass: () => "",
optionClass: () => "",
aboveCursor: false,
icons: true,
addToOptions: [],
positionInfo: defaultPositionInfo,
filterStrict: false,
compareCompletions: (a, b) => a.label.localeCompare(b.label),
interactionDelay: 75,
updateSyncTime: 100
}, {
defaultKeymap: (a, b) => a && b,
closeOnBlur: (a, b) => a && b,
icons: (a, b) => a && b,
tooltipClass: (a, b) => c => joinClass(a(c), b(c)),
optionClass: (a, b) => c => joinClass(a(c), b(c)),
addToOptions: (a, b) => a.concat(b),
filterStrict: (a, b) => a || b
});
}
});
CompletionTooltip = class {
constructor(view, stateField, applyCompletion$2) {
this.view = view;
this.stateField = stateField;
this.applyCompletion = applyCompletion$2;
this.info = null;
this.infoDestroy = null;
this.placeInfoReq = {
read: () => this.measureInfo(),
write: pos => this.placeInfo(pos),
key: this
};
this.space = null;
this.currentClass = "";
let cState = view.state.field(stateField);
let {
options,
selected
} = cState.open;
let config$1 = view.state.facet(completionConfig);
this.optionContent = optionContent(config$1);
this.optionClass = config$1.optionClass;
this.tooltipClass = config$1.tooltipClass;
this.range = rangeAroundSelected(options.length, selected, config$1.maxRenderedOptions);
this.dom = document.createElement("div");
this.dom.className = "cm-tooltip-autocomplete";
this.updateTooltipClass(view.state);
this.dom.addEventListener("mousedown", e => {
let {
options: options$1
} = view.state.field(stateField).open;
for (let dom = e.target, match; dom && dom != this.dom; dom = dom.parentNode) if (dom.nodeName == "LI" && (match = /-(\d+)$/.exec(dom.id)) && +match[1] < options$1.length) {
this.applyCompletion(view, options$1[+match[1]]);
e.preventDefault();
return;
}
});
this.dom.addEventListener("focusout", e => {
let state = view.state.field(this.stateField, false);
if (state && state.tooltip && view.state.facet(completionConfig).closeOnBlur && e.relatedTarget != view.contentDOM) view.dispatch({
effects: closeCompletionEffect.of(null)
});
});
this.showOptions(options, cState.id);
}
mount() {
this.updateSel();
}
showOptions(options, id$1) {
if (this.list) this.list.remove();
this.list = this.dom.appendChild(this.createListBox(options, id$1, this.range));
this.list.addEventListener("scroll", () => {
if (this.info) this.view.requestMeasure(this.placeInfoReq);
});
}
update(update) {
var _a$2;
let cState = update.state.field(this.stateField);
let prevState = update.startState.field(this.stateField);
this.updateTooltipClass(update.state);
if (cState != prevState) {
let {
options,
selected,
disabled
} = cState.open;
if (!prevState.open || prevState.open.options != options) {
this.range = rangeAroundSelected(options.length, selected, update.state.facet(completionConfig).maxRenderedOptions);
this.showOptions(options, cState.id);
}
this.updateSel();
if (disabled != ((_a$2 = prevState.open) === null || _a$2 === void 0 ? void 0 : _a$2.disabled)) this.dom.classList.toggle("cm-tooltip-autocomplete-disabled", !!disabled);
}
}
updateTooltipClass(state) {
let cls = this.tooltipClass(state);
if (cls != this.currentClass) {
for (let c of this.currentClass.split(" ")) if (c) this.dom.classList.remove(c);
for (let c of cls.split(" ")) if (c) this.dom.classList.add(c);
this.currentClass = cls;
}
}
positioned(space$1) {
this.space = space$1;
if (this.info) this.view.requestMeasure(this.placeInfoReq);
}
updateSel() {
let cState = this.view.state.field(this.stateField),
open = cState.open;
if (open.selected > -1 && open.selected < this.range.from || open.selected >= this.range.to) {
this.range = rangeAroundSelected(open.options.length, open.selected, this.view.state.facet(completionConfig).maxRenderedOptions);
this.showOptions(open.options, cState.id);
}
if (this.updateSelectedOption(open.selected)) {
this.destroyInfo();
let {
completion
} = open.options[open.selected];
let {
info
} = completion;
if (!info) return;
let infoResult = typeof info === "string" ? document.createTextNode(info) : info(completion);
if (!infoResult) return;
if ("then" in infoResult) infoResult.then(obj => {
if (obj && this.view.state.field(this.stateField, false) == cState) this.addInfoPane(obj, completion);
}).catch(e => logException$1(this.view.state, e, "completion info"));else this.addInfoPane(infoResult, completion);
}
}
addInfoPane(content$1, completion) {
this.destroyInfo();
let wrap = this.info = document.createElement("div");
wrap.className = "cm-tooltip cm-completionInfo";
if (content$1.nodeType != null) {
wrap.appendChild(content$1);
this.infoDestroy = null;
} else {
let {
dom,
destroy
} = content$1;
wrap.appendChild(dom);
this.infoDestroy = destroy || null;
}
this.dom.appendChild(wrap);
this.view.requestMeasure(this.placeInfoReq);
}
updateSelectedOption(selected) {
let set = null;
for (let opt = this.list.firstChild, i$1 = this.range.from; opt; opt = opt.nextSibling, i$1++) if (opt.nodeName != "LI" || !opt.id) i$1--;else if (i$1 == selected) {
if (!opt.hasAttribute("aria-selected")) {
opt.setAttribute("aria-selected", "true");
set = opt;
}
} else if (opt.hasAttribute("aria-selected")) opt.removeAttribute("aria-selected");
if (set) scrollIntoView$1(this.list, set);
return set;
}
measureInfo() {
let sel = this.dom.querySelector("[aria-selected]");
if (!sel || !this.info) return null;
let listRect = this.dom.getBoundingClientRect();
let infoRect = this.info.getBoundingClientRect();
let selRect = sel.getBoundingClientRect();
let space$1 = this.space;
if (!space$1) {
let win = this.dom.ownerDocument.defaultView || window;
space$1 = {
left: 0,
top: 0,
right: win.innerWidth,
bottom: win.innerHeight
};
}
if (selRect.top > Math.min(space$1.bottom, listRect.bottom) - 10 || selRect.bottom < Math.max(space$1.top, listRect.top) + 10) return null;
return this.view.state.facet(completionConfig).positionInfo(this.view, listRect, selRect, infoRect, space$1, this.dom);
}
placeInfo(pos) {
if (this.info) if (pos) {
if (pos.style) this.info.style.cssText = pos.style;
this.info.className = "cm-tooltip cm-completionInfo " + (pos.class || "");
} else this.info.style.cssText = "top: -1e6px";
}
createListBox(options, id$1, range) {
const ul = document.createElement("ul");
ul.id = id$1;
ul.setAttribute("role", "listbox");
ul.setAttribute("aria-expanded", "true");
ul.setAttribute("aria-label", this.view.state.phrase("Completions"));
let curSection = null;
for (let i$1 = range.from; i$1 < range.to; i$1++) {
let {
completion,
match
} = options[i$1],
{
section
} = completion;
if (section) {
let name$1 = typeof section == "string" ? section : section.name;
if (name$1 != curSection && (i$1 > range.from || range.from == 0)) {
curSection = name$1;
if (typeof section != "string" && section.header) ul.appendChild(section.header(section));else {
let header$1 = ul.appendChild(document.createElement("completion-section"));
header$1.textContent = name$1;
}
}
}
const li = ul.appendChild(document.createElement("li"));
li.id = id$1 + "-" + i$1;
li.setAttribute("role", "option");
let cls = this.optionClass(completion);
if (cls) li.className = cls;
for (let source of this.optionContent) {
let node = source(completion, this.view.state, this.view, match);
if (node) li.appendChild(node);
}
}
if (range.from) ul.classList.add("cm-completionListIncompleteTop");
if (range.to < options.length) ul.classList.add("cm-completionListIncompleteBottom");
return ul;
}
destroyInfo() {
if (this.info) {
if (this.infoDestroy) this.infoDestroy();
this.info.remove();
this.info = null;
}
}
destroy() {
this.destroyInfo();
}
};
CompletionDialog = class CompletionDialog {
constructor(options, attrs, tooltip, timestamp, selected, disabled) {
this.options = options;
this.attrs = attrs;
this.tooltip = tooltip;
this.timestamp = timestamp;
this.selected = selected;
this.disabled = disabled;
}
setSelected(selected, id$1) {
return selected == this.selected || selected >= this.options.length ? this : new CompletionDialog(this.options, makeAttrs(id$1, selected), this.tooltip, this.timestamp, selected, this.disabled);
}
static build(active, state, id$1, prev, conf) {
let options = sortOptions(active, state);
if (!options.length) return prev && active.some(a => a.state == 1) ? new CompletionDialog(prev.options, prev.attrs, prev.tooltip, prev.timestamp, prev.selected, true) : null;
let selected = state.facet(completionConfig).selectOnOpen ? 0 : -1;
if (prev && prev.selected != selected && prev.selected != -1) {
let selectedValue = prev.options[prev.selected].completion;
for (let i$1 = 0; i$1 < options.length; i$1++) if (options[i$1].completion == selectedValue) {
selected = i$1;
break;
}
}
return new CompletionDialog(options, makeAttrs(id$1, selected), {
pos: active.reduce((a, b) => b.hasResult() ? Math.min(a, b.from) : a, 1e8),
create: createTooltip,
above: conf.aboveCursor
}, prev ? prev.timestamp : Date.now(), selected, false);
}
map(changes) {
return new CompletionDialog(this.options, this.attrs, Object.assign(Object.assign({}, this.tooltip), {
pos: changes.mapPos(this.tooltip.pos)
}), this.timestamp, this.selected, this.disabled);
}
};
CompletionState = class CompletionState {
constructor(active, id$1, open) {
this.active = active;
this.id = id$1;
this.open = open;
}
static start() {
return new CompletionState(none$1, "cm-ac-" + Math.floor(Math.random() * 2e6).toString(36), null);
}
update(tr) {
let {
state
} = tr,
conf = state.facet(completionConfig);
let active = (conf.override || state.languageDataAt("autocomplete", cur(state)).map(asSource)).map(source => {
return (this.active.find(s => s.source == source) || new ActiveSource(source, this.active.some(a => a.state != 0) ? 1 : 0)).update(tr, conf);
});
if (active.length == this.active.length && active.every((a, i$1) => a == this.active[i$1])) active = this.active;
let open = this.open;
if (open && tr.docChanged) open = open.map(tr.changes);
if (tr.selection || active.some(a => a.hasResult() && tr.changes.touchesRange(a.from, a.to)) || !sameResults(active, this.active)) open = CompletionDialog.build(active, state, this.id, open, conf);else if (open && open.disabled && !active.some(a => a.state == 1)) open = null;
if (!open && active.every(a => a.state != 1) && active.some(a => a.hasResult())) active = active.map(a => a.hasResult() ? new ActiveSource(a.source, 0) : a);
for (let effect of tr.effects) if (effect.is(setSelectedEffect)) open = open && open.setSelected(effect.value, this.id);
return active == this.active && open == this.open ? this : new CompletionState(active, this.id, open);
}
get tooltip() {
return this.open ? this.open.tooltip : null;
}
get attrs() {
return this.open ? this.open.attrs : baseAttrs;
}
};
baseAttrs = {
"aria-autocomplete": "list"
};
none$1 = [];
ActiveSource = class ActiveSource {
constructor(source, state, explicitPos = -1) {
this.source = source;
this.state = state;
this.explicitPos = explicitPos;
}
hasResult() {
return false;
}
update(tr, conf) {
let event = getUserEvent(tr, conf),
value = this;
if (event) value = value.handleUserEvent(tr, event, conf);else if (tr.docChanged) value = value.handleChange(tr);else if (tr.selection && value.state != 0) value = new ActiveSource(value.source, 0);
for (let effect of tr.effects) if (effect.is(startCompletionEffect)) value = new ActiveSource(value.source, 1, effect.value ? cur(tr.state) : -1);else if (effect.is(closeCompletionEffect)) value = new ActiveSource(value.source, 0);else if (effect.is(setActiveEffect)) {
for (let active of effect.value) if (active.source == value.source) value = active;
}
return value;
}
handleUserEvent(tr, type, conf) {
return type == "delete" || !conf.activateOnTyping ? this.map(tr.changes) : new ActiveSource(this.source, 1);
}
handleChange(tr) {
return tr.changes.touchesRange(cur(tr.startState)) ? new ActiveSource(this.source, 0) : this.map(tr.changes);
}
map(changes) {
return changes.empty || this.explicitPos < 0 ? this : new ActiveSource(this.source, this.state, changes.mapPos(this.explicitPos));
}
};
ActiveResult = class ActiveResult extends ActiveSource {
constructor(source, explicitPos, result, from, to) {
super(source, 2, explicitPos);
this.result = result;
this.from = from;
this.to = to;
}
hasResult() {
return true;
}
handleUserEvent(tr, type, conf) {
var _a$2;
let result = this.result;
if (result.map && !tr.changes.empty) result = result.map(result, tr.changes);
let from = tr.changes.mapPos(this.from),
to = tr.changes.mapPos(this.to, 1);
let pos = cur(tr.state);
if ((this.explicitPos < 0 ? pos <= from : pos < this.from) || pos > to || !result || type == "delete" && cur(tr.startState) == this.from) return new ActiveSource(this.source, type == "input" && conf.activateOnTyping ? 1 : 0);
let explicitPos = this.explicitPos < 0 ? -1 : tr.changes.mapPos(this.explicitPos);
if (checkValid(result.validFor, tr.state, from, to)) return new ActiveResult(this.source, explicitPos, result, from, to);
if (result.update && (result = result.update(result, from, to, new CompletionContext(tr.state, pos, explicitPos >= 0)))) return new ActiveResult(this.source, explicitPos, result, result.from, (_a$2 = result.to) !== null && _a$2 !== void 0 ? _a$2 : cur(tr.state));
return new ActiveSource(this.source, 1, explicitPos);
}
handleChange(tr) {
return tr.changes.touchesRange(this.from, this.to) ? new ActiveSource(this.source, 0) : this.map(tr.changes);
}
map(mapping) {
if (mapping.empty) return this;
if (!(this.result.map ? this.result.map(this.result, mapping) : this.result)) return new ActiveSource(this.source, 0);
return new ActiveResult(this.source, this.explicitPos < 0 ? -1 : mapping.mapPos(this.explicitPos), this.result, mapping.mapPos(this.from), mapping.mapPos(this.to, 1));
}
};
setActiveEffect = /* @__PURE__ */StateEffect$1.define({
map(sources, mapping) {
return sources.map(s => s.map(mapping));
}
});
setSelectedEffect = /* @__PURE__ */StateEffect$1.define();
completionState = /* @__PURE__ */StateField$1.define({
create() {
return CompletionState.start();
},
update(value, tr) {
return value.update(tr);
},
provide: f => [showTooltip.from(f, val => val.tooltip), EditorView.contentAttributes.from(f, state => state.attrs)]
});
createTooltip = /* @__PURE__ */completionTooltip(completionState, applyCompletion$1);
acceptCompletion = view => {
let cState = view.state.field(completionState, false);
if (view.state.readOnly || !cState || !cState.open || cState.open.selected < 0 || cState.open.disabled || Date.now() - cState.open.timestamp < view.state.facet(completionConfig).interactionDelay) return false;
return applyCompletion$1(view, cState.open.options[cState.open.selected]);
};
/**
Explicitly start autocompletion.
*/
_export("it", startCompletion = view => {
if (!view.state.field(completionState, false)) return false;
view.dispatch({
effects: startCompletionEffect.of(true)
});
return true;
});
/**
Close the currently active completion.
*/
_export("Z", closeCompletion = view => {
let cState = view.state.field(completionState, false);
if (!cState || !cState.active.some(a => a.state != 0)) return false;
view.dispatch({
effects: closeCompletionEffect.of(null)
});
return true;
});
RunningQuery = class {
constructor(active, context) {
this.active = active;
this.context = context;
this.time = Date.now();
this.updates = [];
this.done = void 0;
}
};
MaxUpdateCount = 50, MinAbortTime = 1e3;
completionPlugin = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.view = view;
this.debounceUpdate = -1;
this.running = [];
this.debounceAccept = -1;
this.pendingStart = false;
this.composing = 0;
for (let active of view.state.field(completionState).active) if (active.state == 1) this.startQuery(active);
}
update(update) {
let cState = update.state.field(completionState);
let conf = update.state.facet(completionConfig);
if (!update.selectionSet && !update.docChanged && update.startState.field(completionState) == cState) return;
let doesReset = update.transactions.some(tr => {
return (tr.selection || tr.docChanged) && !getUserEvent(tr, conf);
});
for (let i$1 = 0; i$1 < this.running.length; i$1++) {
let query = this.running[i$1];
if (doesReset || query.updates.length + update.transactions.length > MaxUpdateCount && Date.now() - query.time > MinAbortTime) {
for (let handler of query.context.abortListeners) try {
handler();
} catch (e) {
logException$1(this.view.state, e);
}
query.context.abortListeners = null;
this.running.splice(i$1--, 1);
} else query.updates.push(...update.transactions);
}
if (this.debounceUpdate > -1) clearTimeout(this.debounceUpdate);
if (update.transactions.some(tr => tr.effects.some(e => e.is(startCompletionEffect)))) this.pendingStart = true;
let delay = this.pendingStart ? 50 : conf.activateOnTypingDelay;
this.debounceUpdate = cState.active.some(a => a.state == 1 && !this.running.some(q => q.active.source == a.source)) ? setTimeout(() => this.startUpdate(), delay) : -1;
if (this.composing != 0) {
for (let tr of update.transactions) if (getUserEvent(tr, conf) == "input") this.composing = 2;else if (this.composing == 2 && tr.selection) this.composing = 3;
}
}
startUpdate() {
this.debounceUpdate = -1;
this.pendingStart = false;
let {
state
} = this.view,
cState = state.field(completionState);
for (let active of cState.active) if (active.state == 1 && !this.running.some(r => r.active.source == active.source)) this.startQuery(active);
}
startQuery(active) {
let {
state
} = this.view,
pos = cur(state);
let context = new CompletionContext(state, pos, active.explicitPos == pos);
let pending = new RunningQuery(active, context);
this.running.push(pending);
Promise.resolve(active.source(context)).then(result => {
if (!pending.context.aborted) {
pending.done = result || null;
this.scheduleAccept();
}
}, err => {
this.view.dispatch({
effects: closeCompletionEffect.of(null)
});
logException$1(this.view.state, err);
});
}
scheduleAccept() {
if (this.running.every(q => q.done !== void 0)) this.accept();else if (this.debounceAccept < 0) this.debounceAccept = setTimeout(() => this.accept(), this.view.state.facet(completionConfig).updateSyncTime);
}
accept() {
var _a$2;
if (this.debounceAccept > -1) clearTimeout(this.debounceAccept);
this.debounceAccept = -1;
let updated = [];
let conf = this.view.state.facet(completionConfig);
for (let i$1 = 0; i$1 < this.running.length; i$1++) {
let query = this.running[i$1];
if (query.done === void 0) continue;
this.running.splice(i$1--, 1);
if (query.done) {
let active = new ActiveResult(query.active.source, query.active.explicitPos, query.done, query.done.from, (_a$2 = query.done.to) !== null && _a$2 !== void 0 ? _a$2 : cur(query.updates.length ? query.updates[0].startState : this.view.state));
for (let tr of query.updates) active = active.update(tr, conf);
if (active.hasResult()) {
updated.push(active);
continue;
}
}
let current = this.view.state.field(completionState).active.find(a => a.source == query.active.source);
if (current && current.state == 1) if (query.done == null) {
let active = new ActiveSource(query.active.source, 0);
for (let tr of query.updates) active = active.update(tr, conf);
if (active.state != 1) updated.push(active);
} else this.startQuery(current);
}
if (updated.length) this.view.dispatch({
effects: setActiveEffect.of(updated)
});
}
}, {
eventHandlers: {
blur(event) {
let state = this.view.state.field(completionState, false);
if (state && state.tooltip && this.view.state.facet(completionConfig).closeOnBlur) {
let dialog = state.open && getTooltip(this.view, state.open.tooltip);
if (!dialog || !dialog.dom.contains(event.relatedTarget)) setTimeout(() => this.view.dispatch({
effects: closeCompletionEffect.of(null)
}), 10);
}
},
compositionstart() {
this.composing = 1;
},
compositionend() {
if (this.composing == 3) setTimeout(() => this.view.dispatch({
effects: startCompletionEffect.of(false)
}), 20);
this.composing = 0;
}
}
});
windows = typeof navigator == "object" && /* @__PURE__ *//Win/.test(navigator.platform);
commitCharacters = /* @__PURE__ */Prec.highest(/* @__PURE__ */EditorView.domEventHandlers({
keydown(event, view) {
let field = view.state.field(completionState, false);
if (!field || !field.open || field.open.disabled || field.open.selected < 0 || event.key.length > 1 || event.ctrlKey && !(windows && event.altKey) || event.metaKey) return false;
let option = field.open.options[field.open.selected];
let result = field.active.find(a => a.source == option.source);
let commitChars = option.completion.commitCharacters || result.result.commitCharacters;
if (commitChars && commitChars.indexOf(event.key) > -1) applyCompletion$1(view, option);
return false;
}
}));
baseTheme$3 = /* @__PURE__ */EditorView.baseTheme({
".cm-tooltip.cm-tooltip-autocomplete": {
"& > ul": {
fontFamily: "monospace",
whiteSpace: "nowrap",
overflow: "hidden auto",
maxWidth_fallback: "700px",
maxWidth: "min(700px, 95vw)",
minWidth: "250px",
maxHeight: "10em",
height: "100%",
listStyle: "none",
margin: 0,
padding: 0,
"& > li, & > completion-section": {
padding: "1px 3px",
lineHeight: 1.2
},
"& > li": {
overflowX: "hidden",
textOverflow: "ellipsis",
cursor: "pointer"
},
"& > completion-section": {
display: "list-item",
borderBottom: "1px solid silver",
paddingLeft: "0.5em",
opacity: .7
}
}
},
"&light .cm-tooltip-autocomplete ul li[aria-selected]": {
background: "#17c",
color: "white"
},
"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
background: "#777"
},
"&dark .cm-tooltip-autocomplete ul li[aria-selected]": {
background: "#347",
color: "white"
},
"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]": {
background: "#444"
},
".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after": {
content: "\"···\"",
opacity: .5,
display: "block",
textAlign: "center"
},
".cm-tooltip.cm-completionInfo": {
position: "absolute",
padding: "3px 9px",
width: "max-content",
maxWidth: `400px`,
boxSizing: "border-box"
},
".cm-completionInfo.cm-completionInfo-left": {
right: "100%"
},
".cm-completionInfo.cm-completionInfo-right": {
left: "100%"
},
".cm-completionInfo.cm-completionInfo-left-narrow": {
right: `30px`
},
".cm-completionInfo.cm-completionInfo-right-narrow": {
left: `30px`
},
"&light .cm-snippetField": {
backgroundColor: "#00000022"
},
"&dark .cm-snippetField": {
backgroundColor: "#ffffff22"
},
".cm-snippetFieldPosition": {
verticalAlign: "text-top",
width: 0,
height: "1.15em",
display: "inline-block",
margin: "0 -0.7px -.7em",
borderLeft: "1.4px dotted #888"
},
".cm-completionMatchedText": {
textDecoration: "underline"
},
".cm-completionDetail": {
marginLeft: "0.5em",
fontStyle: "italic"
},
".cm-completionIcon": {
fontSize: "90%",
width: ".8em",
display: "inline-block",
textAlign: "center",
paddingRight: ".6em",
opacity: "0.6",
boxSizing: "content-box"
},
".cm-completionIcon-function, .cm-completionIcon-method": {
"&:after": {
content: "'ƒ'"
}
},
".cm-completionIcon-class": {
"&:after": {
content: "'○'"
}
},
".cm-completionIcon-interface": {
"&:after": {
content: "'◌'"
}
},
".cm-completionIcon-variable": {
"&:after": {
content: "'𝑥'"
}
},
".cm-completionIcon-constant": {
"&:after": {
content: "'𝐶'"
}
},
".cm-completionIcon-type": {
"&:after": {
content: "'𝑡'"
}
},
".cm-completionIcon-enum": {
"&:after": {
content: "'∪'"
}
},
".cm-completionIcon-property": {
"&:after": {
content: "'□'"
}
},
".cm-completionIcon-keyword": {
"&:after": {
content: "'🔑︎'"
}
},
".cm-completionIcon-namespace": {
"&:after": {
content: "'▢'"
}
},
".cm-completionIcon-text": {
"&:after": {
content: "'abc'",
fontSize: "50%",
verticalAlign: "middle"
}
}
});
FieldPos = class {
constructor(field, line, from, to) {
this.field = field;
this.line = line;
this.from = from;
this.to = to;
}
};
FieldRange = class FieldRange {
constructor(field, from, to) {
this.field = field;
this.from = from;
this.to = to;
}
map(changes) {
let from = changes.mapPos(this.from, -1, MapMode.TrackDel);
let to = changes.mapPos(this.to, 1, MapMode.TrackDel);
return from == null || to == null ? null : new FieldRange(this.field, from, to);
}
};
Snippet = class Snippet {
constructor(lines, fieldPositions) {
this.lines = lines;
this.fieldPositions = fieldPositions;
}
instantiate(state, pos) {
let text = [],
lineStart = [pos];
let lineObj = state.doc.lineAt(pos),
baseIndent = /^\s*/.exec(lineObj.text)[0];
for (let line of this.lines) {
if (text.length) {
let indent = baseIndent,
tabs$1 = /^\t*/.exec(line)[0].length;
for (let i$1 = 0; i$1 < tabs$1; i$1++) indent += state.facet(indentUnit);
lineStart.push(pos + indent.length - tabs$1);
line = indent + line.slice(tabs$1);
}
text.push(line);
pos += line.length + 1;
}
return {
text,
ranges: this.fieldPositions.map(pos$1 => new FieldRange(pos$1.field, lineStart[pos$1.line] + pos$1.from, lineStart[pos$1.line] + pos$1.to))
};
}
static parse(template$1) {
let fields = [];
let lines = [],
positions = [],
m;
for (let line of template$1.split(/\r\n?|\n/)) {
while (m = /[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(line)) {
let seq = m[1] ? +m[1] : null,
name$1 = m[2] || m[3] || "",
found = -1;
for (let i$1 = 0; i$1 < fields.length; i$1++) if (seq != null ? fields[i$1].seq == seq : name$1 ? fields[i$1].name == name$1 : false) found = i$1;
if (found < 0) {
let i$1 = 0;
while (i$1 < fields.length && (seq == null || fields[i$1].seq != null && fields[i$1].seq < seq)) i$1++;
fields.splice(i$1, 0, {
seq,
name: name$1
});
found = i$1;
for (let pos of positions) if (pos.field >= found) pos.field++;
}
positions.push(new FieldPos(found, lines.length, m.index, m.index + name$1.length));
line = line.slice(0, m.index) + name$1 + line.slice(m.index + m[0].length);
}
for (let esc; esc = /\\([{}])/.exec(line);) {
line = line.slice(0, esc.index) + esc[1] + line.slice(esc.index + esc[0].length);
for (let pos of positions) if (pos.line == lines.length && pos.from > esc.index) {
pos.from--;
pos.to--;
}
}
lines.push(line);
}
return new Snippet(lines, positions);
}
};
fieldMarker = /* @__PURE__ */Decoration$1.widget({
widget: /* @__PURE__ */new class extends WidgetType$1 {
toDOM() {
let span = document.createElement("span");
span.className = "cm-snippetFieldPosition";
return span;
}
ignoreEvent() {
return false;
}
}()
});
fieldRange = /* @__PURE__ */Decoration$1.mark({
class: "cm-snippetField"
});
ActiveSnippet = class ActiveSnippet {
constructor(ranges, active) {
this.ranges = ranges;
this.active = active;
this.deco = Decoration$1.set(ranges.map(r => (r.from == r.to ? fieldMarker : fieldRange).range(r.from, r.to)));
}
map(changes) {
let ranges = [];
for (let r of this.ranges) {
let mapped = r.map(changes);
if (!mapped) return null;
ranges.push(mapped);
}
return new ActiveSnippet(ranges, this.active);
}
selectionInsideField(sel) {
return sel.ranges.every(range => this.ranges.some(r => r.field == this.active && r.from <= range.from && r.to >= range.to));
}
};
setActive = /* @__PURE__ */StateEffect$1.define({
map(value, changes) {
return value && value.map(changes);
}
});
moveToField = /* @__PURE__ */StateEffect$1.define();
snippetState = /* @__PURE__ */StateField$1.define({
create() {
return null;
},
update(value, tr) {
for (let effect of tr.effects) {
if (effect.is(setActive)) return effect.value;
if (effect.is(moveToField) && value) return new ActiveSnippet(value.ranges, effect.value);
}
if (value && tr.docChanged) value = value.map(tr.changes);
if (value && tr.selection && !value.selectionInsideField(tr.selection)) value = null;
return value;
},
provide: f => EditorView.decorations.from(f, val => val ? val.deco : Decoration$1.none)
});
clearSnippet = ({
state,
dispatch
}) => {
if (!state.field(snippetState, false)) return false;
dispatch(state.update({
effects: setActive.of(null)
}));
return true;
};
/**
Move to the next snippet field, if available.
*/
nextSnippetField = /* @__PURE__ */moveField(1);
/**
Move to the previous snippet field, if available.
*/
prevSnippetField = /* @__PURE__ */moveField(-1);
defaultSnippetKeymap = [{
key: "Tab",
run: nextSnippetField,
shift: prevSnippetField
}, {
key: "Escape",
run: clearSnippet
}];
/**
A facet that can be used to configure the key bindings used by
snippets. The default binds Tab to
[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
*/
snippetKeymap = /* @__PURE__ */Facet$1.define({
combine(maps) {
return maps.length ? maps[0] : defaultSnippetKeymap;
}
});
addSnippetKeymap = /* @__PURE__ */Prec.highest(/* @__PURE__ */keymap.compute([snippetKeymap], state => state.facet(snippetKeymap)));
snippetPointerHandler = /* @__PURE__ */EditorView.domEventHandlers({
mousedown(event, view) {
let active = view.state.field(snippetState, false),
pos;
if (!active || (pos = view.posAtCoords({
x: event.clientX,
y: event.clientY
})) == null) return false;
let match = active.ranges.find(r => r.from <= pos && r.to >= pos);
if (!match || match.field == active.active) return false;
view.dispatch({
selection: fieldSelection(active.ranges, match.field),
effects: setActive.of(active.ranges.some(r => r.field > match.field) ? new ActiveSnippet(active.ranges, match.field) : null),
scrollIntoView: true
});
return true;
}
});
defaults = {
brackets: ["(", "[", "{", "'", "\""],
before: ")]}:;>",
stringPrefixes: []
};
closeBracketEffect = /* @__PURE__ */StateEffect$1.define({
map(value, mapping) {
let mapped = mapping.mapPos(value, -1, MapMode.TrackAfter);
return mapped == null ? void 0 : mapped;
}
});
closedBracket = /* @__PURE__ */new class extends RangeValue {}();
closedBracket.startSide = 1;
closedBracket.endSide = -1;
bracketState = /* @__PURE__ */StateField$1.define({
create() {
return RangeSet$1.empty;
},
update(value, tr) {
value = value.map(tr.changes);
if (tr.selection) {
let line = tr.state.doc.lineAt(tr.selection.main.head);
value = value.update({
filter: from => from >= line.from && from <= line.to
});
}
for (let effect of tr.effects) if (effect.is(closeBracketEffect)) value = value.update({
add: [closedBracket.range(effect.value, effect.value + 1)]
});
return value;
}
});
definedClosing = "()[]{}<>";
android$1 = typeof navigator == "object" && /* @__PURE__ *//Android\b/.test(navigator.userAgent);
inputHandler$1 = /* @__PURE__ */EditorView.inputHandler.of((view, from, to, insert$2) => {
if ((android$1 ? view.composing : view.compositionStarted) || view.state.readOnly) return false;
let sel = view.state.selection.main;
if (insert$2.length > 2 || insert$2.length == 2 && codePointSize(codePointAt(insert$2, 0)) == 1 || from != sel.from || to != sel.to) return false;
let tr = insertBracket(view.state, insert$2);
if (!tr) return false;
view.dispatch(tr);
return true;
});
/**
Command that implements deleting a pair of matching brackets when
the cursor is between them.
*/
deleteBracketPair = ({
state,
dispatch
}) => {
if (state.readOnly) return false;
let tokens = config(state, state.selection.main.head).brackets || defaults.brackets;
let dont = null,
changes = state.changeByRange(range => {
if (range.empty) {
let before = prevChar(state.doc, range.head);
for (let token of tokens) if (token == before && nextChar(state.doc, range.head) == closing(codePointAt(token, 0))) return {
changes: {
from: range.head - token.length,
to: range.head + token.length
},
range: EditorSelection.cursor(range.head - token.length)
};
}
return {
range: dont = range
};
});
if (!dont) dispatch(state.update(changes, {
scrollIntoView: true,
userEvent: "delete.backward"
}));
return !dont;
};
/**
Close-brackets related key bindings. Binds Backspace to
[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
*/
_export("X", closeBracketsKeymap = [{
key: "Backspace",
run: deleteBracketPair
}]);
completionKeymap = [{
key: "Ctrl-Space",
run: startCompletion
}, {
key: "Escape",
run: closeCompletion
}, {
key: "ArrowDown",
run: /* @__PURE__ */moveCompletionSelection(true)
}, {
key: "ArrowUp",
run: /* @__PURE__ */moveCompletionSelection(false)
}, {
key: "PageDown",
run: /* @__PURE__ */moveCompletionSelection(true, "page")
}, {
key: "PageUp",
run: /* @__PURE__ */moveCompletionSelection(false, "page")
}, {
key: "Enter",
run: acceptCompletion
}];
completionKeymapExt = /* @__PURE__ */Prec.highest(/* @__PURE__ */keymap.computeN([completionConfig], state => state.facet(completionConfig).defaultKeymap ? [completionKeymap] : []));
init_dist();
/**
A parse stack. These are used internally by the parser to track
parsing progress. They also provide some properties and methods
that external code such as a tokenizer can use to get information
about the parse state.
*/
Stack = class Stack {
/**
@internal
*/
constructor(p, stack, state, reducePos, pos, score$1, buffer, bufferBase, curContext, lookAhead = 0, parent) {
this.p = p;
this.stack = stack;
this.state = state;
this.reducePos = reducePos;
this.pos = pos;
this.score = score$1;
this.buffer = buffer;
this.bufferBase = bufferBase;
this.curContext = curContext;
this.lookAhead = lookAhead;
this.parent = parent;
}
/**
@internal
*/
toString() {
return `[${this.stack.filter((_, i$1) => i$1 % 3 == 0).concat(this.state)}]@${this.pos}${this.score ? "!" + this.score : ""}`;
}
/**
@internal
*/
static start(p, state, pos = 0) {
let cx = p.parser.context;
return new Stack(p, [], state, pos, pos, 0, [], 0, cx ? new StackContext(cx, cx.start) : null, 0, null);
}
/**
The stack's current [context](#lr.ContextTracker) value, if
any. Its type will depend on the context tracker's type
parameter, or it will be `null` if there is no context
tracker.
*/
get context() {
return this.curContext ? this.curContext.context : null;
}
/**
@internal
*/
pushState(state, start) {
this.stack.push(this.state, start, this.bufferBase + this.buffer.length);
this.state = state;
}
/**
@internal
*/
reduce(action) {
var _a$2;
let depth = action >> 19,
type = action & 65535;
let {
parser: parser$3
} = this.p;
let dPrec = parser$3.dynamicPrecedence(type);
if (dPrec) this.score += dPrec;
if (depth == 0) {
this.pushState(parser$3.getGoto(this.state, type, true), this.reducePos);
if (type < parser$3.minRepeatTerm) this.storeNode(type, this.reducePos, this.reducePos, 4, true);
this.reduceContext(type, this.reducePos);
return;
}
let base$1 = this.stack.length - (depth - 1) * 3 - (action & 262144 ? 6 : 0);
let start = base$1 ? this.stack[base$1 - 2] : this.p.ranges[0].from,
size = this.reducePos - start;
if (size >= 2e3 && !((_a$2 = this.p.parser.nodeSet.types[type]) === null || _a$2 === void 0 ? void 0 : _a$2.isAnonymous)) {
if (start == this.p.lastBigReductionStart) {
this.p.bigReductionCount++;
this.p.lastBigReductionSize = size;
} else if (this.p.lastBigReductionSize < size) {
this.p.bigReductionCount = 1;
this.p.lastBigReductionStart = start;
this.p.lastBigReductionSize = size;
}
}
let bufferBase = base$1 ? this.stack[base$1 - 1] : 0,
count = this.bufferBase + this.buffer.length - bufferBase;
if (type < parser$3.minRepeatTerm || action & 131072) {
let pos = parser$3.stateFlag(this.state, 1) ? this.pos : this.reducePos;
this.storeNode(type, start, pos, count + 4, true);
}
if (action & 262144) this.state = this.stack[base$1];else {
let baseStateID = this.stack[base$1 - 3];
this.state = parser$3.getGoto(baseStateID, type, true);
}
while (this.stack.length > base$1) this.stack.pop();
this.reduceContext(type, start);
}
/**
@internal
*/
storeNode(term, start, end, size = 4, isReduce = false) {
if (term == 0 && (!this.stack.length || this.stack[this.stack.length - 1] < this.buffer.length + this.bufferBase)) {
let cur$1 = this,
top$1 = this.buffer.length;
if (top$1 == 0 && cur$1.parent) {
top$1 = cur$1.bufferBase - cur$1.parent.bufferBase;
cur$1 = cur$1.parent;
}
if (top$1 > 0 && cur$1.buffer[top$1 - 4] == 0 && cur$1.buffer[top$1 - 1] > -1) {
if (start == end) return;
if (cur$1.buffer[top$1 - 2] >= start) {
cur$1.buffer[top$1 - 2] = end;
return;
}
}
}
if (!isReduce || this.pos == end) this.buffer.push(term, start, end, size);else {
let index = this.buffer.length;
if (index > 0 && this.buffer[index - 4] != 0) while (index > 0 && this.buffer[index - 2] > end) {
this.buffer[index] = this.buffer[index - 4];
this.buffer[index + 1] = this.buffer[index - 3];
this.buffer[index + 2] = this.buffer[index - 2];
this.buffer[index + 3] = this.buffer[index - 1];
index -= 4;
if (size > 4) size -= 4;
}
this.buffer[index] = term;
this.buffer[index + 1] = start;
this.buffer[index + 2] = end;
this.buffer[index + 3] = size;
}
}
/**
@internal
*/
shift(action, type, start, end) {
if (action & 131072) this.pushState(action & 65535, this.pos);else if ((action & 262144) == 0) {
let nextState = action,
{
parser: parser$3
} = this.p;
if (end > this.pos || type <= parser$3.maxNode) {
this.pos = end;
if (!parser$3.stateFlag(nextState, 1)) this.reducePos = end;
}
this.pushState(nextState, start);
this.shiftContext(type, start);
if (type <= parser$3.maxNode) this.buffer.push(type, start, end, 4);
} else {
this.pos = end;
this.shiftContext(type, start);
if (type <= this.p.parser.maxNode) this.buffer.push(type, start, end, 4);
}
}
/**
@internal
*/
apply(action, next, nextStart, nextEnd) {
if (action & 65536) this.reduce(action);else this.shift(action, next, nextStart, nextEnd);
}
/**
@internal
*/
useNode(value, next) {
let index = this.p.reused.length - 1;
if (index < 0 || this.p.reused[index] != value) {
this.p.reused.push(value);
index++;
}
let start = this.pos;
this.reducePos = this.pos = start + value.length;
this.pushState(next, start);
this.buffer.push(index, start, this.reducePos, -1);
if (this.curContext) this.updateContext(this.curContext.tracker.reuse(this.curContext.context, value, this, this.p.stream.reset(this.pos - value.length)));
}
/**
@internal
*/
split() {
let parent = this;
let off = parent.buffer.length;
while (off > 0 && parent.buffer[off - 2] > parent.reducePos) off -= 4;
let buffer = parent.buffer.slice(off),
base$1 = parent.bufferBase + off;
while (parent && base$1 == parent.bufferBase) parent = parent.parent;
return new Stack(this.p, this.stack.slice(), this.state, this.reducePos, this.pos, this.score, buffer, base$1, this.curContext, this.lookAhead, parent);
}
/**
@internal
*/
recoverByDelete(next, nextEnd) {
let isNode = next <= this.p.parser.maxNode;
if (isNode) this.storeNode(next, this.pos, nextEnd, 4);
this.storeNode(0, this.pos, nextEnd, isNode ? 8 : 4);
this.pos = this.reducePos = nextEnd;
this.score -= 190;
}
/**
Check if the given term would be able to be shifted (optionally
after some reductions) on this stack. This can be useful for
external tokenizers that want to make sure they only provide a
given token when it applies.
*/
canShift(term) {
for (let sim = new SimulatedStack(this);;) {
let action = this.p.parser.stateSlot(sim.state, 4) || this.p.parser.hasAction(sim.state, term);
if (action == 0) return false;
if ((action & 65536) == 0) return true;
sim.reduce(action);
}
}
/**
@internal
*/
recoverByInsert(next) {
if (this.stack.length >= 300) return [];
let nextStates = this.p.parser.nextStates(this.state);
if (nextStates.length > 8 || this.stack.length >= 120) {
let best = [];
for (let i$1 = 0, s; i$1 < nextStates.length; i$1 += 2) if ((s = nextStates[i$1 + 1]) != this.state && this.p.parser.hasAction(s, next)) best.push(nextStates[i$1], s);
if (this.stack.length < 120) for (let i$1 = 0; best.length < 8 && i$1 < nextStates.length; i$1 += 2) {
let s = nextStates[i$1 + 1];
if (!best.some((v, i$2) => i$2 & 1 && v == s)) best.push(nextStates[i$1], s);
}
nextStates = best;
}
let result = [];
for (let i$1 = 0; i$1 < nextStates.length && result.length < 4; i$1 += 2) {
let s = nextStates[i$1 + 1];
if (s == this.state) continue;
let stack = this.split();
stack.pushState(s, this.pos);
stack.storeNode(0, stack.pos, stack.pos, 4, true);
stack.shiftContext(nextStates[i$1], this.pos);
stack.reducePos = this.pos;
stack.score -= 200;
result.push(stack);
}
return result;
}
/**
@internal
*/
forceReduce() {
let {
parser: parser$3
} = this.p;
let reduce = parser$3.stateSlot(this.state, 5);
if ((reduce & 65536) == 0) return false;
if (!parser$3.validAction(this.state, reduce)) {
let depth = reduce >> 19,
term = reduce & 65535;
let target = this.stack.length - depth * 3;
if (target < 0 || parser$3.getGoto(this.stack[target], term, false) < 0) {
let backup = this.findForcedReduction();
if (backup == null) return false;
reduce = backup;
}
this.storeNode(0, this.pos, this.pos, 4, true);
this.score -= 100;
}
this.reducePos = this.pos;
this.reduce(reduce);
return true;
}
/**
Try to scan through the automaton to find some kind of reduction
that can be applied. Used when the regular ForcedReduce field
isn't a valid action. @internal
*/
findForcedReduction() {
let {
parser: parser$3
} = this.p,
seen = [];
let explore = (state, depth) => {
if (seen.includes(state)) return;
seen.push(state);
return parser$3.allActions(state, action => {
if (action & 393216) ;else if (action & 65536) {
let rDepth = (action >> 19) - depth;
if (rDepth > 1) {
let term = action & 65535,
target = this.stack.length - rDepth * 3;
if (target >= 0 && parser$3.getGoto(this.stack[target], term, false) >= 0) return rDepth << 19 | 65536 | term;
}
} else {
let found = explore(action, depth + 1);
if (found != null) return found;
}
});
};
return explore(this.state, 0);
}
/**
@internal
*/
forceAll() {
while (!this.p.parser.stateFlag(this.state, 2)) if (!this.forceReduce()) {
this.storeNode(0, this.pos, this.pos, 4, true);
break;
}
return this;
}
/**
Check whether this state has no further actions (assumed to be a direct descendant of the
top state, since any other states must be able to continue
somehow). @internal
*/
get deadEnd() {
if (this.stack.length != 3) return false;
let {
parser: parser$3
} = this.p;
return parser$3.data[parser$3.stateSlot(this.state, 1)] == 65535 && !parser$3.stateSlot(this.state, 4);
}
/**
Restart the stack (put it back in its start state). Only safe
when this.stack.length == 3 (state is directly below the top
state). @internal
*/
restart() {
this.storeNode(0, this.pos, this.pos, 4, true);
this.state = this.stack[0];
this.stack.length = 0;
}
/**
@internal
*/
sameState(other) {
if (this.state != other.state || this.stack.length != other.stack.length) return false;
for (let i$1 = 0; i$1 < this.stack.length; i$1 += 3) if (this.stack[i$1] != other.stack[i$1]) return false;
return true;
}
/**
Get the parser used by this stack.
*/
get parser() {
return this.p.parser;
}
/**
Test whether a given dialect (by numeric ID, as exported from
the terms file) is enabled.
*/
dialectEnabled(dialectID) {
return this.p.parser.dialect.flags[dialectID];
}
shiftContext(term, start) {
if (this.curContext) this.updateContext(this.curContext.tracker.shift(this.curContext.context, term, this, this.p.stream.reset(start)));
}
reduceContext(term, start) {
if (this.curContext) this.updateContext(this.curContext.tracker.reduce(this.curContext.context, term, this, this.p.stream.reset(start)));
}
/**
@internal
*/
emitContext() {
let last = this.buffer.length - 1;
if (last < 0 || this.buffer[last] != -3) this.buffer.push(this.curContext.hash, this.pos, this.pos, -3);
}
/**
@internal
*/
emitLookAhead() {
let last = this.buffer.length - 1;
if (last < 0 || this.buffer[last] != -4) this.buffer.push(this.lookAhead, this.pos, this.pos, -4);
}
updateContext(context) {
if (context != this.curContext.context) {
let newCx = new StackContext(this.curContext.tracker, context);
if (newCx.hash != this.curContext.hash) this.emitContext();
this.curContext = newCx;
}
}
/**
@internal
*/
setLookAhead(lookAhead) {
if (lookAhead > this.lookAhead) {
this.emitLookAhead();
this.lookAhead = lookAhead;
}
}
/**
@internal
*/
close() {
if (this.curContext && this.curContext.tracker.strict) this.emitContext();
if (this.lookAhead > 0) this.emitLookAhead();
}
};
StackContext = class {
constructor(tracker, context) {
this.tracker = tracker;
this.context = context;
this.hash = tracker.strict ? tracker.hash(context) : 0;
}
};
SimulatedStack = class {
constructor(start) {
this.start = start;
this.state = start.state;
this.stack = start.stack;
this.base = this.stack.length;
}
reduce(action) {
let term = action & 65535,
depth = action >> 19;
if (depth == 0) {
if (this.stack == this.start.stack) this.stack = this.stack.slice();
this.stack.push(this.state, 0, 0);
this.base += 3;
} else this.base -= (depth - 1) * 3;
this.state = this.start.p.parser.getGoto(this.stack[this.base - 3], term, true);
}
};
StackBufferCursor = class StackBufferCursor {
constructor(stack, pos, index) {
this.stack = stack;
this.pos = pos;
this.index = index;
this.buffer = stack.buffer;
if (this.index == 0) this.maybeNext();
}
static create(stack, pos = stack.bufferBase + stack.buffer.length) {
return new StackBufferCursor(stack, pos, pos - stack.bufferBase);
}
maybeNext() {
let next = this.stack.parent;
if (next != null) {
this.index = this.stack.bufferBase - next.bufferBase;
this.stack = next;
this.buffer = next.buffer;
}
}
get id() {
return this.buffer[this.index - 4];
}
get start() {
return this.buffer[this.index - 3];
}
get end() {
return this.buffer[this.index - 2];
}
get size() {
return this.buffer[this.index - 1];
}
next() {
this.index -= 4;
this.pos -= 4;
if (this.index == 0) this.maybeNext();
}
fork() {
return new StackBufferCursor(this.stack, this.pos, this.index);
}
};
CachedToken = class {
constructor() {
this.start = -1;
this.value = -1;
this.end = -1;
this.extended = -1;
this.lookAhead = 0;
this.mask = 0;
this.context = 0;
}
};
nullToken = new CachedToken();
/**
[Tokenizers](#lr.ExternalTokenizer) interact with the input
through this interface. It presents the input as a stream of
characters, tracking lookahead and hiding the complexity of
[ranges](#common.Parser.parse^ranges) from tokenizer code.
*/
InputStream = class {
/**
@internal
*/
constructor(input, ranges) {
this.input = input;
this.ranges = ranges;
/**
@internal
*/
this.chunk = "";
/**
@internal
*/
this.chunkOff = 0;
/**
Backup chunk
*/
this.chunk2 = "";
this.chunk2Pos = 0;
/**
The character code of the next code unit in the input, or -1
when the stream is at the end of the input.
*/
this.next = -1;
/**
@internal
*/
this.token = nullToken;
this.rangeIndex = 0;
this.pos = this.chunkPos = ranges[0].from;
this.range = ranges[0];
this.end = ranges[ranges.length - 1].to;
this.readNext();
}
/**
@internal
*/
resolveOffset(offset, assoc) {
let range = this.range,
index = this.rangeIndex;
let pos = this.pos + offset;
while (pos < range.from) {
if (!index) return null;
let next = this.ranges[--index];
pos -= range.from - next.to;
range = next;
}
while (assoc < 0 ? pos > range.to : pos >= range.to) {
if (index == this.ranges.length - 1) return null;
let next = this.ranges[++index];
pos += next.from - range.to;
range = next;
}
return pos;
}
/**
@internal
*/
clipPos(pos) {
if (pos >= this.range.from && pos < this.range.to) return pos;
for (let range of this.ranges) if (range.to > pos) return Math.max(pos, range.from);
return this.end;
}
/**
Look at a code unit near the stream position. `.peek(0)` equals
`.next`, `.peek(-1)` gives you the previous character, and so
on.
Note that looking around during tokenizing creates dependencies
on potentially far-away content, which may reduce the
effectiveness incremental parsing—when looking forward—or even
cause invalid reparses when looking backward more than 25 code
units, since the library does not track lookbehind.
*/
peek(offset) {
let idx = this.chunkOff + offset,
pos,
result;
if (idx >= 0 && idx < this.chunk.length) {
pos = this.pos + offset;
result = this.chunk.charCodeAt(idx);
} else {
let resolved = this.resolveOffset(offset, 1);
if (resolved == null) return -1;
pos = resolved;
if (pos >= this.chunk2Pos && pos < this.chunk2Pos + this.chunk2.length) result = this.chunk2.charCodeAt(pos - this.chunk2Pos);else {
let i$1 = this.rangeIndex,
range = this.range;
while (range.to <= pos) range = this.ranges[++i$1];
this.chunk2 = this.input.chunk(this.chunk2Pos = pos);
if (pos + this.chunk2.length > range.to) this.chunk2 = this.chunk2.slice(0, range.to - pos);
result = this.chunk2.charCodeAt(0);
}
}
if (pos >= this.token.lookAhead) this.token.lookAhead = pos + 1;
return result;
}
/**
Accept a token. By default, the end of the token is set to the
current stream position, but you can pass an offset (relative to
the stream position) to change that.
*/
acceptToken(token, endOffset = 0) {
let end = endOffset ? this.resolveOffset(endOffset, -1) : this.pos;
if (end == null || end < this.token.start) throw new RangeError("Token end out of bounds");
this.token.value = token;
this.token.end = end;
}
/**
Accept a token ending at a specific given position.
*/
acceptTokenTo(token, endPos) {
this.token.value = token;
this.token.end = endPos;
}
getChunk() {
if (this.pos >= this.chunk2Pos && this.pos < this.chunk2Pos + this.chunk2.length) {
let {
chunk,
chunkPos
} = this;
this.chunk = this.chunk2;
this.chunkPos = this.chunk2Pos;
this.chunk2 = chunk;
this.chunk2Pos = chunkPos;
this.chunkOff = this.pos - this.chunkPos;
} else {
this.chunk2 = this.chunk;
this.chunk2Pos = this.chunkPos;
let nextChunk = this.input.chunk(this.pos);
this.chunk = this.pos + nextChunk.length > this.range.to ? nextChunk.slice(0, this.range.to - this.pos) : nextChunk;
this.chunkPos = this.pos;
this.chunkOff = 0;
}
}
readNext() {
if (this.chunkOff >= this.chunk.length) {
this.getChunk();
if (this.chunkOff == this.chunk.length) return this.next = -1;
}
return this.next = this.chunk.charCodeAt(this.chunkOff);
}
/**
Move the stream forward N (defaults to 1) code units. Returns
the new value of [`next`](#lr.InputStream.next).
*/
advance(n = 1) {
this.chunkOff += n;
while (this.pos + n >= this.range.to) {
if (this.rangeIndex == this.ranges.length - 1) return this.setDone();
n -= this.range.to - this.pos;
this.range = this.ranges[++this.rangeIndex];
this.pos = this.range.from;
}
this.pos += n;
if (this.pos >= this.token.lookAhead) this.token.lookAhead = this.pos + 1;
return this.readNext();
}
setDone() {
this.pos = this.chunkPos = this.end;
this.range = this.ranges[this.rangeIndex = this.ranges.length - 1];
this.chunk = "";
return this.next = -1;
}
/**
@internal
*/
reset(pos, token) {
if (token) {
this.token = token;
token.start = pos;
token.lookAhead = pos + 1;
token.value = token.extended = -1;
} else this.token = nullToken;
if (this.pos != pos) {
this.pos = pos;
if (pos == this.end) {
this.setDone();
return this;
}
while (pos < this.range.from) this.range = this.ranges[--this.rangeIndex];
while (pos >= this.range.to) this.range = this.ranges[++this.rangeIndex];
if (pos >= this.chunkPos && pos < this.chunkPos + this.chunk.length) this.chunkOff = pos - this.chunkPos;else {
this.chunk = "";
this.chunkOff = 0;
}
this.readNext();
}
return this;
}
/**
@internal
*/
read(from, to) {
if (from >= this.chunkPos && to <= this.chunkPos + this.chunk.length) return this.chunk.slice(from - this.chunkPos, to - this.chunkPos);
if (from >= this.chunk2Pos && to <= this.chunk2Pos + this.chunk2.length) return this.chunk2.slice(from - this.chunk2Pos, to - this.chunk2Pos);
if (from >= this.range.from && to <= this.range.to) return this.input.read(from, to);
let result = "";
for (let r of this.ranges) {
if (r.from >= to) break;
if (r.to > from) result += this.input.read(Math.max(r.from, from), Math.min(r.to, to));
}
return result;
}
};
/**
@internal
*/
TokenGroup = class {
constructor(data, id$1) {
this.data = data;
this.id = id$1;
}
token(input, stack) {
let {
parser: parser$3
} = stack.p;
readToken(this.data, input, stack, this.id, parser$3.data, parser$3.tokenPrecTable);
}
};
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
/**
@hide
*/
LocalTokenGroup = class {
constructor(data, precTable, elseToken) {
this.precTable = precTable;
this.elseToken = elseToken;
this.data = typeof data == "string" ? decodeArray(data) : data;
}
token(input, stack) {
let start = input.pos,
skipped = 0;
for (;;) {
let atEof = input.next < 0,
nextPos = input.resolveOffset(1, 1);
readToken(this.data, input, stack, 0, this.data, this.precTable);
if (input.token.value > -1) break;
if (this.elseToken == null) return;
if (!atEof) skipped++;
if (nextPos == null) break;
input.reset(nextPos, input.token);
}
if (skipped) {
input.reset(start, input.token);
input.acceptToken(this.elseToken, skipped);
}
}
};
LocalTokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
/**
`@external tokens` declarations in the grammar should resolve to
an instance of this class.
*/
_export("G", ExternalTokenizer = class {
/**
Create a tokenizer. The first argument is the function that,
given an input stream, scans for the types of tokens it
recognizes at the stream's position, and calls
[`acceptToken`](#lr.InputStream.acceptToken) when it finds
one.
*/
constructor(token, options = {}) {
this.token = token;
this.contextual = !!options.contextual;
this.fallback = !!options.fallback;
this.extend = !!options.extend;
}
});
verbose = typeof process$1 != "undefined" && /\bparse\b/.test({}.LOG);
stackIDs = null;
FragmentCursor = class {
constructor(fragments, nodeSet) {
this.fragments = fragments;
this.nodeSet = nodeSet;
this.i = 0;
this.fragment = null;
this.safeFrom = -1;
this.safeTo = -1;
this.trees = [];
this.start = [];
this.index = [];
this.nextFragment();
}
nextFragment() {
let fr = this.fragment = this.i == this.fragments.length ? null : this.fragments[this.i++];
if (fr) {
this.safeFrom = fr.openStart ? cutAt(fr.tree, fr.from + fr.offset, 1) - fr.offset : fr.from;
this.safeTo = fr.openEnd ? cutAt(fr.tree, fr.to + fr.offset, -1) - fr.offset : fr.to;
while (this.trees.length) {
this.trees.pop();
this.start.pop();
this.index.pop();
}
this.trees.push(fr.tree);
this.start.push(-fr.offset);
this.index.push(0);
this.nextStart = this.safeFrom;
} else this.nextStart = 1e9;
}
nodeAt(pos) {
if (pos < this.nextStart) return null;
while (this.fragment && this.safeTo <= pos) this.nextFragment();
if (!this.fragment) return null;
for (;;) {
let last = this.trees.length - 1;
if (last < 0) {
this.nextFragment();
return null;
}
let top$1 = this.trees[last],
index = this.index[last];
if (index == top$1.children.length) {
this.trees.pop();
this.start.pop();
this.index.pop();
continue;
}
let next = top$1.children[index];
let start = this.start[last] + top$1.positions[index];
if (start > pos) {
this.nextStart = start;
return null;
}
if (next instanceof Tree) {
if (start == pos) {
if (start < this.safeFrom) return null;
let end = start + next.length;
if (end <= this.safeTo) {
let lookAhead = next.prop(NodeProp.lookAhead);
if (!lookAhead || end + lookAhead < this.fragment.to) return next;
}
}
this.index[last]++;
if (start + next.length >= Math.max(this.safeFrom, pos)) {
this.trees.push(next);
this.start.push(start);
this.index.push(0);
}
} else {
this.index[last]++;
this.nextStart = start + next.length;
}
}
}
};
TokenCache = class {
constructor(parser$3, stream) {
this.stream = stream;
this.tokens = [];
this.mainToken = null;
this.actions = [];
this.tokens = parser$3.tokenizers.map(_ => new CachedToken());
}
getActions(stack) {
let actionIndex = 0;
let main = null;
let {
parser: parser$3
} = stack.p,
{
tokenizers
} = parser$3;
let mask = parser$3.stateSlot(stack.state, 3);
let context = stack.curContext ? stack.curContext.hash : 0;
let lookAhead = 0;
for (let i$1 = 0; i$1 < tokenizers.length; i$1++) {
if ((1 << i$1 & mask) == 0) continue;
let tokenizer = tokenizers[i$1],
token = this.tokens[i$1];
if (main && !tokenizer.fallback) continue;
if (tokenizer.contextual || token.start != stack.pos || token.mask != mask || token.context != context) {
this.updateCachedToken(token, tokenizer, stack);
token.mask = mask;
token.context = context;
}
if (token.lookAhead > token.end + 25) lookAhead = Math.max(token.lookAhead, lookAhead);
if (token.value != 0) {
let startIndex = actionIndex;
if (token.extended > -1) actionIndex = this.addActions(stack, token.extended, token.end, actionIndex);
actionIndex = this.addActions(stack, token.value, token.end, actionIndex);
if (!tokenizer.extend) {
main = token;
if (actionIndex > startIndex) break;
}
}
}
while (this.actions.length > actionIndex) this.actions.pop();
if (lookAhead) stack.setLookAhead(lookAhead);
if (!main && stack.pos == this.stream.end) {
main = new CachedToken();
main.value = stack.p.parser.eofTerm;
main.start = main.end = stack.pos;
actionIndex = this.addActions(stack, main.value, main.end, actionIndex);
}
this.mainToken = main;
return this.actions;
}
getMainToken(stack) {
if (this.mainToken) return this.mainToken;
let main = new CachedToken(),
{
pos,
p
} = stack;
main.start = pos;
main.end = Math.min(pos + 1, p.stream.end);
main.value = pos == p.stream.end ? p.parser.eofTerm : 0;
return main;
}
updateCachedToken(token, tokenizer, stack) {
let start = this.stream.clipPos(stack.pos);
tokenizer.token(this.stream.reset(start, token), stack);
if (token.value > -1) {
let {
parser: parser$3
} = stack.p;
for (let i$1 = 0; i$1 < parser$3.specialized.length; i$1++) if (parser$3.specialized[i$1] == token.value) {
let result = parser$3.specializers[i$1](this.stream.read(token.start, token.end), stack);
if (result >= 0 && stack.p.parser.dialect.allows(result >> 1)) {
if ((result & 1) == 0) token.value = result >> 1;else token.extended = result >> 1;
break;
}
}
} else {
token.value = 0;
token.end = this.stream.clipPos(start + 1);
}
}
putAction(action, token, end, index) {
for (let i$1 = 0; i$1 < index; i$1 += 3) if (this.actions[i$1] == action) return index;
this.actions[index++] = action;
this.actions[index++] = token;
this.actions[index++] = end;
return index;
}
addActions(stack, token, end, index) {
let {
state
} = stack,
{
parser: parser$3
} = stack.p,
{
data
} = parser$3;
for (let set = 0; set < 2; set++) for (let i$1 = parser$3.stateSlot(state, set ? 2 : 1);; i$1 += 3) {
if (data[i$1] == 65535) if (data[i$1 + 1] == 1) i$1 = pair(data, i$1 + 2);else {
if (index == 0 && data[i$1 + 1] == 2) index = this.putAction(pair(data, i$1 + 2), token, end, index);
break;
}
if (data[i$1] == token) index = this.putAction(pair(data, i$1 + 1), token, end, index);
}
return index;
}
};
Parse = class {
constructor(parser$3, input, fragments, ranges) {
this.parser = parser$3;
this.input = input;
this.ranges = ranges;
this.recovering = 0;
this.nextStackID = 9812;
this.minStackPos = 0;
this.reused = [];
this.stoppedAt = null;
this.lastBigReductionStart = -1;
this.lastBigReductionSize = 0;
this.bigReductionCount = 0;
this.stream = new InputStream(input, ranges);
this.tokens = new TokenCache(parser$3, this.stream);
this.topTerm = parser$3.top[1];
let {
from
} = ranges[0];
this.stacks = [Stack.start(this, parser$3.top[0], from)];
this.fragments = fragments.length && this.stream.end - from > parser$3.bufferLength * 4 ? new FragmentCursor(fragments, parser$3.nodeSet) : null;
}
get parsedPos() {
return this.minStackPos;
}
advance() {
let stacks = this.stacks,
pos = this.minStackPos;
let newStacks = this.stacks = [];
let stopped, stoppedTokens;
if (this.bigReductionCount > 300 && stacks.length == 1) {
let [s] = stacks;
while (s.forceReduce() && s.stack.length && s.stack[s.stack.length - 2] >= this.lastBigReductionStart);
this.bigReductionCount = this.lastBigReductionSize = 0;
}
for (let i$1 = 0; i$1 < stacks.length; i$1++) {
let stack = stacks[i$1];
for (;;) {
this.tokens.mainToken = null;
if (stack.pos > pos) newStacks.push(stack);else if (this.advanceStack(stack, newStacks, stacks)) continue;else {
if (!stopped) {
stopped = [];
stoppedTokens = [];
}
stopped.push(stack);
let tok = this.tokens.getMainToken(stack);
stoppedTokens.push(tok.value, tok.end);
}
break;
}
}
if (!newStacks.length) {
let finished = stopped && findFinished(stopped);
if (finished) {
if (verbose) console.log("Finish with " + this.stackID(finished));
return this.stackToTree(finished);
}
if (this.parser.strict) {
if (verbose && stopped) console.log("Stuck with token " + (this.tokens.mainToken ? this.parser.getName(this.tokens.mainToken.value) : "none"));
throw new SyntaxError("No parse at " + pos);
}
if (!this.recovering) this.recovering = 5;
}
if (this.recovering && stopped) {
let finished = this.stoppedAt != null && stopped[0].pos > this.stoppedAt ? stopped[0] : this.runRecovery(stopped, stoppedTokens, newStacks);
if (finished) {
if (verbose) console.log("Force-finish " + this.stackID(finished));
return this.stackToTree(finished.forceAll());
}
}
if (this.recovering) {
let maxRemaining = this.recovering == 1 ? 1 : this.recovering * 3;
if (newStacks.length > maxRemaining) {
newStacks.sort((a, b) => b.score - a.score);
while (newStacks.length > maxRemaining) newStacks.pop();
}
if (newStacks.some(s => s.reducePos > pos)) this.recovering--;
} else if (newStacks.length > 1) {
outer: for (let i$1 = 0; i$1 < newStacks.length - 1; i$1++) {
let stack = newStacks[i$1];
for (let j = i$1 + 1; j < newStacks.length; j++) {
let other = newStacks[j];
if (stack.sameState(other) || stack.buffer.length > 500 && other.buffer.length > 500) if ((stack.score - other.score || stack.buffer.length - other.buffer.length) > 0) newStacks.splice(j--, 1);else {
newStacks.splice(i$1--, 1);
continue outer;
}
}
}
if (newStacks.length > 12) newStacks.splice(12, newStacks.length - 12);
}
this.minStackPos = newStacks[0].pos;
for (let i$1 = 1; i$1 < newStacks.length; i$1++) if (newStacks[i$1].pos < this.minStackPos) this.minStackPos = newStacks[i$1].pos;
return null;
}
stopAt(pos) {
if (this.stoppedAt != null && this.stoppedAt < pos) throw new RangeError("Can't move stoppedAt forward");
this.stoppedAt = pos;
}
advanceStack(stack, stacks, split) {
let start = stack.pos,
{
parser: parser$3
} = this;
let base$1 = verbose ? this.stackID(stack) + " -> " : "";
if (this.stoppedAt != null && start > this.stoppedAt) return stack.forceReduce() ? stack : null;
if (this.fragments) {
let strictCx = stack.curContext && stack.curContext.tracker.strict,
cxHash = strictCx ? stack.curContext.hash : 0;
for (let cached = this.fragments.nodeAt(start); cached;) {
let match = this.parser.nodeSet.types[cached.type.id] == cached.type ? parser$3.getGoto(stack.state, cached.type.id) : -1;
if (match > -1 && cached.length && (!strictCx || (cached.prop(NodeProp.contextHash) || 0) == cxHash)) {
stack.useNode(cached, match);
if (verbose) console.log(base$1 + this.stackID(stack) + ` (via reuse of ${parser$3.getName(cached.type.id)})`);
return true;
}
if (!(cached instanceof Tree) || cached.children.length == 0 || cached.positions[0] > 0) break;
let inner = cached.children[0];
if (inner instanceof Tree && cached.positions[0] == 0) cached = inner;else break;
}
}
let defaultReduce = parser$3.stateSlot(stack.state, 4);
if (defaultReduce > 0) {
stack.reduce(defaultReduce);
if (verbose) console.log(base$1 + this.stackID(stack) + ` (via always-reduce ${parser$3.getName(defaultReduce & 65535)})`);
return true;
}
if (stack.stack.length >= 8400) while (stack.stack.length > 6e3 && stack.forceReduce());
let actions = this.tokens.getActions(stack);
for (let i$1 = 0; i$1 < actions.length;) {
let action = actions[i$1++],
term = actions[i$1++],
end = actions[i$1++];
let last = i$1 == actions.length || !split;
let localStack = last ? stack : stack.split();
let main = this.tokens.mainToken;
localStack.apply(action, term, main ? main.start : localStack.pos, end);
if (verbose) console.log(base$1 + this.stackID(localStack) + ` (via ${(action & 65536) == 0 ? "shift" : `reduce of ${parser$3.getName(action & 65535)}`} for ${parser$3.getName(term)} @ ${start}${localStack == stack ? "" : ", split"})`);
if (last) return true;else if (localStack.pos > start) stacks.push(localStack);else split.push(localStack);
}
return false;
}
advanceFully(stack, newStacks) {
let pos = stack.pos;
for (;;) {
if (!this.advanceStack(stack, null, null)) return false;
if (stack.pos > pos) {
pushStackDedup(stack, newStacks);
return true;
}
}
}
runRecovery(stacks, tokens, newStacks) {
let finished = null,
restarted = false;
for (let i$1 = 0; i$1 < stacks.length; i$1++) {
let stack = stacks[i$1],
token = tokens[i$1 << 1],
tokenEnd = tokens[(i$1 << 1) + 1];
let base$1 = verbose ? this.stackID(stack) + " -> " : "";
if (stack.deadEnd) {
if (restarted) continue;
restarted = true;
stack.restart();
if (verbose) console.log(base$1 + this.stackID(stack) + " (restarted)");
if (this.advanceFully(stack, newStacks)) continue;
}
let force = stack.split(),
forceBase = base$1;
for (let j = 0; force.forceReduce() && j < 10; j++) {
if (verbose) console.log(forceBase + this.stackID(force) + " (via force-reduce)");
if (this.advanceFully(force, newStacks)) break;
if (verbose) forceBase = this.stackID(force) + " -> ";
}
for (let insert$2 of stack.recoverByInsert(token)) {
if (verbose) console.log(base$1 + this.stackID(insert$2) + " (via recover-insert)");
this.advanceFully(insert$2, newStacks);
}
if (this.stream.end > stack.pos) {
if (tokenEnd == stack.pos) {
tokenEnd++;
token = 0;
}
stack.recoverByDelete(token, tokenEnd);
if (verbose) console.log(base$1 + this.stackID(stack) + ` (via recover-delete ${this.parser.getName(token)})`);
pushStackDedup(stack, newStacks);
} else if (!finished || finished.score < stack.score) finished = stack;
}
return finished;
}
stackToTree(stack) {
stack.close();
return Tree.build({
buffer: StackBufferCursor.create(stack),
nodeSet: this.parser.nodeSet,
topID: this.topTerm,
maxBufferLength: this.parser.bufferLength,
reused: this.reused,
start: this.ranges[0].from,
length: stack.pos - this.ranges[0].from,
minRepeatType: this.parser.minRepeatTerm
});
}
stackID(stack) {
let id$1 = (stackIDs || (stackIDs = /* @__PURE__ */new WeakMap())).get(stack);
if (!id$1) stackIDs.set(stack, id$1 = String.fromCodePoint(this.nextStackID++));
return id$1 + stack;
}
};
Dialect = class {
constructor(source, flags, disabled) {
this.source = source;
this.flags = flags;
this.disabled = disabled;
}
allows(term) {
return !this.disabled || this.disabled[term] == 0;
}
};
id = x => x;
/**
Context trackers are used to track stateful context (such as
indentation in the Python grammar, or parent elements in the XML
grammar) needed by external tokenizers. You declare them in a
grammar file as `@context exportName from "module"`.
Context values should be immutable, and can be updated (replaced)
on shift or reduce actions.
The export used in a `@context` declaration should be of this
type.
*/
_export("W", ContextTracker = class {
/**
Define a context tracker.
*/
constructor(spec) {
this.start = spec.start;
this.shift = spec.shift || id;
this.reduce = spec.reduce || id;
this.reuse = spec.reuse || id;
this.hash = spec.hash || (() => 0);
this.strict = spec.strict !== false;
}
});
/**
Holds the parse tables for a given grammar, as generated by
`lezer-generator`, and provides [methods](#common.Parser) to parse
content with.
*/
_export("K", LRParser = class LRParser extends Parser {
/**
@internal
*/
constructor(spec) {
super();
/**
@internal
*/
this.wrappers = [];
if (spec.version != 14) throw new RangeError(`Parser version (${spec.version}) doesn't match runtime version (14)`);
let nodeNames = spec.nodeNames.split(" ");
this.minRepeatTerm = nodeNames.length;
for (let i$1 = 0; i$1 < spec.repeatNodeCount; i$1++) nodeNames.push("");
let topTerms = Object.keys(spec.topRules).map(r => spec.topRules[r][1]);
let nodeProps = [];
for (let i$1 = 0; i$1 < nodeNames.length; i$1++) nodeProps.push([]);
function setProp(nodeID, prop, value) {
nodeProps[nodeID].push([prop, prop.deserialize(String(value))]);
}
if (spec.nodeProps) for (let propSpec of spec.nodeProps) {
let prop = propSpec[0];
if (typeof prop == "string") prop = NodeProp[prop];
for (let i$1 = 1; i$1 < propSpec.length;) {
let next = propSpec[i$1++];
if (next >= 0) setProp(next, prop, propSpec[i$1++]);else {
let value = propSpec[i$1 + -next];
for (let j = -next; j > 0; j--) setProp(propSpec[i$1++], prop, value);
i$1++;
}
}
}
this.nodeSet = new NodeSet(nodeNames.map((name$1, i$1) => NodeType.define({
name: i$1 >= this.minRepeatTerm ? void 0 : name$1,
id: i$1,
props: nodeProps[i$1],
top: topTerms.indexOf(i$1) > -1,
error: i$1 == 0,
skipped: spec.skippedNodes && spec.skippedNodes.indexOf(i$1) > -1
})));
if (spec.propSources) this.nodeSet = this.nodeSet.extend(...spec.propSources);
this.strict = false;
this.bufferLength = DefaultBufferLength;
let tokenArray = decodeArray(spec.tokenData);
this.context = spec.context;
this.specializerSpecs = spec.specialized || [];
this.specialized = new Uint16Array(this.specializerSpecs.length);
for (let i$1 = 0; i$1 < this.specializerSpecs.length; i$1++) this.specialized[i$1] = this.specializerSpecs[i$1].term;
this.specializers = this.specializerSpecs.map(getSpecializer);
this.states = decodeArray(spec.states, Uint32Array);
this.data = decodeArray(spec.stateData);
this.goto = decodeArray(spec.goto);
this.maxTerm = spec.maxTerm;
this.tokenizers = spec.tokenizers.map(value => typeof value == "number" ? new TokenGroup(tokenArray, value) : value);
this.topRules = spec.topRules;
this.dialects = spec.dialects || {};
this.dynamicPrecedences = spec.dynamicPrecedences || null;
this.tokenPrecTable = spec.tokenPrec;
this.termNames = spec.termNames || null;
this.maxNode = this.nodeSet.types.length - 1;
this.dialect = this.parseDialect();
this.top = this.topRules[Object.keys(this.topRules)[0]];
}
createParse(input, fragments, ranges) {
let parse = new Parse(this, input, fragments, ranges);
for (let w of this.wrappers) parse = w(parse, input, fragments, ranges);
return parse;
}
/**
Get a goto table entry @internal
*/
getGoto(state, term, loose = false) {
let table = this.goto;
if (term >= table[0]) return -1;
for (let pos = table[term + 1];;) {
let groupTag = table[pos++],
last = groupTag & 1;
let target = table[pos++];
if (last && loose) return target;
for (let end = pos + (groupTag >> 1); pos < end; pos++) if (table[pos] == state) return target;
if (last) return -1;
}
}
/**
Check if this state has an action for a given terminal @internal
*/
hasAction(state, terminal) {
let data = this.data;
for (let set = 0; set < 2; set++) for (let i$1 = this.stateSlot(state, set ? 2 : 1), next;; i$1 += 3) {
if ((next = data[i$1]) == 65535) if (data[i$1 + 1] == 1) next = data[i$1 = pair(data, i$1 + 2)];else if (data[i$1 + 1] == 2) return pair(data, i$1 + 2);else break;
if (next == terminal || next == 0) return pair(data, i$1 + 1);
}
return 0;
}
/**
@internal
*/
stateSlot(state, slot) {
return this.states[state * 6 + slot];
}
/**
@internal
*/
stateFlag(state, flag) {
return (this.stateSlot(state, 0) & flag) > 0;
}
/**
@internal
*/
validAction(state, action) {
return !!this.allActions(state, a => a == action ? true : null);
}
/**
@internal
*/
allActions(state, action) {
let deflt = this.stateSlot(state, 4);
let result = deflt ? action(deflt) : void 0;
for (let i$1 = this.stateSlot(state, 1); result == null; i$1 += 3) {
if (this.data[i$1] == 65535) if (this.data[i$1 + 1] == 1) i$1 = pair(this.data, i$1 + 2);else break;
result = action(pair(this.data, i$1 + 1));
}
return result;
}
/**
Get the states that can follow this one through shift actions or
goto jumps. @internal
*/
nextStates(state) {
let result = [];
for (let i$1 = this.stateSlot(state, 1);; i$1 += 3) {
if (this.data[i$1] == 65535) if (this.data[i$1 + 1] == 1) i$1 = pair(this.data, i$1 + 2);else break;
if ((this.data[i$1 + 2] & 1) == 0) {
let value = this.data[i$1 + 1];
if (!result.some((v, i$2) => i$2 & 1 && v == value)) result.push(this.data[i$1], value);
}
}
return result;
}
/**
Configure the parser. Returns a new parser instance that has the
given settings modified. Settings not provided in `config` are
kept from the original parser.
*/
configure(config$1) {
let copy = Object.assign(Object.create(LRParser.prototype), this);
if (config$1.props) copy.nodeSet = this.nodeSet.extend(...config$1.props);
if (config$1.top) {
let info = this.topRules[config$1.top];
if (!info) throw new RangeError(`Invalid top rule name ${config$1.top}`);
copy.top = info;
}
if (config$1.tokenizers) copy.tokenizers = this.tokenizers.map(t$1 => {
let found = config$1.tokenizers.find(r => r.from == t$1);
return found ? found.to : t$1;
});
if (config$1.specializers) {
copy.specializers = this.specializers.slice();
copy.specializerSpecs = this.specializerSpecs.map((s, i$1) => {
let found = config$1.specializers.find(r => r.from == s.external);
if (!found) return s;
let spec = Object.assign(Object.assign({}, s), {
external: found.to
});
copy.specializers[i$1] = getSpecializer(spec);
return spec;
});
}
if (config$1.contextTracker) copy.context = config$1.contextTracker;
if (config$1.dialect) copy.dialect = this.parseDialect(config$1.dialect);
if (config$1.strict != null) copy.strict = config$1.strict;
if (config$1.wrap) copy.wrappers = copy.wrappers.concat(config$1.wrap);
if (config$1.bufferLength != null) copy.bufferLength = config$1.bufferLength;
return copy;
}
/**
Tells you whether any [parse wrappers](#lr.ParserConfig.wrap)
are registered for this parser.
*/
hasWrappers() {
return this.wrappers.length > 0;
}
/**
Returns the name associated with a given term. This will only
work for all terms when the parser was generated with the
`--names` option. By default, only the names of tagged terms are
stored.
*/
getName(term) {
return this.termNames ? this.termNames[term] : String(term <= this.maxNode && this.nodeSet.types[term].name || term);
}
/**
The eof term id is always allocated directly after the node
types. @internal
*/
get eofTerm() {
return this.maxNode + 1;
}
/**
The type of top node produced by the parser.
*/
get topNode() {
return this.nodeSet.types[this.top[1]];
}
/**
@internal
*/
dynamicPrecedence(term) {
let prec$2 = this.dynamicPrecedences;
return prec$2 == null ? 0 : prec$2[term] || 0;
}
/**
@internal
*/
parseDialect(dialect) {
let values = Object.keys(this.dialects),
flags = values.map(() => false);
if (dialect) for (let part of dialect.split(" ")) {
let id$1 = values.indexOf(part);
if (id$1 >= 0) flags[id$1] = true;
}
let disabled = null;
for (let i$1 = 0; i$1 < values.length; i$1++) if (!flags[i$1]) for (let j = this.dialects[values[i$1]], id$1; (id$1 = this.data[j++]) != 65535;) (disabled || (disabled = new Uint8Array(this.maxTerm + 1)))[id$1] = 1;
return new Dialect(dialect, flags, disabled);
}
/**
Used by the output of the parser generator. Not available to
user code. @hide
*/
static deserialize(spec) {
return new LRParser(spec);
}
});
TSExtends = 1, noSemi = 281, incdec = 2, incdecPrefix = 3, templateContent = 282, InterpolationStart = 4, templateEnd = 283, insertSemi = 284, spaces = 286, newline = 287, LineComment = 5, BlockComment = 6, Dialect_ts = 1;
space = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200, 8201, 8202, 8232, 8233, 8239, 8287, 12288];
braceR = 125, braceL = 123, semicolon = 59, slash = 47, star = 42, plus = 43, minus = 45, dollar = 36, backtick = 96, backslash = 92;
trackNewline = new ContextTracker({
start: false,
shift(context, term) {
return term == LineComment || term == BlockComment || term == spaces ? context : term == newline;
},
strict: false
});
insertSemicolon = new ExternalTokenizer((input, stack) => {
let {
next
} = input;
if ((next == braceR || next == -1 || stack.context) && stack.canShift(insertSemi)) input.acceptToken(insertSemi);
}, {
contextual: true,
fallback: true
});
noSemicolon = new ExternalTokenizer((input, stack) => {
let {
next
} = input,
after;
if (space.indexOf(next) > -1) return;
if (next == slash && ((after = input.peek(1)) == slash || after == star)) return;
if (next != braceR && next != semicolon && next != -1 && !stack.context && stack.canShift(noSemi)) input.acceptToken(noSemi);
}, {
contextual: true
});
incdecToken = new ExternalTokenizer((input, stack) => {
let {
next
} = input;
if (next == plus || next == minus) {
input.advance();
if (next == input.next) {
input.advance();
let mayPostfix = !stack.context && stack.canShift(incdec);
input.acceptToken(mayPostfix ? incdec : incdecPrefix);
}
}
}, {
contextual: true
});
template = new ExternalTokenizer(input => {
for (let afterDollar = false, i$1 = 0;; i$1++) {
let {
next
} = input;
if (next < 0) {
if (i$1) input.acceptToken(templateContent);
break;
} else if (next == backtick) {
if (i$1) input.acceptToken(templateContent);else input.acceptToken(templateEnd, 1);
break;
} else if (next == braceL && afterDollar) {
if (i$1 == 1) input.acceptToken(InterpolationStart, 1);else input.acceptToken(templateContent, -1);
break;
} else if (next == 10 && i$1) {
input.advance();
input.acceptToken(templateContent);
break;
} else if (next == backslash) input.advance();
afterDollar = next == dollar;
input.advance();
}
});
tsExtends = new ExternalTokenizer((input, stack) => {
if (input.next != 101 || !stack.dialectEnabled(Dialect_ts)) return;
input.advance();
for (let i$1 = 0; i$1 < 6; i$1++) {
if (input.next != "xtends".charCodeAt(i$1)) return;
input.advance();
}
if (input.next >= 57 && input.next <= 65 || input.next >= 48 && input.next <= 90 || input.next == 95 || input.next >= 97 && input.next <= 122 || input.next > 160) return;
input.acceptToken(TSExtends);
});
jsHighlight = styleTags({
"get set async static": tags.modifier,
"for while do if else switch try catch finally return throw break continue default case": tags.controlKeyword,
"in of await yield void typeof delete instanceof": tags.operatorKeyword,
"let var const function class extends": tags.definitionKeyword,
"import export from": tags.moduleKeyword,
"with debugger as new": tags.keyword,
TemplateString: tags.special(tags.string),
super: tags.atom,
BooleanLiteral: tags.bool,
this: tags.self,
null: tags.null,
Star: tags.modifier,
VariableName: tags.variableName,
"CallExpression/VariableName TaggedTemplateExpression/VariableName": tags.function(tags.variableName),
VariableDefinition: tags.definition(tags.variableName),
Label: tags.labelName,
PropertyName: tags.propertyName,
PrivatePropertyName: tags.special(tags.propertyName),
"CallExpression/MemberExpression/PropertyName": tags.function(tags.propertyName),
"FunctionDeclaration/VariableDefinition": tags.function(tags.definition(tags.variableName)),
"ClassDeclaration/VariableDefinition": tags.definition(tags.className),
PropertyDefinition: tags.definition(tags.propertyName),
PrivatePropertyDefinition: tags.definition(tags.special(tags.propertyName)),
UpdateOp: tags.updateOperator,
LineComment: tags.lineComment,
BlockComment: tags.blockComment,
Number: tags.number,
String: tags.string,
ArithOp: tags.arithmeticOperator,
LogicOp: tags.logicOperator,
BitOp: tags.bitwiseOperator,
CompareOp: tags.compareOperator,
RegExp: tags.regexp,
Equals: tags.definitionOperator,
Arrow: tags.function(tags.punctuation),
": Spread": tags.punctuation,
"( )": tags.paren,
"[ ]": tags.squareBracket,
"{ }": tags.brace,
"InterpolationStart InterpolationEnd": tags.special(tags.brace),
".": tags.derefOperator,
", ;": tags.separator,
TypeName: tags.typeName,
TypeDefinition: tags.definition(tags.typeName),
"type enum interface implements namespace module declare": tags.definitionKeyword,
"abstract global Privacy readonly override": tags.modifier,
"is keyof unique infer": tags.operatorKeyword,
JSXAttributeValue: tags.attributeValue,
JSXText: tags.content,
"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag": tags.angleBracket,
"JSXIdentifier JSXNameSpacedName": tags.tagName,
"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName": tags.attributeName
});
spec_identifier = {
__proto__: null,
export: 18,
as: 23,
from: 29,
default: 32,
async: 37,
function: 38,
this: 48,
true: 56,
false: 56,
void: 66,
typeof: 70,
null: 86,
super: 88,
new: 122,
await: 139,
yield: 141,
delete: 142,
class: 152,
extends: 154,
public: 197,
private: 197,
protected: 197,
readonly: 199,
instanceof: 220,
in: 222,
const: 224,
import: 256,
keyof: 307,
unique: 311,
infer: 317,
is: 351,
abstract: 371,
implements: 373,
type: 375,
let: 378,
var: 380,
interface: 387,
enum: 391,
namespace: 397,
module: 399,
declare: 403,
global: 407,
for: 428,
of: 437,
while: 440,
with: 444,
do: 448,
if: 452,
else: 454,
switch: 458,
case: 464,
try: 470,
catch: 474,
finally: 478,
return: 482,
throw: 486,
break: 490,
continue: 494,
debugger: 498
};
spec_word = {
__proto__: null,
async: 109,
get: 111,
set: 113,
public: 161,
private: 161,
protected: 161,
static: 163,
abstract: 165,
override: 167,
readonly: 173,
new: 355
};
spec_LessThan = {
__proto__: null,
"<": 129
};
parser$2 = LRParser.deserialize({
version: 14,
states: "$8SO`QdOOO'QQ(C|O'#ChO'XOWO'#DVO)dQdO'#D]O)tQdO'#DhO){QdO'#DrO-xQdO'#DxOOQO'#E]'#E]O.]Q`O'#E[O.bQ`O'#E[OOQ(C['#Ef'#EfO0aQ(C|O'#ItO2wQ(C|O'#IuO3eQ`O'#EzO3jQ!bO'#FaOOQ(C['#FS'#FSO3rO#tO'#FSO4QQ&jO'#FhO5bQ`O'#FgOOQ(C['#Iu'#IuOOQ(CW'#It'#ItOOQS'#J^'#J^O5gQ`O'#HpO5lQ(ChO'#HqOOQS'#Ih'#IhOOQS'#Hr'#HrQ`QdOOO){QdO'#DjO5tQ`O'#G[O5yQ&jO'#CmO6XQ`O'#EZO6dQ`O'#EgO6iQ,UO'#FRO7TQ`O'#G[O7YQ`O'#G`O7eQ`O'#G`O7sQ`O'#GcO7sQ`O'#GdO7sQ`O'#GfO5tQ`O'#GiO8dQ`O'#GlO9rQ`O'#CdO:SQ`O'#GyO:[Q`O'#HPO:[Q`O'#HRO`QdO'#HTO:[Q`O'#HVO:[Q`O'#HYO:aQ`O'#H`O:fQ(CjO'#HfO){QdO'#HhO:qQ(CjO'#HjO:|Q(CjO'#HlO5lQ(ChO'#HnO){QdO'#DWOOOW'#Ht'#HtO;XOWO,59qOOQ(C[,59q,59qO=jQtO'#ChO=tQdO'#HuO>XQ`O'#IvO@WQtO'#IvO'dQdO'#IvO@_Q`O,59wO@uQ7[O'#DbOAnQ`O'#E]OA{Q`O'#JROBWQ`O'#JQOBWQ`O'#JQOB`Q`O,5:yOBeQ`O'#JPOBlQaO'#DyO5yQ&jO'#EZOBzQ`O'#EZOCVQpO'#FROOQ(C[,5:S,5:SOC_QdO,5:SOE]Q(C|O,5:^OEyQ`O,5:dOFdQ(ChO'#JOO7YQ`O'#I}OFkQ`O'#I}OFsQ`O,5:xOFxQ`O'#I}OGWQdO,5:vOIWQ&jO'#EWOJeQ`O,5:vOKwQ&jO'#DlOLOQdO'#DqOLYQ7[O,5;PO){QdO,5;POOQS'#Er'#ErOOQS'#Et'#EtO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;RO){QdO,5;ROOQS'#Ex'#ExOLbQdO,5;cOOQ(C[,5;h,5;hOOQ(C[,5;i,5;iONbQ`O,5;iOOQ(C[,5;j,5;jO){QdO'#IPONgQ(ChO,5<TO! RQ&jO,5;RO){QdO,5;fO! kQ!bO'#JVO! YQ!bO'#JVO! rQ!bO'#JVO!!TQ!bO,5;qOOOO,5;{,5;{O!!cQdO'#FcOOOO'#IO'#IOO3rO#tO,5;nO!!jQ!bO'#FeOOQ(C[,5;n,5;nO!#WQ,VO'#CrOOQ(C]'#Cu'#CuO!#kQ`O'#CuO!#pOWO'#CyO!$^Q,VO,5<QO!$eQ`O,5<SO!%tQ&jO'#FrO!&RQ`O'#FsO!&WQ`O'#FsO!&]Q&jO'#FwO!'[Q7[O'#F{O!'}Q,VO'#IqOOQ(C]'#Iq'#IqO!(XQaO'#IpO!(gQ`O'#IoO!(oQ`O'#CqOOQ(C]'#Cs'#CsOOQ(C]'#C|'#C|O!(wQ`O'#DOOJjQ&jO'#FjOJjQ&jO'#FlO!(|Q`O'#FnO!)RQ`O'#FoO!&WQ`O'#FuOJjQ&jO'#FzO!)WQ`O'#E^O!)oQ`O,5<RO`QdO,5>[OOQS'#Ik'#IkOOQS,5>],5>]OOQS-E;p-E;pO!+kQ(C|O,5:UOOQ(CX'#Cp'#CpO!,[Q&kO,5<vOOQO'#Cf'#CfO!,mQ(ChO'#IlO5bQ`O'#IlO:aQ`O,59XO!-OQ!bO,59XO!-WQ&jO,59XO5yQ&jO,59XO!-cQ`O,5:vO!-kQ`O'#GxO!-yQ`O'#JbO){QdO,5;kO!.RQ7[O,5;mO!.WQ`O,5=cO!.]Q`O,5=cO!.bQ`O,5=cO5lQ(ChO,5=cO5tQ`O,5<vO!.pQ`O'#E_O!/UQ7[O'#E`OOQ(CW'#JP'#JPO!/gQ(ChO'#J_O5lQ(ChO,5<zO7sQ`O,5=QOOQP'#Cr'#CrO!/rQ!bO,5<}O!/zQ!cO,5=OO!0VQ`O,5=QO!0[QpO,5=TO:aQ`O'#GnO5tQ`O'#GpO!0dQ`O'#GpO5yQ&jO'#GsO!0iQ`O'#GsOOQS,5=W,5=WO!0nQ`O'#GtO!0vQ`O'#CmO!0{Q`O,59OO!1VQ`O,59OO!3XQdO,59OOOQS,59O,59OO!3fQ(ChO,59OO){QdO,59OO!3qQdO'#G{OOQS'#G|'#G|OOQS'#G}'#G}O`QdO,5=eO!4RQ`O,5=eO){QdO'#DxO`QdO,5=kO`QdO,5=mO!4WQ`O,5=oO`QdO,5=qO!4]Q`O,5=tO!4bQdO,5=zOOQS,5>Q,5>QO){QdO,5>QO5lQ(ChO,5>SOOQS,5>U,5>UO!8cQ`O,5>UOOQS,5>W,5>WO!8cQ`O,5>WOOQS,5>Y,5>YO!8hQpO,59rOOOW-E;r-E;rOOQ(C[1G/]1G/]O!8mQtO,5>aO'dQdO,5>aOOQO,5>f,5>fO!8wQdO'#HuOOQO-E;s-E;sO!9UQ`O,5?bO!9^QtO,5?bO!9eQ`O,5?lOOQ(C[1G/c1G/cO!9mQ!bO'#DTOOQO'#Ix'#IxO){QdO'#IxO!:[Q!bO'#IxO!:yQ!bO'#DcO!;[Q7[O'#DcO!=gQdO'#DcO!=nQ`O'#IwO!=vQ`O,59|O!={Q`O'#EaO!>ZQ`O'#JSO!>cQ`O,5:zO!>yQ7[O'#DcO){QdO,5?mO!?TQ`O'#HzOOQO-E;x-E;xO!9eQ`O,5?lOOQ(CW1G0e1G0eO!@aQ7[O'#D|OOQ(C[,5:e,5:eO){QdO,5:eOIWQ&jO,5:eO!@hQaO,5:eO:aQ`O,5:uO!-OQ!bO,5:uO!-WQ&jO,5:uO5yQ&jO,5:uOOQ(C[1G/n1G/nOOQ(C[1G0O1G0OOOQ(CW'#EV'#EVO){QdO,5?jO!@sQ(ChO,5?jO!AUQ(ChO,5?jO!A]Q`O,5?iO!AeQ`O'#H|O!A]Q`O,5?iOOQ(CW1G0d1G0dO7YQ`O,5?iOOQ(C[1G0b1G0bO!BPQ(C|O1G0bO!CRQ(CyO,5:rOOQ(C]'#Fq'#FqO!CoQ(C}O'#IqOGWQdO1G0bO!EqQ,VO'#IyO!E{Q`O,5:WO!FQQtO'#IzO){QdO'#IzO!F[Q`O,5:]OOQ(C]'#DT'#DTOOQ(C[1G0k1G0kO!FaQ`O1G0kO!HrQ(C|O1G0mO!HyQ(C|O1G0mO!K^Q(C|O1G0mO!KeQ(C|O1G0mO!MlQ(C|O1G0mO!NPQ(C|O1G0mO#!pQ(C|O1G0mO#!wQ(C|O1G0mO#%[Q(C|O1G0mO#%cQ(C|O1G0mO#'WQ(C|O1G0mO#*QQMlO'#ChO#+{QMlO1G0}O#-vQMlO'#IuOOQ(C[1G1T1G1TO#.ZQ(C|O,5>kOOQ(CW-E;}-E;}O#.zQ(C}O1G0mOOQ(C[1G0m1G0mO#1PQ(C|O1G1QO#1pQ!bO,5;sO#1uQ!bO,5;tO#1zQ!bO'#F[O#2`Q`O'#FZOOQO'#JW'#JWOOQO'#H}'#H}O#2eQ!bO1G1]OOQ(C[1G1]1G1]OOOO1G1f1G1fO#2sQMlO'#ItO#2}Q`O,5;}OLbQdO,5;}OOOO-E;|-E;|OOQ(C[1G1Y1G1YOOQ(C[,5<P,5<PO#3SQ!bO,5<POOQ(C],59a,59aOIWQ&jO'#C{OOOW'#Hs'#HsO#3XOWO,59eOOQ(C],59e,59eO){QdO1G1lO!)RQ`O'#IRO#3dQ`O,5<eOOQ(C],5<b,5<bOOQO'#GV'#GVOJjQ&jO,5<pOOQO'#GX'#GXOJjQ&jO,5<rOIWQ&jO,5<tOOQO1G1n1G1nO#3oQqO'#CpO#4SQqO,5<^O#4ZQ`O'#JZO5tQ`O'#JZO#4iQ`O,5<`OJjQ&jO,5<_O#4nQ`O'#FtO#4yQ`O,5<_O#5OQqO'#FqO#5]QqO'#J[O#5gQ`O'#J[OIWQ&jO'#J[O#5lQ`O,5<cOOQ(CW'#Dg'#DgO#5qQ!bO'#F|O!'VQ7[O'#F|O!'VQ7[O'#GOO#6SQ`O'#GPO!&WQ`O'#GSO#6XQ(ChO'#ITO#6dQ7[O,5<gOOQ(C],5<g,5<gO#6kQ7[O'#F|O#6yQ7[O'#F}O#7RQ7[O'#F}OOQ(C],5<u,5<uOJjQ&jO,5?[OJjQ&jO,5?[O#7WQ`O'#IUO#7cQ`O,5?ZO#7kQ`O,59]OOQ(C]'#Ch'#ChO#8[Q,VO,59jOOQ(C],59j,59jO#8}Q,VO,5<UO#9pQ,VO,5<WO#9zQ`O,5<YOOQ(C],5<Z,5<ZO#:PQ`O,5<aO#:UQ,VO,5<fOGWQdO1G1mO#:fQ`O1G1mOOQS1G3v1G3vOOQ(C[1G/p1G/pONbQ`O1G/pOOQS1G2b1G2bOIWQ&jO1G2bO){QdO1G2bOIWQ&jO1G2bO#:kQaO1G2bO#<QQ&jO'#EWOOQ(CW,5?W,5?WO#<[Q(ChO,5?WOOQS1G.s1G.sO:aQ`O1G.sO!-OQ!bO1G.sO!-WQ&jO1G.sO#<mQ`O1G0bO#<rQ`O'#ChO#<}Q`O'#JcO#=VQ`O,5=dO#=[Q`O'#JcO#=aQ`O'#JcO#=iQ`O'#I^O#=wQ`O,5?|O#>PQtO1G1VOOQ(C[1G1X1G1XO5tQ`O1G2}O#>WQ`O1G2}O#>]Q`O1G2}O#>bQ`O1G2}OOQS1G2}1G2}O#>gQ&kO1G2bO7YQ`O'#JQO7YQ`O'#EaO7YQ`O'#IWO#>xQ(ChO,5?yOOQS1G2f1G2fO!0VQ`O1G2lOIWQ&jO1G2iO#?TQ`O1G2iOOQS1G2j1G2jOIWQ&jO1G2jO#?YQaO1G2jO#?bQ7[O'#GhOOQS1G2l1G2lO!'VQ7[O'#IYO!0[QpO1G2oOOQS1G2o1G2oOOQS,5=Y,5=YO#?jQ&kO,5=[O5tQ`O,5=[O#6SQ`O,5=_O5bQ`O,5=_O!-OQ!bO,5=_O!-WQ&jO,5=_O5yQ&jO,5=_O#?{Q`O'#JaO#@WQ`O,5=`OOQS1G.j1G.jO#@]Q(ChO1G.jO#@hQ`O1G.jO#@mQ`O1G.jO5lQ(ChO1G.jO#@uQtO,5@OO#APQ`O,5@OO#A[QdO,5=gO#AcQ`O,5=gO7YQ`O,5@OOOQS1G3P1G3PO`QdO1G3POOQS1G3V1G3VOOQS1G3X1G3XO:[Q`O1G3ZO#AhQdO1G3]O#EcQdO'#H[OOQS1G3`1G3`O#EpQ`O'#HbO:aQ`O'#HdOOQS1G3f1G3fO#ExQdO1G3fO5lQ(ChO1G3lOOQS1G3n1G3nOOQ(CW'#Fx'#FxO5lQ(ChO1G3pO5lQ(ChO1G3rOOOW1G/^1G/^O#IvQpO,5<TO#JOQtO1G3{OOQO1G4Q1G4QO){QdO,5>aO#JYQ`O1G4|O#JbQ`O1G5WO#JjQ`O,5?dOLbQdO,5:{O7YQ`O,5:{O:aQ`O,59}OLbQdO,59}O!-OQ!bO,59}O#JoQMlO,59}OOQO,5:{,5:{O#JyQ7[O'#HvO#KaQ`O,5?cOOQ(C[1G/h1G/hO#KiQ7[O'#H{O#K}Q`O,5?nOOQ(CW1G0f1G0fO!;[Q7[O,59}O#LVQtO1G5XO7YQ`O,5>fOOQ(CW'#ES'#ESO#LaQ(DjO'#ETO!@XQ7[O'#D}OOQO'#Hy'#HyO#L{Q7[O,5:hOOQ(C[,5:h,5:hO#MSQ7[O'#D}O#MeQ7[O'#D}O#MlQ7[O'#EYO#MoQ7[O'#ETO#M|Q7[O'#ETO!@XQ7[O'#ETO#NaQ`O1G0PO#NfQqO1G0POOQ(C[1G0P1G0PO){QdO1G0POIWQ&jO1G0POOQ(C[1G0a1G0aO:aQ`O1G0aO!-OQ!bO1G0aO!-WQ&jO1G0aO#NmQ(C|O1G5UO){QdO1G5UO#N}Q(ChO1G5UO$ `Q`O1G5TO7YQ`O,5>hOOQO,5>h,5>hO$ hQ`O,5>hOOQO-E;z-E;zO$ `Q`O1G5TO$ vQ(C}O,59jO$#xQ(C}O,5<UO$%}Q(C}O,5<WO$(SQ(C}O,5<fOOQ(C[7+%|7+%|O$*_Q(C|O7+%|O$+OQ&jO'#HwO$+YQ`O,5?eOOQ(C]1G/r1G/rO$+bQdO'#HxO$+oQ`O,5?fO$+wQtO,5?fOOQ(C[1G/w1G/wOOQ(C[7+&V7+&VO$,RQMlO,5:^O){QdO7+&iO$,]QMlO,5:UOOQO1G1_1G1_OOQO1G1`1G1`O$,jQ!LQO,5;vOLbQdO,5;uOOQO-E;{-E;{OOQ(C[7+&w7+&wOOOO7+'Q7+'QOOOO1G1i1G1iO$,uQ`O1G1iOOQ(C[1G1k1G1kO$,zQqO,59gOOOW-E;q-E;qOOQ(C]1G/P1G/PO$-RQ(C|O7+'WOOQ(C],5>m,5>mO$-rQ`O,5>mOOQ(C]1G2P1G2PP$-wQ`O'#IRPOQ(C]-E<P-E<PO$.hQ,VO1G2[O$/ZQ,VO1G2^O$/eQqO1G2`OOQ(C]1G1x1G1xO$/lQ`O'#IQO$/zQ`O,5?uO$/zQ`O,5?uO$0SQ`O,5?uO$0_Q`O,5?uOOQO1G1z1G1zO$0mQ,VO1G1yOJjQ&jO1G1yO$0}Q&jO'#ISO$1_Q`O,5?vOIWQ&jO,5?vO$1gQqO,5?vOOQ(C]1G1}1G1}OOQ(CW,5<h,5<hOOQ(CW,5<i,5<iO$1qQ`O,5<iO#5}Q`O,5<iO!-OQ!bO,5<hO$1vQ`O,5<jOOQ(CW,5<k,5<kO$1qQ`O,5<nOOQO,5>o,5>oOOQO-E<R-E<ROOQ(C]1G2R1G2RO!'VQ7[O,5<hO$2OQ`O,5<iO!'VQ7[O,5<jO!'VQ7[O,5<iO$2ZQ,VO1G4vO$2eQ,VO1G4vOOQO,5>p,5>pOOQO-E<S-E<SOOQP1G.w1G.wO!.RQ7[O,59lO){QdO,59lO$2rQ`O1G1tOJjQ&jO1G1{O$2wQ(C|O7+'XOOQ(C[7+'X7+'XOGWQdO7+'XOOQ(C[7+%[7+%[O$3hQqO'#J]O#NaQ`O7+'|O$3rQ`O7+'|O$3zQqO7+'|OOQS7+'|7+'|OIWQ&jO7+'|O){QdO7+'|OIWQ&jO7+'|O$4UQ(CyO'#ChO$4iQ(CyO,5<lO$5ZQ`O,5<lOOQ(CW1G4r1G4rOOQS7+$_7+$_O:aQ`O7+$_O!-OQ!bO7+$_OGWQdO7+%|O$5`Q`O'#I]O$5qQ`O,5?}OOQO1G3O1G3OO5tQ`O,5?}O$5qQ`O,5?}O$5yQ`O,5?}OOQO,5>x,5>xOOQO-E<[-E<[OOQ(C[7+&q7+&qO$6OQ`O7+(iO5lQ(ChO7+(iO5tQ`O7+(iO$6TQ`O7+(iO$6YQaO7+'|OOQ(CW,5>r,5>rOOQ(CW-E<U-E<UOOQS7+(W7+(WO$6hQ(CyO7+(TOIWQ&jO7+(TO$6rQqO7+(UOOQS7+(U7+(UOIWQ&jO7+(UO$6yQ`O'#J`O$7UQ`O,5=SOOQO,5>t,5>tOOQO-E<W-E<WOOQS7+(Z7+(ZO$8OQ7[O'#GqOOQS1G2v1G2vOIWQ&jO1G2vO){QdO1G2vOIWQ&jO1G2vO$8VQaO1G2vO$8eQ&kO1G2vO5lQ(ChO1G2yO#6SQ`O1G2yO5bQ`O1G2yO!-OQ!bO1G2yO!-WQ&jO1G2yO$8vQ`O'#I[O$9RQ`O,5?{O$9ZQ7[O,5?{OOQ(CW1G2z1G2zOOQS7+$U7+$UO$9cQ`O7+$UO5lQ(ChO7+$UO$9hQ`O7+$UO){QdO1G5jO){QdO1G5kO$9mQdO1G3RO$9tQ`O1G3RO$9yQdO1G3RO$:QQ(ChO1G5jOOQS7+(k7+(kO5lQ(ChO7+(uO`QdO7+(wOOQS'#Jf'#JfOOQS'#I_'#I_O$:[QdO,5=vOOQS,5=v,5=vO){QdO'#H]O$:iQ`O'#H_OOQS,5=|,5=|O7YQ`O,5=|OOQS,5>O,5>OOOQS7+)Q7+)QOOQS7+)W7+)WOOQS7+)[7+)[OOQS7+)^7+)^OOQO1G5O1G5OO$:nQMlO1G0gO$:xQ`O1G0gOOQO1G/i1G/iO$;TQMlO1G/iO:aQ`O1G/iOLbQdO'#DcOOQO,5>b,5>bOOQO-E;t-E;tOOQO,5>g,5>gOOQO-E;y-E;yO!-OQ!bO1G/iO:aQ`O,5:iOOQO,5:o,5:oO){QdO,5:oO$;_Q(ChO,5:oO$;jQ(ChO,5:oO!-OQ!bO,5:iOOQO-E;w-E;wOOQ(C[1G0S1G0SO!@XQ7[O,5:iO$;xQ7[O,5:iO$<ZQ(DjO,5:oO$<uQ7[O,5:iO!@XQ7[O,5:oOOQO,5:t,5:tO$<|Q7[O,5:oO$=ZQ(ChO,5:oOOQ(C[7+%k7+%kO#NaQ`O7+%kO#NfQqO7+%kOOQ(C[7+%{7+%{O:aQ`O7+%{O!-OQ!bO7+%{O$=oQ(C|O7+*pO){QdO7+*pOOQO1G4S1G4SO7YQ`O1G4SO$>PQ`O7+*oO$>XQ(C}O1G2[O$@^Q(C}O1G2^O$BcQ(C}O1G1yO$DnQ,VO,5>cOOQO-E;u-E;uO$DxQtO,5>dO){QdO,5>dOOQO-E;v-E;vO$ESQ`O1G5QO$E[QMlO1G0bO$GcQMlO1G0mO$GjQMlO1G0mO$IkQMlO1G0mO$IrQMlO1G0mO$KgQMlO1G0mO$KzQMlO1G0mO$NXQMlO1G0mO$N`QMlO1G0mO%!aQMlO1G0mO%!hQMlO1G0mO%$]QMlO1G0mO%$pQ(C|O<<JTO%%rQMmO1G0mO%'|QMmO'#IqO%)iQMlO1G1QOLbQdO'#F^OOQO'#JX'#JXOOQO1G1b1G1bO%)vQ`O1G1aO%){QMlO,5>kOOOO7+'T7+'TOOOW1G/R1G/ROOQ(C]1G4X1G4XOJjQ&jO7+'zO%*VQ`O,5>lO5tQ`O,5>lOOQO-E<O-E<OO%*eQ`O1G5aO%*eQ`O1G5aO%*mQ`O1G5aO%*xQ,VO7+'eO%+YQqO,5>nO%+dQ`O,5>nOIWQ&jO,5>nOOQO-E<Q-E<QO%+iQqO1G5bO%+sQ`O1G5bOOQ(CW1G2T1G2TO$1qQ`O1G2TOOQ(CW1G2S1G2SO%+{Q`O1G2UOIWQ&jO1G2UOOQ(CW1G2Y1G2YO!-OQ!bO1G2SO#5}Q`O1G2TO%,QQ`O1G2UO%,YQ`O1G2TOJjQ&jO7+*bOOQ(C]1G/W1G/WO%,eQ`O1G/WOOQ(C]7+'`7+'`O%,jQ,VO7+'gO%,zQ(C|O<<JsOOQ(C[<<Js<<JsOIWQ&jO'#IVO%-kQ`O,5?wOOQS<<Kh<<KhOIWQ&jO<<KhO#NaQ`O<<KhO%-sQ`O<<KhO%-{QqO<<KhOIWQ&jO1G2WOOQS<<Gy<<GyO:aQ`O<<GyO%.VQ(C|O<<IhOOQ(C[<<Ih<<IhOOQO,5>w,5>wO%.vQ`O,5>wO%.{Q`O,5>wOOQO-E<Z-E<ZO%/TQ`O1G5iO%/TQ`O1G5iO5tQ`O1G5iO%/]Q`O<<LTOOQS<<LT<<LTO%/bQ`O<<LTO5lQ(ChO<<LTO){QdO<<KhOIWQ&jO<<KhOOQS<<Ko<<KoO$6hQ(CyO<<KoOOQS<<Kp<<KpO$6rQqO<<KpO%/gQ7[O'#IXO%/rQ`O,5?zOLbQdO,5?zOOQS1G2n1G2nO#LaQ(DjO'#ETO!@XQ7[O'#GrOOQO'#IZ'#IZO%/zQ7[O,5=]OOQS,5=],5=]O%0RQ7[O'#ETO%0^Q7[O'#ETO%0uQ7[O'#ETO%1PQ7[O'#GrO%1bQ`O7+(bO%1gQ`O7+(bO%1oQqO7+(bOOQS7+(b7+(bOIWQ&jO7+(bO){QdO7+(bOIWQ&jO7+(bO%1yQaO7+(bOOQS7+(e7+(eO5lQ(ChO7+(eO#6SQ`O7+(eO5bQ`O7+(eO!-OQ!bO7+(eO%2XQ`O,5>vOOQO-E<Y-E<YOOQO'#Gu'#GuO%2dQ`O1G5gO5lQ(ChO<<GpOOQS<<Gp<<GpO%2lQ`O<<GpO%2qQ`O7++UO%2vQ`O7++VOOQS7+(m7+(mO%2{Q`O7+(mO%3QQdO7+(mO%3XQ`O7+(mO){QdO7++UO){QdO7++VOOQS<<La<<LaOOQS<<Lc<<LcOOQS-E<]-E<]OOQS1G3b1G3bO%3^Q`O,5=wOOQS,5=y,5=yO%3cQ`O1G3hOLbQdO7+&ROOQO7+%T7+%TO%3hQMlO1G5XO:aQ`O7+%TOOQO1G0T1G0TO%3rQ(C|O1G0ZOOQO1G0Z1G0ZO){QdO1G0ZO%3|Q(ChO1G0ZO:aQ`O1G0TO!-OQ!bO1G0TO!@XQ7[O1G0TO%4XQ(ChO1G0ZO%4gQ7[O1G0TO%4xQ(ChO1G0ZO%5^Q(DjO1G0ZO%5hQ7[O1G0TO!@XQ7[O1G0ZOOQ(C[<<IV<<IVOOQ(C[<<Ig<<IgO:aQ`O<<IgO%5oQ(C|O<<N[OOQO7+)n7+)nO%6PQ(C}O7+'eO%8[Q(C}O7+'gO%:gQtO1G4OO%:qQMlO7+%|O%;gQMmO,59jO%=hQMmO,5<UO%?lQMmO,5<WO%A[QMmO,5<fO%B}QMlO7+'WO%C[QMlO7+'XO%CiQ`O,5;xOOQO7+&{7+&{O%CnQ,VO<<KfOOQO1G4W1G4WO%CuQ`O1G4WO%DQQ`O1G4WO%D`Q`O7+*{O%D`Q`O7+*{OIWQ&jO1G4YO%DhQqO1G4YO%DrQ`O7+*|OOQ(CW7+'o7+'oO$1qQ`O7+'pO%DzQqO7+'pOOQ(CW7+'n7+'nO$1qQ`O7+'oO%ERQ`O7+'pOIWQ&jO7+'pO#5}Q`O7+'oO%EWQ,VO<<M|OOQ(C]7+$r7+$rO%EbQqO,5>qOOQO-E<T-E<TO#NaQ`OANASOOQSANASANASOIWQ&jOANASO%ElQ(CyO7+'rOOQSAN=eAN=eO5tQ`O1G4cOOQO1G4c1G4cO%E|Q`O1G4cO%FRQ`O7++TO%FRQ`O7++TO5lQ(ChOANAoO%FZQ`OANAoOOQSANAoANAoO%F`Q`OANASO%FhQqOANASOOQSANAZANAZOOQSANA[ANA[O%FrQ`O,5>sOOQO-E<V-E<VO%F}QMlO1G5fO#6SQ`O,5=^O5bQ`O,5=^O!-OQ!bO,5=^OOQO-E<X-E<XOOQS1G2w1G2wO$<ZQ(DjO,5:oO!@XQ7[O,5=^O%GXQ7[O,5=^O%GjQ7[O,5:oOOQS<<K|<<K|OIWQ&jO<<K|O%1bQ`O<<K|O%GtQ`O<<K|O%G|QqO<<K|O){QdO<<K|OIWQ&jO<<K|OOQS<<LP<<LPO5lQ(ChO<<LPO#6SQ`O<<LPO5bQ`O<<LPO%HWQ7[O1G4bO%H`Q`O7++ROOQSAN=[AN=[O5lQ(ChOAN=[OOQS<<Np<<NpOOQS<<Nq<<NqOOQS<<LX<<LXO%HhQ`O<<LXO%HmQdO<<LXO%HtQ`O<<NpO%HyQ`O<<NqOOQS1G3c1G3cO:aQ`O7+)SO%IOQMlO<<ImOOQO<<Ho<<HoOOQO7+%u7+%uO%3rQ(C|O7+%uO){QdO7+%uOOQO7+%o7+%oO:aQ`O7+%oO!-OQ!bO7+%oO%IYQ(ChO7+%uO!@XQ7[O7+%oO%IeQ(ChO7+%uO%IsQ7[O7+%oO%JUQ(ChO7+%uOOQ(C[AN?RAN?RO%JjQMlO<<JTO%JwQMmO1G1yO%MOQMmO1G2[O& SQMmO1G2^O&!rQMlO<<JsO&#PQMlO<<IhOOQO1G1d1G1dOJjQ&jOANAQOOQO7+)r7+)rO&#^Q`O7+)rO&#iQ`O<<NgO&#qQqO7+)tOOQ(CW<<K[<<K[O$1qQ`O<<K[OOQ(CW<<KZ<<KZO&#{QqO<<K[O$1qQ`O<<KZOOQSG26nG26nO#NaQ`OG26nOOQO7+)}7+)}O5tQ`O7+)}O&$SQ`O<<NoOOQSG27ZG27ZO5lQ(ChOG27ZOIWQ&jOG26nOLbQdO1G4_O&$[Q`O7++QO5lQ(ChO1G2xO#6SQ`O1G2xO5bQ`O1G2xO!-OQ!bO1G2xO!@XQ7[O1G2xO%5^Q(DjO1G0ZO&$dQ7[O1G2xO%1bQ`OANAhOOQSANAhANAhOIWQ&jOANAhO&$uQ`OANAhO&$}QqOANAhOOQSANAkANAkO5lQ(ChOANAkO#6SQ`OANAkOOQO'#Gv'#GvOOQO7+)|7+)|OOQSG22vG22vOOQSANAsANAsO&%XQ`OANAsOOQSAND[AND[OOQSAND]AND]OOQS<<Ln<<LnOOQO<<Ia<<IaO%3rQ(C|O<<IaOOQO<<IZ<<IZO:aQ`O<<IZO){QdO<<IaO!-OQ!bO<<IZO&%^Q(ChO<<IaO!@XQ7[O<<IZO&%iQ(ChO<<IaO&%wQMmO7+'eO&'jQMmO7+'gO&)]Q,VOG26lOOQO<<M^<<M^OOQ(CWAN@vAN@vO$1qQ`OAN@vOOQ(CWAN@uAN@uOOQSLD,YLD,YOOQO<<Mi<<MiOOQSLD,uLD,uO#NaQ`OLD,YO&)mQMlO7+)yOOQO7+(d7+(dO5lQ(ChO7+(dO#6SQ`O7+(dO5bQ`O7+(dO!-OQ!bO7+(dO!@XQ7[O7+(dOOQSG27SG27SO%1bQ`OG27SOIWQ&jOG27SOOQSG27VG27VO5lQ(ChOG27VOOQSG27_G27_OOQOAN>{AN>{OOQOAN>uAN>uO%3rQ(C|OAN>{O:aQ`OAN>uO){QdOAN>{O!-OQ!bOAN>uO&)wQ(ChOAN>{O&*SQ(C}OG26lOOQ(CWG26bG26bOOQS!$( t!$( tOOQO<<LO<<LOO5lQ(ChO<<LOO#6SQ`O<<LOO5bQ`O<<LOO!-OQ!bO<<LOOOQSLD,nLD,nO%1bQ`OLD,nOOQSLD,qLD,qOOQOG24gG24gOOQOG24aG24aO%3rQ(C|OG24gO:aQ`OG24aO){QdOG24gO&,pQ!LRO,5:rO&-gQ$ITO'#IqOOQOANAjANAjO5lQ(ChOANAjO#6SQ`OANAjO5bQ`OANAjOOQS!$(!Y!$(!YOOQOLD*RLD*ROOQOLD){LD){O%3rQ(C|OLD*RO&.ZQMmOG26lO&/|Q!LRO,59jO&0pQ!LRO,5<UO&1dQ!LRO,5<WO&2WQ!LRO,5<fOOQOG27UG27UO5lQ(ChOG27UO#6SQ`OG27UOOQO!$'Mm!$'MmO&2}Q!LRO1G2[O&3qQ!LRO1G2^O&4eQ!LRO1G1yOOQOLD,pLD,pO5lQ(ChOLD,pO&5[Q!LRO7+'eO&6RQ!LRO7+'gOOQO!$(![!$(![O&6xQ!LROG26lOLbQdO'#DrO&7oQtO'#ItOLbQdO'#DjO&7vQ(C|O'#ChO&8aQtO'#ChO&8qQdO,5:vO&:qQ&jO'#EWOLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO,5;ROLbQdO'#IPO&<OQ`O,5<TO&=eQ&jO,5;ROLbQdO,5;fO!(wQ`O'#DOO!(wQ`O'#DOO!(wQ`O'#DOOIWQ&jO'#FjO&:qQ&jO'#FjO&<WQ&jO'#FjOIWQ&jO'#FlO&:qQ&jO'#FlO&<WQ&jO'#FlOIWQ&jO'#FzO&:qQ&jO'#FzO&<WQ&jO'#FzOLbQdO,5?mO&8qQdO1G0bO&=lQMlO'#ChOLbQdO1G1lOIWQ&jO,5<pO&:qQ&jO,5<pO&<WQ&jO,5<pOIWQ&jO,5<rO&:qQ&jO,5<rO&<WQ&jO,5<rOIWQ&jO,5<_O&:qQ&jO,5<_O&<WQ&jO,5<_O&8qQdO1G1mOLbQdO7+&iOIWQ&jO1G1yO&:qQ&jO1G1yO&<WQ&jO1G1yOIWQ&jO1G1{O&:qQ&jO1G1{O&<WQ&jO1G1{O&8qQdO7+'XO&8qQdO7+%|O&=vQ`O7+'pOIWQ&jOANAQO&:qQ&jOANAQO&<WQ&jOANAQO&=vQ`O<<K[O&=vQ`OAN@vO&={Q`O'#E[O&>QQ`O'#E[O&>YQ`O'#EzO&>_Q`O'#EgO&>dQ`O'#JRO&>oQ`O'#JPO&>zQ`O,5:vO&?PQ,VO,5<QO&?WQ`O'#FsO&?]Q`O'#FsO&?bQ`O'#FsO&?gQ`O,5<RO&?oQ`O,5:vO&?wQMlO1G0}O&@OQ`O,5<_O&@TQ`O,5<_O&@YQ`O,5<_O&@_Q`O,5<aO&@dQ`O,5<aO&@iQ`O,5<aO&@nQ`O1G1mO&@sQ`O1G0bO&@xQ`O1G2UO&@}Q,VO<<KfO&AUQ,VO<<KfO&A]Q,VO<<KfO&AdQqO7+'pO&AkQ`O7+'pO&ApQqO<<K[O4QQ&jO'#FhO5bQ`O'#FgOBzQ`O'#EZOLbQdO,5;cO!&WQ`O'#FsO!&WQ`O'#FsO!&WQ`O'#FsO!&WQ`O'#FuO!&WQ`O'#FuO!&WQ`O'#FuO&AwQ`O,5<jOJjQ&jO7+'zOJjQ&jO7+'zOJjQ&jO7+'zOIWQ&jO1G2UO&BPQ`O1G2UOIWQ&jO7+'pO!'VQ7[O'#GOO$/eQqO1G2`O$/eQqO1G2`O$/eQqO1G2`O!'VQ7[O,5<jOIWQ&jO,5<tOIWQ&jO,5<tOIWQ&jO,5<t",
stateData: "&B}~O'YOS'ZOSTOSUOS~OQTORTOXyO]cO_hObnOcmOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!TSO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!nlO#dsO#tpO#x^O%PqO%RtO%TrO%UrO%XuO%ZvO%^wO%_wO%axO%nzO%t{O%v|O%x}O%z!OO%}!PO&T!QO&Z!RO&]!SO&_!TO&a!UO&c!VO']PO'fQO'oYO'|aO~OQ[XZ[X_[Xj[Xu[Xv[Xx[X!R[X!a[X!b[X!d[X!j[X!{[X#WdX#[[X#][X#^[X#_[X#`[X#a[X#b[X#c[X#e[X#g[X#i[X#j[X#o[X'W[X'f[X'p[X'w[X'x[X~O!]$lX~P$zOS!WO'U!XO'V!ZO~OQTORTO]cOb!kOc!jOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!T!bO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!n!iO#t!lO#x^O']![O'fQO'oYO'|aO~O!Q!`O!R!]O!O'jP!O'tP~P'dO!S!mO~P`OQTORTO]cOb!kOc!jOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!T!bO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!n!iO#t!lO#x^O']9aO'fQO'oYO'|aO~OQTORTO]cOb!kOc!jOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!T!bO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!n!iO#t!lO#x^O'fQO'oYO'|aO~O!Q!rO#U!uO#V!rO']9bO!c'qP~P+{O#W!vO~O!]!wO#W!vO~OQ#^OZ#dOj#ROu!{Ov!{Ox!|O!R#bO!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO#j#ZO'fQO'p#[O'w!}O'x#OO~O_'hX'W'hX!c'hX!O'hX!T'hX%Q'hX!]'hX~P.jO!{#eO#o#eOQ'iXZ'iX_'iXj'iXu'iXv'iXx'iX!R'iX!a'iX!b'iX!d'iX!j'iX#['iX#]'iX#^'iX#_'iX#`'iX#a'iX#b'iX#e'iX#g'iX#i'iX#j'iX'f'iX'p'iX'w'iX'x'iX~O#c'iX'W'iX!O'iX!c'iXn'iX!T'iX%Q'iX!]'iX~P0zO!{#eO~O#z#fO$R#jO~O!T#kO#x^O$U#lO$W#nO~O]#qOh$QOj#rOk#qOl#qOq$ROs$SOx#yO!T#zO!_$XO!d#vO#V$YO#t$VO$_$TO$a$UO$d$WO']#pO'b$PO'f#sO'a'cP~O!d$ZO~O!]$]O~O_$^O'W$^O~O']$bO~O!d$ZO']$bO'^$dO'b$PO~Oc$jO!d$ZO']$bO~O#c#TO~O]$sOu$oO!T$lO!d$nO%R$rO']$bO'^$dO^(UP~O!n$tO~Ox$uO!T$vO']$bO~Ox$uO!T$vO%Z$zO']$bO~O']${O~O#dsO%RtO%TrO%UrO%XuO%ZvO%^wO%_wO~Ob%UOc%TO!n%RO%P%SO%c%QO~P7xOb%XOcmO!T%WO!nlO#dsO%PqO%TrO%UrO%XuO%ZvO%^wO%_wO%axO~O`%[O!{%_O%R%YO'^$dO~P8wO!d%`O!g%dO~O!d%eO~O!TSO~O_$^O'T%mO'W$^O~O_$^O'T%pO'W$^O~O_$^O'T%rO'W$^O~OS!WO'U!XO'V%vO~OQ[XZ[Xj[Xu[Xv[Xx[X!R[X!RdX!a[X!b[X!d[X!j[X!{[X!{dX#WdX#[[X#][X#^[X#_[X#`[X#a[X#b[X#c[X#e[X#g[X#i[X#j[X#o[X'f[X'p[X'w[X'x[X~O!O[X!OdX~P;dO!Q%xO!O&iX!O&nX!R&iX!R&nX~P'dO!R%zO!O'jX~OQ#^OZ#dOj#ROu!{Ov!{Ox!|O!R%zO!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO#j#ZO'fQO'p#[O'w!}O'x#OO~O!O'jX~P>aO!O&PO~Ox&SO!W&^O!X&VO!Y&VO'^$dO~O]&TOk&TO!Q&WO'g&QO!S'kP!S'vP~P@dO!O'sX!R'sX!]'sX!c'sX'p'sX~O!{'sX#W#PX!S'sX~PA]O!{&_O!O'uX!R'uX~O!R&`O!O'tX~O!O&cO~O!{#eO~PA]OP&gO!T&dO!o&fO']$bO~Oc&lO!d$ZO']$bO~Ou$oO!d$nO~O!S&mO~P`Ou!{Ov!{Ox!|O!b!yO!d!zO'fQOQ!faZ!faj!fa!R!fa!a!fa!j!fa#[!fa#]!fa#^!fa#_!fa#`!fa#a!fa#b!fa#c!fa#e!fa#g!fa#i!fa#j!fa'p!fa'w!fa'x!fa~O_!fa'W!fa!O!fa!c!fan!fa!T!fa%Q!fa!]!fa~PCfO!c&nO~O!]!wO!{&pO'p&oO!R'rX_'rX'W'rX~O!c'rX~PFOO!R&tO!c'qX~O!c&vO~Ox$uO!T$vO#V&wO']$bO~OQTORTO]cOb!kOc!jOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!TSO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!n!iO#t!lO#x^O']9aO'fQO'oYO'|aO~O]#qOh$QOj#rOk#qOl#qOq$ROs9tOx#yO!T#zO!_;eO!d#vO#V9}O#t$VO$_9wO$a9zO$d$WO']&{O'b$PO'f#sO~O#W&}O~O]#qOh$QOj#rOk#qOl#qOq$ROs$SOx#yO!T#zO!_$XO!d#vO#V$YO#t$VO$_$TO$a$UO$d$WO']&{O'b$PO'f#sO~O'a'mP~PJjO!Q'RO!c'nP~P){O'g'TO'oYO~OQ9^OR9^O]cOb;`Oc!jOhcOj9^OkcOlcOq9^Os9^OxRO{cO|cO}cO!T!bO!_9`O!dUO!g9^O!h9^O!i9^O!j9^O!k9^O!n!iO#t!lO#x^O']'cO'fQO'oYO'|;^O~O!d!zO~O!R#bO_$]a'W$]a!c$]a!O$]a!T$]a%Q$]a!]$]a~O#d'jO~PIWO!]'lO!T'yX#w'yX#z'yX$R'yX~Ou'mO~P! YOu'mO!T'yX#w'yX#z'yX$R'yX~O!T'oO#w'sO#z'nO$R'tO~O!Q'wO~PLbO#z#fO$R'zO~OP$eXu$eXx$eX!b$eX'w$eX'x$eX~OPfX!RfX!{fX'afX'a$eX~P!!rOk'|O~OS'}O'U(OO'V(QO~OP(ZOu(SOx(TO'w(VO'x(XO~O'a(RO~P!#{O'a([O~O]#qOh$QOj#rOk#qOl#qOq$ROs9tOx#yO!T#zO!_;eO!d#vO#V9}O#t$VO$_9wO$a9zO$d$WO'b$PO'f#sO~O!Q(`O'](]O!c'}P~P!$jO#W(bO~O!d(cO~O!Q(hO'](eO!O(OP~P!$jOj(uOx(mO!W(sO!X(lO!Y(lO!d(cO!x(tO$w(oO'^$dO'g(jO~O!S(rO~P!&jO!b!yOP'eXu'eXx'eX'w'eX'x'eX!R'eX!{'eX~O'a'eX#m'eX~P!'cOP(xO!{(wO!R'dX'a'dX~O!R(yO'a'cX~O']${O'a'cP~O'](|O~O!d)RO~O']&{O~Ox$uO!Q!rO!T$vO#U!uO#V!rO']$bO!c'qP~O!]!wO#W)VO~OQ#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO#j#ZO'fQO'p#[O'w!}O'x#OO~O_!^a!R!^a'W!^a!O!^a!c!^an!^a!T!^a%Q!^a!]!^a~P!)wOP)_O!T&dO!o)^O%Q)]O'b$PO~O!])aO!T'`X_'`X!R'`X'W'`X~O!d$ZO'b$PO~O!d$ZO']$bO'b$PO~O!]!wO#W&}O~O])lO%R)mO'])iO!S(VP~O!R)nO^(UX~O'g'TO~OZ)rO~O^)sO~O!T$lO']$bO'^$dO^(UP~Ox$uO!Q)xO!R&`O!T$vO']$bO!O'tP~O]&ZOk&ZO!Q)yO'g'TO!S'vP~O!R)zO_(RX'W(RX~O!{*OO'b$PO~OP*RO!T#zO'b$PO~O!T*TO~Ou*VO!TSO~O!n*[O~Oc*aO~O'](|O!S(TP~Oc$jO~O%RtO']${O~P8wOZ*gO^*fO~OQTORTO]cObnOcmOhcOjTOkcOlcOqTOsTOxRO{cO|cO}cO!_kO!dUO!gTO!hTO!iTO!jTO!kTO!nlO#x^O%PqO'fQO'oYO'|aO~O!T!bO#t!lO']9aO~P!1_O^*fO_$^O'W$^O~O_*kO#d*mO%T*mO%U*mO~P){O!d%`O~O%t*rO~O!T*tO~O&V*vO&X*wOQ&SaR&SaX&Sa]&Sa_&Sab&Sac&Sah&Saj&Sak&Sal&Saq&Sas&Sax&Sa{&Sa|&Sa}&Sa!T&Sa!_&Sa!d&Sa!g&Sa!h&Sa!i&Sa!j&Sa!k&Sa!n&Sa#d&Sa#t&Sa#x&Sa%P&Sa%R&Sa%T&Sa%U&Sa%X&Sa%Z&Sa%^&Sa%_&Sa%a&Sa%n&Sa%t&Sa%v&Sa%x&Sa%z&Sa%}&Sa&T&Sa&Z&Sa&]&Sa&_&Sa&a&Sa&c&Sa'S&Sa']&Sa'f&Sa'o&Sa'|&Sa!S&Sa%{&Sa`&Sa&Q&Sa~O']*|O~On+PO~O!O&ia!R&ia~P!)wO!Q+TO!O&iX!R&iX~P){O!R%zO!O'ja~O!O'ja~P>aO!R&`O!O'ta~O!RwX!R!ZX!SwX!S!ZX!]wX!]!ZX!d!ZX!{wX'b!ZX~O!]+YO!{+XO!R#TX!R'lX!S#TX!S'lX!]'lX!d'lX'b'lX~O!]+[O!d$ZO'b$PO!R!VX!S!VX~O]&ROk&ROx&SO'g(jO~OQ9^OR9^O]cOb;`Oc!jOhcOj9^OkcOlcOq9^Os9^OxRO{cO|cO}cO!T!bO!_9`O!dUO!g9^O!h9^O!i9^O!j9^O!k9^O!n!iO#t!lO#x^O'fQO'oYO'|;^O~O']:SO~P!;jO!R+`O!S'kX~O!S+bO~O!]+YO!{+XO!R#TX!S#TX~O!R+cO!S'vX~O!S+eO~O]&ROk&ROx&SO'^$dO'g(jO~O!X+fO!Y+fO~P!>hOx$uO!Q+hO!T$vO']$bO!O&nX!R&nX~O_+lO!W+oO!X+kO!Y+kO!r+sO!s+qO!t+rO!u+pO!x+tO'^$dO'g(jO'o+iO~O!S+nO~P!?iOP+yO!T&dO!o+xO~O!{,PO!R'ra!c'ra_'ra'W'ra~O!]!wO~P!@sO!R&tO!c'qa~Ox$uO!Q,SO!T$vO#U,UO#V,SO']$bO!R&pX!c&pX~O_#Oi!R#Oi'W#Oi!O#Oi!c#Oin#Oi!T#Oi%Q#Oi!]#Oi~P!)wOP;tOu(SOx(TO'w(VO'x(XO~O#W!za!R!za!c!za!{!za!T!za_!za'W!za!O!za~P!BpO#W'eXQ'eXZ'eX_'eXj'eXv'eX!a'eX!d'eX!j'eX#['eX#]'eX#^'eX#_'eX#`'eX#a'eX#b'eX#c'eX#e'eX#g'eX#i'eX#j'eX'W'eX'f'eX'p'eX!c'eX!O'eX!T'eXn'eX%Q'eX!]'eX~P!'cO!R,_O'a'mX~P!#{O'a,aO~O!R,bO!c'nX~P!)wO!c,eO~O!O,fO~OQ#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'fQOZ#Zi_#Zij#Zi!R#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O#[#Zi~P!FfO#[#PO~P!FfOQ#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO'fQOZ#Zi_#Zi!R#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~Oj#Zi~P!IQOj#RO~P!IQOQ#^Oj#ROu!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO'fQO_#Zi!R#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'w#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P!KlOZ#dO!a#TO#a#TO#b#TO#c#TO~P!KlOQ#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO'fQO_#Zi!R#Zi#g#Zi#i#Zi#j#Zi'W#Zi'p#Zi'x#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'w#Zi~P!NdO'w!}O~P!NdOQ#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO'fQO'w!}O_#Zi!R#Zi#i#Zi#j#Zi'W#Zi'p#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~O'x#Zi~P##OO'x#OO~P##OOQ#^OZ#dOj#ROu!{Ov!{Ox!|O!a#TO!b!yO!d!zO!j#^O#[#PO#]#QO#^#QO#_#QO#`#SO#a#TO#b#TO#c#TO#e#UO#g#WO#i#YO'fQO'w!}O'x#OO~O_#Zi!R#Zi#j#Zi'W#Zi'p#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P#%jOQ[XZ[Xj[Xu[Xv[Xx[X!a[X!b[X!d[X!j[X!{[X#WdX#[[X#][X#^[X#_[X#`[X#a[X#b[X#c[X#e[X#g[X#i[X#j[X#o[X'f[X'p[X'w[X'x[X!R[X!S[X~O#m[X~P#'}OQ#^OZ9rOj9gOu!{Ov!{Ox!|O!a9iO!b!yO!d!zO!j#^O#[9eO#]9fO#^9fO#_9fO#`9hO#a9iO#b9iO#c9iO#e9jO#g9lO#i9nO#j9oO'fQO'p#[O'w!}O'x#OO~O#m,hO~P#*XOQ'iXZ'iXj'iXu'iXv'iXx'iX!a'iX!b'iX!d'iX!j'iX#['iX#]'iX#^'iX#_'iX#`'iX#a'iX#b'iX#e'iX#g'iX#i'iX#j'iX'f'iX'p'iX'w'iX'x'iX!R'iX~O!{9sO#o9sO#c'iX#m'iX!S'iX~P#,SO_&sa!R&sa'W&sa!c&san&sa!O&sa!T&sa%Q&sa!]&sa~P!)wOQ#ZiZ#Zi_#Zij#Ziv#Zi!R#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi'W#Zi'f#Zi'p#Zi!O#Zi!c#Zin#Zi!T#Zi%Q#Zi!]#Zi~P!BpO_#ni!R#ni'W#ni!O#ni!c#nin#ni!T#ni%Q#ni!]#ni~P!)wO#z,jO~O#z,kO~O!]'lO!{,lO!T$OX#w$OX#z$OX$R$OX~O!Q,mO~O!T'oO#w,oO#z'nO$R,pO~O!R9pO!S'hX~P#*XO!S,qO~O$R,sO~OS'}O'U(OO'V,vO~O],yOk,yO!O,zO~O!RdX!]dX!cdX!c$eX'pdX~P!!rO!c-QO~P!BpO!R-RO!]!wO'p&oO!c'}X~O!c-WO~O!Q(`O']$bO!c'}P~O#W-YO~O!O$eX!R$eX!]$lX~P!!rO!R-ZO!O(OX~P!BpO!]-]O~O!O-_O~Oj-cO!]!wO!d$ZO'b$PO'p&oO~O!])aO~O_$^O!R-hO'W$^O~O!S-jO~P!&jO!X-kO!Y-kO'^$dO'g(jO~Ox-mO'g(jO~O!x-nO~O']${O!R&xX'a&xX~O!R(yO'a'ca~O'a-sO~Ou-tOv-tOx-uOPra'wra'xra!Rra!{ra~O'ara#mra~P#7pOu(SOx(TOP$^a'w$^a'x$^a!R$^a!{$^a~O'a$^a#m$^a~P#8fOu(SOx(TOP$`a'w$`a'x$`a!R$`a!{$`a~O'a$`a#m$`a~P#9XO]-vO~O#W-wO~O'a$na!R$na!{$na#m$na~P!#{O#W-zO~OP.TO!T&dO!o.SO%Q.RO~O]#qOj#rOk#qOl#qOq$ROs9tOx#yO!T#zO!_;eO!d#vO#V9}O#t$VO$_9wO$a9zO$d$WO'b$PO'f#sO~Oh.VO'].UO~P#:yO!])aO!T'`a_'`a!R'`a'W'`a~O#W.]O~OZ[X!RdX!SdX~O!R.^O!S(VX~O!S.`O~OZ.aO~O].cO'])iO~O!T$lO']$bO^'QX!R'QX~O!R)nO^(Ua~O!c.fO~P!)wO].hO~OZ.iO~O^.jO~OP.TO!T&dO!o.SO%Q.RO'b$PO~O!R)zO_(Ra'W(Ra~O!{.pO~OP.sO!T#zO~O'g'TO!S(SP~OP.}O!T.yO!o.|O%Q.{O'b$PO~OZ/XO!R/VO!S(TX~O!S/YO~O^/[O_$^O'W$^O~O]/]O~O]/^O'](|O~O#c/_O%r/`O~P0zO!{#eO#c/_O%r/`O~O_/aO~P){O_/cO~O%{/gOQ%yiR%yiX%yi]%yi_%yib%yic%yih%yij%yik%yil%yiq%yis%yix%yi{%yi|%yi}%yi!T%yi!_%yi!d%yi!g%yi!h%yi!i%yi!j%yi!k%yi!n%yi#d%yi#t%yi#x%yi%P%yi%R%yi%T%yi%U%yi%X%yi%Z%yi%^%yi%_%yi%a%yi%n%yi%t%yi%v%yi%x%yi%z%yi%}%yi&T%yi&Z%yi&]%yi&_%yi&a%yi&c%yi'S%yi']%yi'f%yi'o%yi'|%yi!S%yi`%yi&Q%yi~O`/mO!S/kO&Q/lO~P`O!TSO!d/oO~O&X*wOQ&SiR&SiX&Si]&Si_&Sib&Sic&Sih&Sij&Sik&Sil&Siq&Sis&Six&Si{&Si|&Si}&Si!T&Si!_&Si!d&Si!g&Si!h&Si!i&Si!j&Si!k&Si!n&Si#d&Si#t&Si#x&Si%P&Si%R&Si%T&Si%U&Si%X&Si%Z&Si%^&Si%_&Si%a&Si%n&Si%t&Si%v&Si%x&Si%z&Si%}&Si&T&Si&Z&Si&]&Si&_&Si&a&Si&c&Si'S&Si']&Si'f&Si'o&Si'|&Si!S&Si%{&Si`&Si&Q&Si~O!R#bOn$]a~O!O&ii!R&ii~P!)wO!R%zO!O'ji~O!R&`O!O'ti~O!O/uO~O!R!Va!S!Va~P#*XO]&ROk&RO!Q/{O'g(jO!R&jX!S&jX~P@dO!R+`O!S'ka~O]&ZOk&ZO!Q)yO'g'TO!R&oX!S&oX~O!R+cO!S'va~O!O'ui!R'ui~P!)wO_$^O!]!wO!d$ZO!j0VO!{0TO'W$^O'b$PO'p&oO~O!S0YO~P!?iO!X0ZO!Y0ZO'^$dO'g(jO'o+iO~O!W0[O~P#MSO!TSO!W0[O!u0^O!x0_O~P#MSO!W0[O!s0aO!t0aO!u0^O!x0_O~P#MSO!T&dO~O!T&dO~P!BpO!R'ri!c'ri_'ri'W'ri~P!)wO!{0jO!R'ri!c'ri_'ri'W'ri~O!R&tO!c'qi~Ox$uO!T$vO#V0lO']$bO~O#WraQraZra_rajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra'Wra'fra'pra!cra!Ora!Tranra%Qra!]ra~P#7pO#W$^aQ$^aZ$^a_$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a'W$^a'f$^a'p$^a!c$^a!O$^a!T$^an$^a%Q$^a!]$^a~P#8fO#W$`aQ$`aZ$`a_$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a'W$`a'f$`a'p$`a!c$`a!O$`a!T$`an$`a%Q$`a!]$`a~P#9XO#W$naQ$naZ$na_$naj$nav$na!R$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na'W$na'f$na'p$na!c$na!O$na!T$na!{$nan$na%Q$na!]$na~P!BpO_#Oq!R#Oq'W#Oq!O#Oq!c#Oqn#Oq!T#Oq%Q#Oq!]#Oq~P!)wO!R&kX'a&kX~PJjO!R,_O'a'ma~O!Q0tO!R&lX!c&lX~P){O!R,bO!c'na~O!R,bO!c'na~P!)wO#m!fa!S!fa~PCfO#m!^a!R!^a!S!^a~P#*XO!T1XO#x^O$P1YO~O!S1^O~On1_O~P!BpO_$Yq!R$Yq'W$Yq!O$Yq!c$Yqn$Yq!T$Yq%Q$Yq!]$Yq~P!)wO!O1`O~O],yOk,yO~Ou(SOx(TO'x(XOP$xi'w$xi!R$xi!{$xi~O'a$xi#m$xi~P$.POu(SOx(TOP$zi'w$zi'x$zi!R$zi!{$zi~O'a$zi#m$zi~P$.rO'p#[O~P!BpO!Q1cO']$bO!R&tX!c&tX~O!R-RO!c'}a~O!R-RO!]!wO!c'}a~O!R-RO!]!wO'p&oO!c'}a~O'a$gi!R$gi!{$gi#m$gi~P!#{O!Q1kO'](eO!O&vX!R&vX~P!$jO!R-ZO!O(Oa~O!R-ZO!O(Oa~P!BpO!]!wO~O!]!wO#c1sO~Oj1vO!]!wO'p&oO~O!R'di'a'di~P!#{O!{1yO!R'di'a'di~P!#{O!c1|O~O_$Zq!R$Zq'W$Zq!O$Zq!c$Zqn$Zq!T$Zq%Q$Zq!]$Zq~P!)wO!R2QO!T(PX~P!BpO!T&dO%Q2TO~O!T&dO%Q2TO~P!BpO!T$eX$u[X_$eX!R$eX'W$eX~P!!rO$u2XOPgXugXxgX!TgX'wgX'xgX_gX!RgX'WgX~O$u2XO~O]2_O%R2`O'])iO!R'PX!S'PX~O!R.^O!S(Va~OZ2dO~O^2eO~O]2hO~OP2jO!T&dO!o2iO%Q2TO~O_$^O'W$^O~P!BpO!T#zO~P!BpO!R2oO!{2qO!S(SX~O!S2rO~Ox;oO!W2{O!X2tO!Y2tO!r2zO!s2yO!t2yO!x2xO'^$dO'g(jO'o+iO~O!S2wO~P$7ZOP3SO!T.yO!o3RO%Q3QO~OP3SO!T.yO!o3RO%Q3QO'b$PO~O'](|O!R'OX!S'OX~O!R/VO!S(Ta~O]3^O'g3]O~O]3_O~O^3aO~O!c3dO~P){O_3fO~O_3fO~P){O#c3hO%r3iO~PFOO`/mO!S3mO&Q/lO~P`O!]3oO~O!R#Ti!S#Ti~P#*XO!{3qO!R#Ti!S#Ti~O!R!Vi!S!Vi~P#*XO_$^O!{3xO'W$^O~O_$^O!]!wO!{3xO'W$^O~O!X3|O!Y3|O'^$dO'g(jO'o+iO~O_$^O!]!wO!d$ZO!j3}O!{3xO'W$^O'b$PO'p&oO~O!W4OO~P$;xO!W4OO!u4RO!x4SO~P$;xO_$^O!]!wO!j3}O!{3xO'W$^O'p&oO~O!R'rq!c'rq_'rq'W'rq~P!)wO!R&tO!c'qq~O#W$xiQ$xiZ$xi_$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi'W$xi'f$xi'p$xi!c$xi!O$xi!T$xin$xi%Q$xi!]$xi~P$.PO#W$ziQ$ziZ$zi_$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi'W$zi'f$zi'p$zi!c$zi!O$zi!T$zin$zi%Q$zi!]$zi~P$.rO#W$giQ$giZ$gi_$gij$giv$gi!R$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi'W$gi'f$gi'p$gi!c$gi!O$gi!T$gi!{$gin$gi%Q$gi!]$gi~P!BpO!R&ka'a&ka~P!#{O!R&la!c&la~P!)wO!R,bO!c'ni~O#m#Oi!R#Oi!S#Oi~P#*XOQ#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O'fQOZ#Zij#Zi!a#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~O#[#Zi~P$EiO#[9eO~P$EiOQ#^Ou!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9eO#]9fO#^9fO#_9fO'fQOZ#Zi!a#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~Oj#Zi~P$GqOj9gO~P$GqOQ#^Oj9gOu!{Ov!{Ox!|O!b!yO!d!zO!j#^O#[9eO#]9fO#^9fO#_9fO#`9hO'fQO#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'w#Zi'x#Zi!R#Zi!S#Zi~OZ#Zi!a#Zi#a#Zi#b#Zi#c#Zi~P$IyOZ9rO!a9iO#a9iO#b9iO#c9iO~P$IyOQ#^OZ9rOj9gOu!{Ov!{Ox!|O!a9iO!b!yO!d!zO!j#^O#[9eO#]9fO#^9fO#_9fO#`9hO#a9iO#b9iO#c9iO#e9jO'fQO#g#Zi#i#Zi#j#Zi#m#Zi'p#Zi'x#Zi!R#Zi!S#Zi~O'w#Zi~P$L_O'w!}O~P$L_OQ#^OZ9rOj9gOu!{Ov!{Ox!|O!a9iO!b!yO!d!zO!j#^O#[9eO#]9fO#^9fO#_9fO#`9hO#a9iO#b9iO#c9iO#e9jO#g9lO'fQO'w!}O#i#Zi#j#Zi#m#Zi'p#Zi!R#Zi!S#Zi~O'x#Zi~P$NgO'x#OO~P$NgOQ#^OZ9rOj9gOu!{Ov!{Ox!|O!a9iO!b!yO!d!zO!j#^O#[9eO#]9fO#^9fO#_9fO#`9hO#a9iO#b9iO#c9iO#e9jO#g9lO#i9nO'fQO'w!}O'x#OO~O#j#Zi#m#Zi'p#Zi!R#Zi!S#Zi~P%!oO_#ky!R#ky'W#ky!O#ky!c#kyn#ky!T#ky%Q#ky!]#ky~P!)wOP;vOu(SOx(TO'w(VO'x(XO~OQ#ZiZ#Zij#Ziv#Zi!a#Zi!b#Zi!d#Zi!j#Zi#[#Zi#]#Zi#^#Zi#_#Zi#`#Zi#a#Zi#b#Zi#c#Zi#e#Zi#g#Zi#i#Zi#j#Zi#m#Zi'f#Zi'p#Zi!R#Zi!S#Zi~P%%aO!b!yOP'eXu'eXx'eX'w'eX'x'eX!S'eX~OQ'eXZ'eXj'eXv'eX!a'eX!d'eX!j'eX#['eX#]'eX#^'eX#_'eX#`'eX#a'eX#b'eX#c'eX#e'eX#g'eX#i'eX#j'eX#m'eX'f'eX'p'eX!R'eX~P%'eO#m#ni!R#ni!S#ni~P#*XO!S4eO~O!R&sa!S&sa~P#*XO!]!wO'p&oO!R&ta!c&ta~O!R-RO!c'}i~O!R-RO!]!wO!c'}i~O'a$gq!R$gq!{$gq#m$gq~P!#{O!O&va!R&va~P!BpO!]4lO~O!R-ZO!O(Oi~P!BpO!R-ZO!O(Oi~O!O4pO~O!]!wO#c4uO~Oj4vO!]!wO'p&oO~O!O4xO~O'a$iq!R$iq!{$iq#m$iq~P!#{O_$Zy!R$Zy'W$Zy!O$Zy!c$Zyn$Zy!T$Zy%Q$Zy!]$Zy~P!)wO!R2QO!T(Pa~O!T&dO%Q4}O~O!T&dO%Q4}O~P!BpO_#Oy!R#Oy'W#Oy!O#Oy!c#Oyn#Oy!T#Oy%Q#Oy!]#Oy~P!)wOZ5QO~O]5SO'])iO~O!R.^O!S(Vi~O]5VO~O^5WO~O'g'TO!R&{X!S&{X~O!R2oO!S(Sa~O!S5eO~P$7ZOx;sO'g(jO'o+iO~O!W5hO!X5gO!Y5gO!x0_O'^$dO'g(jO'o+iO~O!s5iO!t5iO~P%0^O!X5gO!Y5gO'^$dO'g(jO'o+iO~O!T.yO~O!T.yO%Q5kO~O!T.yO%Q5kO~P!BpOP5pO!T.yO!o5oO%Q5kO~OZ5uO!R'Oa!S'Oa~O!R/VO!S(Ti~O]5xO~O!c5yO~O!c5zO~O!c5{O~O!c5{O~P){O_5}O~O!]6QO~O!c6RO~O!R'ui!S'ui~P#*XO_$^O'W$^O~P!)wO_$^O!{6WO'W$^O~O_$^O!]!wO!{6WO'W$^O~O!X6]O!Y6]O'^$dO'g(jO'o+iO~O_$^O!]!wO!j6^O!{6WO'W$^O'p&oO~O!d$ZO'b$PO~P%4xO!W6_O~P%4gO!R'ry!c'ry_'ry'W'ry~P!)wO#W$gqQ$gqZ$gq_$gqj$gqv$gq!R$gq!a$gq!b$gq!d$gq!j$gq#[$gq#]$gq#^$gq#_$gq#`$gq#a$gq#b$gq#c$gq#e$gq#g$gq#i$gq#j$gq'W$gq'f$gq'p$gq!c$gq!O$gq!T$gq!{$gqn$gq%Q$gq!]$gq~P!BpO#W$iqQ$iqZ$iq_$iqj$iqv$iq!R$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq'W$iq'f$iq'p$iq!c$iq!O$iq!T$iq!{$iqn$iq%Q$iq!]$iq~P!BpO!R&li!c&li~P!)wO#m#Oq!R#Oq!S#Oq~P#*XOu-tOv-tOx-uOPra'wra'xra!Sra~OQraZrajra!ara!bra!dra!jra#[ra#]ra#^ra#_ra#`ra#ara#bra#cra#era#gra#ira#jra#mra'fra'pra!Rra~P%;OOu(SOx(TOP$^a'w$^a'x$^a!S$^a~OQ$^aZ$^aj$^av$^a!a$^a!b$^a!d$^a!j$^a#[$^a#]$^a#^$^a#_$^a#`$^a#a$^a#b$^a#c$^a#e$^a#g$^a#i$^a#j$^a#m$^a'f$^a'p$^a!R$^a~P%=SOu(SOx(TOP$`a'w$`a'x$`a!S$`a~OQ$`aZ$`aj$`av$`a!a$`a!b$`a!d$`a!j$`a#[$`a#]$`a#^$`a#_$`a#`$`a#a$`a#b$`a#c$`a#e$`a#g$`a#i$`a#j$`a#m$`a'f$`a'p$`a!R$`a~P%?WOQ$naZ$naj$nav$na!a$na!b$na!d$na!j$na#[$na#]$na#^$na#_$na#`$na#a$na#b$na#c$na#e$na#g$na#i$na#j$na#m$na'f$na'p$na!R$na!S$na~P%%aO#m$Yq!R$Yq!S$Yq~P#*XO#m$Zq!R$Zq!S$Zq~P#*XO!S6hO~O#m6iO~P!#{O!]!wO!R&ti!c&ti~O!]!wO'p&oO!R&ti!c&ti~O!R-RO!c'}q~O!O&vi!R&vi~P!BpO!R-ZO!O(Oq~O!O6oO~P!BpO!O6oO~O!R'dy'a'dy~P!#{O!R&ya!T&ya~P!BpO!T$tq_$tq!R$tq'W$tq~P!BpOZ6vO~O!R.^O!S(Vq~O]6yO~O!T&dO%Q6zO~O!T&dO%Q6zO~P!BpO!{6{O!R&{a!S&{a~O!R2oO!S(Si~P#*XO!X7RO!Y7RO'^$dO'g(jO'o+iO~O!W7TO!x4SO~P%GXO!T.yO%Q7WO~O!T.yO%Q7WO~P!BpO]7_O'g7^O~O!R/VO!S(Tq~O!c7aO~O!c7aO~P){O!c7cO~O!c7dO~O!R#Ty!S#Ty~P#*XO_$^O!{7jO'W$^O~O_$^O!]!wO!{7jO'W$^O~O!X7mO!Y7mO'^$dO'g(jO'o+iO~O_$^O!]!wO!j7nO!{7jO'W$^O'p&oO~O#m#ky!R#ky!S#ky~P#*XOQ$giZ$gij$giv$gi!a$gi!b$gi!d$gi!j$gi#[$gi#]$gi#^$gi#_$gi#`$gi#a$gi#b$gi#c$gi#e$gi#g$gi#i$gi#j$gi#m$gi'f$gi'p$gi!R$gi!S$gi~P%%aOu(SOx(TO'x(XOP$xi'w$xi!S$xi~OQ$xiZ$xij$xiv$xi!a$xi!b$xi!d$xi!j$xi#[$xi#]$xi#^$xi#_$xi#`$xi#a$xi#b$xi#c$xi#e$xi#g$xi#i$xi#j$xi#m$xi'f$xi'p$xi!R$xi~P%LjOu(SOx(TOP$zi'w$zi'x$zi!S$zi~OQ$ziZ$zij$ziv$zi!a$zi!b$zi!d$zi!j$zi#[$zi#]$zi#^$zi#_$zi#`$zi#a$zi#b$zi#c$zi#e$zi#g$zi#i$zi#j$zi#m$zi'f$zi'p$zi!R$zi~P%NnO#m$Zy!R$Zy!S$Zy~P#*XO#m#Oy!R#Oy!S#Oy~P#*XO!]!wO!R&tq!c&tq~O!R-RO!c'}y~O!O&vq!R&vq~P!BpO!O7tO~P!BpO!R.^O!S(Vy~O!R2oO!S(Sq~O!X8QO!Y8QO'^$dO'g(jO'o+iO~O!T.yO%Q8TO~O!T.yO%Q8TO~P!BpO!c8WO~O_$^O!{8]O'W$^O~O_$^O!]!wO!{8]O'W$^O~OQ$gqZ$gqj$gqv$gq!a$gq!b$gq!d$gq!j$gq#[$gq#]$gq#^$gq#_$gq#`$gq#a$gq#b$gq#c$gq#e$gq#g$gq#i$gq#j$gq#m$gq'f$gq'p$gq!R$gq!S$gq~P%%aOQ$iqZ$iqj$iqv$iq!a$iq!b$iq!d$iq!j$iq#[$iq#]$iq#^$iq#_$iq#`$iq#a$iq#b$iq#c$iq#e$iq#g$iq#i$iq#j$iq#m$iq'f$iq'p$iq!R$iq!S$iq~P%%aO'a$|!Z!R$|!Z!{$|!Z#m$|!Z~P!#{O!R&{q!S&{q~P#*XO_$^O!{8oO'W$^O~O#W$|!ZQ$|!ZZ$|!Z_$|!Zj$|!Zv$|!Z!R$|!Z!a$|!Z!b$|!Z!d$|!Z!j$|!Z#[$|!Z#]$|!Z#^$|!Z#_$|!Z#`$|!Z#a$|!Z#b$|!Z#c$|!Z#e$|!Z#g$|!Z#i$|!Z#j$|!Z'W$|!Z'f$|!Z'p$|!Z!c$|!Z!O$|!Z!T$|!Z!{$|!Zn$|!Z%Q$|!Z!]$|!Z~P!BpOP;uOu(SOx(TO'w(VO'x(XO~O!S!za!W!za!X!za!Y!za!r!za!s!za!t!za!x!za'^!za'g!za'o!za~P&,_O!W'eX!X'eX!Y'eX!r'eX!s'eX!t'eX!x'eX'^'eX'g'eX'o'eX~P%'eOQ$|!ZZ$|!Zj$|!Zv$|!Z!a$|!Z!b$|!Z!d$|!Z!j$|!Z#[$|!Z#]$|!Z#^$|!Z#_$|!Z#`$|!Z#a$|!Z#b$|!Z#c$|!Z#e$|!Z#g$|!Z#i$|!Z#j$|!Z#m$|!Z'f$|!Z'p$|!Z!R$|!Z!S$|!Z~P%%aO!Wra!Xra!Yra!rra!sra!tra!xra'^ra'gra'ora~P%;OO!W$^a!X$^a!Y$^a!r$^a!s$^a!t$^a!x$^a'^$^a'g$^a'o$^a~P%=SO!W$`a!X$`a!Y$`a!r$`a!s$`a!t$`a!x$`a'^$`a'g$`a'o$`a~P%?WO!S$na!W$na!X$na!Y$na!r$na!s$na!t$na!x$na'^$na'g$na'o$na~P&,_O!W$xi!X$xi!Y$xi!r$xi!s$xi!t$xi!x$xi'^$xi'g$xi'o$xi~P%LjO!W$zi!X$zi!Y$zi!r$zi!s$zi!t$zi!x$zi'^$zi'g$zi'o$zi~P%NnO!S$gi!W$gi!X$gi!Y$gi!r$gi!s$gi!t$gi!x$gi'^$gi'g$gi'o$gi~P&,_O!S$gq!W$gq!X$gq!Y$gq!r$gq!s$gq!t$gq!x$gq'^$gq'g$gq'o$gq~P&,_O!S$iq!W$iq!X$iq!Y$iq!r$iq!s$iq!t$iq!x$iq'^$iq'g$iq'o$iq~P&,_O!S$|!Z!W$|!Z!X$|!Z!Y$|!Z!r$|!Z!s$|!Z!t$|!Z!x$|!Z'^$|!Z'g$|!Z'o$|!Z~P&,_On'hX~P.jOn[X!O[X!c[X%r[X!T[X%Q[X!][X~P$zO!]dX!c[X!cdX'pdX~P;dOQ9^OR9^O]cOb;`Oc!jOhcOj9^OkcOlcOq9^Os9^OxRO{cO|cO}cO!TSO!_9`O!dUO!g9^O!h9^O!i9^O!j9^O!k9^O!n!iO#t!lO#x^O']'cO'fQO'oYO'|;^O~O]#qOh$QOj#rOk#qOl#qOq$ROs9uOx#yO!T#zO!_;fO!d#vO#V:OO#t$VO$_9xO$a9{O$d$WO']&{O'b$PO'f#sO~O!R9pO!S$]a~O]#qOh$QOj#rOk#qOl#qOq$ROs9vOx#yO!T#zO!_;gO!d#vO#V:PO#t$VO$_9yO$a9|O$d$WO']&{O'b$PO'f#sO~O#d'jO~P&<WO!S[X!SdX~P;dO!]9dO~O#W9cO~O!]!wO#W9cO~O!{9sO~O#c9iO~O!{:QO!R'uX!S'uX~O!{9sO!R'sX!S'sX~O#W:RO~O'a:TO~P!#{O#W:[O~O#W:]O~O#W:^O~O!]!wO#W:_O~O!]!wO#W:RO~O#m:`O~P#*XO#W:aO~O#W:bO~O#W:cO~O#W:dO~O#W:eO~O#W:fO~O#W:gO~O#W:hO~O!O:iO~O#m:jO~P!#{O#m:kO~P!#{O#m:lO~P!#{O!O:mO~P!BpO!O:mO~O!O:nO~P!BpO!]!wO#c;lO~O!]!wO#c;nO~O#x~!b!r!t!u#U#V'|$_$a$d$u%P%Q%R%X%Z%^%_%a%c~UT#x'|#]}'Y'Z#z'Y']'g~",
goto: "#Kk(ZPPPPPPPP([P(lP*`PPPP-zPP.a3s7o8SP8SPPP8SP:U8SP8SP:YPP:`P:t?VPPPP?ZPPPP?ZA{PPPBRDdP?ZPFwPPPPHp?ZPPPPPJi?ZPPMjNgPPPPNk!!TP!!]!#^PNg?Z?Z!&n!)i!.[!.[!1kPPP!1r!4h?ZPPPPPPPPPP!7_P!8pPP?Z!9}P?ZP?Z?Z?Z?ZP?Z!;dPP!>]P!AQ!AY!A^!A^P!>YP!Ab!AbP!DVP!DZ?Z?Z!Da!GT8SP8SP8S8SP!HW8S8S!Jf8S!M_8S# g8S8S#!T#$c#$c#$g#$c#$oP#$cP8S#%k8S#'X8S8S-zPPP#(yPP#)c#)cP#)cP#)x#)cPP#*OP#)uP#)u#*b!!X#)u#+P#+V#+Y([#+]([P#+d#+d#+dP([P([P([P([PP([P#+j#+mP#+m([P#+qP#+tP([P([P([P([P([P([([#+z#,U#,[#,b#,p#,v#,|#-W#-^#-m#-s#.R#.X#._#.m#/S#0z#1Y#1`#1f#1l#1r#1|#2S#2Y#2d#2v#2|PPPPPPPP#3SPP#3v#7OPP#8f#8m#8uPP#>a#@t#Fp#Fs#Fv#GR#GUPP#GX#G]#Gz#Hq#Hu#IZPP#I_#Ie#IiP#Il#Ip#Is#Jc#Jy#KO#KR#KU#K[#K_#Kc#KgmhOSj}!n$]%c%f%g%i*o*t/g/jQ$imQ$ppQ%ZyS&V!b+`Q&k!jS(l#z(qQ)g$jQ)t$rQ*`%TQ+f&^S+k&d+mQ+}&lQ-k(sQ/U*aY0Z+o+p+q+r+sS2t.y2vU3|0[0^0aU5g2y2z2{S6]4O4RS7R5h5iQ7m6_R8Q7T$p[ORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#b#e$]$n%[%_%c%e%f%g%i%m%x%z&S&_&f&p&}'R(R)V)^*k*o*t+T+x,P,b,h-u-z.S.].|/_/`/a/c/g/j/l0T0j0t2i3R3f3h3i3x5o5}6W7j8]8o!j'e#]#k&W'w+X+[,m/{1X2q3q6{9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aQ(}$SQ)l$lQ*b%WQ*i%`Q,X9tQ.W)aQ.c)mQ/^*gQ2_.^Q3Z/VQ4^9vQ5S2`R8{9upeOSjy}!n$]%Y%c%f%g%i*o*t/g/jR*d%[&WVOSTjkn}!S!W!k!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#]#b#e#k$]$n%[%_%`%c%e%f%g%i%m%z&S&_&f&p&}'R'w(R)V)^*k*o*t+T+X+[+x,P,b,h,m-u-z.S.].|/_/`/a/c/g/j/l/{0T0j0t1X2i2q3R3f3h3i3q3x5o5}6W6{7j8]8o9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;`;a[!cRU!]!`%x&WQ$clQ$hmS$mp$rv$wrs!r!u$Z$u&`&t&w)x)y)z*m+Y+h,S,U/o0lQ%PwQ&h!iQ&j!jS(_#v(cS)f$i$jQ)j$lQ)w$tQ*Z%RQ*_%TS+|&k&lQ-V(`Q.[)gQ.b)mQ.d)nQ.g)rQ/P*[S/T*`*aQ0h+}Q1b-RQ2^.^Q2b.aQ2g.iQ3Y/UQ4i1cQ5R2`Q5U2dQ6u5QR7w6vx#xa!y$T$U$Y(W(Y(b(w(x,_-Y-w1a1y6i;^;i;j;k!Y$fm!j$h$i$j&U&j&k&l(k)f)g+]+j+|+}-d.[0Q0W0]0h1u3{4Q6Z7k8^Q)`$cQ*P$|Q*S$}Q*^%TQ.k)wQ/O*ZU/S*_*`*aQ3T/PS3X/T/UQ5b2sQ5t3YS7P5c5fS8O7Q7SQ8f8PQ8u8g#[;b!w#d#v#y&g'}(Z(h)])_)a*O*R+y-Z-].R.T.p.s.{.}1k1s2Q2T2X2j3Q3S4l4u4}5k5p6z7W8T9w9z9}:U:X:[:a:d:j;l;n;t;u;vd;c9d9x9{:O:V:Y:]:b:e:ke;d9r9y9|:P:W:Z:^:c:f:lW#}a$P(y;^S$|t%YQ$}uQ%OvR)}$z%P#|a!w!y#d#v#y$T$U$Y&g'}(W(Y(Z(b(h(w(x)])_)a*O*R+y,_-Y-Z-]-w.R.T.p.s.{.}1a1k1s1y2Q2T2X2j3Q3S4l4u4}5k5p6i6z7W8T9d9r9w9x9y9z9{9|9}:O:P:U:V:W:X:Y:Z:[:]:^:a:b:c:d:e:f:j:k:l;^;i;j;k;l;n;t;u;vT(O#s(PX)O$S9t9u9vU&Z!b$v+cQ'U!{Q)q$oQ.t*TQ1z-tR5^2o&^cORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#]#b#e#k$]$n%[%_%`%c%e%f%g%i%m%x%z&S&W&_&f&p&}'R'w(R)V)^*k*o*t+T+X+[+x,P,b,h,m-u-z.S.].|/_/`/a/c/g/j/l/{0T0j0t1X2i2q3R3f3h3i3q3x5o5}6W6{7j8]8o9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;a$]#aZ!_!o$a%w%}&y'Q'W'X'Y'Z'[']'^'_'`'a'b'd'g'k'u)p+R+^+g,O,^,d,g,i,w-x/v/y0i0s0w0x0y0z0{0|0}1O1P1Q1R1S1T1W1]2O2[3s3v4W4[4]4b4c5`6S6V6b6f6g7g7z8Z8m8y9_:|T!XQ!Y&_cORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#]#b#e#k$]$n%[%_%`%c%e%f%g%i%m%x%z&S&W&_&f&p&}'R'w(R)V)^*k*o*t+T+X+[+x,P,b,h,m-u-z.S.].|/_/`/a/c/g/j/l/{0T0j0t1X2i2q3R3f3h3i3q3x5o5}6W6{7j8]8o9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aQ&X!bR/|+`Y&R!b&V&^+`+fS(k#z(qS+j&d+mS-d(l(sQ-e(mQ-l(tQ.v*VU0W+k+o+pU0]+q+r+sS0b+t2xQ1u-kQ1w-mQ1x-nS2s.y2vU3{0Z0[0^Q4P0_Q4Q0aS5c2t2{S5f2y2zU6Z3|4O4RQ6`4SS7Q5g5hQ7S5iS7k6]6_S8P7R7TQ8^7mQ8g8QQ;h;oR;m;slhOSj}!n$]%c%f%g%i*o*t/g/jQ%k!QS&x!v9cQ)d$gQ*X%PQ*Y%QQ+z&iS,]&}:RS-y)V:_Q.Y)eQ.x*WQ/n*vQ/p*wQ/x+ZQ0`+qQ0f+{S2P-z:gQ2Y.ZS2].]:hQ3r/zQ3u0RQ4U0gQ5P2ZQ6T3tQ6X3zQ6a4VQ7e6RQ7h6YQ8Y7iQ8l8[R8x8n$W#`Z!_!o%w%}&y'Q'W'X'Y'Z'[']'^'_'`'a'b'd'g'k'u)p+R+^+g,O,^,d,g,w-x/v/y0i0s0w0x0y0z0{0|0}1O1P1Q1R1S1T1W1]2O2[3s3v4W4[4]4b4c5`6S6V6b6f6g7g7z8Z8m8y9_:|W(v#{&|1V8qT)Z$a,i$W#_Z!_!o%w%}&y'Q'W'X'Y'Z'[']'^'_'`'a'b'd'g'k'u)p+R+^+g,O,^,d,g,w-x/v/y0i0s0w0x0y0z0{0|0}1O1P1Q1R1S1T1W1]2O2[3s3v4W4[4]4b4c5`6S6V6b6f6g7g7z8Z8m8y9_:|Q'f#`S)Y$a,iR-{)Z&^cORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#]#b#e#k$]$n%[%_%`%c%e%f%g%i%m%x%z&S&W&_&f&p&}'R'w(R)V)^*k*o*t+T+X+[+x,P,b,h,m-u-z.S.].|/_/`/a/c/g/j/l/{0T0j0t1X2i2q3R3f3h3i3q3x5o5}6W6{7j8]8o9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aQ%f{Q%g|Q%i!OQ%j!PR/f*rQ&e!iQ)[$cQ+w&hS.Q)`)wS0c+u+vW2S-}.O.P.kS4T0d0eU4|2U2V2WU6s4{5Y5ZQ7v6tR8b7yT+l&d+mS+j&d+mU0W+k+o+pU0]+q+r+sS0b+t2xS2s.y2vU3{0Z0[0^Q4P0_Q4Q0aS5c2t2{S5f2y2zU6Z3|4O4RQ6`4SS7Q5g5hQ7S5iS7k6]6_S8P7R7TQ8^7mR8g8QS+l&d+mT2u.y2vS&r!q/dQ-U(_Q-b(kS0V+j2sQ1g-VS1p-c-lU3}0]0b5fQ4h1bS4s1v1xU6^4P4Q7SQ6k4iQ6r4vR7n6`Q!xXS&q!q/dQ)W$[Q)b$eQ)h$kQ,Q&rQ-T(_Q-a(kQ-f(nQ.X)cQ/Q*]S0U+j2sS1f-U-VS1o-b-lQ1r-eQ1t-gQ3V/RW3y0V0]0b5fQ4g1bQ4k1gS4o1p1xQ4t1wQ5r3WW6[3}4P4Q7SS6j4h4iS6n4p:iQ6p4sQ6}5aQ7[5sS7l6^6`Q7r6kS7s6o:mQ7u6rQ7|7OQ8V7]Q8_7nS8a7t:nQ8d7}Q8s8eQ9Q8tQ9X9RQ:u:pQ;T:zQ;U:{Q;V;hR;[;m$rWORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#b#e$]$n%[%_%`%c%e%f%g%i%m%x%z&S&_&f&p&}'R(R)V)^*k*o*t+T+x,P,b,h-u-z.S.].|/_/`/a/c/g/j/l0T0j0t2i3R3f3h3i3x5o5}6W7j8]8oS!xn!k!j:o#]#k&W'w+X+[,m/{1X2q3q6{9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aR:u;`$rXORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#b#e$]$n%[%_%`%c%e%f%g%i%m%x%z&S&_&f&p&}'R(R)V)^*k*o*t+T+x,P,b,h-u-z.S.].|/_/`/a/c/g/j/l0T0j0t2i3R3f3h3i3x5o5}6W7j8]8oQ$[b!Y$em!j$h$i$j&U&j&k&l(k)f)g+]+j+|+}-d.[0Q0W0]0h1u3{4Q6Z7k8^S$kn!kQ)c$fQ*]%TW/R*^*_*`*aU3W/S/T/UQ5a2sS5s3X3YU7O5b5c5fQ7]5tU7}7P7Q7SS8e8O8PS8t8f8gQ9R8u!j:p#]#k&W'w+X+[,m/{1X2q3q6{9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aQ:z;_R:{;`$f]OSTjk}!S!W!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#b#e$]$n%[%_%c%e%f%g%i%m%z&S&_&f&p&}'R(R)V)^*k*o*t+T+x,P,b,h-u-z.S.].|/_/`/a/c/g/j/l0T0j0t2i3R3f3h3i3x5o5}6W7j8]8oY!hRU!]!`%xv$wrs!r!u$Z$u&`&t&w)x)y)z*m+Y+h,S,U/o0lQ*j%`!h:q#]#k'w+X+[,m/{1X2q3q6{9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aR:t&WS&[!b$vR0O+c$p[ORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#b#e$]$n%[%_%c%e%f%g%i%m%x%z&S&_&f&p&}'R(R)V)^*k*o*t+T+x,P,b,h-u-z.S.].|/_/`/a/c/g/j/l0T0j0t2i3R3f3h3i3x5o5}6W7j8]8o!j'e#]#k&W'w+X+[,m/{1X2q3q6{9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aR*i%`$roORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#b#e$]$n%[%_%`%c%e%f%g%i%m%x%z&S&_&f&p&}'R(R)V)^*k*o*t+T+x,P,b,h-u-z.S.].|/_/`/a/c/g/j/l0T0j0t2i3R3f3h3i3x5o5}6W7j8]8oQ'U!{!k:r#]#k&W'w+X+[,m/{1X2q3q6{9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;a!h#VZ!_$a%w%}&y'Q'_'`'a'b'g'k)p+R+g,O,^,d,w-x0i0s1T2O2[3v4W4[6V7g8Z8m8y9_!R9k'd'u+^,i/v/y0w1P1Q1R1S1W1]3s4]4b4c5`6S6b6f6g7z:|!d#XZ!_$a%w%}&y'Q'a'b'g'k)p+R+g,O,^,d,w-x0i0s1T2O2[3v4W4[6V7g8Z8m8y9_}9m'd'u+^,i/v/y0w1R1S1W1]3s4]4b4c5`6S6b6f6g7z:|!`#]Z!_$a%w%}&y'Q'g'k)p+R+g,O,^,d,w-x0i0s1T2O2[3v4W4[6V7g8Z8m8y9_Q1a-Px;a'd'u+^,i/v/y0w1W1]3s4]4b4c5`6S6b6f6g7z:|Q;i;pQ;j;qR;k;r&^cORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#]#b#e#k$]$n%[%_%`%c%e%f%g%i%m%x%z&S&W&_&f&p&}'R'w(R)V)^*k*o*t+T+X+[+x,P,b,h,m-u-z.S.].|/_/`/a/c/g/j/l/{0T0j0t1X2i2q3R3f3h3i3q3x5o5}6W6{7j8]8o9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aS#l`#mR1Y,l&e_ORSTU`jk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#]#b#e#k#m$]$n%[%_%`%c%e%f%g%i%m%x%z&S&W&_&f&p&}'R'w(R)V)^*k*o*t+T+X+[+x,P,b,h,l,m-u-z.S.].|/_/`/a/c/g/j/l/{0T0j0t1X2i2q3R3f3h3i3q3x5o5}6W6{7j8]8o9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aS#g^#nT'n#i'rT#h^#nT'p#i'r&e`ORSTU`jk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#]#b#e#k#m$]$n%[%_%`%c%e%f%g%i%m%x%z&S&W&_&f&p&}'R'w(R)V)^*k*o*t+T+X+[+x,P,b,h,l,m-u-z.S.].|/_/`/a/c/g/j/l/{0T0j0t1X2i2q3R3f3h3i3q3x5o5}6W6{7j8]8o9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;aT#l`#mQ#o`R'y#m$rbORSTUjk}!S!W!]!`!n!v!z!|#P#Q#R#S#T#U#V#W#X#Y#Z#b#e$]$n%[%_%`%c%e%f%g%i%m%x%z&S&_&f&p&}'R(R)V)^*k*o*t+T+x,P,b,h-u-z.S.].|/_/`/a/c/g/j/l0T0j0t2i3R3f3h3i3x5o5}6W7j8]8o!k;_#]#k&W'w+X+[,m/{1X2q3q6{9^9`9c9e9f9g9h9i9j9k9l9m9n9o9p9s:Q:R:T:_:`:g:h;a#RdOSUj}!S!W!n!|#k$]%[%_%`%c%e%f%g%i%m&S&f'w)^*k*o*t+x,m-u.S.|/_/`/a/c/g/j/l1X2i3R3f3h3i5o5}x#{a!y$T$U$Y(W(Y(b(w(x,_-Y-w1a1y6i;^;i;j;k#[&|!w#d#v#y&g'}(Z(h)])_)a*O*R+y-Z-].R.T.p.s.{.}1k1s2Q2T2X2j3Q3S4l4u4}5k5p6z7W8T9w9z9}:U:X:[:a:d:j;l;n;t;u;vQ)S$WQ,x(Sd1V9r9y9|:P:W:Z:^:c:f:le8q9d9x9{:O:V:Y:]:b:e:kx#wa!y$T$U$Y(W(Y(b(w(x,_-Y-w1a1y6i;^;i;j;kQ(d#xS(n#z(qQ)T$XQ-g(o#[:w!w#d#v#y&g'}(Z(h)])_)a*O*R+y-Z-].R.T.p.s.{.}1k1s2Q2T2X2j3Q3S4l4u4}5k5p6z7W8T9w9z9}:U:X:[:a:d:j;l;n;t;u;vd:x9d9x9{:O:V:Y:]:b:e:kd:y9r9y9|:P:W:Z:^:c:f:lQ:};bQ;O;cQ;P;dQ;Q;eQ;R;fR;S;gx#{a!y$T$U$Y(W(Y(b(w(x,_-Y-w1a1y6i;^;i;j;k#[&|!w#d#v#y&g'}(Z(h)])_)a*O*R+y-Z-].R.T.p.s.{.}1k1s2Q2T2X2j3Q3S4l4u4}5k5p6z7W8T9w9z9}:U:X:[:a:d:j;l;n;t;u;vd1V9r9y9|:P:W:Z:^:c:f:le8q9d9x9{:O:V:Y:]:b:e:klfOSj}!n$]%c%f%g%i*o*t/g/jQ(g#yQ*}%pQ+O%rR1j-Z%O#|a!w!y#d#v#y$T$U$Y&g'}(W(Y(Z(b(h(w(x)])_)a*O*R+y,_-Y-Z-]-w.R.T.p.s.{.}1a1k1s1y2Q2T2X2j3Q3S4l4u4}5k5p6i6z7W8T9d9r9w9x9y9z9{9|9}:O:P:U:V:W:X:Y:Z:[:]:^:a:b:c:d:e:f:j:k:l;^;i;j;k;l;n;t;u;vQ*Q$}Q.r*SQ2m.qR5]2nT(p#z(qS(p#z(qT2u.y2vQ)b$eQ-f(nQ.X)cQ/Q*]Q3V/RQ5r3WQ6}5aQ7[5sQ7|7OQ8V7]Q8d7}Q8s8eQ9Q8tR9X9Rp(W#t'O)U-X-o-p0q1h1}4f4w7q:v;W;X;Y!n:U&z'i(^(f+v,[,t-P-^-|.P.o.q0e0p1i1m2W2l2n3O4Y4Z4m4q4y5O5Z5n6m6q7Y8`;Z;];p;q;r[:V8p9O9V9Y9Z9]]:W1U4a6c7o7p8zr(Y#t'O)U,}-X-o-p0q1h1}4f4w7q:v;W;X;Y!p:X&z'i(^(f+v,[,t-P-^-|.P.o.q0e0n0p1i1m2W2l2n3O4Y4Z4m4q4y5O5Z5n6m6q7Y8`;Z;];p;q;r^:Y8p9O9T9V9Y9Z9]_:Z1U4a6c6d7o7p8zpeOSjy}!n$]%Y%c%f%g%i*o*t/g/jQ%VxR*k%`peOSjy}!n$]%Y%c%f%g%i*o*t/g/jR%VxQ*U%OR.n)}qeOSjy}!n$]%Y%c%f%g%i*o*t/g/jQ.z*ZS3P/O/PW5j2|2}3O3TU7V5l5m5nU8R7U7X7YQ8h8SR8v8iQ%^yR*e%YR3^/XR7_5uS$mp$rR.d)nQ%czR*o%dR*u%jT/h*t/jR*y%kQ*x%kR/q*yQjOQ!nST$`j!nQ(P#sR,u(PQ!YQR%u!YQ!^RU%{!^%|+UQ%|!_R+U%}Q+a&XR/}+aQ,`'OR0r,`Q,c'QS0u,c0vR0v,dQ+m&dR0X+mS!eR$uU&a!e&b+VQ&b!fR+V&OQ+d&[R0P+dQ&u!sQ,R&sU,V&u,R0mR0m,WQ'r#iR,n'rQ#m`R'x#mQ#cZU'h#c+Q9qQ+Q9_R9q'uQ-S(_W1d-S1e4j6lU1e-T-U-VS4j1f1gR6l4k$k(U#t&z'O'i(^(f)P)Q)U+v,Y,Z,[,t,}-O-P-X-^-o-p-|.P.o.q0e0n0o0p0q1U1h1i1m1}2W2l2n3O4Y4Z4_4`4a4f4m4q4w4y5O5Z5n6c6d6e6m6q7Y7o7p7q8`8p8z8|8}9O9T9U9V9Y9Z9]:v;W;X;Y;Z;];p;q;rQ-[(fU1l-[1n4nQ1n-^R4n1mQ(q#zR-i(qQ(z$OR-r(zQ2R-|R4z2RQ){$xR.m){Q2p.tS5_2p6|R6|5`Q*W%PR.w*WQ2v.yR5d2vQ/W*bS3[/W5vR5v3^Q._)jW2a._2c5T6wQ2c.bQ5T2bR6w5UQ)o$mR.e)oQ/j*tR3l/jWiOSj!nQ%h}Q)X$]Q*n%cQ*p%fQ*q%gQ*s%iQ/e*oS/h*t/jR3k/gQ$_gQ%l!RQ%o!TQ%q!UQ%s!VQ)v$sQ)|$yQ*d%^Q*{%nQ-h(pS/Z*e*hQ/r*zQ/s*}Q/t+OS0S+j2sQ2f.hQ2k.oQ3U/QQ3`/]Q3j/fY3w0U0V0]0b5fQ5X2hQ5[2lQ5q3VQ5w3_[6U3v3y3}4P4Q7SQ6x5VQ7Z5rQ7`5xW7f6V6[6^6`Q7x6yQ7{6}Q8U7[U8X7g7l7nQ8c7|Q8j8VS8k8Z8_Q8r8dQ8w8mQ9P8sQ9S8yQ9W9QR9[9XQ$gmQ&i!jU)e$h$i$jQ+Z&UU+{&j&k&lQ-`(kS.Z)f)gQ/z+]Q0R+jS0g+|+}Q1q-dQ2Z.[Q3t0QS3z0W0]Q4V0hQ4r1uS6Y3{4QQ7i6ZQ8[7kR8n8^S#ua;^R({$PU$Oa$P;^R-q(yQ#taS&z!w)aQ'O!yQ'i#dQ(^#vQ(f#yQ)P$TQ)Q$UQ)U$YQ+v&gQ,Y9wQ,Z9zQ,[9}Q,t'}Q,}(WQ-O(YQ-P(ZQ-X(bQ-^(hQ-o(wQ-p(xd-|)].R.{2T3Q4}5k6z7W8TQ.P)_Q.o*OQ.q*RQ0e+yQ0n:UQ0o:XQ0p:[Q0q,_Q1U9rQ1h-YQ1i-ZQ1m-]Q1}-wQ2W.TQ2l.pQ2n.sQ3O.}Q4Y:aQ4Z:dQ4_9yQ4`9|Q4a:PQ4f1aQ4m1kQ4q1sQ4w1yQ4y2QQ5O2XQ5Z2jQ5n3SQ6c:^Q6d:WQ6e:ZQ6m4lQ6q4uQ7Y5pQ7o:cQ7p:fQ7q6iQ8`:jQ8p9dQ8z:lQ8|9xQ8}9{Q9O:OQ9T:VQ9U:YQ9V:]Q9Y:bQ9Z:eQ9]:kQ:v;^Q;W;iQ;X;jQ;Y;kQ;Z;lQ;];nQ;p;tQ;q;uR;r;vlgOSj}!n$]%c%f%g%i*o*t/g/jS!pU%eQ%n!SQ%t!WQ'V!|Q'v#kS*h%[%_Q*l%`Q*z%mQ+W&SQ+u&fQ,r'wQ.O)^Q/b*kQ0d+xQ1[,mQ1{-uQ2V.SQ2}.|Q3b/_Q3c/`Q3e/aQ3g/cQ3n/lQ4d1XQ5Y2iQ5m3RQ5|3fQ6O3hQ6P3iQ7X5oR7b5}!vZOSUj}!S!n!|$]%[%_%`%c%e%f%g%i%m&S&f)^*k*o*t+x-u.S.|/_/`/a/c/g/j/l2i3R3f3h3i5o5}Q!_RQ!oTQ$akS%w!]%zQ%}!`Q&y!vQ'Q!zQ'W#PQ'X#QQ'Y#RQ'Z#SQ'[#TQ']#UQ'^#VQ'_#WQ'`#XQ'a#YQ'b#ZQ'd#]Q'g#bQ'k#eW'u#k'w,m1XQ)p$nS+R%x+TS+^&W/{Q+g&_Q,O&pQ,^&}Q,d'RQ,g9^Q,i9`Q,w(RQ-x)VQ/v+XQ/y+[Q0i,PQ0s,bQ0w9cQ0x9eQ0y9fQ0z9gQ0{9hQ0|9iQ0}9jQ1O9kQ1P9lQ1Q9mQ1R9nQ1S9oQ1T,hQ1W9sQ1]9pQ2O-zQ2[.]Q3s:QQ3v0TQ4W0jQ4[0tQ4]:RQ4b:TQ4c:_Q5`2qQ6S3qQ6V3xQ6b:`Q6f:gQ6g:hQ7g6WQ7z6{Q8Z7jQ8m8]Q8y8oQ9_!WR:|;aR!aRR&Y!bS&U!b+`S+]&V&^R0Q+fR'P!yR'S!zT!tU$ZS!sU$ZU$xrs*mS&s!r!uQ,T&tQ,W&wQ.l)zS0k,S,UR4X0l`!dR!]!`$u%x&`)x+hh!qUrs!r!u$Z&t&w)z,S,U0lQ/d*mQ/w+YQ3p/oT:s&W)yT!gR$uS!fR$uS%y!]&`S&O!`)xS+S%x+hT+_&W)yT&]!b$vQ#i^R'{#nT'q#i'rR1Z,lT(a#v(cR(i#yQ-})]Q2U.RQ2|.{Q4{2TQ5l3QQ6t4}Q7U5kQ7y6zQ8S7WR8i8TlhOSj}!n$]%c%f%g%i*o*t/g/jQ%]yR*d%YV$yrs*mR.u*TR*c%WQ$qpR)u$rR)k$lT%az%dT%bz%dT/i*t/j",
nodeNames: "⚠ extends ArithOp ArithOp InterpolationStart LineComment BlockComment Script ExportDeclaration export Star as VariableName String from ; default FunctionDeclaration async function VariableDefinition TypeParamList TypeDefinition ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Interpolation null super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression await yield delete LogicOp BitOp ParenthesizedExpression ClassExpression class extends ClassBody MethodDeclaration Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression PrivatePropertyName BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXStartTag JSXSelfClosingTag JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody MethodDeclaration AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement",
maxTerm: 332,
context: trackNewline,
nodeProps: [["closedBy", 4, "InterpolationEnd", 40, "]", 51, "}", 66, ")", 132, "JSXSelfCloseEndTag JSXEndTag", 146, "JSXEndTag"], ["group", -26, 8, 15, 17, 58, 184, 188, 191, 192, 194, 197, 200, 211, 213, 219, 221, 223, 225, 228, 234, 240, 242, 244, 246, 248, 250, 251, "Statement", -30, 12, 13, 24, 27, 28, 41, 43, 44, 45, 47, 52, 60, 68, 74, 75, 91, 92, 101, 103, 119, 122, 124, 125, 126, 127, 129, 130, 148, 149, 151, "Expression", -22, 23, 25, 29, 32, 34, 152, 154, 156, 157, 159, 160, 161, 163, 164, 165, 167, 168, 169, 178, 180, 182, 183, "Type", -3, 79, 85, 90, "ClassItem"], ["openedBy", 30, "InterpolationStart", 46, "[", 50, "{", 65, "(", 131, "JSXStartTag", 141, "JSXStartTag JSXStartCloseTag"]],
propSources: [jsHighlight],
skippedNodes: [0, 5, 6],
repeatNodeCount: 28,
tokenData: "!C}~R!`OX%TXY%cYZ'RZ[%c[]%T]^'R^p%Tpq%cqr'crs(kst0htu2`uv4pvw5ewx6cxy<yyz=Zz{=k{|>k|}?O}!O>k!O!P?`!P!QCl!Q!R!0[!R![!1q![!]!7s!]!^!8V!^!_!8g!_!`!9d!`!a!:[!a!b!<R!b!c%T!c!}2`!}#O!=d#O#P%T#P#Q!=t#Q#R!>U#R#S2`#S#T!>i#T#o2`#o#p!>y#p#q!?O#q#r!?f#r#s!?x#s$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$I|2`$I|$I}!Bq$I}$JO!Bq$JO$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`W%YR$UWO!^%T!_#o%T#p~%T7Z%jg$UW'Y7ROX%TXY%cYZ%TZ[%c[p%Tpq%cq!^%T!_#o%T#p$f%T$f$g%c$g#BY%T#BY#BZ%c#BZ$IS%T$IS$I_%c$I_$JT%T$JT$JU%c$JU$KV%T$KV$KW%c$KW&FU%T&FU&FV%c&FV?HT%T?HT?HU%c?HU~%T7Z'YR$UW'Z7RO!^%T!_#o%T#p~%T$T'jS$UW!j#{O!^%T!_!`'v!`#o%T#p~%T$O'}S#e#v$UWO!^%T!_!`(Z!`#o%T#p~%T$O(bR#e#v$UWO!^%T!_#o%T#p~%T)X(rZ$UW]#eOY(kYZ)eZr(krs*rs!^(k!^!_+U!_#O(k#O#P-b#P#o(k#o#p+U#p~(k&r)jV$UWOr)ers*Ps!^)e!^!_*a!_#o)e#o#p*a#p~)e&r*WR$P&j$UWO!^%T!_#o%T#p~%T&j*dROr*ars*ms~*a&j*rO$P&j)X*{R$P&j$UW]#eO!^%T!_#o%T#p~%T)P+ZV]#eOY+UYZ*aZr+Urs+ps#O+U#O#P+w#P~+U)P+wO$P&j]#e)P+zROr+Urs,Ts~+U)P,[U$P&j]#eOY,nZr,nrs-Vs#O,n#O#P-[#P~,n#e,sU]#eOY,nZr,nrs-Vs#O,n#O#P-[#P~,n#e-[O]#e#e-_PO~,n)X-gV$UWOr(krs-|s!^(k!^!_+U!_#o(k#o#p+U#p~(k)X.VZ$P&j$UW]#eOY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x#m/PZ$UW]#eOY.xYZ%TZr.xrs/rs!^.x!^!_,n!_#O.x#O#P0S#P#o.x#o#p,n#p~.x#m/yR$UW]#eO!^%T!_#o%T#p~%T#m0XT$UWO!^.x!^!_,n!_#o.x#o#p,n#p~.x3]0mZ$UWOt%Ttu1`u!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`3]1g]$UW'o3TOt%Ttu1`u!Q%T!Q![1`![!^%T!_!c%T!c!}1`!}#R%T#R#S1`#S#T%T#T#o1`#p$g%T$g~1`7Z2k_$UW#zS']$y'g3SOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`[3q_$UW#zSOt%Ttu3ju}%T}!O3j!O!Q%T!Q![3j![!^%T!_!c%T!c!}3j!}#R%T#R#S3j#S#T%T#T#o3j#p$g%T$g~3j$O4wS#^#v$UWO!^%T!_!`5T!`#o%T#p~%T$O5[R$UW#o#vO!^%T!_#o%T#p~%T5b5lU'x5Y$UWOv%Tvw6Ow!^%T!_!`5T!`#o%T#p~%T$O6VS$UW#i#vO!^%T!_!`5T!`#o%T#p~%T)X6jZ$UW]#eOY6cYZ7]Zw6cwx*rx!^6c!^!_8T!_#O6c#O#P:T#P#o6c#o#p8T#p~6c&r7bV$UWOw7]wx*Px!^7]!^!_7w!_#o7]#o#p7w#p~7]&j7zROw7wwx*mx~7w)P8YV]#eOY8TYZ7wZw8Twx+px#O8T#O#P8o#P~8T)P8rROw8Twx8{x~8T)P9SU$P&j]#eOY9fZw9fwx-Vx#O9f#O#P9}#P~9f#e9kU]#eOY9fZw9fwx-Vx#O9f#O#P9}#P~9f#e:QPO~9f)X:YV$UWOw6cwx:ox!^6c!^!_8T!_#o6c#o#p8T#p~6c)X:xZ$P&j$UW]#eOY;kYZ%TZw;kwx/rx!^;k!^!_9f!_#O;k#O#P<e#P#o;k#o#p9f#p~;k#m;rZ$UW]#eOY;kYZ%TZw;kwx/rx!^;k!^!_9f!_#O;k#O#P<e#P#o;k#o#p9f#p~;k#m<jT$UWO!^;k!^!_9f!_#o;k#o#p9f#p~;k&i=QR!d&a$UWO!^%T!_#o%T#p~%Tk=bR!cc$UWO!^%T!_#o%T#p~%T7V=tU'^4V#_#v$UWOz%Tz{>W{!^%T!_!`5T!`#o%T#p~%T$O>_S#[#v$UWO!^%T!_!`5T!`#o%T#p~%T%w>rSj%o$UWO!^%T!_!`5T!`#o%T#p~%T&i?VR!R&a$UWO!^%T!_#o%T#p~%T7Z?gVu5^$UWO!O%T!O!P?|!P!Q%T!Q![@r![!^%T!_#o%T#p~%T!{@RT$UWO!O%T!O!P@b!P!^%T!_#o%T#p~%T!{@iR!Q!s$UWO!^%T!_#o%T#p~%T!{@yZ$UWk!sO!Q%T!Q![@r![!^%T!_!g%T!g!hAl!h#R%T#R#S@r#S#X%T#X#YAl#Y#o%T#p~%T!{AqZ$UWO{%T{|Bd|}%T}!OBd!O!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%T!{BiV$UWO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%T!{CVV$UWk!sO!Q%T!Q![CO![!^%T!_#R%T#R#SCO#S#o%T#p~%T7ZCs`$UW#]#vOYDuYZ%TZzDuz{Jl{!PDu!P!Q!-e!Q!^Du!^!_Fx!_!`!.^!`!a!/]!a!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXD|[$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~DuXEy_$UW}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%TPF}V}POYFxZ!PFx!P!QGd!Q!}Fx!}#OG{#O#PHh#P~FxPGiU}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGdPHOTOYG{Z#OG{#O#PH_#P#QFx#Q~G{PHbQOYG{Z~G{PHkQOYFxZ~FxXHvY$UWOYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~HqXIkV$UWOYHqYZ%TZ!^Hq!^!_G{!_#oHq#o#pG{#p~HqXJVV$UWOYDuYZ%TZ!^Du!^!_Fx!_#oDu#o#pFx#p~Du7ZJs^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q!,R!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl7ZKtV$UWOzKoz{LZ{!^Ko!^!_M]!_#oKo#o#pM]#p~Ko7ZL`X$UWOzKoz{LZ{!PKo!P!QL{!Q!^Ko!^!_M]!_#oKo#o#pM]#p~Ko7ZMSR$UWU7RO!^%T!_#o%T#p~%T7RM`ROzM]z{Mi{~M]7RMlTOzM]z{Mi{!PM]!P!QM{!Q~M]7RNQOU7R7ZNX^$UW}POYJlYZKoZzJlz{NQ{!PJl!P!Q! T!Q!^Jl!^!_!!]!_!}Jl!}#O!'|#O#P!+a#P#oJl#o#p!!]#p~Jl7Z! ^_$UWU7R}PO!^%T!_#Z%T#Z#[Er#[#]%T#]#^Er#^#a%T#a#bEr#b#g%T#g#hEr#h#i%T#i#jEr#j#m%T#m#nEr#n#o%T#p~%T7R!!bY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!&x!Q!}!!]!}#O!$`#O#P!&f#P~!!]7R!#VY}POY!!]YZM]Zz!!]z{!#Q{!P!!]!P!Q!#u!Q!}!!]!}#O!$`#O#P!&f#P~!!]7R!#|UU7R}P#Z#[Gd#]#^Gd#a#bGd#g#hGd#i#jGd#m#nGd7R!$cWOY!$`YZM]Zz!$`z{!${{#O!$`#O#P!&S#P#Q!!]#Q~!$`7R!%OYOY!$`YZM]Zz!$`z{!${{!P!$`!P!Q!%n!Q#O!$`#O#P!&S#P#Q!!]#Q~!$`7R!%sTU7ROYG{Z#OG{#O#PH_#P#QFx#Q~G{7R!&VTOY!$`YZM]Zz!$`z{!${{~!$`7R!&iTOY!!]YZM]Zz!!]z{!#Q{~!!]7R!&}_}POzM]z{Mi{#ZM]#Z#[!&x#[#]M]#]#^!&x#^#aM]#a#b!&x#b#gM]#g#h!&x#h#iM]#i#j!&x#j#mM]#m#n!&x#n~M]7Z!(R[$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|7Z!(|^$UWOY!'|YZKoZz!'|z{!(w{!P!'|!P!Q!)x!Q!^!'|!^!_!$`!_#O!'|#O#P!*o#P#QJl#Q#o!'|#o#p!$`#p~!'|7Z!*PY$UWU7ROYHqYZ%TZ!^Hq!^!_G{!_#OHq#O#PIf#P#QDu#Q#oHq#o#pG{#p~Hq7Z!*tX$UWOY!'|YZKoZz!'|z{!(w{!^!'|!^!_!$`!_#o!'|#o#p!$`#p~!'|7Z!+fX$UWOYJlYZKoZzJlz{NQ{!^Jl!^!_!!]!_#oJl#o#p!!]#p~Jl7Z!,Yc$UW}POzKoz{LZ{!^Ko!^!_M]!_#ZKo#Z#[!,R#[#]Ko#]#^!,R#^#aKo#a#b!,R#b#gKo#g#h!,R#h#iKo#i#j!,R#j#mKo#m#n!,R#n#oKo#o#pM]#p~Ko7Z!-lV$UWT7ROY!-eYZ%TZ!^!-e!^!_!.R!_#o!-e#o#p!.R#p~!-e7R!.WQT7ROY!.RZ~!.R$P!.g[$UW#o#v}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Du]!/f[#wS$UW}POYDuYZ%TZ!PDu!P!QEr!Q!^Du!^!_Fx!_!}Du!}#OHq#O#PJQ#P#oDu#o#pFx#p~Du!{!0cd$UWk!sO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#U%T#U#V!3X#V#X%T#X#YAl#Y#b%T#b#c!2w#c#d!4m#d#l%T#l#m!5{#m#o%T#p~%T!{!1x_$UWk!sO!O%T!O!P@r!P!Q%T!Q![!1q![!^%T!_!g%T!g!hAl!h#R%T#R#S!1q#S#X%T#X#YAl#Y#b%T#b#c!2w#c#o%T#p~%T!{!3OR$UWk!sO!^%T!_#o%T#p~%T!{!3^W$UWO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#o%T#p~%T!{!3}Y$UWk!sO!Q%T!Q!R!3v!R!S!3v!S!^%T!_#R%T#R#S!3v#S#b%T#b#c!2w#c#o%T#p~%T!{!4rV$UWO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#o%T#p~%T!{!5`X$UWk!sO!Q%T!Q!Y!5X!Y!^%T!_#R%T#R#S!5X#S#b%T#b#c!2w#c#o%T#p~%T!{!6QZ$UWO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#o%T#p~%T!{!6z]$UWk!sO!Q%T!Q![!6s![!^%T!_!c%T!c!i!6s!i#R%T#R#S!6s#S#T%T#T#Z!6s#Z#b%T#b#c!2w#c#o%T#p~%T$u!7|R!]V$UW#m$fO!^%T!_#o%T#p~%T!q!8^R_!i$UWO!^%T!_#o%T#p~%T5w!8rR'bd!a/n#x&s'|P!P!Q!8{!^!_!9Q!_!`!9_W!9QO$WW#v!9VP#`#v!_!`!9Y#v!9_O#o#v#v!9dO#a#v$u!9kT!{$m$UWO!^%T!_!`'v!`!a!9z!a#o%T#p~%T$P!:RR#W#w$UWO!^%T!_#o%T#p~%T%V!:gT'a!R#a#v$RS$UWO!^%T!_!`!:v!`!a!;W!a#o%T#p~%T$O!:}R#a#v$UWO!^%T!_#o%T#p~%T$O!;_T#`#v$UWO!^%T!_!`5T!`!a!;n!a#o%T#p~%T$O!;uS#`#v$UWO!^%T!_!`5T!`#o%T#p~%T*a!<YV'p#{$UWO!O%T!O!P!<o!P!^%T!_!a%T!a!b!=P!b#o%T#p~%T*[!<vRv*S$UWO!^%T!_#o%T#p~%T$O!=WS$UW#j#vO!^%T!_!`5T!`#o%T#p~%T7V!=kRx6}$UWO!^%T!_#o%T#p~%Tk!={R!Oc$UWO!^%T!_#o%T#p~%T$O!>]S#g#v$UWO!^%T!_!`5T!`#o%T#p~%T$a!>pR$UW'f$XO!^%T!_#o%T#p~%T~!?OO!T~5b!?VT'w5Y$UWO!^%T!_!`5T!`#o%T#p#q!=P#q~%T6X!?oR!S5}nQ$UWO!^%T!_#o%T#p~%TX!@PR!kP$UWO!^%T!_#o%T#p~%T7Z!@gr$UW'Y7R#zS']$y'g3SOX%TXY%cYZ%TZ[%c[p%Tpq%cqt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$f%T$f$g%c$g#BY2`#BY#BZ!@Y#BZ$IS2`$IS$I_!@Y$I_$JT2`$JT$JU!@Y$JU$KV2`$KV$KW!@Y$KW&FU2`&FU&FV!@Y&FV?HT2`?HT?HU!@Y?HU~2`7Z!CO_$UW'Z7R#zS']$y'g3SOt%Ttu2`u}%T}!O3j!O!Q%T!Q![2`![!^%T!_!c%T!c!}2`!}#R%T#R#S2`#S#T%T#T#o2`#p$g%T$g~2`",
tokenizers: [tsExtends, noSemicolon, incdecToken, template, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, insertSemicolon],
topRules: {
"Script": [0, 7]
},
dialects: {
jsx: 12107,
ts: 12109
},
dynamicPrecedences: {
"149": 1,
"176": 1
},
specialized: [{
term: 289,
get: value => spec_identifier[value] || -1
}, {
term: 299,
get: value => spec_word[value] || -1
}, {
term: 63,
get: value => spec_LessThan[value] || -1
}],
tokenPrec: 12130
}); //#endregion
//#region ../../../node_modules/.pnpm/@codemirror+lang-javascript@6.2.2/node_modules/@codemirror/lang-javascript/dist/index.js
/**
A collection of JavaScript-related
[snippets](https://codemirror.net/6/docs/ref/#autocomplete.snippet).
*/
_export("V", snippets = [/* @__PURE__ */snippetCompletion("function ${name}(${params}) {\n ${}\n}", {
label: "function",
detail: "definition",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}", {
label: "for",
detail: "loop",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("for (let ${name} of ${collection}) {\n ${}\n}", {
label: "for",
detail: "of loop",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("do {\n ${}\n} while (${})", {
label: "do",
detail: "loop",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("while (${}) {\n ${}\n}", {
label: "while",
detail: "loop",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("try {\n ${}\n} catch (${error}) {\n ${}\n}", {
label: "try",
detail: "/ catch block",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("if (${}) {\n ${}\n}", {
label: "if",
detail: "block",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("if (${}) {\n ${}\n} else {\n ${}\n}", {
label: "if",
detail: "/ else block",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("class ${name} {\n constructor(${params}) {\n ${}\n }\n}", {
label: "class",
detail: "definition",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("import {${names}} from \"${module}\"\n${}", {
label: "import",
detail: "named",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("import ${name} from \"${module}\"\n${}", {
label: "import",
detail: "default",
type: "keyword"
})]);
/**
A collection of snippet completions for TypeScript. Includes the
JavaScript [snippets](https://codemirror.net/6/docs/ref/#lang-javascript.snippets).
*/
typescriptSnippets = /* @__PURE__ */snippets.concat([/* @__PURE__ */snippetCompletion("interface ${name} {\n ${}\n}", {
label: "interface",
detail: "definition",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("type ${name} = ${type}", {
label: "type",
detail: "definition",
type: "keyword"
}), /* @__PURE__ */snippetCompletion("enum ${name} {\n ${}\n}", {
label: "enum",
detail: "definition",
type: "keyword"
})]);
cache = /* @__PURE__ */new NodeWeakMap();
ScopeNodes = /* @__PURE__ */new Set(["Script", "Block", "FunctionExpression", "FunctionDeclaration", "ArrowFunction", "MethodDeclaration", "ForStatement"]);
functionContext = ["FunctionDeclaration"];
gatherCompletions = {
FunctionDeclaration: /* @__PURE__ */defID("function"),
ClassDeclaration: /* @__PURE__ */defID("class"),
ClassExpression: () => true,
EnumDeclaration: /* @__PURE__ */defID("constant"),
TypeAliasDeclaration: /* @__PURE__ */defID("type"),
NamespaceDeclaration: /* @__PURE__ */defID("namespace"),
VariableDefinition(node, def) {
if (!node.matchContext(functionContext)) def(node, "variable");
},
TypeDefinition(node, def) {
def(node, "type");
},
__proto__: null
};
Identifier = /^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/;
dontComplete = ["TemplateString", "String", "RegExp", "LineComment", "BlockComment", "VariableDefinition", "TypeDefinition", "Label", "PropertyDefinition", "PropertyName", "PrivatePropertyDefinition", "PrivatePropertyName", ".", "?."];
_export("R", javascriptLanguage = /* @__PURE__ */LRLanguage.define({
name: "javascript",
parser: /* @__PURE__ */parser$2.configure({
props: [/* @__PURE__ */indentNodeProp.add({
IfStatement: /* @__PURE__ */continuedIndent({
except: /^\s*({|else\b)/
}),
TryStatement: /* @__PURE__ */continuedIndent({
except: /^\s*({|catch\b|finally\b)/
}),
LabeledStatement: flatIndent,
SwitchBody: context => {
let after = context.textAfter,
closed = /^\s*\}/.test(after),
isCase = /^\s*(case|default)\b/.test(after);
return context.baseIndent + (closed ? 0 : isCase ? 1 : 2) * context.unit;
},
Block: /* @__PURE__ */delimitedIndent({
closing: "}"
}),
ArrowFunction: cx => cx.baseIndent + cx.unit,
"TemplateString BlockComment": () => null,
"Statement Property": /* @__PURE__ */continuedIndent({
except: /^{/
}),
JSXElement(context) {
let closed = /^\s*<\//.test(context.textAfter);
return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
},
JSXEscape(context) {
let closed = /\s*\}/.test(context.textAfter);
return context.lineIndent(context.node.from) + (closed ? 0 : context.unit);
},
"JSXOpenTag JSXSelfClosingTag"(context) {
return context.column(context.node.from) + context.unit;
}
}), /* @__PURE__ */foldNodeProp.add({
"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType": foldInside,
BlockComment(tree) {
return {
from: tree.from + 2,
to: tree.to - 2
};
}
})]
}),
languageData: {
closeBrackets: {
brackets: ["(", "[", "{", "'", "\"", "`"]
},
commentTokens: {
line: "//",
block: {
open: "/*",
close: "*/"
}
},
indentOnInput: /^\s*(?:case |default:|\{|\}|<\/)$/,
wordChars: "$"
}
}));
jsxSublanguage = {
test: node => /^JSX/.test(node.name),
facet: /* @__PURE__ */defineLanguageFacet$1({
commentTokens: {
block: {
open: "{/*",
close: "*/}"
}
}
})
};
/**
A language provider for TypeScript.
*/
_export("U", typescriptLanguage = /* @__PURE__ */javascriptLanguage.configure({
dialect: "ts"
}, "typescript"));
/**
Language provider for JSX.
*/
_export("z", jsxLanguage = /* @__PURE__ */javascriptLanguage.configure({
dialect: "jsx",
props: [/* @__PURE__ */sublanguageProp$1.add(n => n.isTop ? [jsxSublanguage] : void 0)]
}));
/**
Language provider for JSX + TypeScript.
*/
_export("H", tsxLanguage = /* @__PURE__ */javascriptLanguage.configure({
dialect: "jsx ts",
props: [/* @__PURE__ */sublanguageProp$1.add(n => n.isTop ? [jsxSublanguage] : void 0)]
}, "typescript"));
kwCompletion = name$1 => ({
label: name$1,
type: "keyword"
});
keywords = /* @__PURE__ */"break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(kwCompletion);
typescriptKeywords = /* @__PURE__ */keywords.concat(/* @__PURE__ */["declare", "implements", "private", "protected", "public"].map(kwCompletion));
android = typeof navigator == "object" && /* @__PURE__ *//Android\b/.test(navigator.userAgent);
/**
Extension that will automatically insert JSX close tags when a `>` or
`/` is typed.
*/
autoCloseTags = /* @__PURE__ */EditorView.inputHandler.of((view, from, to, text, defaultInsert) => {
if ((android ? view.composing : view.compositionStarted) || view.state.readOnly || from != to || text != ">" && text != "/" || !javascriptLanguage.isActiveAt(view.state, from, -1)) return false;
let base$1 = defaultInsert(),
{
state
} = base$1;
let closeTags = state.changeByRange(range => {
var _a$2;
let {
head
} = range,
around = syntaxTree$1(state).resolveInner(head - 1, -1),
name$1;
if (around.name == "JSXStartTag") around = around.parent;
if (state.doc.sliceString(head - 1, head) != text || around.name == "JSXAttributeValue" && around.to > head) ;else if (text == ">" && around.name == "JSXFragmentTag") return {
range,
changes: {
from: head,
insert: `</>`
}
};else if (text == "/" && around.name == "JSXStartCloseTag") {
let empty$1 = around.parent,
base$2 = empty$1.parent;
if (base$2 && empty$1.from == head - 2 && ((name$1 = elementName(state.doc, base$2.firstChild, head)) || ((_a$2 = base$2.firstChild) === null || _a$2 === void 0 ? void 0 : _a$2.name) == "JSXFragmentTag")) {
let insert$2 = `${name$1}>`;
return {
range: EditorSelection.cursor(head + insert$2.length, -1),
changes: {
from: head,
insert: insert$2
}
};
}
} else if (text == ">") {
let openTag = findOpenTag(around);
if (openTag && openTag.name == "JSXOpenTag" && !/^\/?>|^<\//.test(state.doc.sliceString(head, head + 2)) && (name$1 = elementName(state.doc, openTag, head))) return {
range,
changes: {
from: head,
insert: `</${name$1}>`
}
};
}
return {
range
};
});
if (closeTags.changes.empty) return false;
view.dispatch([base$1, state.update(closeTags, {
userEvent: "input.complete",
scrollIntoView: true
})]);
return true;
});
_export("I", prefixMatch = (first, second) => first.toLocaleLowerCase().startsWith(second.toLocaleLowerCase()));
isPseudoParam = candidate => {
return ["notice"].includes(candidate);
};
/**
* Whether a string may be used as a key in object dot access notation.
*/
_export("N", isAllowedInDotNotation = str => {
return !/^(\d)|[\\ `!@#$%^&*()+\-=[\]{};':"\\|,.<>?~\/]/g.test(str);
});
isCredentialsModalOpen = () => useUIStore().modalsById[CREDENTIAL_EDIT_MODAL_KEY].open;
isInHttpNodePagination = targetNodeParameterContext => {
let nodeType;
let path;
if (targetNodeParameterContext) {
nodeType = targetNodeParameterContext.nodeName;
path = targetNodeParameterContext.parameterPath;
} else {
const ndvStore = useNDVStore();
nodeType = ndvStore.activeNode?.type;
path = ndvStore.focusedInputPath;
}
return nodeType === "n8n-nodes-base.httpRequest" && path.startsWith("parameters.options.pagination");
};
hasActiveNode = targetNodeParameterContext => targetNodeParameterContext !== void 0 && useWorkflowsStore().getNodeByName(targetNodeParameterContext.nodeName) !== null || useNDVStore().activeNode?.name !== void 0;
isSplitInBatchesAbsent = () => !useWorkflowsStore().workflow.nodes.some(node => node.type === SPLIT_IN_BATCHES_NODE_TYPE);
stripExcessParens = context => option => {
const followedByParens = context.state.sliceDoc(context.pos, context.pos + 2) === "()";
if (option.label.endsWith("()") && followedByParens) option.label = option.label.slice(0, -2);
const closingChars = getClosingChars(context.state.sliceDoc(context.pos));
const commonClosingChars = findCommonBoundary(option.label, closingChars);
if (commonClosingChars > 0) option.apply = (view, completion, from, to) => {
const tx = {
...insertCompletionText(view.state, option.label.slice(0, -commonClosingChars), from, to),
annotations: pickedCompletion.of(completion)
};
tx.selection = EditorSelection.cursor(from + option.label.length);
view.dispatch(tx);
};
return option;
};
getDefaultArgs = doc$2 => {
return doc$2?.args?.filter(arg => !arg.optional).map(arg => arg.default).filter(def => !!def) ?? [];
};
insertDefaultArgs = (label, args) => {
if (!label.endsWith("()")) return label;
const argList = args.join(", ");
return `${label.replace("()", "")}(${argList})`;
};
/**
* When a function completion is selected, set the cursor correctly
*
* @example `.includes()` -> `.includes(<cursor>)`
* @example `$max()` -> `$max()<cursor>`
*/
applyCompletion = ({
hasArgs = true,
defaultArgs = [],
transformLabel = label => label
} = {}) => (view, completion, from, to) => {
const isFunction = completion.label.endsWith("()");
const label = insertDefaultArgs(transformLabel(completion.label), defaultArgs);
const tx = {
...insertCompletionText(view.state, label, from, to),
annotations: pickedCompletion.of(completion)
};
if (isFunction) {
if (defaultArgs.length > 0) tx.selection = {
anchor: from + label.indexOf("(") + 1,
head: from + label.length - 1
};else if (hasArgs) {
const cursorPosition = from + label.length - 1;
tx.selection = {
anchor: cursorPosition,
head: cursorPosition
};
}
}
view.dispatch(tx);
};
applyBracketAccess = key => {
return `['${escapeMappingString(key)}']`;
};
/**
* Apply a bracket-access completion
*
* @example `$json.` -> `$json['key with spaces']`
* @example `$json` -> `$json['key with spaces']`
*/
applyBracketAccessCompletion = (view, completion, from, to) => {
const label = applyBracketAccess(completion.label);
const completionAtDot = view.state.sliceDoc(from - 1, from) === ".";
view.dispatch({
...insertCompletionText(view.state, label, completionAtDot ? from - 1 : from, to),
annotations: pickedCompletion.of(completion)
});
};
hasRequiredArgs = doc$2 => {
if (!doc$2) return false;
return (doc$2?.args?.filter(arg => !arg.name.endsWith("?") && !arg.optional) ?? []).length > 0;
};
sortCompletionsAlpha = completions => {
return completions.sort((a, b) => a.label.localeCompare(b.label));
};
renderSectionHeader = section => {
const container$1 = document.createElement("li");
container$1.classList.add("cm-section-header");
const inner = document.createElement("div");
inner.classList.add("cm-section-title");
inner.textContent = section.name;
container$1.appendChild(inner);
return container$1;
};
withSectionHeader = section => {
section.header = renderSectionHeader;
return section;
};
_export("P", isCompletionSection = section => {
return typeof section === "object";
});
getDisplayType = value => {
if (Array.isArray(value)) {
if (value.length > 0) return `${getDisplayType(value[0])}[]`;
return "Array";
}
if (value === null) return "null";
if (typeof value === "object") return "Object";
return (typeof value).toLocaleLowerCase();
};
shouldHighlightArgument = (arg, index, highlightArgIndex) => {
if (arg.variadic) return (highlightArgIndex ?? 0) >= index;
return highlightArgIndex === index;
};
renderFunctionHeader = (doc$2, highlightArgIndex) => {
const header$1 = document.createElement("div");
if (doc$2) {
const functionNameSpan = document.createElement("span");
functionNameSpan.classList.add("autocomplete-info-name");
functionNameSpan.textContent = doc$2.name;
header$1.appendChild(functionNameSpan);
const openBracketsSpan = document.createElement("span");
openBracketsSpan.textContent = "(";
header$1.appendChild(openBracketsSpan);
const argsSpan = document.createElement("span");
doc$2.args?.forEach((arg, index, array) => {
const optional = arg.optional && !arg.name.endsWith("?");
const argSpan = document.createElement(shouldHighlightArgument(arg, index, highlightArgIndex) ? "strong" : "span");
argSpan.classList.add("autocomplete-info-arg");
argSpan.textContent = arg.name;
if (optional) argSpan.textContent += "?";
if (arg.variadic) argSpan.textContent = "..." + argSpan.textContent;
argsSpan.appendChild(argSpan);
if (index !== array.length - 1) {
const separatorSpan = document.createElement("span");
separatorSpan.textContent = ", ";
argsSpan.appendChild(separatorSpan);
}
});
header$1.appendChild(argsSpan);
const closingBracket = document.createElement("span");
closingBracket.textContent = ")";
header$1.appendChild(closingBracket);
}
return header$1;
};
renderPropHeader = doc$2 => {
const header$1 = document.createElement("div");
if (doc$2) {
const propNameSpan = document.createElement("span");
propNameSpan.classList.add("autocomplete-info-name");
propNameSpan.textContent = doc$2.name;
header$1.appendChild(propNameSpan);
}
return header$1;
};
renderDescription = ({
description,
docUrl,
example
}) => {
const descriptionBody = document.createElement("div");
descriptionBody.classList.add("autocomplete-info-description");
const descriptionText = document.createElement("p");
const separator = !description.endsWith(".") && docUrl ? ". " : " ";
descriptionText.innerHTML = sanitizeHtml(description.replace(/`(.*?)`/g, "<code>$1</code>") + separator);
descriptionBody.appendChild(descriptionText);
if (docUrl) {
const descriptionLink = document.createElement("a");
descriptionLink.setAttribute("target", "_blank");
descriptionLink.setAttribute("href", docUrl);
descriptionLink.innerText = i18n.autocompleteUIValues.docLinkLabel ?? i18n.baseText("generic.learnMore");
descriptionLink.addEventListener("mousedown", event => {
event.preventDefault();
});
descriptionLink.classList.add("autocomplete-info-doc-link");
descriptionText.appendChild(descriptionLink);
}
if (example) {
const renderedExample = renderExample(example);
descriptionBody.appendChild(renderedExample);
}
return descriptionBody;
};
renderArg = (arg, highlight) => {
const argItem = document.createElement("li");
const argName = document.createElement(highlight ? "strong" : "span");
argName.classList.add("autocomplete-info-arg-name");
argName.textContent = arg.name.replaceAll("?", "");
const tags$1 = [];
if (arg.type) tags$1.push(arg.type);
if (!!arg.optional || arg.name.endsWith("?")) tags$1.push(i18n.baseText("codeNodeEditor.optional"));
if (tags$1.length > 0) argName.textContent += ` (${tags$1.join(", ")})`;
if (arg.description) argName.textContent += ":";
argItem.appendChild(argName);
if (arg.description) {
const argDescription = document.createElement("span");
argDescription.classList.add("autocomplete-info-arg-description");
if (arg.default && arg.optional && !arg.description.toLowerCase().includes("default")) {
const separator = arg.description.endsWith(".") ? " " : ". ";
arg.description += separator + i18n.baseText("codeNodeEditor.defaultsTo", {
interpolate: {
default: arg.default
}
});
}
argDescription.innerHTML = sanitizeHtml(arg.description.replace(/`(.*?)`/g, "<code>$1</code>"));
argItem.appendChild(argDescription);
}
if (Array.isArray(arg.args)) argItem.appendChild(renderArgList(arg.args));
return argItem;
};
renderArgList = (args, highlightArgIndex) => {
const argsList = document.createElement("ul");
argsList.classList.add("autocomplete-info-args");
args.forEach((arg, index) => {
argsList.appendChild(renderArg(arg, shouldHighlightArgument(arg, index, highlightArgIndex)));
});
return argsList;
};
renderArgs = (args, highlightArgIndex) => {
const argsContainer = document.createElement("div");
argsContainer.classList.add("autocomplete-info-args-container");
const argsTitle = document.createElement("div");
argsTitle.classList.add("autocomplete-info-section-title");
argsTitle.textContent = i18n.baseText("codeNodeEditor.parameters");
argsContainer.appendChild(argsTitle);
argsContainer.appendChild(renderArgList(args, highlightArgIndex));
return argsContainer;
};
renderExample = example => {
const examplePre = document.createElement("pre");
examplePre.classList.add("autocomplete-info-example");
const exampleCode = document.createElement("code");
examplePre.appendChild(exampleCode);
if (example.description) {
const exampleDescription = document.createElement("span");
exampleDescription.classList.add("autocomplete-info-example-comment");
exampleDescription.textContent = `// ${example.description}\n`;
exampleCode.appendChild(exampleDescription);
}
const exampleExpression = document.createElement("span");
exampleExpression.classList.add("autocomplete-info-example-expr");
exampleExpression.textContent = example.example + "\n";
exampleCode.appendChild(exampleExpression);
if (example.evaluated) {
const exampleEvaluated = document.createElement("span");
exampleEvaluated.classList.add("autocomplete-info-example-comment");
exampleEvaluated.textContent = `// => ${example.evaluated}\n`;
exampleCode.appendChild(exampleEvaluated);
}
return examplePre;
};
renderExamples = examples => {
const examplesContainer = document.createElement("div");
examplesContainer.classList.add("autocomplete-info-examples");
const examplesTitle = document.createElement("div");
examplesTitle.classList.add("autocomplete-info-section-title");
examplesTitle.textContent = i18n.baseText("codeNodeEditor.examples");
examplesContainer.appendChild(examplesTitle);
const examplesList = document.createElement("div");
examplesList.classList.add("autocomplete-info-examples-list");
for (const example of examples) {
const renderedExample = renderExample(example);
examplesList.appendChild(renderedExample);
}
examplesContainer.appendChild(examplesList);
return examplesContainer;
};
_export("j", createInfoBoxRenderer = (doc$2, isFunction = false) => (_completion, highlightArgIndex = -1) => {
const tooltipContainer = document.createElement("div");
tooltipContainer.setAttribute("tabindex", "-1");
tooltipContainer.setAttribute("title", "");
tooltipContainer.classList.add("autocomplete-info-container");
if (!doc$2) return null;
const {
examples,
args
} = doc$2;
const hasArgs = args && args.length > 0;
const hasExamples = examples && examples.length > 0;
const header$1 = isFunction ? renderFunctionHeader(doc$2, highlightArgIndex) : renderPropHeader(doc$2);
header$1.classList.add("autocomplete-info-header");
tooltipContainer.appendChild(header$1);
if (doc$2.description) {
const descriptionBody = renderDescription({
description: doc$2.description,
docUrl: doc$2.docURL,
example: hasArgs && hasExamples ? examples[0] : void 0
});
tooltipContainer.appendChild(descriptionBody);
}
if (hasArgs) {
const argsContainer = renderArgs(args, highlightArgIndex);
tooltipContainer.appendChild(argsContainer);
}
if (hasExamples && (examples.length > 1 || !hasArgs)) {
const examplesContainer = renderExamples(examples);
tooltipContainer.appendChild(examplesContainer);
}
return tooltipContainer;
}); //#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/constants.ts
_export("k", FIELDS_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.fields"),
rank: -1
}));
RECOMMENDED_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.recommended"),
rank: 0
});
RECOMMENDED_METHODS_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.recommendedMethods"),
rank: 0
});
PREVIOUS_NODES_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.prevNodes"),
rank: 1
});
PROPERTIES_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.properties"),
rank: 2
});
METHODS_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.methods"),
rank: 3
});
METADATA_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.metadata"),
rank: 4
});
OTHER_METHODS_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.otherMethods"),
rank: 100
});
OTHER_SECTION = withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.other"),
rank: 101
});
ROOT_DOLLAR_COMPLETIONS = [{
label: "$json",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$json",
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.json"),
docURL: "https://docs.n8n.io/data/data-structure/"
})
}, {
label: "$binary",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$binary",
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.binary")
})
}, {
label: "$now",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$now",
returnType: "DateTime",
description: i18n.baseText("codeNodeEditor.completer.$now")
})
}, {
label: "$if()",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$if",
returnType: "any",
description: i18n.baseText("codeNodeEditor.completer.$if"),
args: [{
name: "condition",
description: i18n.baseText("codeNodeEditor.completer.$if.args.condition"),
type: "boolean"
}, {
name: "valueIfTrue",
description: i18n.baseText("codeNodeEditor.completer.$if.args.valueIfTrue"),
type: "any"
}, {
name: "valueIfFalse",
description: i18n.baseText("codeNodeEditor.completer.$if.args.valueIfFalse"),
type: "any"
}],
examples: [{
example: "$if($now.hour < 17, \"Good day\", \"Good evening\")",
description: i18n.baseText("codeNodeEditor.completer.$if.examples.1")
}, {
description: i18n.baseText("codeNodeEditor.completer.$if.examples.2"),
example: "$if($now.hour < 10, \"Good morning\", $if($now.hour < 17, \"Good day\", \"Good evening\"))"
}]
}, true)
}, {
label: "$ifEmpty()",
section: RECOMMENDED_SECTION,
info: createInfoBoxRenderer({
name: "$ifEmpty",
returnType: "any",
description: i18n.baseText("codeNodeEditor.completer.$ifEmpty"),
args: [{
name: "value",
description: i18n.baseText("codeNodeEditor.completer.$ifEmpty.args.value"),
type: "any"
}, {
name: "valueIfEmpty",
description: i18n.baseText("codeNodeEditor.completer.$ifEmpty.args.valueIfEmpty"),
type: "any"
}],
examples: [{
example: "\"Hi \" + $ifEmpty(name, \"there\")",
evaluated: "e.g. \"Hi Nathan\" or \"Hi there\""
}]
}, true)
}, {
label: "$execution",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$execution",
returnType: "ExecData",
description: i18n.baseText("codeNodeEditor.completer.$execution")
})
}, {
label: "$itemIndex",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$itemIndex",
returnType: "number",
description: i18n.baseText("codeNodeEditor.completer.$itemIndex")
})
}, {
label: "$input",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$input",
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.$input")
})
}, {
label: "$parameter",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$parameter",
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.$parameter")
})
}, {
label: "$prevNode",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$prevNode",
returnType: "PrevNodeData",
description: i18n.baseText("codeNodeEditor.completer.$prevNode")
})
}, {
label: "$runIndex",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$runIndex",
returnType: "number",
description: i18n.baseText("codeNodeEditor.completer.$runIndex")
})
}, {
label: "$today",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$today",
returnType: "DateTime",
description: i18n.baseText("codeNodeEditor.completer.$today")
})
}, {
label: "$vars",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$vars",
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.$vars")
})
}, {
label: "$workflow",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$workflow",
returnType: "WorkflowData",
description: i18n.baseText("codeNodeEditor.completer.$workflow")
})
}, {
label: "$jmespath()",
section: METHODS_SECTION,
info: createInfoBoxRenderer({
name: "$jmespath",
description: i18n.baseText("codeNodeEditor.completer.$jmespath"),
returnType: "any",
args: [{
name: "obj",
description: i18n.baseText("codeNodeEditor.completer.$jmespath.args.obj"),
type: "Object | Array"
}, {
name: "expression",
description: i18n.baseText("codeNodeEditor.completer.$jmespath.args.expression"),
type: "string"
}],
examples: [{
example: "data = {\n \"people\": [\n {\n \"name\": \"Bob\",\n \"age\": 20,\n \"other\": \"foo\"\n },\n {\n \"name\": \"Fred\",\n \"age\": 25,\n \"other\": \"bar\"\n },\n {\n \"name\": \"George\",\n \"age\": 30,\n \"other\": \"baz\"\n }\n ]\n}\n\n$jmespath(data.people, '[*].name')",
evaluated: "['Bob', 'Fred', 'George']",
description: i18n.baseText("codeNodeEditor.completer.$jmespath.examples.1")
}, {
example: "$jmespath(data.people, '[?age > `20`].[name, age]')",
evaluated: "[['Fred', 25], ['George', 30]]",
description: i18n.baseText("codeNodeEditor.completer.$jmespath.examples.2")
}, {
example: "$jmespath(data.people, '[?age > `20`].name | [0]')",
evaluated: "Fred",
description: i18n.baseText("codeNodeEditor.completer.$jmespath.examples.3")
}, {
example: "data = {\n \"reservations\": [\n {\n \"id\": 1,\n \"guests\": [\n {\n \"name\": \"Nathan\",\n \"requirements\": {\n \"room\": \"double\",\n \"meal\": \"vegetarian\"\n }\n },\n {\n \"name\": \"Meg\",\n \"requirements\": {\n \"room\": \"single\"\n }\n }\n ]\n },\n {\n \"id\": 2,\n \"guests\": [\n {\n \"name\": \"Lex\",\n \"requirements\": {\n \"room\": \"double\"\n }\n }\n ]\n }\n ]\n}\n\n$jmespath(data, \"reservations[].guests[?requirements.room=='double'][].name\")",
evaluated: "['Nathan', 'Lex']",
description: i18n.baseText("codeNodeEditor.completer.$jmespath.examples.4")
}]
}, true)
}, {
label: "$fromAI()",
section: METHODS_SECTION,
info: createInfoBoxRenderer({
name: "$fromAI",
returnType: "any",
description: "Populate this with the parameter passed from the large language model",
docURL: "https://docs.n8n.io/advanced-ai/examples/using-the-fromai-function/",
args: [{
name: "key",
description: "The key or name of the argument, must be between 1 and 64 characters long and only contain lowercase letters, uppercase letters, numbers, underscores, and hyphens",
type: "string"
}, {
name: "description",
description: "Description of the argument",
type: "string",
optional: true
}, {
name: "type",
description: "Type of the argument",
type: "string | number | boolean | json",
optional: true
}, {
name: "defaultValue",
description: "Default value for the argument",
type: "any",
optional: true
}],
examples: [{
example: "$fromAI(\"name\")",
description: "Get the name of the person"
}, {
example: "$fromAI(\"age\", \"The age of the person\", \"number\", 18)",
description: "Get the age of the person as number with default value 18"
}, {
example: "$fromAI(\"isStudent\", \"Is the person a student\", \"boolean\", false)",
description: "Get the student status of the person as boolean with default value false"
}]
}, true)
}, {
label: "$max()",
section: METHODS_SECTION,
info: createInfoBoxRenderer({
name: "$max",
returnType: "number",
description: i18n.baseText("codeNodeEditor.completer.$max"),
args: [{
name: "numbers",
description: i18n.baseText("codeNodeEditor.completer.$max.args.numbers"),
type: "number",
variadic: true
}],
examples: [{
example: "$max(1, 5, 42, 0.5)",
evaluated: "42"
}]
}, true)
}, {
label: "$min()",
section: METHODS_SECTION,
info: createInfoBoxRenderer({
name: "$min",
returnType: "number",
description: i18n.baseText("codeNodeEditor.completer.$min"),
args: [{
name: "numbers",
description: i18n.baseText("codeNodeEditor.completer.$max.args.numbers"),
variadic: true,
type: "number"
}],
examples: [{
example: "$min(1, 5, 42, 0.5)",
evaluated: "0.5"
}]
}, true)
}, {
label: "$nodeVersion",
section: METADATA_SECTION,
info: createInfoBoxRenderer({
name: "$nodeVersion",
returnType: "number",
description: i18n.baseText("codeNodeEditor.completer.$nodeVersion")
})
}];
STRING_RECOMMENDED_OPTIONS = ["includes()", "split()", "startsWith()", "replaceAll()", "length"];
LUXON_RECOMMENDED_OPTIONS = ["format()", "minus()", "plus()", "diffTo()", "extract()"];
OBJECT_RECOMMENDED_OPTIONS = ["keys()", "values()", "isEmpty()", "hasField()"];
ARRAY_RECOMMENDED_OPTIONS = ["length", "last()", "includes()", "map()", "filter()"];
ARRAY_NUMBER_ONLY_METHODS = ["max()", "min()", "sum()", "average()"];
LUXON_SECTIONS = {
edit: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.edit"),
rank: 1
}),
compare: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.compare"),
rank: 2
}),
format: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.format"),
rank: 3
}),
query: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.component"),
rank: 4
})
};
STRING_SECTIONS = {
edit: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.edit"),
rank: 1
}),
query: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.query"),
rank: 2
}),
validation: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.validation"),
rank: 3
}),
case: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.case"),
rank: 4
}),
cast: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.cast"),
rank: 5
})
};
VARIABLE_SECTIONS = {
project: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.variable.project"),
rank: 1
}),
global: withSectionHeader({
name: i18n.baseText("codeNodeEditor.completer.section.variable.global"),
rank: 2
})
};
_export("A", TARGET_NODE_PARAMETER_FACET = Facet$1.define({
combine: values => values[0]
}));
_export("O", luxonInstanceDocs = {
typeName: "DateTime",
properties: {
day: {
doc: {
name: "day",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.day"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeday",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.day",
evaluated: "30"
}]
}
},
daysInMonth: {
doc: {
name: "daysInMonth",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimedaysinmonth",
returnType: "number"
}
},
daysInYear: {
doc: {
name: "daysInYear",
hidden: true,
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimedaysinyear",
returnType: "number"
}
},
hour: {
doc: {
name: "hour",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.hour"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimehour",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.hour",
evaluated: "18"
}]
}
},
locale: {
doc: {
name: "locale",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.locale"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimelocale",
returnType: "string",
examples: [{
example: "$now.locale",
evaluated: "'en-US'"
}]
}
},
millisecond: {
doc: {
name: "millisecond",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.millisecond"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimemillisecond",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.millisecond",
evaluated: "234"
}]
}
},
minute: {
doc: {
name: "minute",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.minute"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeminute",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.minute",
evaluated: "49"
}]
}
},
month: {
doc: {
name: "month",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.month"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimemonth",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.month",
evaluated: "3"
}]
}
},
monthLong: {
doc: {
name: "monthLong",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.monthLong"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimemonthlong",
returnType: "string",
examples: [{
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.monthLong",
evaluated: "'March'"
}, {
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.setLocale('de-DE').monthLong",
evaluated: "'März'"
}]
}
},
monthShort: {
doc: {
name: "monthShort",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.monthShort"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimemonthshort",
returnType: "string",
examples: [{
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.monthShort",
evaluated: "'Mar'"
}, {
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.setLocale('de-DE').monthShort",
evaluated: "'Mär'"
}]
}
},
numberingSystem: {
doc: {
name: "numberingSystem",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimenumberingsystem",
returnType: "string"
}
},
offset: {
doc: {
name: "offset",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeoffset",
returnType: "number"
}
},
offsetNameLong: {
doc: {
name: "offsetNameLong",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeoffsetnamelong",
returnType: "string"
}
},
offsetNameShort: {
doc: {
name: "offsetNameShort",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeoffsetnameshort",
returnType: "string"
}
},
ordinal: {
doc: {
name: "ordinal",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeordinal",
returnType: "string"
}
},
outputCalendar: {
doc: {
name: "outputCalendar",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeoutputcalendar",
returnType: "string"
}
},
quarter: {
doc: {
name: "quarter",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.quarter"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimequarter",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.quarter",
evaluated: "1"
}, {
example: "'2024-12-01T18:49'.toDateTime().quarter",
evaluated: "4"
}]
}
},
second: {
doc: {
name: "second",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.second"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimesecond",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49:07.234'.toDateTime()\ndt.second",
evaluated: "7"
}]
}
},
weekday: {
doc: {
name: "weekday",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.weekday"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeweekday",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.weekday",
evaluated: "6"
}]
}
},
weekdayLong: {
doc: {
name: "weekdayLong",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.weekdayLong"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeweekdaylong",
returnType: "string",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.weekdayLong",
evaluated: "'Saturday'"
}, {
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.setLocale('de-DE').weekdayLong",
evaluated: "'Samstag'"
}]
}
},
weekdayShort: {
doc: {
name: "weekdayShort",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.weekdayShort"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeweekdayshort",
returnType: "string",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.weekdayShort",
evaluated: "'Sat'"
}, {
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.setLocale('fr-FR').weekdayShort",
evaluated: "'sam.'"
}]
}
},
weekNumber: {
doc: {
name: "weekNumber",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.weekNumber"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeweeknumber",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.weekNumber",
evaluated: "13"
}]
}
},
weeksInWeekYear: {
doc: {
name: "weeksInWeekYear",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeweeksinweekyear",
returnType: "number"
}
},
weekYear: {
doc: {
name: "weekYear",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeweekyear",
returnType: "number"
}
},
year: {
doc: {
name: "year",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.year"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeyear",
returnType: "number",
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.year",
evaluated: "2024"
}]
}
},
zone: {
doc: {
name: "zone",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.zone"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimezone",
returnType: "Zone",
examples: [{
example: "$now.zone",
evaluated: "{ zoneName: \"Europe/Berlin\", valid: true }"
}]
}
},
zoneName: {
doc: {
name: "zoneName",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimezonename",
returnType: "string"
}
},
isInDST: {
doc: {
name: "isInDST",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.isInDST"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeisindst",
returnType: "boolean"
}
},
isInLeapYear: {
doc: {
name: "isInLeapYear",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.isInLeapYear"),
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeisinleapyear",
returnType: "boolean",
examples: [{
example: "'2024'.toDateTime().isInLeapYear",
evaluated: "true"
}, {
example: "'2025'.toDateTime().isInLeapYear",
evaluated: "false"
}]
}
},
isOffsetFixed: {
doc: {
name: "isOffsetFixed",
section: "query",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeisoffsetfixed",
returnType: "boolean"
}
},
isValid: {
doc: {
name: "isValid",
hidden: true,
section: "query",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeisvalid",
returnType: "boolean"
}
}
},
functions: {
diff: {
doc: {
name: "diff",
hidden: true,
section: "compare",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimediff",
returnType: "Duration",
args: [{
name: "other",
type: "DateTime"
}, {
name: "unit",
type: "string | string[]"
}, {
name: "options",
type: "Object"
}]
}
},
diffNow: {
doc: {
name: "diffNow",
hidden: true,
section: "compare",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimediffnow",
returnType: "Duration",
args: [{
name: "unit",
type: "string | string[]"
}, {
name: "options",
type: "Object"
}]
}
},
endOf: {
doc: {
name: "endOf",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.endOf"),
section: "edit",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeendof",
returnType: "DateTime",
args: [{
name: "unit",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.endOf.args.unit"),
type: "string"
}, {
name: "options",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.endOf.args.opts"),
default: "{}",
type: "Object"
}],
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.endOf('month')",
evaluated: "[DateTime: 2024-03-31T23:59:59.999Z]"
}]
}
},
equals: {
doc: {
name: "equals",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.equals"),
section: "compare",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeequals",
returnType: "boolean",
args: [{
name: "other",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.equals.args.other"),
type: "DateTime"
}],
examples: [{
example: "dt = '2024-03-20T18:49+02:00'.toDateTime()\ndt.equals('2024-03-20T19:49+02:00'.toDateTime())",
evaluated: "false"
}]
}
},
hasSame: {
doc: {
name: "hasSame",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.hasSame"),
section: "compare",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimehassame",
returnType: "boolean",
args: [{
name: "other",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.hasSame.args.other"),
type: "DateTime"
}, {
name: "unit",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.hasSame.args.unit"),
type: "string"
}],
examples: [{
example: "'2024-03-20'.toDateTime().hasSame('2024-03-18'.toDateTime(), 'month')",
evaluated: "true"
}, {
example: "'1982-03-20'.toDateTime().hasSame('2024-03-18'.toDateTime(), 'month')",
evaluated: "false"
}]
}
},
reconfigure: {
doc: {
name: "reconfigure",
section: "other",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimereconfigure",
returnType: "DateTime",
args: [{
name: "properties",
type: "Object"
}]
}
},
resolvedLocaleOptions: {
doc: {
name: "resolvedLocaleOptions",
section: "other",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeresolvedlocaleoptions",
returnType: "Object",
args: [{
name: "options",
type: "Object"
}]
}
},
set: {
doc: {
name: "set",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.set"),
section: "edit",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeset",
returnType: "DateTime",
args: [{
name: "values",
optional: false,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.set.args.values"),
type: "Object"
}],
examples: [{
example: "dt = '2024-03-30T18:49'.toDateTime()\ndt.set({ year:1982, month:10 })",
evaluated: "[DateTime: 1982-10-20T18:49:00.000Z]"
}]
}
},
setLocale: {
doc: {
name: "setLocale",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.setLocale"),
section: "edit",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimesetlocale",
returnType: "DateTime",
args: [{
name: "locale",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.setLocale.args.locale"),
type: "string"
}],
examples: [{
example: "$now.setLocale('de-DE').toLocaleString({ dateStyle: 'long' })",
evaluated: "'5. Oktober 2024'"
}, {
example: "$now.setLocale('fr-FR').toLocaleString({ dateStyle: 'long' })",
evaluated: "'5 octobre 2024'"
}]
}
},
setZone: {
doc: {
name: "setZone",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.setZone"),
section: "edit",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimesetzone",
returnType: "DateTime",
args: [{
name: "zone",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.setZone.args.zone"),
default: "\"local\"",
type: "string"
}, {
name: "options",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.setZone.args.opts"),
type: "Object"
}],
examples: [{
example: "dt = '2024-01-01T00:00:00.000+02:00'.toDateTime()\ndt.setZone('America/Buenos_Aires')",
evaluated: "[DateTime: 2023-12-31T19:00:00.000-03:00]"
}, {
example: "dt = '2024-01-01T00:00:00.000+02:00'.toDateTime()\ndt.setZone('UTC+7')",
evaluated: "[DateTime: 2024-01-01T05:00:00.000+07:00]"
}]
}
},
startOf: {
doc: {
name: "startOf",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.startOf"),
section: "edit",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimestartof",
returnType: "DateTime",
args: [{
name: "unit",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.startOf.args.unit"),
type: "string"
}, {
name: "options",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.startOf.args.opts"),
type: "Object"
}],
examples: [{
example: "'2024-03-20T18:49'.toDateTime().startOf('month')",
evaluated: "[DateTime: 2024-03-01T00:00:00.000Z]"
}]
}
},
toBSON: {
doc: {
name: "toBSON",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetobson",
returnType: "Date"
}
},
toFormat: {
doc: {
name: "toFormat",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetime",
returnType: "string",
args: [{
name: "fmt",
type: "string"
}, {
name: "options",
type: "Object"
}]
}
},
toHTTP: {
doc: {
name: "toHTTP",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetohttp",
returnType: "string"
}
},
toISO: {
doc: {
name: "toISO",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toISO"),
section: "format",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetoiso",
returnType: "string",
args: [{
name: "options",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toISO.args.opts"),
type: "Object"
}],
examples: [{
example: "$now.toISO()",
evaluated: "'2024-04-05T18:44:55.525+02:00'"
}]
}
},
toISODate: {
doc: {
name: "toISODate",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetoisodate",
returnType: "string",
args: [{
name: "options",
type: "Object"
}]
}
},
toISOTime: {
doc: {
name: "toISOTime",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetoisotime",
returnType: "string",
args: [{
name: "options",
type: "Object"
}]
}
},
toISOWeekDate: {
doc: {
name: "toISOWeekDate",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetoisoweekdate",
returnType: "string"
}
},
toJSDate: {
doc: {
name: "toJSDate",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetojsdate",
returnType: "Date"
}
},
toJSON: {
doc: {
name: "toJSON",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetojson",
returnType: "string"
}
},
toLocal: {
doc: {
name: "toLocal",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocal"),
section: "edit",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetolocal",
returnType: "DateTime",
examples: [{
example: "dt = '2024-01-01T00:00:00.000Z'.toDateTime()\ndt.toLocal()",
evaluated: "[DateTime: 2024-01-01T01:00:00.000+01:00]",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocal.example")
}]
}
},
toLocaleParts: {
doc: {
name: "toLocaleParts",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetolocaleparts",
returnType: "string",
args: [{
name: "formatOpts",
type: "any"
}, {
name: "options",
type: "Object"
}]
}
},
toLocaleString: {
doc: {
name: "toLocaleString",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocaleString"),
section: "format",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetolocalestring",
returnType: "string",
args: [{
name: "formatOpts",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocaleString.args.opts"),
type: "Object"
}],
examples: [{
example: "$now.toLocaleString()",
evaluated: "'4/30/2024'"
}, {
example: "$now.toLocaleString({ dateStyle: 'medium', timeStyle: 'short' })",
evaluated: "'Apr 30, 2024, 10:00 PM'",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocaleString.example")
}, {
example: "$now.setLocale('de-DE').toLocaleString()",
evaluated: "'30.4.2024'"
}, {
example: "$now.toLocaleString({ dateStyle: 'short' })",
evaluated: "'4/30/2024'"
}, {
example: "$now.toLocaleString({ dateStyle: 'medium' })",
evaluated: "'Apr 30, 2024'"
}, {
example: "$now.toLocaleString({ dateStyle: 'long' })",
evaluated: "'April 30, 2024'"
}, {
example: "$now.toLocaleString({ dateStyle: 'full' })",
evaluated: "'Tuesday, April 30, 2024'",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocaleString.example")
}, {
example: "$now.toLocaleString({ year: 'numeric', month: 'numeric', day: 'numeric' })",
evaluated: "'4/30/2024'"
}, {
example: "$now.toLocaleString({ year: '2-digit', month: '2-digit', day: '2-digit' })",
evaluated: "'04/30/24'"
}, {
example: "$now.toLocaleString({ month: 'short', weekday: 'short', day: 'numeric' })",
evaluated: "'Tue, Apr 30'"
}, {
example: "$now.toLocaleString({ month: 'long', weekday: 'long', day: 'numeric' })",
evaluated: "'Tuesday, April 30'",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocaleString.example")
}, {
example: "$now.toLocaleString({ timeStyle: 'short' })",
evaluated: "'10:00 PM'"
}, {
example: "$now.toLocaleString({ timeStyle: 'medium' })",
evaluated: "'10:00:58 PM'"
}, {
example: "$now.toLocaleString({ timeStyle: 'long' })",
evaluated: "'10:00:58 PM GMT+2'"
}, {
example: "$now.toLocaleString({ timeStyle: 'full' })",
evaluated: "'10:00:58 PM Central European Summer Time'",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocaleString.example")
}, {
example: "$now.toLocaleString({ hour: 'numeric', minute: 'numeric', hourCycle: 'h24' })",
evaluated: "'22:00'"
}, {
example: "$now.toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h12' })",
evaluated: "'10:00 PM'",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toLocaleString.example")
}]
}
},
toMillis: {
doc: {
name: "toMillis",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toMillis"),
section: "format",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetomillis",
returnType: "number",
examples: [{
example: "$now.toMillis()",
evaluated: "1712334324677"
}]
}
},
toObject: {
doc: {
name: "toObject",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetoobject",
returnType: "Object",
args: [{
name: "options",
type: "any"
}]
}
},
toRelative: {
doc: {
name: "toRelative",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toRelative"),
section: "format",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetorelative",
returnType: "string",
args: [{
name: "options",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toRelative.args.opts"),
type: "Object"
}]
}
},
toRelativeCalendar: {
doc: {
name: "toRelativeCalendar",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetorelativecalendar",
returnType: "string",
args: [{
name: "options",
type: "Object"
}]
}
},
toRFC2822: {
doc: {
name: "toRFC2822",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetorfc2822",
returnType: "string"
}
},
toSeconds: {
doc: {
name: "toSeconds",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toSeconds"),
section: "format",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetoseconds",
returnType: "number",
examples: [{
example: "$now.toSeconds()",
evaluated: "1712334442.372"
}]
}
},
toSQL: {
doc: {
name: "toSQL",
section: "format",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetosql",
returnType: "string",
hidden: true,
args: [{
name: "options",
type: "Object"
}]
}
},
toSQLDate: {
doc: {
name: "toSQLDate",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetosqldate",
returnType: "string"
}
},
toSQLTime: {
doc: {
name: "toSQLTime",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetosqltime",
returnType: "string"
}
},
toString: {
doc: {
name: "toString",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toString"),
section: "format",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetostring",
returnType: "string",
examples: [{
example: "$now.toString()",
evaluated: "'2024-04-05T18:44:55.525+02:00'"
}]
}
},
toUnixInteger: {
doc: {
name: "toUnixInteger",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetounixinteger",
returnType: "number"
}
},
toUTC: {
doc: {
name: "toUTC",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toUTC"),
section: "edit",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimetoutc",
returnType: "DateTime",
args: [{
name: "offset",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toUTC.args.offset"),
default: "0",
type: "number"
}, {
name: "options",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.toUTC.args.opts"),
type: "Object"
}],
examples: [{
example: "dt = '2024-01-01T00:00:00.000+02:00'.toDateTime()\ndt.toUTC()",
evaluated: "[DateTime: 2023-12-31T22:00:00.000Z]"
}]
}
},
until: {
doc: {
name: "until",
section: "compare",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeuntil",
returnType: "Interval",
args: [{
name: "other",
type: "DateTime"
}]
}
},
valueOf: {
doc: {
name: "valueOf",
section: "format",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimevalueof",
returnType: "number"
}
}
}
}); //#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/nativesAutocompleteDocs/luxon.static.docs.ts
_export("D", luxonStaticDocs = {
typeName: "DateTime",
properties: {},
functions: {
now: {
doc: {
name: "now",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.now"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimenow",
returnType: "DateTime"
}
},
local: {
doc: {
name: "local",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.local"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimelocal",
returnType: "DateTime",
args: [{
name: "year",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.year")
}, {
name: "month",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.month")
}, {
name: "day",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.day")
}, {
name: "hour",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.hour")
}, {
name: "minute",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.minute")
}, {
name: "second",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.second")
}, {
name: "millisecond",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.millisecond")
}],
examples: [{
example: "DateTime.local(1982, 12, 3)",
evaluated: "[DateTime: 1982-12-03T00:00:00.000-05:00]"
}]
}
},
utc: {
doc: {
name: "utc",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.utc"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeutc",
returnType: "DateTime",
args: [{
name: "year",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.year")
}, {
name: "month",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.month")
}, {
name: "day",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.day")
}, {
name: "hour",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.hour")
}, {
name: "minute",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.minute")
}, {
name: "second",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.second")
}, {
name: "millisecond",
optional: true,
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.instanceMethods.millisecond")
}],
examples: [{
example: "DateTime.utc(1982, 12, 3)",
evaluated: "[DateTime: 1982-12-03T00:00:00.000Z]"
}]
}
},
fromJSDate: {
doc: {
name: "fromJSDate",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromjsdate",
returnType: "DateTime",
args: [{
name: "date",
type: "Date"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
fromMillis: {
doc: {
name: "fromMillis",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromMillis"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefrommillis",
returnType: "DateTime",
args: [{
name: "milliseconds",
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromMillis.args.milliseconds")
}, {
name: "options",
optional: true,
type: "Object",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromMillis.args.opts")
}],
examples: [{
example: "DateTime.fromMillis(1711838940000)",
evaluated: "[DateTime: 2024-03-30T18:49:00.000Z]"
}]
}
},
fromSeconds: {
doc: {
name: "fromSeconds",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromSeconds"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromseconds",
returnType: "DateTime",
args: [{
name: "seconds",
type: "number",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromSeconds.args.seconds")
}, {
name: "options",
optional: true,
type: "Object",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromSeconds.args.opts")
}],
examples: [{
example: "DateTime.fromSeconds(1711838940)",
evaluated: "[DateTime: 2024-03-30T18:49:00.000Z]"
}]
}
},
fromObject: {
doc: {
name: "fromObject",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromobject",
returnType: "DateTime",
hidden: true,
args: [{
name: "obj",
type: "Object"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
fromISO: {
doc: {
name: "fromISO",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromISO"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromiso",
returnType: "DateTime",
args: [{
name: "isoString",
type: "string",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromISO.args.isoString")
}, {
name: "options",
optional: true,
type: "Object",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.fromISO.args.opts")
}],
examples: [{
example: "DateTime.fromISO('2024-05-10T14:15:59.493Z')",
evaluated: "[DateTime: 2024-05-10T14:15:59.493Z]"
}]
}
},
fromRFC2822: {
doc: {
name: "fromRFC2822",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromrfc2822",
returnType: "DateTime",
args: [{
name: "text",
type: "string"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
fromHTTP: {
doc: {
name: "fromHTTP",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromhttp",
returnType: "DateTime",
args: [{
name: "text",
type: "string"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
fromFormat: {
doc: {
name: "fromFormat",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromformat",
returnType: "DateTime",
args: [{
name: "text",
type: "string"
}, {
name: "fmt",
type: "string"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
fromSQL: {
doc: {
name: "fromSQL",
hidden: true,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromsql",
returnType: "DateTime",
args: [{
name: "text",
type: "string"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
invalid: {
doc: {
name: "invalid",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeinvalid",
returnType: "DateTime",
hidden: true,
args: [{
name: "reason",
type: "DateTime"
}, {
name: "explanation",
optional: true,
type: "string"
}]
}
},
isDateTime: {
doc: {
name: "isDateTime",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.isDateTime"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeisdatetime",
returnType: "boolean",
args: [{
name: "maybeDateTime",
type: "any",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.isDateTime.args.maybeDateTime")
}]
}
},
expandFormat: {
doc: {
name: "expandFormat",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeexpandformat",
returnType: "string",
hidden: true,
args: [{
name: "fmt",
type: "any"
}, {
name: "localeOpts",
optional: true,
type: "any"
}]
}
},
fromFormatExplain: {
doc: {
name: "fromFormatExplain",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromformatexplain",
returnType: "Object",
hidden: true,
args: [{
name: "text",
type: "string"
}, {
name: "fmt",
type: "string"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
fromString: {
doc: {
name: "fromString",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromstring",
returnType: "DateTime",
hidden: true,
args: [{
name: "text",
type: "string"
}, {
name: "fmt",
type: "string"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
fromStringExplain: {
doc: {
name: "fromStringExplain",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimefromstringexplain",
returnType: "Object",
hidden: true,
args: [{
name: "text",
type: "string"
}, {
name: "fmt",
type: "string"
}, {
name: "options",
optional: true,
type: "Object"
}]
}
},
max: {
doc: {
name: "max",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.max"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimemax",
returnType: "DateTime",
args: [{
name: "dateTimes",
variadic: true,
type: "DateTime",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.max.args.dateTimes")
}],
examples: [{
example: "DateTime.max('2024-03-30T18:49'.toDateTime(), '2025-03-30T18:49'.toDateTime())",
evaluated: "[DateTime: 2025-03-30T18:49:00.000Z]"
}]
}
},
min: {
doc: {
name: "min",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.min"),
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimemin",
returnType: "DateTime",
args: [{
name: "dateTimes",
variadic: true,
type: "DateTime",
description: i18n.baseText("codeNodeEditor.completer.luxon.dateTimeStaticMethods.min.args.dateTimes")
}],
examples: [{
example: "DateTime.min('2024-03-30T18:49'.toDateTime(), '2025-03-30T18:49'.toDateTime())",
evaluated: "[DateTime: 2024-03-30T18:49:00.000Z]"
}]
}
},
parseFormatForOpts: {
doc: {
name: "parseFormatForOpts",
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetimeparseformatforopts",
returnType: "string",
hidden: true,
args: [{
name: "fmt",
type: "any"
}, {
name: "localeOpts",
optional: true,
type: "any"
}]
}
}
}
}); //#endregion
//#region src/features/shared/editors/plugins/codemirror/completions/datatype.completions.ts
import_uniqBy = /* @__PURE__ */__toESM(require_uniqBy());
natives = ({
typeName: typeName$1,
transformLabel = label => label
}) => {
const nativeDocs = NATIVE_METHODS.find(ee => ee.typeName.toLowerCase() === typeName$1);
if (!nativeDocs) return [];
const nativeProps = nativeDocs.properties ? toOptions({
fnToDoc: nativeDocs.properties,
includeHidden: false,
isFunction: false,
transformLabel
}) : [];
const nativeMethods = toOptions({
fnToDoc: nativeDocs.functions,
includeHidden: false,
isFunction: true,
transformLabel
});
return [...nativeProps, ...nativeMethods];
};
extensions = ({
typeName: typeName$1,
includeHidden = false,
transformLabel = label => label
}) => {
const expressionExtensions = EXTENSION_OBJECTS.find(ee => ee.typeName.toLowerCase() === typeName$1);
if (!expressionExtensions) return [];
return toOptions({
fnToDoc: Object.entries(expressionExtensions.functions).reduce((acc, [fnName, fn]) => {
delete fn.doc?.docURL;
return {
...acc,
[fnName]: {
doc: fn.doc
}
};
}, {}),
isFunction: true,
includeHidden,
transformLabel
});
};
isInputData = base$1 => {
return /^\$input\..*\.json]/.test(base$1) || /^\$json/.test(base$1) || /^\$\(.*\)\..*\.json/.test(base$1);
};
isItem = input => {
const {
base: base$1,
resolved
} = input;
return /^(\$\(.*\)|\$input)/.test(base$1) && "pairedItem" in resolved;
};
isBinary = input => {
const {
base: base$1,
resolved
} = input;
return /^(\$\(.*\)\..*\.binary\..*|\$binary)/.test(base$1) && "mimeType" in resolved && "fileExtension" in resolved;
};
getDetail = (base$1, value) => {
const type = getDisplayType(value);
if (!isInputData(base$1) || type === "function") return void 0;
return type;
};
toOptions = ({
fnToDoc,
isFunction = false,
includeHidden = false,
transformLabel = label => label
}) => {
return Object.entries(fnToDoc).sort((a, b) => a[0].localeCompare(b[0])).filter(([, docInfo]) => Boolean(docInfo.doc && !docInfo.doc?.hidden) || includeHidden).map(([fnName, docInfo]) => {
return createCompletionOption({
name: fnName,
doc: docInfo.doc,
isFunction,
transformLabel
});
});
};
createCompletionOption = ({
name: name$1,
doc: doc$2,
isFunction = false,
transformLabel = label => label,
type
}) => {
const option = {
label: isFunction ? name$1 + "()" : name$1,
section: doc$2?.section,
apply: applyCompletion({
hasArgs: hasRequiredArgs(doc$2),
defaultArgs: getDefaultArgs(doc$2),
transformLabel
}),
type
};
option.info = createInfoBoxRenderer(doc$2, isFunction);
return option;
};
customObjectOptions = input => {
const {
base: base$1,
resolved
} = input;
if (!resolved) return [];
if (base$1 === "$execution") return executionOptions();else if (base$1 === "$execution.customData") return customDataOptions();else if (base$1 === "$workflow") return workflowOptions();else if (base$1 === "$input") return inputOptions(base$1);else if (base$1 === "$prevNode") return prevNodeOptions();else if (/^\$\(['"][\S\s]+['"]\)$/.test(base$1)) return nodeRefOptions(base$1);else if (base$1 === "$response") return responseOptions();else if (isItem(input)) return itemOptions();else if (isBinary(input)) return binaryOptions();
return [];
};
objectOptions = input => {
const {
base: base$1,
resolved,
transformLabel = label => label
} = input;
const SKIP = new Set(["__ob__", "pairedItem"]);
if (isSplitInBatchesAbsent()) SKIP.add("context");
let rawKeys = Object.keys(resolved);
if (base$1 === "Math") {
const descriptors = Object.getOwnPropertyDescriptors(Math);
rawKeys = Object.keys(descriptors).sort((a, b) => a.localeCompare(b));
}
const customOptions = customObjectOptions(input);
if (customOptions.length > 0) return customOptions.filter(option => option.label in resolved);
const localKeys = rawKeys.filter(key => !SKIP.has(key) && !isPseudoParam(key)).map(key => {
ensureKeyCanBeResolved(resolved, key);
const needsBracketAccess = !isAllowedInDotNotation(key);
const resolvedProp = resolved[key];
const isFunction = typeof resolvedProp === "function";
const hasArgs = isFunction && resolvedProp.length > 0;
return {
label: isFunction ? key + "()" : key,
section: isFunction ? METHODS_SECTION : FIELDS_SECTION,
apply: needsBracketAccess ? applyBracketAccessCompletion : applyCompletion({
hasArgs,
transformLabel
}),
detail: getDetail(base$1, resolvedProp)
};
});
if (resolved.isProxy || resolved.json || /json('])$/.test(base$1) || base$1 === "$execution" || base$1.endsWith("params") || base$1.endsWith("binary") || base$1 === "Math") return sortCompletionsAlpha([...localKeys, ...natives({
typeName: "object"
})]);
return applySections({
options: sortCompletionsAlpha([...localKeys, ...natives({
typeName: "object"
}), ...extensions({
typeName: "object"
})]),
recommended: OBJECT_RECOMMENDED_OPTIONS,
recommendedSection: RECOMMENDED_METHODS_SECTION,
propSection: FIELDS_SECTION,
methodsSection: OTHER_METHODS_SECTION,
excludeRecommended: true
});
};
applySections = ({
options,
sections,
recommended = [],
excludeRecommended = false,
methodsSection = METHODS_SECTION,
propSection = PROPERTIES_SECTION,
recommendedSection = RECOMMENDED_SECTION
}) => {
const recommendedSet = new Set(recommended);
const optionByLabel = options.reduce((acc, option) => {
acc[option.label] = option;
return acc;
}, {});
return recommended.map(reco => {
const option = optionByLabel[typeof reco === "string" ? reco : reco.label];
const label = typeof reco === "string" ? option.label : insertDefaultArgs(reco.label, reco.args);
return {
...option,
label,
section: recommendedSection
};
}).concat(options.filter(option => !excludeRecommended || !recommendedSet.has(option.label)).map(option => {
if (sections) option.section = sections[option.section] ?? OTHER_SECTION;else option.section = option.label.endsWith("()") ? methodsSection : propSection;
return option;
}));
};
isUrl = url => {
return attempt(() => {
new URL(url);
return true;
}, () => false);
};
stringOptions = input => {
const {
resolved,
transformLabel
} = input;
const options = sortCompletionsAlpha([...natives({
typeName: "string",
transformLabel
}), ...extensions({
typeName: "string",
includeHidden: false,
transformLabel
})]);
if (resolved && validateFieldType("string", resolved, "number").valid) {
const recommended = ["toNumber()"];
const timestampUnit = toTimestampUnit(Number(resolved));
if (timestampUnit) return applySections({
options,
recommended: [...recommended, {
label: "toDateTime()",
args: [`'${timestampUnit}'`]
}],
sections: STRING_SECTIONS
});
return applySections({
options,
recommended,
sections: STRING_SECTIONS
});
}
if (validateFieldType("string", resolved, "dateTime").valid) return applySections({
options,
recommended: ["toDateTime()"],
sections: STRING_SECTIONS
});
if (VALID_EMAIL_REGEX.test(resolved)) return applySections({
options,
recommended: ["extractDomain()", "isEmail()", ...STRING_RECOMMENDED_OPTIONS],
sections: STRING_SECTIONS
});
if (isUrl(resolved)) return applySections({
options,
recommended: ["extractDomain()", "extractUrlPath()", ...STRING_RECOMMENDED_OPTIONS],
sections: STRING_SECTIONS
});
if (resolved.split(/\s/).find(token => VALID_EMAIL_REGEX.test(token))) return applySections({
options,
recommended: ["extractEmail()", ...STRING_RECOMMENDED_OPTIONS],
sections: STRING_SECTIONS
});
const trimmed = resolved.trim();
if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]")) return applySections({
options,
recommended: ["parseJson()", ...STRING_RECOMMENDED_OPTIONS],
sections: STRING_SECTIONS
});
if (["true", "false"].includes(resolved.toLocaleLowerCase())) return applySections({
options,
recommended: ["toBoolean()", ...STRING_RECOMMENDED_OPTIONS],
sections: STRING_SECTIONS
});
return applySections({
options,
recommended: STRING_RECOMMENDED_OPTIONS,
sections: STRING_SECTIONS
});
};
booleanOptions = () => {
return applySections({
options: sortCompletionsAlpha([...natives({
typeName: "boolean"
}), ...extensions({
typeName: "boolean"
})])
});
};
isWithinMargin = (ts, now, margin) => {
return ts > now - margin && ts < now + margin;
};
toTimestampUnit = ts => {
const nowMillis = Date.now();
const marginMillis = 946707779e3;
if (isWithinMargin(ts, nowMillis, marginMillis)) return "ms";
if (isWithinMargin(ts, nowMillis / 1e3, marginMillis / 1e3)) return "s";
if (isWithinMargin(ts, nowMillis * 1e3, marginMillis * 1e3)) return "us";
return null;
};
numberOptions = input => {
const {
resolved,
transformLabel
} = input;
const options = sortCompletionsAlpha([...natives({
typeName: "number",
transformLabel
}), ...extensions({
typeName: "number",
includeHidden: false,
transformLabel
})]);
const ONLY_INTEGER = ["isEven()", "isOdd()"];
if (Number.isInteger(resolved)) {
const timestampUnit = toTimestampUnit(resolved);
if (timestampUnit) return applySections({
options,
recommended: [{
label: "toDateTime()",
args: [`'${timestampUnit}'`]
}]
});
if (resolved === 0 || resolved === 1) return applySections({
options,
recommended: ["toBoolean()"]
});
return applySections({
options,
recommended: ONLY_INTEGER
});
} else {
const exclude = new Set(ONLY_INTEGER);
return applySections({
options: options.filter(option => !exclude.has(option.label)),
recommended: ["round()", "floor()", "ceil()"]
});
}
};
dateOptions = input => {
const {
transformLabel
} = input;
return extensions({
typeName: "date",
includeHidden: true,
transformLabel
}).filter(ext => ext.label === "toDateTime()");
};
luxonOptions = input => {
const {
transformLabel
} = input;
return applySections({
options: sortCompletionsAlpha((0, import_uniqBy.default)([...extensions({
typeName: "date",
includeHidden: false,
transformLabel
}), ...luxonInstanceOptions({
includeHidden: false,
transformLabel
})], option => option.label)),
recommended: LUXON_RECOMMENDED_OPTIONS,
sections: LUXON_SECTIONS
});
};
arrayOptions = input => {
const {
resolved,
transformLabel
} = input;
const options = applySections({
options: sortCompletionsAlpha([...natives({
typeName: "array",
transformLabel
}), ...extensions({
typeName: "array",
includeHidden: false,
transformLabel
})]),
recommended: ARRAY_RECOMMENDED_OPTIONS,
methodsSection: OTHER_SECTION,
propSection: OTHER_SECTION,
excludeRecommended: true
});
if (resolved.length > 0 && resolved.some(i$1 => typeof i$1 !== "number")) {
const NUMBER_ONLY_ARRAY_EXTENSIONS = new Set(ARRAY_NUMBER_ONLY_METHODS);
return options.filter(m => !NUMBER_ONLY_ARRAY_EXTENSIONS.has(m.label));
}
return options;
};
variablesOptions = () => {
const variables = useEnvironmentsStore().scopedVariables;
const getDescription = (isGlobal, isOverridden, projectName) => {
if (isGlobal && isOverridden) return i18n.baseText("codeNodeEditor.completer.$vars.varName.global.overridden", {
interpolate: {
projectName: projectName ?? ""
}
});
if (isGlobal) return i18n.baseText("codeNodeEditor.completer.$vars.varName.global");
return i18n.baseText("codeNodeEditor.completer.$vars.varName.project", {
interpolate: {
projectName: projectName ?? ""
}
});
};
return applySections({
options: variables.map(variable => {
const isOverridden = !variable.project && !!variables.find(v => v.key === variable.key && v.project);
return createCompletionOption({
name: variable.key,
doc: {
section: variable.project ? "project" : "global",
name: variable.key,
returnType: "string",
description: getDescription(!variable.project, isOverridden, variable.project?.name),
docURL: "https://docs.n8n.io/code/variables/"
},
type: isOverridden ? "strikethrough" : void 0
});
}),
sections: VARIABLE_SECTIONS
});
};
responseOptions = () => {
return [{
name: "statusCode",
returnType: "number",
docURL: "https://docs.n8n.io/code/builtin/http-node-variables/",
description: i18n.baseText("codeNodeEditor.completer.$response.statusCode")
}, {
name: "statusMessage",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.$response.statusMessage")
}, {
name: "headers",
returnType: "Object",
docURL: "https://docs.n8n.io/code/builtin/http-node-variables/",
description: i18n.baseText("codeNodeEditor.completer.$response.headers")
}, {
name: "body",
returnType: "Object",
docURL: "https://docs.n8n.io/code/builtin/http-node-variables/",
description: i18n.baseText("codeNodeEditor.completer.$response.body")
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2
}));
};
executionOptions = () => {
return [{
name: "id",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.$execution.id")
}, {
name: "mode",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.$execution.mode")
}, {
name: "resumeUrl",
returnType: "string",
docURL: "https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.wait/",
description: i18n.baseText("codeNodeEditor.completer.$execution.resumeUrl")
}, {
name: "resumeFormUrl",
returnType: "string",
docURL: "https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.wait/",
description: i18n.baseText("codeNodeEditor.completer.$execution.resumeFormUrl")
}, {
name: "customData",
returnType: "CustomData",
docURL: "https://docs.n8n.io/workflows/executions/custom-executions-data/",
description: i18n.baseText("codeNodeEditor.completer.$execution.customData")
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2
}));
};
customDataOptions = () => {
return [{
name: "get",
returnType: "any",
docURL: "https://docs.n8n.io/workflows/executions/custom-executions-data/",
args: [{
name: "key",
description: "The key (identifier) under which the data is stored",
type: "string"
}],
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.get"),
examples: [{
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.get.examples.1"),
example: "$execution.customData.get(\"user_email\")",
evaluated: "\"me@example.com\""
}]
}, {
name: "set",
returnType: "void",
args: [{
name: "key",
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.set.args.key"),
type: "string"
}, {
name: "value",
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.set.args.value"),
type: "any"
}],
docURL: "https://docs.n8n.io/workflows/executions/custom-executions-data/",
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.set"),
examples: [{
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.set.examples.1"),
example: "$execution.customData.set(\"user_email\", \"me@example.com\")"
}]
}, {
name: "getAll",
returnType: "Object",
docURL: "https://docs.n8n.io/workflows/executions/custom-executions-data/",
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.getAll"),
examples: [{
example: "$execution.customData.getAll()",
evaluated: "{ user_email: \"me@example.com\", id: 1234 }"
}]
}, {
name: "setAll",
returnType: "void",
args: [{
name: "obj",
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.setAll.args.obj"),
type: "object"
}],
docURL: "https://docs.n8n.io/workflows/executions/custom-executions-data/",
description: i18n.baseText("codeNodeEditor.completer.$execution.customData.setAll"),
examples: [{
example: "$execution.customData.setAll({ user_email: \"me@example.com\", id: 1234 })"
}]
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2,
isFunction: true
}));
};
nodeRefOptions = base$1 => {
const itemArgs = [{
name: "branchIndex",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.selector.args.branchIndex"),
default: "0",
type: "number"
}, {
name: "runIndex",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.selector.args.runIndex"),
default: "0",
type: "number"
}];
return applySections({
options: [{
doc: {
name: "item",
returnType: "Item",
docURL: "https://docs.n8n.io/data/data-mapping/data-item-linking/",
description: i18n.baseText("codeNodeEditor.completer.selector.item")
}
}, {
doc: {
name: "isExecuted",
returnType: "boolean",
description: i18n.baseText("codeNodeEditor.completer.selector.isExecuted")
}
}, {
doc: {
name: "params",
returnType: "NodeParams",
description: i18n.baseText("codeNodeEditor.completer.selector.params")
}
}, {
doc: {
name: "itemMatching",
returnType: "Item",
args: [{
name: "currentItemIndex",
description: i18n.baseText("codeNodeEditor.completer.selector.itemMatching.args.currentItemIndex"),
default: "0",
type: "number"
}],
docURL: "https://docs.n8n.io/data/data-mapping/data-item-linking/",
description: i18n.baseText("codeNodeEditor.completer.selector.itemMatching")
},
isFunction: true
}, {
doc: {
name: "first",
returnType: "Item",
args: itemArgs,
description: i18n.baseText("codeNodeEditor.completer.selector.first")
},
isFunction: true
}, {
doc: {
name: "last",
returnType: "Item",
args: itemArgs,
description: i18n.baseText("codeNodeEditor.completer.selector.last")
},
isFunction: true
}, {
doc: {
name: "all",
returnType: "Item[]",
args: itemArgs,
description: i18n.baseText("codeNodeEditor.completer.selector.all")
},
isFunction: true
}].filter(option => !(option.doc.name === "params" && hasNoParams(base$1))).map(({
doc: doc$2,
isFunction
}) => createCompletionOption({
name: doc$2.name,
doc: doc$2,
isFunction
})),
sections: {},
recommended: ["item"]
});
};
inputOptions = base$1 => {
const itemArgs = [{
name: "branchIndex",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.selector.args.branchIndex"),
default: "0",
type: "number"
}, {
name: "runIndex",
optional: true,
description: i18n.baseText("codeNodeEditor.completer.selector.args.runIndex"),
default: "0",
type: "number"
}];
return applySections({
options: [{
doc: {
name: "item",
returnType: "Item",
docURL: "https://docs.n8n.io/data/data-mapping/data-item-linking/",
description: i18n.baseText("codeNodeEditor.completer.selector.item")
}
}, {
doc: {
name: "params",
returnType: "NodeParams",
description: i18n.baseText("codeNodeEditor.completer.selector.params")
}
}, {
doc: {
name: "first",
returnType: "Item",
args: itemArgs,
description: i18n.baseText("codeNodeEditor.completer.selector.first")
},
isFunction: true
}, {
doc: {
name: "last",
returnType: "Item",
args: itemArgs,
description: i18n.baseText("codeNodeEditor.completer.selector.last")
},
isFunction: true
}, {
doc: {
name: "all",
returnType: "Item[]",
args: itemArgs,
description: i18n.baseText("codeNodeEditor.completer.selector.all")
},
isFunction: true
}].filter(option => !(option.doc.name === "params" && hasNoParams(base$1))).map(({
doc: doc$2,
isFunction
}) => createCompletionOption({
name: doc$2.name,
doc: doc$2,
isFunction
})),
recommended: ["item"],
sections: {}
});
};
prevNodeOptions = () => {
return [{
name: "name",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.$prevNode.name")
}, {
name: "outputIndex",
returnType: "number",
description: i18n.baseText("codeNodeEditor.completer.$prevNode.outputIndex")
}, {
name: "runIndex",
returnType: "number",
description: i18n.baseText("codeNodeEditor.completer.$prevNode.runIndex")
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2
}));
};
itemOptions = () => {
return [{
name: "json",
returnType: "Object",
docURL: "https://docs.n8n.io/data/data-structure/",
description: i18n.baseText("codeNodeEditor.completer.item.json")
}, {
name: "binary",
returnType: "Object",
docURL: "https://docs.n8n.io/data/data-structure/",
description: i18n.baseText("codeNodeEditor.completer.item.binary")
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2
}));
};
binaryOptions = () => {
return [{
name: "id",
returnType: "String",
description: i18n.baseText("codeNodeEditor.completer.binary.id")
}, {
name: "fileExtension",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.binary.fileExtension")
}, {
name: "fileName",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.binary.fileName")
}, {
name: "fileSize",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.binary.fileSize")
}, {
name: "fileType",
returnType: "String",
description: i18n.baseText("codeNodeEditor.completer.binary.fileType")
}, {
name: "mimeType",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.binary.mimeType")
}, {
name: "directory",
returnType: "String",
description: i18n.baseText("codeNodeEditor.completer.binary.directory")
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2
}));
};
workflowOptions = () => {
return [{
name: "id",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.$workflow.id")
}, {
name: "name",
returnType: "string",
description: i18n.baseText("codeNodeEditor.completer.$workflow.name")
}, {
name: "active",
returnType: "boolean",
description: i18n.baseText("codeNodeEditor.completer.$workflow.active")
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2
}));
};
secretOptions = base$1 => {
const externalSecretsStore = useExternalSecretsStore();
let resolved;
try {
resolved = Expression.resolveWithoutWorkflow(`{{ ${base$1} }}`, {
$secrets: externalSecretsStore.secretsAsObject
});
} catch {
return [];
}
if (resolved === null) return [];
try {
if (typeof resolved !== "object") return [];
return Object.entries(resolved).map(([secret, value]) => {
const needsBracketAccess = /\//.test(secret);
const option = createCompletionOption({
name: secret,
doc: {
name: secret,
returnType: typeof value,
description: i18n.baseText("codeNodeEditor.completer.$secrets.provider.varName"),
docURL: i18n.baseText("settings.externalSecrets.docs")
}
});
if (needsBracketAccess) option.apply = applyBracketAccessCompletion;
return option;
});
} catch {
return [];
}
};
secretProvidersOptions = () => {
const externalSecretsStore = useExternalSecretsStore();
return Object.keys(externalSecretsStore.secretsAsObject).map(provider => createCompletionOption({
name: provider,
doc: {
name: provider,
returnType: "Object",
description: i18n.baseText("codeNodeEditor.completer.$secrets.provider"),
docURL: i18n.baseText("settings.externalSecrets.docs")
}
}));
};
/**
* Methods and fields defined on a Luxon `DateTime` class instance.
*/
luxonInstanceOptions = ({
includeHidden = false,
transformLabel = label => label
} = {}) => {
const SKIP = new Set(["constructor", "get", "invalidExplanation", "invalidReason"]);
return Object.entries(Object.getOwnPropertyDescriptors(DateTime.prototype)).filter(([key]) => !SKIP.has(key)).sort(([a], [b]) => a.localeCompare(b)).map(([key, descriptor]) => {
return createLuxonAutocompleteOption({
name: key,
isFunction: typeof descriptor.value === "function",
docs: luxonInstanceDocs,
includeHidden,
transformLabel
});
}).filter(Boolean);
};
/**
* Methods defined on a Luxon `DateTime` class.
*/
luxonStaticOptions = () => {
const SKIP = new Set(["prototype", "name", "length", "invalid"]);
return sortCompletionsAlpha(Object.keys(Object.getOwnPropertyDescriptors(DateTime)).filter(key => !SKIP.has(key) && !key.includes("_")).map(key => {
return createLuxonAutocompleteOption({
name: key,
isFunction: true,
docs: luxonStaticDocs
});
}).filter(Boolean));
};
createLuxonAutocompleteOption = ({
name: name$1,
docs,
isFunction = false,
includeHidden = false,
transformLabel = label$1 => label$1
}) => {
const label = isFunction ? name$1 + "()" : name$1;
let doc$2;
if (docs.properties?.hasOwnProperty(name$1)) doc$2 = docs.properties[name$1].doc;else if (docs.functions.hasOwnProperty(name$1)) doc$2 = docs.functions[name$1].doc;else {
const optionType = typeof DateTime.prototype[name$1];
doc$2 = {
name: name$1,
returnType: !optionType || optionType === "undefined" ? "" : optionType,
docURL: "https://moment.github.io/luxon/api-docs/index.html#datetime"
};
}
if (!doc$2 || doc$2?.hidden && !includeHidden) return null;
const option = {
label,
section: doc$2?.section,
apply: applyCompletion({
hasArgs: hasRequiredArgs(doc$2),
defaultArgs: getDefaultArgs(doc$2),
transformLabel
})
};
option.info = createCompletionOption({
name: name$1,
isFunction,
doc: doc$2,
transformLabel
}).info;
return option;
};
/**
* Methods defined on the global `Object`.
*/
objectGlobalOptions = () => {
return [{
name: "assign",
description: i18n.baseText("codeNodeEditor.completer.globalObject.assign"),
args: [{
name: "target",
type: "object"
}, {
name: "sources",
variadic: true,
type: "object"
}],
examples: [{
example: "Object.assign(\n {},\n { id: 1, name: 'Apple' },\n { name: 'Banana' }\n);",
evaluated: "{ id: 1, name: 'Banana' }"
}],
returnType: "Object",
docURL: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign"
}, {
name: "entries",
returnType: "Array<[string, any]>",
args: [{
name: "obj",
type: "object"
}],
examples: [{
example: "Object.entries({ id: 1, name: 'Apple' })",
evaluated: "[['id', 1], ['name', 'Apple']]"
}],
description: i18n.baseText("codeNodeEditor.completer.globalObject.entries"),
docURL: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries"
}, {
name: "keys",
args: [{
name: "obj",
type: "object"
}],
examples: [{
example: "Object.keys({ id: 1, name: 'Apple' })",
evaluated: "['id', 'name']"
}],
returnType: "string[]",
description: i18n.baseText("codeNodeEditor.completer.globalObject.keys"),
docURL: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys"
}, {
name: "values",
args: [{
name: "obj",
type: "object"
}],
examples: [{
example: "Object.values({ id: 1, name: 'Apple' })",
evaluated: "[1, 'Apple']"
}],
description: i18n.baseText("codeNodeEditor.completer.globalObject.values"),
returnType: "Array",
docURL: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values"
}].map(doc$2 => createCompletionOption({
name: doc$2.name,
doc: doc$2,
isFunction: true
}));
};
DATATYPE_REGEX = new RegExp(Object.values({
generalRef: /\$[^$'"]+\.(.*)/,
selectorRef: /\$\(['"][\S\s]+['"]\)\.(.*)/,
numberLiteral: /\((\d+)\.?(\d*)\)\.(.*)/,
singleQuoteStringLiteral: /('.*')\.([^'{\s])*/,
booleanLiteral: /(true|false)\.([^'{\s])*/,
doubleQuoteStringLiteral: /(".*")\.([^"{\s])*/,
dateLiteral: /\(?new Date\(\(?.*?\)\)?\.(.*)/,
arrayLiteral: /\(?(\[.*\])\)?\.(.*)/,
indexedAccess: /([^"{\s]+\[.+\])\.(.*)/,
objectLiteral: /\(\{.*\}\)\.(.*)/,
mathGlobal: /Math\.(.*)/,
datetimeGlobal: /DateTime\.(.*)/,
objectGlobal: /Object\.(.*)/
}).map(regex => regex.source).join("|"));
setDropCursorPos = StateEffect$1.define({
map(pos, mapping) {
return pos === null ? null : mapping.mapPos(pos);
}
});
dropCursorPos = StateField$1.define({
create() {
return null;
},
update(pos, tr) {
if (pos !== null) pos = tr.changes.mapPos(pos);
return tr.effects.reduce((p, e) => e.is(setDropCursorPos) ? e.value : p, pos);
}
});
drawDropCursor = ViewPlugin$1.fromClass(class {
cursor = null;
measureReq;
ndvStore;
constructor(view) {
this.view = view;
this.measureReq = {
read: this.readPos.bind(this),
write: this.drawCursor.bind(this)
};
this.ndvStore = useNDVStore();
}
update(update) {
const cursorPos = update.state.field(dropCursorPos);
if (cursorPos === null) {
if (this.cursor !== null) {
this.cursor?.remove();
this.cursor = null;
}
} else {
if (!this.cursor) {
this.cursor = this.view.scrollDOM.appendChild(document.createElement("div"));
this.cursor.className = "cm-dropCursor";
}
if (update.startState.field(dropCursorPos) !== cursorPos || update.docChanged || update.geometryChanged) this.view.requestMeasure(this.measureReq);
}
}
readPos() {
const {
view
} = this;
const pos = view.state.field(dropCursorPos);
const rect = pos !== null && view.coordsAtPos(pos);
if (!rect) return null;
const outer = view.scrollDOM.getBoundingClientRect();
return {
left: rect.left - outer.left + view.scrollDOM.scrollLeft * view.scaleX,
top: rect.top - outer.top + view.scrollDOM.scrollTop * view.scaleY,
height: rect.bottom - rect.top
};
}
drawCursor(pos) {
if (this.cursor) {
const {
scaleX,
scaleY
} = this.view;
if (pos) {
this.cursor.style.left = pos.left / scaleX + "px";
this.cursor.style.top = pos.top / scaleY + "px";
this.cursor.style.height = pos.height / scaleY + "px";
} else this.cursor.style.left = "-100000px";
}
}
destroy() {
if (this.cursor) this.cursor.remove();
}
setDropPos(pos) {
if (this.view.state.field(dropCursorPos) !== pos) this.view.dispatch({
effects: setDropCursorPos.of(pos)
});
}
}, {
eventObservers: {
mousemove(event) {
if (!this.ndvStore.isDraggableDragging || this.ndvStore.draggableType !== "mapping") return;
const pos = this.view.posAtCoords(eventToCoord(event), false);
this.setDropPos(pos);
},
mouseleave() {
this.setDropPos(null);
},
mouseup() {
this.setDropPos(null);
}
}
});
expressionBracketSpacing = EditorView.updateListener.of(update => {
if (!update.changes || update.changes.empty) return;
update.changes.iterChanges((_fromA, _toA, fromB, toB, inserted) => {
const doc$2 = update.state.doc;
if (inserted.eq(Text.of(["{}"])) && doc$2.sliceString(fromB - 1, fromB) === "{" && doc$2.sliceString(toB, toB + 1) === "}") {
update.view.dispatch({
changes: [{
from: fromB + 1,
insert: " "
}],
selection: EditorSelection.cursor(toB)
});
startCompletion(update.view);
}
});
});
_export("x", expressionCloseBracketsConfig = {
brackets: ["{", "(", "\"", "'", "["],
before: ")]}:;<>'\""
});
_export("b", expressionCloseBrackets = () => [expressionBracketSpacing, closeBrackets(), keymap.of(closeBracketsKeymap)]);
basicNormalize = typeof String.prototype.normalize == "function" ? x => x.normalize("NFKD") : x => x;
/**
A search cursor provides an iterator over text matches in a
document.
*/
SearchCursor = class {
/**
Create a text cursor. The query is the search string, `from` to
`to` provides the region to search.
When `normalize` is given, it will be called, on both the query
string and the content it is matched against, before comparing.
You can, for example, create a case-insensitive search by
passing `s => s.toLowerCase()`.
Text is always normalized with
[`.normalize("NFKD")`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize)
(when supported).
*/
constructor(text, query, from = 0, to = text.length, normalize, test) {
this.test = test;
/**
The current match (only holds a meaningful value after
[`next`](https://codemirror.net/6/docs/ref/#search.SearchCursor.next) has been called and when
`done` is false).
*/
this.value = {
from: 0,
to: 0
};
/**
Whether the end of the iterated region has been reached.
*/
this.done = false;
this.matches = [];
this.buffer = "";
this.bufferPos = 0;
this.iter = text.iterRange(from, to);
this.bufferStart = from;
this.normalize = normalize ? x => normalize(basicNormalize(x)) : basicNormalize;
this.query = this.normalize(query);
}
peek() {
if (this.bufferPos == this.buffer.length) {
this.bufferStart += this.buffer.length;
this.iter.next();
if (this.iter.done) return -1;
this.bufferPos = 0;
this.buffer = this.iter.value;
}
return codePointAt(this.buffer, this.bufferPos);
}
/**
Look for the next match. Updates the iterator's
[`value`](https://codemirror.net/6/docs/ref/#search.SearchCursor.value) and
[`done`](https://codemirror.net/6/docs/ref/#search.SearchCursor.done) properties. Should be called
at least once before using the cursor.
*/
next() {
while (this.matches.length) this.matches.pop();
return this.nextOverlapping();
}
/**
The `next` method will ignore matches that partially overlap a
previous match. This method behaves like `next`, but includes
such matches.
*/
nextOverlapping() {
for (;;) {
let next = this.peek();
if (next < 0) {
this.done = true;
return this;
}
let str = fromCodePoint(next),
start = this.bufferStart + this.bufferPos;
this.bufferPos += codePointSize(next);
let norm = this.normalize(str);
for (let i$1 = 0, pos = start;; i$1++) {
let code$1 = norm.charCodeAt(i$1);
let match = this.match(code$1, pos, this.bufferPos + this.bufferStart);
if (i$1 == norm.length - 1) {
if (match) {
this.value = match;
return this;
}
break;
}
if (pos == start && i$1 < str.length && str.charCodeAt(i$1) == code$1) pos++;
}
}
}
match(code$1, pos, end) {
let match = null;
for (let i$1 = 0; i$1 < this.matches.length; i$1 += 2) {
let index = this.matches[i$1],
keep = false;
if (this.query.charCodeAt(index) == code$1) if (index == this.query.length - 1) match = {
from: this.matches[i$1 + 1],
to: end
};else {
this.matches[i$1]++;
keep = true;
}
if (!keep) {
this.matches.splice(i$1, 2);
i$1 -= 2;
}
}
if (this.query.charCodeAt(0) == code$1) if (this.query.length == 1) match = {
from: pos,
to: end
};else this.matches.push(1, pos);
if (match && this.test && !this.test(match.from, match.to, this.buffer, this.bufferStart)) match = null;
return match;
}
};
if (typeof Symbol != "undefined") SearchCursor.prototype[Symbol.iterator] = function () {
return this;
};
empty = {
from: -1,
to: -1,
match: /* @__PURE__ *//.*/.exec("")
};
baseFlags = "gm" + (/x/.unicode == null ? "" : "u");
/**
This class is similar to [`SearchCursor`](https://codemirror.net/6/docs/ref/#search.SearchCursor)
but searches for a regular expression pattern instead of a plain
string.
*/
RegExpCursor = class {
/**
Create a cursor that will search the given range in the given
document. `query` should be the raw pattern (as you'd pass it to
`new RegExp`).
*/
constructor(text, query, options, from = 0, to = text.length) {
this.text = text;
this.to = to;
this.curLine = "";
/**
Set to `true` when the cursor has reached the end of the search
range.
*/
this.done = false;
/**
Will contain an object with the extent of the match and the
match object when [`next`](https://codemirror.net/6/docs/ref/#search.RegExpCursor.next)
sucessfully finds a match.
*/
this.value = empty;
if (/\\[sWDnr]|\n|\r|\[\^/.test(query)) return new MultilineRegExpCursor(text, query, options, from, to);
this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
this.test = options === null || options === void 0 ? void 0 : options.test;
this.iter = text.iter();
this.curLineStart = text.lineAt(from).from;
this.matchPos = toCharEnd(text, from);
this.getLine(this.curLineStart);
}
getLine(skip) {
this.iter.next(skip);
if (this.iter.lineBreak) this.curLine = "";else {
this.curLine = this.iter.value;
if (this.curLineStart + this.curLine.length > this.to) this.curLine = this.curLine.slice(0, this.to - this.curLineStart);
this.iter.next();
}
}
nextLine() {
this.curLineStart = this.curLineStart + this.curLine.length + 1;
if (this.curLineStart > this.to) this.curLine = "";else this.getLine(0);
}
/**
Move to the next match, if there is one.
*/
next() {
for (let off = this.matchPos - this.curLineStart;;) {
this.re.lastIndex = off;
let match = this.matchPos <= this.to && this.re.exec(this.curLine);
if (match) {
let from = this.curLineStart + match.index,
to = from + match[0].length;
this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
if (from == this.curLineStart + this.curLine.length) this.nextLine();
if ((from < to || from > this.value.to) && (!this.test || this.test(from, to, match))) {
this.value = {
from,
to,
match
};
return this;
}
off = this.matchPos - this.curLineStart;
} else if (this.curLineStart + this.curLine.length < this.to) {
this.nextLine();
off = 0;
} else {
this.done = true;
return this;
}
}
}
};
flattened = /* @__PURE__ */new WeakMap();
FlattenedDoc = class FlattenedDoc {
constructor(from, text) {
this.from = from;
this.text = text;
}
get to() {
return this.from + this.text.length;
}
static get(doc$2, from, to) {
let cached = flattened.get(doc$2);
if (!cached || cached.from >= to || cached.to <= from) {
let flat = new FlattenedDoc(from, doc$2.sliceString(from, to));
flattened.set(doc$2, flat);
return flat;
}
if (cached.from == from && cached.to == to) return cached;
let {
text,
from: cachedFrom
} = cached;
if (cachedFrom > from) {
text = doc$2.sliceString(from, cachedFrom) + text;
cachedFrom = from;
}
if (cached.to < to) text += doc$2.sliceString(cached.to, to);
flattened.set(doc$2, new FlattenedDoc(cachedFrom, text));
return new FlattenedDoc(from, text.slice(from - cachedFrom, to - cachedFrom));
}
};
MultilineRegExpCursor = class {
constructor(text, query, options, from, to) {
this.text = text;
this.to = to;
this.done = false;
this.value = empty;
this.matchPos = toCharEnd(text, from);
this.re = new RegExp(query, baseFlags + ((options === null || options === void 0 ? void 0 : options.ignoreCase) ? "i" : ""));
this.test = options === null || options === void 0 ? void 0 : options.test;
this.flat = FlattenedDoc.get(text, from, this.chunkEnd(from + 5e3));
}
chunkEnd(pos) {
return pos >= this.to ? this.to : this.text.lineAt(pos).to;
}
next() {
for (;;) {
let off = this.re.lastIndex = this.matchPos - this.flat.from;
let match = this.re.exec(this.flat.text);
if (match && !match[0] && match.index == off) {
this.re.lastIndex = off + 1;
match = this.re.exec(this.flat.text);
}
if (match) {
let from = this.flat.from + match.index,
to = from + match[0].length;
if ((this.flat.to >= this.to || match.index + match[0].length <= this.flat.text.length - 10) && (!this.test || this.test(from, to, match))) {
this.value = {
from,
to,
match
};
this.matchPos = toCharEnd(this.text, to + (from == to ? 1 : 0));
return this;
}
}
if (this.flat.to == this.to) {
this.done = true;
return this;
}
this.flat = FlattenedDoc.get(this.text, this.flat.from, this.chunkEnd(this.flat.from + this.flat.text.length * 2));
}
}
};
if (typeof Symbol != "undefined") RegExpCursor.prototype[Symbol.iterator] = MultilineRegExpCursor.prototype[Symbol.iterator] = function () {
return this;
};
dialogEffect = /* @__PURE__ */StateEffect$1.define();
dialogField = /* @__PURE__ */StateField$1.define({
create() {
return true;
},
update(value, tr) {
for (let e of tr.effects) if (e.is(dialogEffect)) value = e.value;
return value;
},
provide: f => showPanel.from(f, val => val ? createLineDialog : null)
});
/**
Command that shows a dialog asking the user for a line number, and
when a valid position is provided, moves the cursor to that line.
Supports line numbers, relative line offsets prefixed with `+` or
`-`, document percentages suffixed with `%`, and an optional
column position by adding `:` and a second number after the line
number.
*/
gotoLine = view => {
let panel = getPanel(view, createLineDialog);
if (!panel) {
let effects = [dialogEffect.of(true)];
if (view.state.field(dialogField, false) == null) effects.push(StateEffect$1.appendConfig.of([dialogField, baseTheme$1$1]));
view.dispatch({
effects
});
panel = getPanel(view, createLineDialog);
}
if (panel) panel.dom.querySelector("input").select();
return true;
};
baseTheme$1$1 = /* @__PURE__ */EditorView.baseTheme({
".cm-panel.cm-gotoLine": {
padding: "2px 6px 4px",
"& label": {
fontSize: "80%"
}
}
});
defaultHighlightOptions = {
highlightWordAroundCursor: false,
minSelectionLength: 1,
maxMatches: 100,
wholeWords: false
};
highlightConfig = /* @__PURE__ */Facet$1.define({
combine(options) {
return combineConfig$1(options, defaultHighlightOptions, {
highlightWordAroundCursor: (a, b) => a || b,
minSelectionLength: Math.min,
maxMatches: Math.min
});
}
});
matchDeco = /* @__PURE__ */Decoration$1.mark({
class: "cm-selectionMatch"
});
mainMatchDeco = /* @__PURE__ */Decoration$1.mark({
class: "cm-selectionMatch cm-selectionMatch-main"
});
matchHighlighter = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.decorations = this.getDeco(view);
}
update(update) {
if (update.selectionSet || update.docChanged || update.viewportChanged) this.decorations = this.getDeco(update.view);
}
getDeco(view) {
let conf = view.state.facet(highlightConfig);
let {
state
} = view,
sel = state.selection;
if (sel.ranges.length > 1) return Decoration$1.none;
let range = sel.main,
query,
check = null;
if (range.empty) {
if (!conf.highlightWordAroundCursor) return Decoration$1.none;
let word = state.wordAt(range.head);
if (!word) return Decoration$1.none;
check = state.charCategorizer(range.head);
query = state.sliceDoc(word.from, word.to);
} else {
let len = range.to - range.from;
if (len < conf.minSelectionLength || len > 200) return Decoration$1.none;
if (conf.wholeWords) {
query = state.sliceDoc(range.from, range.to);
check = state.charCategorizer(range.head);
if (!(insideWordBoundaries(check, state, range.from, range.to) && insideWord(check, state, range.from, range.to))) return Decoration$1.none;
} else {
query = state.sliceDoc(range.from, range.to);
if (!query) return Decoration$1.none;
}
}
let deco = [];
for (let part of view.visibleRanges) {
let cursor = new SearchCursor(state.doc, query, part.from, part.to);
while (!cursor.next().done) {
let {
from,
to
} = cursor.value;
if (!check || insideWordBoundaries(check, state, from, to)) {
if (range.empty && from <= range.from && to >= range.to) deco.push(mainMatchDeco.range(from, to));else if (from >= range.to || to <= range.from) deco.push(matchDeco.range(from, to));
if (deco.length > conf.maxMatches) return Decoration$1.none;
}
}
}
return Decoration$1.set(deco);
}
}, {
decorations: v => v.decorations
});
defaultTheme = /* @__PURE__ */EditorView.baseTheme({
".cm-selectionMatch": {
backgroundColor: "#99ff7780"
},
".cm-searchMatch .cm-selectionMatch": {
backgroundColor: "transparent"
}
});
selectWord = ({
state,
dispatch
}) => {
let {
selection
} = state;
let newSel = EditorSelection.create(selection.ranges.map(range => state.wordAt(range.head) || EditorSelection.cursor(range.head)), selection.mainIndex);
if (newSel.eq(selection)) return false;
dispatch(state.update({
selection: newSel
}));
return true;
};
selectNextOccurrence = ({
state,
dispatch
}) => {
let {
ranges
} = state.selection;
if (ranges.some(sel => sel.from === sel.to)) return selectWord({
state,
dispatch
});
let searchedText = state.sliceDoc(ranges[0].from, ranges[0].to);
if (state.selection.ranges.some(r => state.sliceDoc(r.from, r.to) != searchedText)) return false;
let range = findNextOccurrence(state, searchedText);
if (!range) return false;
dispatch(state.update({
selection: state.selection.addRange(EditorSelection.range(range.from, range.to), false),
effects: EditorView.scrollIntoView(range.to)
}));
return true;
};
searchConfigFacet = /* @__PURE__ */Facet$1.define({
combine(configs) {
return combineConfig$1(configs, {
top: false,
caseSensitive: false,
literal: false,
regexp: false,
wholeWord: false,
createPanel: view => new SearchPanel(view),
scrollToMatch: range => EditorView.scrollIntoView(range)
});
}
});
/**
A search query. Part of the editor's search state.
*/
SearchQuery = class {
/**
Create a query object.
*/
constructor(config$1) {
this.search = config$1.search;
this.caseSensitive = !!config$1.caseSensitive;
this.literal = !!config$1.literal;
this.regexp = !!config$1.regexp;
this.replace = config$1.replace || "";
this.valid = !!this.search && (!this.regexp || validRegExp(this.search));
this.unquoted = this.unquote(this.search);
this.wholeWord = !!config$1.wholeWord;
}
/**
@internal
*/
unquote(text) {
return this.literal ? text : text.replace(/\\([nrt\\])/g, (_, ch) => ch == "n" ? "\n" : ch == "r" ? "\r" : ch == "t" ? " " : "\\");
}
/**
Compare this query to another query.
*/
eq(other) {
return this.search == other.search && this.replace == other.replace && this.caseSensitive == other.caseSensitive && this.regexp == other.regexp && this.wholeWord == other.wholeWord;
}
/**
@internal
*/
create() {
return this.regexp ? new RegExpQuery(this) : new StringQuery(this);
}
/**
Get a search cursor for this query, searching through the given
range in the given state.
*/
getCursor(state, from = 0, to) {
let st = state.doc ? state : EditorState.create({
doc: state
});
if (to == null) to = st.doc.length;
return this.regexp ? regexpCursor(this, st, from, to) : stringCursor(this, st, from, to);
}
};
QueryType$1 = class {
constructor(spec) {
this.spec = spec;
}
};
StringQuery = class extends QueryType$1 {
constructor(spec) {
super(spec);
}
nextMatch(state, curFrom, curTo) {
let cursor = stringCursor(this.spec, state, curTo, state.doc.length).nextOverlapping();
if (cursor.done) cursor = stringCursor(this.spec, state, 0, curFrom).nextOverlapping();
return cursor.done ? null : cursor.value;
}
prevMatchInRange(state, from, to) {
for (let pos = to;;) {
let start = Math.max(from, pos - 1e4 - this.spec.unquoted.length);
let cursor = stringCursor(this.spec, state, start, pos),
range = null;
while (!cursor.nextOverlapping().done) range = cursor.value;
if (range) return range;
if (start == from) return null;
pos -= 1e4;
}
}
prevMatch(state, curFrom, curTo) {
return this.prevMatchInRange(state, 0, curFrom) || this.prevMatchInRange(state, curTo, state.doc.length);
}
getReplacement(_result) {
return this.spec.unquote(this.spec.replace);
}
matchAll(state, limit) {
let cursor = stringCursor(this.spec, state, 0, state.doc.length),
ranges = [];
while (!cursor.next().done) {
if (ranges.length >= limit) return null;
ranges.push(cursor.value);
}
return ranges;
}
highlight(state, from, to, add$1) {
let cursor = stringCursor(this.spec, state, Math.max(0, from - this.spec.unquoted.length), Math.min(to + this.spec.unquoted.length, state.doc.length));
while (!cursor.next().done) add$1(cursor.value.from, cursor.value.to);
}
};
RegExpQuery = class extends QueryType$1 {
nextMatch(state, curFrom, curTo) {
let cursor = regexpCursor(this.spec, state, curTo, state.doc.length).next();
if (cursor.done) cursor = regexpCursor(this.spec, state, 0, curFrom).next();
return cursor.done ? null : cursor.value;
}
prevMatchInRange(state, from, to) {
for (let size = 1;; size++) {
let start = Math.max(from, to - size * 1e4);
let cursor = regexpCursor(this.spec, state, start, to),
range = null;
while (!cursor.next().done) range = cursor.value;
if (range && (start == from || range.from > start + 10)) return range;
if (start == from) return null;
}
}
prevMatch(state, curFrom, curTo) {
return this.prevMatchInRange(state, 0, curFrom) || this.prevMatchInRange(state, curTo, state.doc.length);
}
getReplacement(result) {
return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g, (m, i$1) => i$1 == "$" ? "$" : i$1 == "&" ? result.match[0] : i$1 != "0" && +i$1 < result.match.length ? result.match[i$1] : m);
}
matchAll(state, limit) {
let cursor = regexpCursor(this.spec, state, 0, state.doc.length),
ranges = [];
while (!cursor.next().done) {
if (ranges.length >= limit) return null;
ranges.push(cursor.value);
}
return ranges;
}
highlight(state, from, to, add$1) {
let cursor = regexpCursor(this.spec, state, Math.max(0, from - 250), Math.min(to + 250, state.doc.length));
while (!cursor.next().done) add$1(cursor.value.from, cursor.value.to);
}
};
/**
A state effect that updates the current search query. Note that
this only has an effect if the search state has been initialized
(by including [`search`](https://codemirror.net/6/docs/ref/#search.search) in your configuration or
by running [`openSearchPanel`](https://codemirror.net/6/docs/ref/#search.openSearchPanel) at least
once).
*/
setSearchQuery = /* @__PURE__ */StateEffect$1.define();
togglePanel$1 = /* @__PURE__ */StateEffect$1.define();
searchState = /* @__PURE__ */StateField$1.define({
create(state) {
return new SearchState(defaultQuery(state).create(), null);
},
update(value, tr) {
for (let effect of tr.effects) if (effect.is(setSearchQuery)) value = new SearchState(effect.value.create(), value.panel);else if (effect.is(togglePanel$1)) value = new SearchState(value.query, effect.value ? createSearchPanel : null);
return value;
},
provide: f => showPanel.from(f, val => val.panel)
});
SearchState = class {
constructor(query, panel) {
this.query = query;
this.panel = panel;
}
};
matchMark = /* @__PURE__ */Decoration$1.mark({
class: "cm-searchMatch"
}), selectedMatchMark = /* @__PURE__ */Decoration$1.mark({
class: "cm-searchMatch cm-searchMatch-selected"
});
searchHighlighter = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.view = view;
this.decorations = this.highlight(view.state.field(searchState));
}
update(update) {
let state = update.state.field(searchState);
if (state != update.startState.field(searchState) || update.docChanged || update.selectionSet || update.viewportChanged) this.decorations = this.highlight(state);
}
highlight({
query,
panel
}) {
if (!panel || !query.spec.valid) return Decoration$1.none;
let {
view
} = this;
let builder = new RangeSetBuilder$1();
for (let i$1 = 0, ranges = view.visibleRanges, l = ranges.length; i$1 < l; i$1++) {
let {
from,
to
} = ranges[i$1];
while (i$1 < l - 1 && to > ranges[i$1 + 1].from - 500) to = ranges[++i$1].to;
query.highlight(view.state, from, to, (from$1, to$1) => {
let selected = view.state.selection.ranges.some(r => r.from == from$1 && r.to == to$1);
builder.add(from$1, to$1, selected ? selectedMatchMark : matchMark);
});
}
return builder.finish();
}
}, {
decorations: v => v.decorations
});
findNext = /* @__PURE__ */searchCommand((view, {
query
}) => {
let {
to
} = view.state.selection.main;
let next = query.nextMatch(view.state, to, to);
if (!next) return false;
let selection = EditorSelection.single(next.from, next.to);
let config$1 = view.state.facet(searchConfigFacet);
view.dispatch({
selection,
effects: [announceMatch(view, next), config$1.scrollToMatch(selection.main, view)],
userEvent: "select.search"
});
selectSearchInput(view);
return true;
});
/**
Move the selection to the previous instance of the search query,
before the current main selection. Will wrap past the start
of the document to start searching at the end again.
*/
findPrevious = /* @__PURE__ */searchCommand((view, {
query
}) => {
let {
state
} = view,
{
from
} = state.selection.main;
let prev = query.prevMatch(state, from, from);
if (!prev) return false;
let selection = EditorSelection.single(prev.from, prev.to);
let config$1 = view.state.facet(searchConfigFacet);
view.dispatch({
selection,
effects: [announceMatch(view, prev), config$1.scrollToMatch(selection.main, view)],
userEvent: "select.search"
});
selectSearchInput(view);
return true;
});
/**
Select all instances of the search query.
*/
selectMatches = /* @__PURE__ */searchCommand((view, {
query
}) => {
let ranges = query.matchAll(view.state, 1e3);
if (!ranges || !ranges.length) return false;
view.dispatch({
selection: EditorSelection.create(ranges.map(r => EditorSelection.range(r.from, r.to))),
userEvent: "select.search.matches"
});
return true;
});
/**
Select all instances of the currently selected text.
*/
selectSelectionMatches = ({
state,
dispatch
}) => {
let sel = state.selection;
if (sel.ranges.length > 1 || sel.main.empty) return false;
let {
from,
to
} = sel.main;
let ranges = [],
main = 0;
for (let cur$1 = new SearchCursor(state.doc, state.sliceDoc(from, to)); !cur$1.next().done;) {
if (ranges.length > 1e3) return false;
if (cur$1.value.from == from) main = ranges.length;
ranges.push(EditorSelection.range(cur$1.value.from, cur$1.value.to));
}
dispatch(state.update({
selection: EditorSelection.create(ranges, main),
userEvent: "select.search.matches"
}));
return true;
};
/**
Replace the current match of the search query.
*/
replaceNext = /* @__PURE__ */searchCommand((view, {
query
}) => {
let {
state
} = view,
{
from,
to
} = state.selection.main;
if (state.readOnly) return false;
let next = query.nextMatch(state, from, from);
if (!next) return false;
let changes = [],
selection,
replacement;
let effects = [];
if (next.from == from && next.to == to) {
replacement = state.toText(query.getReplacement(next));
changes.push({
from: next.from,
to: next.to,
insert: replacement
});
next = query.nextMatch(state, next.from, next.to);
effects.push(EditorView.announce.of(state.phrase("replaced match on line $", state.doc.lineAt(from).number) + "."));
}
if (next) {
let off = changes.length == 0 || changes[0].from >= next.to ? 0 : next.to - next.from - replacement.length;
selection = EditorSelection.single(next.from - off, next.to - off);
effects.push(announceMatch(view, next));
effects.push(state.facet(searchConfigFacet).scrollToMatch(selection.main, view));
}
view.dispatch({
changes,
selection,
effects,
userEvent: "input.replace"
});
return true;
});
/**
Replace all instances of the search query with the given
replacement.
*/
replaceAll = /* @__PURE__ */searchCommand((view, {
query
}) => {
if (view.state.readOnly) return false;
let changes = query.matchAll(view.state, 1e9).map(match => {
let {
from,
to
} = match;
return {
from,
to,
insert: query.getReplacement(match)
};
});
if (!changes.length) return false;
let announceText = view.state.phrase("replaced $ matches", changes.length) + ".";
view.dispatch({
changes,
effects: EditorView.announce.of(announceText),
userEvent: "input.replace.all"
});
return true;
});
openSearchPanel = view => {
let state = view.state.field(searchState, false);
if (state && state.panel) {
let searchInput = getSearchInput(view);
if (searchInput && searchInput != view.root.activeElement) {
let query = defaultQuery(view.state, state.query.spec);
if (query.valid) view.dispatch({
effects: setSearchQuery.of(query)
});
searchInput.focus();
searchInput.select();
}
} else view.dispatch({
effects: [togglePanel$1.of(true), state ? setSearchQuery.of(defaultQuery(view.state, state.query.spec)) : StateEffect$1.appendConfig.of(searchExtensions)]
});
return true;
};
/**
Close the search panel.
*/
closeSearchPanel = view => {
let state = view.state.field(searchState, false);
if (!state || !state.panel) return false;
let panel = getPanel(view, createSearchPanel);
if (panel && panel.dom.contains(view.root.activeElement)) view.focus();
view.dispatch({
effects: togglePanel$1.of(false)
});
return true;
};
SearchPanel = class {
constructor(view) {
this.view = view;
let query = this.query = view.state.field(searchState).query.spec;
this.commit = this.commit.bind(this);
this.searchField = crelt("input", {
value: query.search,
placeholder: phrase(view, "Find"),
"aria-label": phrase(view, "Find"),
class: "cm-textfield",
name: "search",
form: "",
"main-field": "true",
onchange: this.commit,
onkeyup: this.commit
});
this.replaceField = crelt("input", {
value: query.replace,
placeholder: phrase(view, "Replace"),
"aria-label": phrase(view, "Replace"),
class: "cm-textfield",
name: "replace",
form: "",
onchange: this.commit,
onkeyup: this.commit
});
this.caseField = crelt("input", {
type: "checkbox",
name: "case",
form: "",
checked: query.caseSensitive,
onchange: this.commit
});
this.reField = crelt("input", {
type: "checkbox",
name: "re",
form: "",
checked: query.regexp,
onchange: this.commit
});
this.wordField = crelt("input", {
type: "checkbox",
name: "word",
form: "",
checked: query.wholeWord,
onchange: this.commit
});
function button(name$1, onclick, content$1) {
return crelt("button", {
class: "cm-button",
name: name$1,
onclick,
type: "button"
}, content$1);
}
this.dom = crelt("div", {
onkeydown: e => this.keydown(e),
class: "cm-search"
}, [this.searchField, button("next", () => findNext(view), [phrase(view, "next")]), button("prev", () => findPrevious(view), [phrase(view, "previous")]), button("select", () => selectMatches(view), [phrase(view, "all")]), crelt("label", null, [this.caseField, phrase(view, "match case")]), crelt("label", null, [this.reField, phrase(view, "regexp")]), crelt("label", null, [this.wordField, phrase(view, "by word")]), ...(view.state.readOnly ? [] : [crelt("br"), this.replaceField, button("replace", () => replaceNext(view), [phrase(view, "replace")]), button("replaceAll", () => replaceAll(view), [phrase(view, "replace all")])]), crelt("button", {
name: "close",
onclick: () => closeSearchPanel(view),
"aria-label": phrase(view, "close"),
type: "button"
}, ["×"])]);
}
commit() {
let query = new SearchQuery({
search: this.searchField.value,
caseSensitive: this.caseField.checked,
regexp: this.reField.checked,
wholeWord: this.wordField.checked,
replace: this.replaceField.value
});
if (!query.eq(this.query)) {
this.query = query;
this.view.dispatch({
effects: setSearchQuery.of(query)
});
}
}
keydown(e) {
if (runScopeHandlers(this.view, e, "search-panel")) e.preventDefault();else if (e.keyCode == 13 && e.target == this.searchField) {
e.preventDefault();
(e.shiftKey ? findPrevious : findNext)(this.view);
} else if (e.keyCode == 13 && e.target == this.replaceField) {
e.preventDefault();
replaceNext(this.view);
}
}
update(update) {
for (let tr of update.transactions) for (let effect of tr.effects) if (effect.is(setSearchQuery) && !effect.value.eq(this.query)) this.setQuery(effect.value);
}
setQuery(query) {
this.query = query;
this.searchField.value = query.search;
this.replaceField.value = query.replace;
this.caseField.checked = query.caseSensitive;
this.reField.checked = query.regexp;
this.wordField.checked = query.wholeWord;
}
mount() {
this.searchField.select();
}
get pos() {
return 80;
}
get top() {
return this.view.state.facet(searchConfigFacet).top;
}
};
AnnounceMargin = 30;
Break = /[\s\.,:;?!]/;
baseTheme$2 = /* @__PURE__ */EditorView.baseTheme({
".cm-panel.cm-search": {
padding: "2px 6px 4px",
position: "relative",
"& [name=close]": {
position: "absolute",
top: "0",
right: "4px",
backgroundColor: "inherit",
border: "none",
font: "inherit",
padding: 0,
margin: 0
},
"& input, & button, & label": {
margin: ".2em .6em .2em 0"
},
"& input[type=checkbox]": {
marginRight: ".2em"
},
"& label": {
fontSize: "80%",
whiteSpace: "pre"
}
},
"&light .cm-searchMatch": {
backgroundColor: "#ffff0054"
},
"&dark .cm-searchMatch": {
backgroundColor: "#00ffff8a"
},
"&light .cm-searchMatch-selected": {
backgroundColor: "#ff6a0054"
},
"&dark .cm-searchMatch-selected": {
backgroundColor: "#ff00ff8a"
}
});
searchExtensions = [searchState, /* @__PURE__ */Prec.low(searchHighlighter), baseTheme$2]; //#endregion
//#region src/features/shared/editors/plugins/codemirror/multiCursor.ts
createAddCursor = direction => view => {
const forward = direction === "down";
let selection = view.state.selection;
for (const r of selection.ranges) selection = selection.addRange(view.moveVertically(r, forward));
view.dispatch({
selection
});
return true;
};
addCursorUp = createAddCursor("up");
addCursorDown = createAddCursor("down");
addCursorAtEachSelectionLine = view => {
let selection = null;
for (const r of view.state.selection.ranges) {
if (r.empty) continue;
for (let pos = r.from; pos <= r.to;) {
const line = view.state.doc.lineAt(pos);
const anchor = Math.min(line.to, r.to);
if (selection) selection = selection.addRange(EditorSelection.range(anchor, anchor));else selection = EditorSelection.single(anchor);
pos = line.to + 1;
}
}
if (!selection) return false;
view.dispatch({
selection
});
return true;
}; //#endregion
//#region ../../../node_modules/.pnpm/@codemirror+lint@6.8.0/node_modules/@codemirror/lint/dist/index.js
SelectedDiagnostic = class {
constructor(from, to, diagnostic) {
this.from = from;
this.to = to;
this.diagnostic = diagnostic;
}
};
LintState = class LintState {
constructor(diagnostics, panel, selected) {
this.diagnostics = diagnostics;
this.panel = panel;
this.selected = selected;
}
static init(diagnostics, panel, state) {
let markedDiagnostics = diagnostics;
let diagnosticFilter = state.facet(lintConfig).markerFilter;
if (diagnosticFilter) markedDiagnostics = diagnosticFilter(markedDiagnostics, state);
let ranges = Decoration$1.set(markedDiagnostics.map(d => {
return d.from == d.to || d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from ? Decoration$1.widget({
widget: new DiagnosticWidget(d),
diagnostic: d
}).range(d.from) : Decoration$1.mark({
attributes: {
class: "cm-lintRange cm-lintRange-" + d.severity + (d.markClass ? " " + d.markClass : "")
},
diagnostic: d,
inclusive: true
}).range(d.from, d.to);
}), true);
return new LintState(ranges, panel, findDiagnostic(ranges));
}
};
setDiagnosticsEffect = /* @__PURE__ */StateEffect$1.define();
togglePanel = /* @__PURE__ */StateEffect$1.define();
movePanelSelection = /* @__PURE__ */StateEffect$1.define();
lintState = /* @__PURE__ */StateField$1.define({
create() {
return new LintState(Decoration$1.none, null, null);
},
update(value, tr) {
if (tr.docChanged && value.diagnostics.size) {
let mapped = value.diagnostics.map(tr.changes),
selected = null,
panel = value.panel;
if (value.selected) {
let selPos = tr.changes.mapPos(value.selected.from, 1);
selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
}
if (!mapped.size && panel && tr.state.facet(lintConfig).autoPanel) panel = null;
value = new LintState(mapped, panel, selected);
}
for (let effect of tr.effects) if (effect.is(setDiagnosticsEffect)) {
let panel = !tr.state.facet(lintConfig).autoPanel ? value.panel : effect.value.length ? LintPanel.open : null;
value = LintState.init(effect.value, panel, tr.state);
} else if (effect.is(togglePanel)) value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected);else if (effect.is(movePanelSelection)) value = new LintState(value.diagnostics, value.panel, effect.value);
return value;
},
provide: f => [showPanel.from(f, val => val.panel), EditorView.decorations.from(f, s => s.diagnostics)]
});
activeMark = /* @__PURE__ */Decoration$1.mark({
class: "cm-lintRange cm-lintRange-active",
inclusive: true
});
openLintPanel = view => {
let field = view.state.field(lintState, false);
if (!field || !field.panel) view.dispatch({
effects: maybeEnableLint(view.state, [togglePanel.of(true)])
});
let panel = getPanel(view, LintPanel.open);
if (panel) panel.dom.querySelector(".cm-panel-lint ul").focus();
return true;
};
/**
Command to close the lint panel, when open.
*/
closeLintPanel = view => {
let field = view.state.field(lintState, false);
if (!field || !field.panel) return false;
view.dispatch({
effects: togglePanel.of(false)
});
return true;
};
/**
Move the selection to the next diagnostic.
*/
nextDiagnostic = view => {
let field = view.state.field(lintState, false);
if (!field) return false;
let sel = view.state.selection.main,
next = field.diagnostics.iter(sel.to + 1);
if (!next.value) {
next = field.diagnostics.iter(0);
if (!next.value || next.from == sel.from && next.to == sel.to) return false;
}
view.dispatch({
selection: {
anchor: next.from,
head: next.to
},
scrollIntoView: true
});
return true;
};
/**
Move the selection to the previous diagnostic.
*/
previousDiagnostic = view => {
let {
state
} = view,
field = state.field(lintState, false);
if (!field) return false;
let sel = state.selection.main;
let prevFrom, prevTo, lastFrom, lastTo;
field.diagnostics.between(0, state.doc.length, (from, to) => {
if (to < sel.to && (prevFrom == null || prevFrom < from)) {
prevFrom = from;
prevTo = to;
}
if (lastFrom == null || from > lastFrom) {
lastFrom = from;
lastTo = to;
}
});
if (lastFrom == null || prevFrom == null && lastFrom == sel.from) return false;
view.dispatch({
selection: {
anchor: prevFrom !== null && prevFrom !== void 0 ? prevFrom : lastFrom,
head: prevTo !== null && prevTo !== void 0 ? prevTo : lastTo
},
scrollIntoView: true
});
return true;
};
lintPlugin = /* @__PURE__ */ViewPlugin$1.fromClass(class {
constructor(view) {
this.view = view;
this.timeout = -1;
this.set = true;
let {
delay
} = view.state.facet(lintConfig);
this.lintTime = Date.now() + delay;
this.run = this.run.bind(this);
this.timeout = setTimeout(this.run, delay);
}
run() {
clearTimeout(this.timeout);
let now = Date.now();
if (now < this.lintTime - 10) this.timeout = setTimeout(this.run, this.lintTime - now);else {
this.set = false;
let {
state
} = this.view,
{
sources
} = state.facet(lintConfig);
if (sources.length) Promise.all(sources.map(source => Promise.resolve(source(this.view)))).then(annotations => {
let all = annotations.reduce((a, b) => a.concat(b));
if (this.view.state.doc == state.doc) this.view.dispatch(setDiagnostics(this.view.state, all));
}, error => {
logException$1(this.view.state, error);
});
}
}
update(update) {
let config$1 = update.state.facet(lintConfig);
if (update.docChanged || config$1 != update.startState.facet(lintConfig) || config$1.needsRefresh && config$1.needsRefresh(update)) {
this.lintTime = Date.now() + config$1.delay;
if (!this.set) {
this.set = true;
this.timeout = setTimeout(this.run, config$1.delay);
}
}
}
force() {
if (this.set) {
this.lintTime = Date.now();
this.run();
}
}
destroy() {
clearTimeout(this.timeout);
}
});
lintConfig = /* @__PURE__ */Facet$1.define({
combine(input) {
return Object.assign({
sources: input.map(i$1 => i$1.source).filter(x => x != null)
}, combineConfig$1(input.map(i$1 => i$1.config), {
delay: 750,
markerFilter: null,
tooltipFilter: null,
needsRefresh: null,
hideOn: () => null
}, {
needsRefresh: (a, b) => !a ? b : !b ? a : u => a(u) || b(u)
}));
}
});
DiagnosticWidget = class extends WidgetType$1 {
constructor(diagnostic) {
super();
this.diagnostic = diagnostic;
}
eq(other) {
return other.diagnostic == this.diagnostic;
}
toDOM() {
return crelt("span", {
class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity
});
}
};
PanelItem = class {
constructor(view, diagnostic) {
this.diagnostic = diagnostic;
this.id = "item_" + Math.floor(Math.random() * 4294967295).toString(16);
this.dom = renderDiagnostic(view, diagnostic, true);
this.dom.id = this.id;
this.dom.setAttribute("role", "option");
}
};
LintPanel = class LintPanel {
constructor(view) {
this.view = view;
this.items = [];
let onkeydown = event => {
if (event.keyCode == 27) {
closeLintPanel(this.view);
this.view.focus();
} else if (event.keyCode == 38 || event.keyCode == 33) this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);else if (event.keyCode == 40 || event.keyCode == 34) this.moveSelection((this.selectedIndex + 1) % this.items.length);else if (event.keyCode == 36) this.moveSelection(0);else if (event.keyCode == 35) this.moveSelection(this.items.length - 1);else if (event.keyCode == 13) this.view.focus();else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) {
let {
diagnostic
} = this.items[this.selectedIndex],
keys = assignKeys(diagnostic.actions);
for (let i$1 = 0; i$1 < keys.length; i$1++) if (keys[i$1].toUpperCase().charCodeAt(0) == event.keyCode) {
let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
if (found) diagnostic.actions[i$1].apply(view, found.from, found.to);
}
} else return;
event.preventDefault();
};
let onclick = event => {
for (let i$1 = 0; i$1 < this.items.length; i$1++) if (this.items[i$1].dom.contains(event.target)) this.moveSelection(i$1);
};
this.list = crelt("ul", {
tabIndex: 0,
role: "listbox",
"aria-label": this.view.state.phrase("Diagnostics"),
onkeydown,
onclick
});
this.dom = crelt("div", {
class: "cm-panel-lint"
}, this.list, crelt("button", {
type: "button",
name: "close",
"aria-label": this.view.state.phrase("close"),
onclick: () => closeLintPanel(this.view)
}, "×"));
this.update();
}
get selectedIndex() {
let selected = this.view.state.field(lintState).selected;
if (!selected) return -1;
for (let i$1 = 0; i$1 < this.items.length; i$1++) if (this.items[i$1].diagnostic == selected.diagnostic) return i$1;
return -1;
}
update() {
let {
diagnostics,
selected
} = this.view.state.field(lintState);
let i$1 = 0,
needsSync = false,
newSelectedItem = null;
diagnostics.between(0, this.view.state.doc.length, (_start, _end, {
spec
}) => {
let found = -1,
item;
for (let j = i$1; j < this.items.length; j++) if (this.items[j].diagnostic == spec.diagnostic) {
found = j;
break;
}
if (found < 0) {
item = new PanelItem(this.view, spec.diagnostic);
this.items.splice(i$1, 0, item);
needsSync = true;
} else {
item = this.items[found];
if (found > i$1) {
this.items.splice(i$1, found - i$1);
needsSync = true;
}
}
if (selected && item.diagnostic == selected.diagnostic) {
if (!item.dom.hasAttribute("aria-selected")) {
item.dom.setAttribute("aria-selected", "true");
newSelectedItem = item;
}
} else if (item.dom.hasAttribute("aria-selected")) item.dom.removeAttribute("aria-selected");
i$1++;
});
while (i$1 < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
needsSync = true;
this.items.pop();
}
if (this.items.length == 0) {
this.items.push(new PanelItem(this.view, {
from: -1,
to: -1,
severity: "info",
message: this.view.state.phrase("No diagnostics")
}));
needsSync = true;
}
if (newSelectedItem) {
this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
this.view.requestMeasure({
key: this,
read: () => ({
sel: newSelectedItem.dom.getBoundingClientRect(),
panel: this.list.getBoundingClientRect()
}),
write: ({
sel,
panel
}) => {
let scaleY = panel.height / this.list.offsetHeight;
if (sel.top < panel.top) this.list.scrollTop -= (panel.top - sel.top) / scaleY;else if (sel.bottom > panel.bottom) this.list.scrollTop += (sel.bottom - panel.bottom) / scaleY;
}
});
} else if (this.selectedIndex < 0) this.list.removeAttribute("aria-activedescendant");
if (needsSync) this.sync();
}
sync() {
let domPos = this.list.firstChild;
function rm$2() {
let prev = domPos;
domPos = prev.nextSibling;
prev.remove();
}
for (let item of this.items) if (item.dom.parentNode == this.list) {
while (domPos != item.dom) rm$2();
domPos = item.dom.nextSibling;
} else this.list.insertBefore(item.dom, domPos);
while (domPos) rm$2();
}
moveSelection(selectedIndex) {
if (this.selectedIndex < 0) return;
let selection = findDiagnostic(this.view.state.field(lintState).diagnostics, this.items[selectedIndex].diagnostic);
if (!selection) return;
this.view.dispatch({
selection: {
anchor: selection.from,
head: selection.to
},
scrollIntoView: true,
effects: movePanelSelection.of(selection)
});
}
static open(view) {
return new LintPanel(view);
}
};
baseTheme = /* @__PURE__ */EditorView.baseTheme({
".cm-diagnostic": {
padding: "3px 6px 3px 8px",
marginLeft: "-1px",
display: "block",
whiteSpace: "pre-wrap"
},
".cm-diagnostic-error": {
borderLeft: "5px solid #d11"
},
".cm-diagnostic-warning": {
borderLeft: "5px solid orange"
},
".cm-diagnostic-info": {
borderLeft: "5px solid #999"
},
".cm-diagnostic-hint": {
borderLeft: "5px solid #66d"
},
".cm-diagnosticAction": {
font: "inherit",
border: "none",
padding: "2px 4px",
backgroundColor: "#444",
color: "white",
borderRadius: "3px",
marginLeft: "8px",
cursor: "pointer"
},
".cm-diagnosticSource": {
fontSize: "70%",
opacity: .7
},
".cm-lintRange": {
backgroundPosition: "left bottom",
backgroundRepeat: "repeat-x",
paddingBottom: "0.7px"
},
".cm-lintRange-error": {
backgroundImage: /* @__PURE__ */underline("#d11")
},
".cm-lintRange-warning": {
backgroundImage: /* @__PURE__ */underline("orange")
},
".cm-lintRange-info": {
backgroundImage: /* @__PURE__ */underline("#999")
},
".cm-lintRange-hint": {
backgroundImage: /* @__PURE__ */underline("#66d")
},
".cm-lintRange-active": {
backgroundColor: "#ffdd9980"
},
".cm-tooltip-lint": {
padding: 0,
margin: 0
},
".cm-lintPoint": {
position: "relative",
"&:after": {
content: "\"\"",
position: "absolute",
bottom: 0,
left: "-2px",
borderLeft: "3px solid transparent",
borderRight: "3px solid transparent",
borderBottom: "4px solid #d11"
}
},
".cm-lintPoint-warning": {
"&:after": {
borderBottomColor: "orange"
}
},
".cm-lintPoint-info": {
"&:after": {
borderBottomColor: "#999"
}
},
".cm-lintPoint-hint": {
"&:after": {
borderBottomColor: "#66d"
}
},
".cm-panel.cm-panel-lint": {
position: "relative",
"& ul": {
maxHeight: "100px",
overflowY: "auto",
"& [aria-selected]": {
backgroundColor: "#ddd",
"& u": {
textDecoration: "underline"
}
},
"&:focus [aria-selected]": {
background_fallback: "#bdf",
backgroundColor: "Highlight",
color_fallback: "white",
color: "HighlightText"
},
"& u": {
textDecoration: "none"
},
padding: 0,
margin: 0
},
"& [name=close]": {
position: "absolute",
top: "0",
right: "2px",
background: "inherit",
border: "none",
font: "inherit",
padding: 0,
margin: 0
}
}
});
LintGutterMarker = class extends GutterMarker$1 {
constructor(diagnostics) {
super();
this.diagnostics = diagnostics;
this.severity = diagnostics.reduce((max, d) => severityWeight(max) < severityWeight(d.severity) ? d.severity : max, "hint");
}
toDOM(view) {
let elt = document.createElement("div");
elt.className = "cm-lint-marker cm-lint-marker-" + this.severity;
let diagnostics = this.diagnostics;
let diagnosticsFilter = view.state.facet(lintGutterConfig).tooltipFilter;
if (diagnosticsFilter) diagnostics = diagnosticsFilter(diagnostics, view.state);
if (diagnostics.length) elt.onmouseover = () => gutterMarkerMouseOver(view, elt, diagnostics);
return elt;
}
};
lintGutterExtension = /* @__PURE__ */gutter$1({
class: "cm-gutter-lint",
markers: view => view.state.field(lintGutterMarkers)
});
lintGutterMarkers = /* @__PURE__ */StateField$1.define({
create() {
return RangeSet$1.empty;
},
update(markers, tr) {
markers = markers.map(tr.changes);
let diagnosticFilter = tr.state.facet(lintGutterConfig).markerFilter;
for (let effect of tr.effects) if (effect.is(setDiagnosticsEffect)) {
let diagnostics = effect.value;
if (diagnosticFilter) diagnostics = diagnosticFilter(diagnostics || [], tr.state);
markers = markersForDiagnostics(tr.state.doc, diagnostics.slice(0));
}
return markers;
}
});
setLintGutterTooltip = /* @__PURE__ */StateEffect$1.define();
lintGutterTooltip = /* @__PURE__ */StateField$1.define({
create() {
return null;
},
update(tooltip, tr) {
if (tooltip && tr.docChanged) tooltip = hideTooltip(tr, tooltip) ? null : Object.assign(Object.assign({}, tooltip), {
pos: tr.changes.mapPos(tooltip.pos)
});
return tr.effects.reduce((t$1, e) => e.is(setLintGutterTooltip) ? e.value : t$1, tooltip);
},
provide: field => showTooltip.from(field)
});
lintGutterTheme = /* @__PURE__ */EditorView.baseTheme({
".cm-gutter-lint": {
width: "1.4em",
"& .cm-gutterElement": {
padding: ".2em"
}
},
".cm-lint-marker": {
width: "1em",
height: "1em"
},
".cm-lint-marker-info": {
content: /* @__PURE__ */svg(`<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>`)
},
".cm-lint-marker-warning": {
content: /* @__PURE__ */svg(`<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`)
},
".cm-lint-marker-error": {
content: /* @__PURE__ */svg(`<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`)
}
});
lintExtensions = [lintState, /* @__PURE__ */EditorView.decorations.compute([lintState], state => {
let {
selected,
panel
} = state.field(lintState);
return !selected || !panel || selected.from == selected.to ? Decoration$1.none : Decoration$1.set([activeMark.range(selected.from, selected.to)]);
}), /* @__PURE__ */hoverTooltip(lintTooltip, {
hideOn: hideTooltip
}), baseTheme];
lintGutterConfig = /* @__PURE__ */Facet$1.define({
combine(configs) {
return combineConfig$1(configs, {
hoverTime: 300,
markerFilter: null,
tooltipFilter: null
});
}
});
_export("g", languageFacet = Facet$1.define({
combine: values => values[0] ?? "javaScript"
}));
SELECTED_AUTOCOMPLETE_OPTION_SELECTOR = ".cm-tooltip-autocomplete li[aria-selected]";
onAutocompleteNavigate = dir => view => {
if (completionStatus(view.state) !== null) {
moveCompletionSelection(dir === "down")(view);
document.querySelector(SELECTED_AUTOCOMPLETE_OPTION_SELECTOR)?.scrollIntoView({
block: "nearest"
});
return true;
}
return false;
};
_export("h", editorKeymap = [{
key: "Ctrl-Space",
run: startCompletion
}, {
key: "Escape",
run: closeCompletion
}, {
key: "Escape",
run: view => {
if (view.state.selection.ranges.length > 1) {
view.dispatch({
selection: EditorSelection.single(view.state.selection.main.head)
});
return true;
}
return false;
}
}, {
key: "ArrowDown",
run: onAutocompleteNavigate("down")
}, {
key: "ArrowUp",
run: onAutocompleteNavigate("up")
}, {
key: "PageDown",
run: moveCompletionSelection(true, "page")
}, {
key: "PageUp",
run: moveCompletionSelection(false, "page")
}, {
key: "Enter",
run: acceptCompletion
}, {
key: "Tab",
run: acceptCompletion
}, {
key: "Mod-f",
run: openSearchPanel,
scope: "editor search-panel"
}, {
key: "Escape",
run: closeSearchPanel,
scope: "editor search-panel"
}, {
key: "Alt-Enter",
run: selectMatches,
scope: "editor search-panel"
}, {
key: "Mod-Alt-Enter",
run: replaceAll,
scope: "editor search-panel"
}, {
key: "Ctrl-g",
run: gotoLine
}, {
key: "Mod-d",
run: selectNextOccurrence,
preventDefault: true
}, {
key: "Shift-Mod-l",
run: selectSelectionMatches
}, {
key: "Enter",
run: insertNewlineAndIndent,
shift: insertNewlineAndIndent
}, {
key: "ArrowLeft",
run: cursorCharLeft,
shift: selectCharLeft,
preventDefault: true
}, {
key: "Mod-ArrowLeft",
mac: "Alt-ArrowLeft",
run: cursorGroupLeft,
shift: selectGroupLeft
}, {
key: "ArrowRight",
run: cursorCharRight,
shift: selectCharRight,
preventDefault: true
}, {
key: "Mod-ArrowRight",
mac: "Alt-ArrowRight",
run: cursorGroupRight,
shift: selectGroupRight
}, {
key: "ArrowUp",
run: cursorLineUp,
shift: selectLineUp,
preventDefault: true
}, {
key: "ArrowDown",
run: cursorLineDown,
shift: selectLineDown,
preventDefault: true
}, {
key: "Home",
run: cursorLineBoundaryBackward,
shift: selectLineBoundaryBackward
}, {
mac: "Cmd-ArrowLeft",
run: cursorLineBoundaryBackward,
shift: selectLineBoundaryBackward
}, {
key: "Mod-Home",
run: cursorDocStart,
shift: selectDocStart
}, {
mac: "Cmd-ArrowUp",
run: cursorDocStart,
shift: selectDocStart
}, {
key: "PageUp",
run: cursorPageUp,
shift: selectPageUp
}, {
mac: "Ctrl-ArrowUp",
run: cursorPageUp,
shift: selectPageUp
}, {
key: "PageDown",
run: cursorPageDown,
shift: selectPageDown
}, {
mac: "Ctrl-ArrowDown",
run: cursorPageDown,
shift: selectPageDown
}, {
key: "End",
run: cursorLineBoundaryForward,
shift: selectLineBoundaryForward
}, {
mac: "Cmd-ArrowRight",
run: cursorLineBoundaryForward,
shift: selectLineBoundaryForward
}, {
key: "Mod-Alt-ArrowUp",
linux: "Shift-Alt-ArrowUp",
run: addCursorUp,
preventDefault: true
}, {
key: "Mod-Alt-ArrowDown",
linux: "Shift-Alt-ArrowDown",
run: addCursorDown,
preventDefault: true
}, {
key: "Shift-Alt-i",
run: addCursorAtEachSelectionLine
}, {
key: "Mod-End",
run: cursorDocEnd,
shift: selectDocEnd
}, {
mac: "Cmd-ArrowDown",
run: cursorDocEnd,
shift: selectDocEnd
}, {
key: "Mod-a",
run: selectAll
}, {
key: "Backspace",
run: deleteBracketPair
}, {
key: "Backspace",
run: deleteCharBackward,
shift: deleteCharBackward
}, {
key: "Delete",
run: deleteCharForward
}, {
key: "Mod-Backspace",
mac: "Alt-Backspace",
run: deleteGroupBackward
}, {
key: "Mod-Delete",
mac: "Alt-Delete",
run: deleteGroupForward
}, {
mac: "Mod-Backspace",
run: deleteToLineStart
}, {
mac: "Mod-Delete",
run: deleteToLineEnd
}, {
mac: "Ctrl-b",
run: cursorCharLeft,
shift: selectCharLeft,
preventDefault: true
}, {
mac: "Ctrl-f",
run: cursorCharRight,
shift: selectCharRight
}, {
mac: "Ctrl-p",
run: cursorLineUp,
shift: selectLineUp
}, {
mac: "Ctrl-n",
run: cursorLineDown,
shift: selectLineDown
}, {
mac: "Ctrl-a",
run: cursorLineStart,
shift: selectLineStart
}, {
mac: "Ctrl-e",
run: cursorLineEnd,
shift: selectLineEnd
}, {
mac: "Ctrl-d",
run: deleteCharForward
}, {
mac: "Ctrl-h",
run: deleteCharBackward
}, {
mac: "Ctrl-k",
run: deleteToLineEnd
}, {
mac: "Ctrl-Alt-h",
run: deleteGroupBackward
}, {
mac: "Ctrl-o",
run: splitLine
}, {
mac: "Ctrl-t",
run: transposeChars
}, {
mac: "Ctrl-v",
run: cursorPageDown
}, {
mac: "Alt-v",
run: cursorPageUp
}, {
key: "Shift-Mod-k",
run: deleteLine
}, {
key: "Alt-ArrowDown",
run: moveLineDown
}, {
key: "Alt-ArrowUp",
run: moveLineUp
}, {
win: "Shift-Alt-ArrowDown",
mac: "Shift-Alt-ArrowDown",
run: copyLineDown
}, {
win: "Shift-Alt-ArrowUp",
mac: "Shift-Alt-ArrowUp",
run: copyLineUp
}, {
key: "Mod-l",
run: selectLine,
preventDefault: true
}, {
key: "Shift-Mod-\\",
run: cursorMatchingBracket
}, {
any(view, event) {
if (event.key === "Tab" || event.key === "Escape" && completionStatus(view.state) !== null) event.stopPropagation();
return false;
}
}, {
key: "Tab",
run: indentMore,
shift: indentLess,
preventDefault: true
}, {
key: "Mod-[",
run: indentLess
}, {
key: "Mod-]",
run: indentMore
}, {
key: "Ctrl-Shift-[",
mac: "Cmd-Alt-[",
run: foldCode
}, {
key: "Ctrl-Shift-]",
mac: "Cmd-Alt-]",
run: unfoldCode
}, {
key: "Mod-k Mod-0",
run: foldAll
}, {
key: "Mod-k Mod-j",
run: unfoldAll
}, {
key: "Mod-k Mod-c",
run: lineComment
}, {
key: "Mod-k Mod-u",
run: lineUncomment
}, {
key: "Mod-/",
run: toggleComment
}, {
key: "Shift-Alt-a",
run: toggleBlockComment
}, {
key: "Mod-z",
run: undo,
preventDefault: true
}, {
key: "Mod-y",
run: redo,
preventDefault: true
}, {
key: "Mod-Shift-z",
run: redo,
preventDefault: true
}, {
key: "Mod-u",
run: undoSelection,
preventDefault: true
}, {
key: "Mod-Shift-m",
run: openLintPanel
}, {
key: "F8",
run: nextDiagnostic
}, {
key: "Shift-F8",
run: previousDiagnostic
}, {
key: "Shift-Alt-f",
linux: "Ctrl-Shift-i",
run: formatDocument
}]); //#endregion
//#region ../../../node_modules/.pnpm/@codemirror+state@6.3.3/node_modules/@codemirror/state/dist/index.js
/**
The data structure for documents. @nonabstract
*/
Text$1 = class Text$1 {
/**
Get the line description around the given position.
*/
lineAt(pos) {
if (pos < 0 || pos > this.length) throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`);
return this.lineInner(pos, false, 1, 0);
}
/**
Get the description for the given (1-based) line number.
*/
line(n) {
if (n < 1 || n > this.lines) throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`);
return this.lineInner(n, true, 1, 0);
}
/**
Replace a range of the text with the given content.
*/
replace(from, to, text) {
[from, to] = clip(this, from, to);
let parts = [];
this.decompose(0, from, parts, 2);
if (text.length) text.decompose(0, text.length, parts, 3);
this.decompose(to, this.length, parts, 1);
return TextNode.from(parts, this.length - (to - from) + text.length);
}
/**
Append another document to this one.
*/
append(other) {
return this.replace(this.length, this.length, other);
}
/**
Retrieve the text between the given points.
*/
slice(from, to = this.length) {
[from, to] = clip(this, from, to);
let parts = [];
this.decompose(from, to, parts, 0);
return TextNode.from(parts, to - from);
}
/**
Test whether this text is equal to another instance.
*/
eq(other) {
if (other == this) return true;
if (other.length != this.length || other.lines != this.lines) return false;
let start = this.scanIdentical(other, 1),
end = this.length - this.scanIdentical(other, -1);
let a = new RawTextCursor(this),
b = new RawTextCursor(other);
for (let skip = start, pos = start;;) {
a.next(skip);
b.next(skip);
skip = 0;
if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) return false;
pos += a.value.length;
if (a.done || pos >= end) return true;
}
}
/**
Iterate over the text. When `dir` is `-1`, iteration happens
from end to start. This will return lines and the breaks between
them as separate strings.
*/
iter(dir = 1) {
return new RawTextCursor(this, dir);
}
/**
Iterate over a range of the text. When `from` > `to`, the
iterator will run in reverse.
*/
iterRange(from, to = this.length) {
return new PartialTextCursor(this, from, to);
}
/**
Return a cursor that iterates over the given range of lines,
_without_ returning the line breaks between, and yielding empty
strings for empty lines.
When `from` and `to` are given, they should be 1-based line numbers.
*/
iterLines(from, to) {
let inner;
if (from == null) inner = this.iter();else {
if (to == null) to = this.lines + 1;
let start = this.line(from).from;
inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to));
}
return new LineCursor(inner);
}
/**
Return the document as a string, using newline characters to
separate lines.
*/
toString() {
return this.sliceString(0);
}
/**
Convert the document to an array of lines (which can be
deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)).
*/
toJSON() {
let lines = [];
this.flatten(lines);
return lines;
}
/**
@internal
*/
constructor() {}
/**
Create a `Text` instance for the given array of lines.
*/
static of(text) {
if (text.length == 0) throw new RangeError("A document must have at least one line");
if (text.length == 1 && !text[0]) return Text$1.empty;
return text.length <= 32 ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, []));
}
};
TextLeaf = class TextLeaf extends Text$1 {
constructor(text, length = textLength(text)) {
super();
this.text = text;
this.length = length;
}
get lines() {
return this.text.length;
}
get children() {
return null;
}
lineInner(target, isLine, line, offset) {
for (let i$1 = 0;; i$1++) {
let string$1 = this.text[i$1],
end = offset + string$1.length;
if ((isLine ? line : end) >= target) return new Line(offset, end, line, string$1);
offset = end + 1;
line++;
}
}
decompose(from, to, target, open) {
let text = from <= 0 && to >= this.length ? this : new TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from));
if (open & 1) {
let prev = target.pop();
let joined = appendText(text.text, prev.text.slice(), 0, text.length);
if (joined.length <= 32) target.push(new TextLeaf(joined, prev.length + text.length));else {
let mid = joined.length >> 1;
target.push(new TextLeaf(joined.slice(0, mid)), new TextLeaf(joined.slice(mid)));
}
} else target.push(text);
}
replace(from, to, text) {
if (!(text instanceof TextLeaf)) return super.replace(from, to, text);
[from, to] = clip(this, from, to);
let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to);
let newLen = this.length + text.length - (to - from);
if (lines.length <= 32) return new TextLeaf(lines, newLen);
return TextNode.from(TextLeaf.split(lines, []), newLen);
}
sliceString(from, to = this.length, lineSep = "\n") {
[from, to] = clip(this, from, to);
let result = "";
for (let pos = 0, i$1 = 0; pos <= to && i$1 < this.text.length; i$1++) {
let line = this.text[i$1],
end = pos + line.length;
if (pos > from && i$1) result += lineSep;
if (from < end && to > pos) result += line.slice(Math.max(0, from - pos), to - pos);
pos = end + 1;
}
return result;
}
flatten(target) {
for (let line of this.text) target.push(line);
}
scanIdentical() {
return 0;
}
static split(text, target) {
let part = [],
len = -1;
for (let line of text) {
part.push(line);
len += line.length + 1;
if (part.length == 32) {
target.push(new TextLeaf(part, len));
part = [];
len = -1;
}
}
if (len > -1) target.push(new TextLeaf(part, len));
return target;
}
};
TextNode = class TextNode extends Text$1 {
constructor(children, length) {
super();
this.children = children;
this.length = length;
this.lines = 0;
for (let child of children) this.lines += child.lines;
}
lineInner(target, isLine, line, offset) {
for (let i$1 = 0;; i$1++) {
let child = this.children[i$1],
end = offset + child.length,
endLine = line + child.lines - 1;
if ((isLine ? endLine : end) >= target) return child.lineInner(target, isLine, line, offset);
offset = end + 1;
line = endLine + 1;
}
}
decompose(from, to, target, open) {
for (let i$1 = 0, pos = 0; pos <= to && i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (from <= end && to >= pos) {
let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0));
if (pos >= from && end <= to && !childOpen) target.push(child);else child.decompose(from - pos, to - pos, target, childOpen);
}
pos = end + 1;
}
}
replace(from, to, text) {
[from, to] = clip(this, from, to);
if (text.lines < this.lines) for (let i$1 = 0, pos = 0; i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (from >= pos && to <= end) {
let updated = child.replace(from - pos, to - pos, text);
let totalLines = this.lines - child.lines + updated.lines;
if (updated.lines < totalLines >> 4 && updated.lines > totalLines >> 6) {
let copy = this.children.slice();
copy[i$1] = updated;
return new TextNode(copy, this.length - (to - from) + text.length);
}
return super.replace(pos, end, updated);
}
pos = end + 1;
}
return super.replace(from, to, text);
}
sliceString(from, to = this.length, lineSep = "\n") {
[from, to] = clip(this, from, to);
let result = "";
for (let i$1 = 0, pos = 0; i$1 < this.children.length && pos <= to; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (pos > from && i$1) result += lineSep;
if (from < end && to > pos) result += child.sliceString(from - pos, to - pos, lineSep);
pos = end + 1;
}
return result;
}
flatten(target) {
for (let child of this.children) child.flatten(target);
}
scanIdentical(other, dir) {
if (!(other instanceof TextNode)) return 0;
let length = 0;
let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1];
for (;; iA += dir, iB += dir) {
if (iA == eA || iB == eB) return length;
let chA = this.children[iA],
chB = other.children[iB];
if (chA != chB) return length + chA.scanIdentical(chB, dir);
length += chA.length + 1;
}
}
static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) {
let lines = 0;
for (let ch of children) lines += ch.lines;
if (lines < 32) {
let flat = [];
for (let ch of children) ch.flatten(flat);
return new TextLeaf(flat, length);
}
let chunk = Math.max(32, lines >> 5),
maxChunk = chunk << 1,
minChunk = chunk >> 1;
let chunked = [],
currentLines = 0,
currentLen = -1,
currentChunk = [];
function add$1(child) {
let last;
if (child.lines > maxChunk && child instanceof TextNode) for (let node of child.children) add$1(node);else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) {
flush();
chunked.push(child);
} else if (child instanceof TextLeaf && currentLines && (last = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last.lines <= 32) {
currentLines += child.lines;
currentLen += child.length + 1;
currentChunk[currentChunk.length - 1] = new TextLeaf(last.text.concat(child.text), last.length + 1 + child.length);
} else {
if (currentLines + child.lines > chunk) flush();
currentLines += child.lines;
currentLen += child.length + 1;
currentChunk.push(child);
}
}
function flush() {
if (currentLines == 0) return;
chunked.push(currentChunk.length == 1 ? currentChunk[0] : TextNode.from(currentChunk, currentLen));
currentLen = -1;
currentLines = currentChunk.length = 0;
}
for (let child of children) add$1(child);
flush();
return chunked.length == 1 ? chunked[0] : new TextNode(chunked, length);
}
};
Text$1.empty = /* @__PURE__ */new TextLeaf([""], 0);
RawTextCursor = class {
constructor(text, dir = 1) {
this.dir = dir;
this.done = false;
this.lineBreak = false;
this.value = "";
this.nodes = [text];
this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1];
}
nextInner(skip, dir) {
this.done = this.lineBreak = false;
for (;;) {
let last = this.nodes.length - 1;
let top$1 = this.nodes[last],
offsetValue = this.offsets[last],
offset = offsetValue >> 1;
let size = top$1 instanceof TextLeaf ? top$1.text.length : top$1.children.length;
if (offset == (dir > 0 ? size : 0)) {
if (last == 0) {
this.done = true;
this.value = "";
return this;
}
if (dir > 0) this.offsets[last - 1]++;
this.nodes.pop();
this.offsets.pop();
} else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) {
this.offsets[last] += dir;
if (skip == 0) {
this.lineBreak = true;
this.value = "\n";
return this;
}
skip--;
} else if (top$1 instanceof TextLeaf) {
let next = top$1.text[offset + (dir < 0 ? -1 : 0)];
this.offsets[last] += dir;
if (next.length > Math.max(0, skip)) {
this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip);
return this;
}
skip -= next.length;
} else {
let next = top$1.children[offset + (dir < 0 ? -1 : 0)];
if (skip > next.length) {
skip -= next.length;
this.offsets[last] += dir;
} else {
if (dir < 0) this.offsets[last]--;
this.nodes.push(next);
this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1);
}
}
}
}
next(skip = 0) {
if (skip < 0) {
this.nextInner(-skip, -this.dir);
skip = this.value.length;
}
return this.nextInner(skip, this.dir);
}
};
PartialTextCursor = class {
constructor(text, start, end) {
this.value = "";
this.done = false;
this.cursor = new RawTextCursor(text, start > end ? -1 : 1);
this.pos = start > end ? text.length : 0;
this.from = Math.min(start, end);
this.to = Math.max(start, end);
}
nextInner(skip, dir) {
if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) {
this.value = "";
this.done = true;
return this;
}
skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos);
let limit = dir < 0 ? this.pos - this.from : this.to - this.pos;
if (skip > limit) skip = limit;
limit -= skip;
let {
value
} = this.cursor.next(skip);
this.pos += (value.length + skip) * dir;
this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit);
this.done = !this.value;
return this;
}
next(skip = 0) {
if (skip < 0) skip = Math.max(skip, this.from - this.pos);else if (skip > 0) skip = Math.min(skip, this.to - this.pos);
return this.nextInner(skip, this.cursor.dir);
}
get lineBreak() {
return this.cursor.lineBreak && this.value != "";
}
};
LineCursor = class {
constructor(inner) {
this.inner = inner;
this.afterBreak = true;
this.value = "";
this.done = false;
}
next(skip = 0) {
let {
done,
lineBreak,
value
} = this.inner.next(skip);
if (done && this.afterBreak) {
this.value = "";
this.afterBreak = false;
} else if (done) {
this.done = true;
this.value = "";
} else if (lineBreak) {
if (this.afterBreak) this.value = "";else {
this.afterBreak = true;
this.next();
}
} else {
this.value = value;
this.afterBreak = false;
}
return this;
}
get lineBreak() {
return false;
}
};
if (typeof Symbol != "undefined") {
Text$1.prototype[Symbol.iterator] = function () {
return this.iter();
};
RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function () {
return this;
};
}
/**
This type describes a line in the document. It is created
on-demand when lines are [queried](https://codemirror.net/6/docs/ref/#state.Text.lineAt).
*/
Line = class {
/**
@internal
*/
constructor(from, to, number$1, text) {
this.from = from;
this.to = to;
this.number = number$1;
this.text = text;
}
/**
The length of the line (not including any line break after it).
*/
get length() {
return this.to - this.from;
}
};
extend = /* @__PURE__ */"lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(s => s ? parseInt(s, 36) : 1);
for (let i$1 = 1; i$1 < extend.length; i$1++) extend[i$1] += extend[i$1 - 1];
ZWJ = 8205;
DefaultSplit = /\r\n?|\n/;
/**
Distinguishes different ways in which positions can be mapped.
*/
MapMode$1 = /* @__PURE__ */function (MapMode$2) {
/**
Map a position to a valid new position, even when its context
was deleted.
*/
MapMode$2[MapMode$2["Simple"] = 0] = "Simple";
/**
Return null if deletion happens across the position.
*/
MapMode$2[MapMode$2["TrackDel"] = 1] = "TrackDel";
/**
Return null if the character _before_ the position is deleted.
*/
MapMode$2[MapMode$2["TrackBefore"] = 2] = "TrackBefore";
/**
Return null if the character _after_ the position is deleted.
*/
MapMode$2[MapMode$2["TrackAfter"] = 3] = "TrackAfter";
return MapMode$2;
}(MapMode$1 || (MapMode$1 = {}));
/**
A change description is a variant of [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet)
that doesn't store the inserted text. As such, it can't be
applied, but is cheaper to store and manipulate.
*/
ChangeDesc = class ChangeDesc {
/**
@internal
*/
constructor(sections) {
this.sections = sections;
}
/**
The length of the document before the change.
*/
get length() {
let result = 0;
for (let i$1 = 0; i$1 < this.sections.length; i$1 += 2) result += this.sections[i$1];
return result;
}
/**
The length of the document after the change.
*/
get newLength() {
let result = 0;
for (let i$1 = 0; i$1 < this.sections.length; i$1 += 2) {
let ins = this.sections[i$1 + 1];
result += ins < 0 ? this.sections[i$1] : ins;
}
return result;
}
/**
False when there are actual changes in this set.
*/
get empty() {
return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0;
}
/**
Iterate over the unchanged parts left by these changes. `posA`
provides the position of the range in the old document, `posB`
the new position in the changed document.
*/
iterGaps(f) {
for (let i$1 = 0, posA = 0, posB = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++];
if (ins < 0) {
f(posA, posB, len);
posB += len;
} else posB += ins;
posA += len;
}
}
/**
Iterate over the ranges changed by these changes. (See
[`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a
variant that also provides you with the inserted text.)
`fromA`/`toA` provides the extent of the change in the starting
document, `fromB`/`toB` the extent of the replacement in the
changed document.
When `individual` is true, adjacent changes (which are kept
separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are
reported separately.
*/
iterChangedRanges(f, individual = false) {
iterChanges(this, f, individual);
}
/**
Get a description of the inverted form of these changes.
*/
get invertedDesc() {
let sections = [];
for (let i$1 = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++];
if (ins < 0) sections.push(len, ins);else sections.push(ins, len);
}
return new ChangeDesc(sections);
}
/**
Compute the combined effect of applying another set of changes
after this one. The length of the document after this set should
match the length before `other`.
*/
composeDesc(other) {
return this.empty ? other : other.empty ? this : composeSets(this, other);
}
/**
Map this description, which should start with the same document
as `other`, over another set of changes, so that it can be
applied after it. When `before` is true, map as if the changes
in `other` happened before the ones in `this`.
*/
mapDesc(other, before = false) {
return other.empty ? this : mapSet(this, other, before);
}
mapPos(pos, assoc = -1, mode = MapMode$1.Simple) {
let posA = 0,
posB = 0;
for (let i$1 = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++],
endA = posA + len;
if (ins < 0) {
if (endA > pos) return posB + (pos - posA);
posB += len;
} else {
if (mode != MapMode$1.Simple && endA >= pos && (mode == MapMode$1.TrackDel && posA < pos && endA > pos || mode == MapMode$1.TrackBefore && posA < pos || mode == MapMode$1.TrackAfter && endA > pos)) return null;
if (endA > pos || endA == pos && assoc < 0 && !len) return pos == posA || assoc < 0 ? posB : posB + ins;
posB += ins;
}
posA = endA;
}
if (pos > posA) throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`);
return posB;
}
/**
Check whether these changes touch a given range. When one of the
changes entirely covers the range, the string `"cover"` is
returned.
*/
touchesRange(from, to = from) {
for (let i$1 = 0, pos = 0; i$1 < this.sections.length && pos <= to;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++],
end = pos + len;
if (ins >= 0 && pos <= to && end >= from) return pos < from && end > to ? "cover" : true;
pos = end;
}
return false;
}
/**
@internal
*/
toString() {
let result = "";
for (let i$1 = 0; i$1 < this.sections.length;) {
let len = this.sections[i$1++],
ins = this.sections[i$1++];
result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : "");
}
return result;
}
/**
Serialize this change desc to a JSON-representable value.
*/
toJSON() {
return this.sections;
}
/**
Create a change desc from its JSON representation (as produced
by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON).
*/
static fromJSON(json$1) {
if (!Array.isArray(json$1) || json$1.length % 2 || json$1.some(a => typeof a != "number")) throw new RangeError("Invalid JSON representation of ChangeDesc");
return new ChangeDesc(json$1);
}
/**
@internal
*/
static create(sections) {
return new ChangeDesc(sections);
}
};
/**
A change set represents a group of modifications to a document. It
stores the document length, and can only be applied to documents
with exactly that length.
*/
ChangeSet$1 = class ChangeSet$1 extends ChangeDesc {
constructor(sections, inserted) {
super(sections);
this.inserted = inserted;
}
/**
Apply the changes to a document, returning the modified
document.
*/
apply(doc$2) {
if (this.length != doc$2.length) throw new RangeError("Applying change set to a document with the wrong length");
iterChanges(this, (fromA, toA, fromB, _toB, text) => doc$2 = doc$2.replace(fromB, fromB + (toA - fromA), text), false);
return doc$2;
}
mapDesc(other, before = false) {
return mapSet(this, other, before, true);
}
/**
Given the document as it existed _before_ the changes, return a
change set that represents the inverse of this set, which could
be used to go from the document created by the changes back to
the document as it existed before the changes.
*/
invert(doc$2) {
let sections = this.sections.slice(),
inserted = [];
for (let i$1 = 0, pos = 0; i$1 < sections.length; i$1 += 2) {
let len = sections[i$1],
ins = sections[i$1 + 1];
if (ins >= 0) {
sections[i$1] = ins;
sections[i$1 + 1] = len;
let index = i$1 >> 1;
while (inserted.length < index) inserted.push(Text$1.empty);
inserted.push(len ? doc$2.slice(pos, pos + len) : Text$1.empty);
}
pos += len;
}
return new ChangeSet$1(sections, inserted);
}
/**
Combine two subsequent change sets into a single set. `other`
must start in the document produced by `this`. If `this` goes
`docA` → `docB` and `other` represents `docB` → `docC`, the
returned value will represent the change `docA` → `docC`.
*/
compose(other) {
return this.empty ? other : other.empty ? this : composeSets(this, other, true);
}
/**
Given another change set starting in the same document, maps this
change set over the other, producing a new change set that can be
applied to the document produced by applying `other`. When
`before` is `true`, order changes as if `this` comes before
`other`, otherwise (the default) treat `other` as coming first.
Given two changes `A` and `B`, `A.compose(B.map(A))` and
`B.compose(A.map(B, true))` will produce the same document. This
provides a basic form of [operational
transformation](https://en.wikipedia.org/wiki/Operational_transformation),
and can be used for collaborative editing.
*/
map(other, before = false) {
return other.empty ? this : mapSet(this, other, before, true);
}
/**
Iterate over the changed ranges in the document, calling `f` for
each, with the range in the original document (`fromA`-`toA`)
and the range that replaces it in the new document
(`fromB`-`toB`).
When `individual` is true, adjacent changes are reported
separately.
*/
iterChanges(f, individual = false) {
iterChanges(this, f, individual);
}
/**
Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change
set.
*/
get desc() {
return ChangeDesc.create(this.sections);
}
/**
@internal
*/
filter(ranges) {
let resultSections = [],
resultInserted = [],
filteredSections = [];
let iter = new SectionIter(this);
done: for (let i$1 = 0, pos = 0;;) {
let next = i$1 == ranges.length ? 1e9 : ranges[i$1++];
while (pos < next || pos == next && iter.len == 0) {
if (iter.done) break done;
let len = Math.min(iter.len, next - pos);
addSection(filteredSections, len, -1);
let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0;
addSection(resultSections, len, ins);
if (ins > 0) addInsert(resultInserted, resultSections, iter.text);
iter.forward(len);
pos += len;
}
let end = ranges[i$1++];
while (pos < end) {
if (iter.done) break done;
let len = Math.min(iter.len, end - pos);
addSection(resultSections, len, -1);
addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0);
iter.forward(len);
pos += len;
}
}
return {
changes: new ChangeSet$1(resultSections, resultInserted),
filtered: ChangeDesc.create(filteredSections)
};
}
/**
Serialize this change set to a JSON-representable value.
*/
toJSON() {
let parts = [];
for (let i$1 = 0; i$1 < this.sections.length; i$1 += 2) {
let len = this.sections[i$1],
ins = this.sections[i$1 + 1];
if (ins < 0) parts.push(len);else if (ins == 0) parts.push([len]);else parts.push([len].concat(this.inserted[i$1 >> 1].toJSON()));
}
return parts;
}
/**
Create a change set for the given changes, for a document of the
given length, using `lineSep` as line separator.
*/
static of(changes, length, lineSep) {
let sections = [],
inserted = [],
pos = 0;
let total = null;
function flush(force = false) {
if (!force && !sections.length) return;
if (pos < length) addSection(sections, length - pos, -1);
let set = new ChangeSet$1(sections, inserted);
total = total ? total.compose(set.map(total)) : set;
sections = [];
inserted = [];
pos = 0;
}
function process(spec) {
if (Array.isArray(spec)) for (let sub of spec) process(sub);else if (spec instanceof ChangeSet$1) {
if (spec.length != length) throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`);
flush();
total = total ? total.compose(spec.map(total)) : spec;
} else {
let {
from,
to = from,
insert: insert$2
} = spec;
if (from > to || from < 0 || to > length) throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`);
let insText = !insert$2 ? Text$1.empty : typeof insert$2 == "string" ? Text$1.of(insert$2.split(lineSep || DefaultSplit)) : insert$2;
let insLen = insText.length;
if (from == to && insLen == 0) return;
if (from < pos) flush();
if (from > pos) addSection(sections, from - pos, -1);
addSection(sections, to - from, insLen);
addInsert(inserted, sections, insText);
pos = to;
}
}
process(changes);
flush(!total);
return total;
}
/**
Create an empty changeset of the given length.
*/
static empty(length) {
return new ChangeSet$1(length ? [length, -1] : [], []);
}
/**
Create a changeset from its JSON representation (as produced by
[`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON).
*/
static fromJSON(json$1) {
if (!Array.isArray(json$1)) throw new RangeError("Invalid JSON representation of ChangeSet");
let sections = [],
inserted = [];
for (let i$1 = 0; i$1 < json$1.length; i$1++) {
let part = json$1[i$1];
if (typeof part == "number") sections.push(part, -1);else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i$2) => i$2 && typeof e != "string")) throw new RangeError("Invalid JSON representation of ChangeSet");else if (part.length == 1) sections.push(part[0], 0);else {
while (inserted.length < i$1) inserted.push(Text$1.empty);
inserted[i$1] = Text$1.of(part.slice(1));
sections.push(part[0], inserted[i$1].length);
}
}
return new ChangeSet$1(sections, inserted);
}
/**
@internal
*/
static createSet(sections, inserted) {
return new ChangeSet$1(sections, inserted);
}
};
SectionIter = class {
constructor(set) {
this.set = set;
this.i = 0;
this.next();
}
next() {
let {
sections
} = this.set;
if (this.i < sections.length) {
this.len = sections[this.i++];
this.ins = sections[this.i++];
} else {
this.len = 0;
this.ins = -2;
}
this.off = 0;
}
get done() {
return this.ins == -2;
}
get len2() {
return this.ins < 0 ? this.len : this.ins;
}
get text() {
let {
inserted
} = this.set,
index = this.i - 2 >> 1;
return index >= inserted.length ? Text$1.empty : inserted[index];
}
textBit(len) {
let {
inserted
} = this.set,
index = this.i - 2 >> 1;
return index >= inserted.length && !len ? Text$1.empty : inserted[index].slice(this.off, len == null ? void 0 : this.off + len);
}
forward(len) {
if (len == this.len) this.next();else {
this.len -= len;
this.off += len;
}
}
forward2(len) {
if (this.ins == -1) this.forward(len);else if (len == this.ins) this.next();else {
this.ins -= len;
this.off += len;
}
}
};
/**
A single selection range. When
[`allowMultipleSelections`](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
is enabled, a [selection](https://codemirror.net/6/docs/ref/#state.EditorSelection) may hold
multiple ranges. By default, selections hold exactly one range.
*/
SelectionRange = class SelectionRange {
constructor(from, to, flags) {
this.from = from;
this.to = to;
this.flags = flags;
}
/**
The anchor of the range—the side that doesn't move when you
extend it.
*/
get anchor() {
return this.flags & 32 ? this.to : this.from;
}
/**
The head of the range, which is moved when the range is
[extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend).
*/
get head() {
return this.flags & 32 ? this.from : this.to;
}
/**
True when `anchor` and `head` are at the same position.
*/
get empty() {
return this.from == this.to;
}
/**
If this is a cursor that is explicitly associated with the
character on one of its sides, this returns the side. -1 means
the character before its position, 1 the character after, and 0
means no association.
*/
get assoc() {
return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0;
}
/**
The bidirectional text level associated with this cursor, if
any.
*/
get bidiLevel() {
let level = this.flags & 7;
return level == 7 ? null : level;
}
/**
The goal column (stored vertical offset) associated with a
cursor. This is used to preserve the vertical position when
[moving](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) across
lines of different length.
*/
get goalColumn() {
let value = this.flags >> 6;
return value == 16777215 ? void 0 : value;
}
/**
Map this range through a change, producing a valid range in the
updated document.
*/
map(change, assoc = -1) {
let from, to;
if (this.empty) from = to = change.mapPos(this.from, assoc);else {
from = change.mapPos(this.from, 1);
to = change.mapPos(this.to, -1);
}
return from == this.from && to == this.to ? this : new SelectionRange(from, to, this.flags);
}
/**
Extend this range to cover at least `from` to `to`.
*/
extend(from, to = from) {
if (from <= this.anchor && to >= this.anchor) return EditorSelection$1.range(from, to);
let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to;
return EditorSelection$1.range(this.anchor, head);
}
/**
Compare this range to another range.
*/
eq(other) {
return this.anchor == other.anchor && this.head == other.head;
}
/**
Return a JSON-serializable object representing the range.
*/
toJSON() {
return {
anchor: this.anchor,
head: this.head
};
}
/**
Convert a JSON representation of a range to a `SelectionRange`
instance.
*/
static fromJSON(json$1) {
if (!json$1 || typeof json$1.anchor != "number" || typeof json$1.head != "number") throw new RangeError("Invalid JSON representation for SelectionRange");
return EditorSelection$1.range(json$1.anchor, json$1.head);
}
/**
@internal
*/
static create(from, to, flags) {
return new SelectionRange(from, to, flags);
}
};
/**
An editor selection holds one or more selection ranges.
*/
EditorSelection$1 = class EditorSelection$1 {
constructor(ranges, mainIndex) {
this.ranges = ranges;
this.mainIndex = mainIndex;
}
/**
Map a selection through a change. Used to adjust the selection
position for changes.
*/
map(change, assoc = -1) {
if (change.empty) return this;
return EditorSelection$1.create(this.ranges.map(r => r.map(change, assoc)), this.mainIndex);
}
/**
Compare this selection to another selection.
*/
eq(other) {
if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex) return false;
for (let i$1 = 0; i$1 < this.ranges.length; i$1++) if (!this.ranges[i$1].eq(other.ranges[i$1])) return false;
return true;
}
/**
Get the primary selection range. Usually, you should make sure
your code applies to _all_ ranges, by using methods like
[`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange).
*/
get main() {
return this.ranges[this.mainIndex];
}
/**
Make sure the selection only has one range. Returns a selection
holding only the main range from this selection.
*/
asSingle() {
return this.ranges.length == 1 ? this : new EditorSelection$1([this.main], 0);
}
/**
Extend this selection with an extra range.
*/
addRange(range, main = true) {
return EditorSelection$1.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1);
}
/**
Replace a given range with another range, and then normalize the
selection to merge and sort ranges if necessary.
*/
replaceRange(range, which = this.mainIndex) {
let ranges = this.ranges.slice();
ranges[which] = range;
return EditorSelection$1.create(ranges, this.mainIndex);
}
/**
Convert this selection to an object that can be serialized to
JSON.
*/
toJSON() {
return {
ranges: this.ranges.map(r => r.toJSON()),
main: this.mainIndex
};
}
/**
Create a selection from a JSON representation.
*/
static fromJSON(json$1) {
if (!json$1 || !Array.isArray(json$1.ranges) || typeof json$1.main != "number" || json$1.main >= json$1.ranges.length) throw new RangeError("Invalid JSON representation for EditorSelection");
return new EditorSelection$1(json$1.ranges.map(r => SelectionRange.fromJSON(r)), json$1.main);
}
/**
Create a selection holding a single range.
*/
static single(anchor, head = anchor) {
return new EditorSelection$1([EditorSelection$1.range(anchor, head)], 0);
}
/**
Sort and merge the given set of ranges, creating a valid
selection.
*/
static create(ranges, mainIndex = 0) {
if (ranges.length == 0) throw new RangeError("A selection needs at least one range");
for (let pos = 0, i$1 = 0; i$1 < ranges.length; i$1++) {
let range = ranges[i$1];
if (range.empty ? range.from <= pos : range.from < pos) return EditorSelection$1.normalized(ranges.slice(), mainIndex);
pos = range.to;
}
return new EditorSelection$1(ranges, mainIndex);
}
/**
Create a cursor selection range at the given position. You can
safely ignore the optional arguments in most situations.
*/
static cursor(pos, assoc = 0, bidiLevel, goalColumn) {
return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)) | (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6);
}
/**
Create a selection range.
*/
static range(anchor, head, goalColumn, bidiLevel) {
let flags = (goalColumn !== null && goalColumn !== void 0 ? goalColumn : 16777215) << 6 | (bidiLevel == null ? 7 : Math.min(6, bidiLevel));
return head < anchor ? SelectionRange.create(head, anchor, 48 | flags) : SelectionRange.create(anchor, head, (head > anchor ? 8 : 0) | flags);
}
/**
@internal
*/
static normalized(ranges, mainIndex = 0) {
let main = ranges[mainIndex];
ranges.sort((a, b) => a.from - b.from);
mainIndex = ranges.indexOf(main);
for (let i$1 = 1; i$1 < ranges.length; i$1++) {
let range = ranges[i$1],
prev = ranges[i$1 - 1];
if (range.empty ? range.from <= prev.to : range.from < prev.to) {
let from = prev.from,
to = Math.max(range.to, prev.to);
if (i$1 <= mainIndex) mainIndex--;
ranges.splice(--i$1, 2, range.anchor > range.head ? EditorSelection$1.range(to, from) : EditorSelection$1.range(from, to));
}
}
return new EditorSelection$1(ranges, mainIndex);
}
};
nextID = 0;
/**
A facet is a labeled value that is associated with an editor
state. It takes inputs from any number of extensions, and combines
those into a single output value.
Examples of uses of facets are the [tab
size](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize), [editor
attributes](https://codemirror.net/6/docs/ref/#view.EditorView^editorAttributes), and [update
listeners](https://codemirror.net/6/docs/ref/#view.EditorView^updateListener).
Note that `Facet` instances can be used anywhere where
[`FacetReader`](https://codemirror.net/6/docs/ref/#state.FacetReader) is expected.
*/
Facet = class Facet {
constructor(combine, compareInput, compare$2, isStatic, enables) {
this.combine = combine;
this.compareInput = compareInput;
this.compare = compare$2;
this.isStatic = isStatic;
/**
@internal
*/
this.id = nextID++;
this.default = combine([]);
this.extensions = typeof enables == "function" ? enables(this) : enables;
}
/**
Returns a facet reader for this facet, which can be used to
[read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it.
*/
get reader() {
return this;
}
/**
Define a new facet.
*/
static define(config$1 = {}) {
return new Facet(config$1.combine || (a => a), config$1.compareInput || ((a, b) => a === b), config$1.compare || (!config$1.combine ? sameArray : (a, b) => a === b), !!config$1.static, config$1.enables);
}
/**
Returns an extension that adds the given value to this facet.
*/
of(value) {
return new FacetProvider([], this, 0, value);
}
/**
Create an extension that computes a value for the facet from a
state. You must take care to declare the parts of the state that
this value depends on, since your function is only called again
for a new state when one of those parts changed.
In cases where your value depends only on a single field, you'll
want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead.
*/
compute(deps, get) {
if (this.isStatic) throw new Error("Can't compute a static facet");
return new FacetProvider(deps, this, 1, get);
}
/**
Create an extension that computes zero or more values for this
facet from a state.
*/
computeN(deps, get) {
if (this.isStatic) throw new Error("Can't compute a static facet");
return new FacetProvider(deps, this, 2, get);
}
from(field, get) {
if (!get) get = x => x;
return this.compute([field], state => get(state.field(field)));
}
};
FacetProvider = class {
constructor(dependencies, facet, type, value) {
this.dependencies = dependencies;
this.facet = facet;
this.type = type;
this.value = value;
this.id = nextID++;
}
dynamicSlot(addresses) {
var _a$2;
let getter = this.value;
let compare$2 = this.facet.compareInput;
let id$1 = this.id,
idx = addresses[id$1] >> 1,
multi = this.type == 2;
let depDoc = false,
depSel = false,
depAddrs = [];
for (let dep of this.dependencies) if (dep == "doc") depDoc = true;else if (dep == "selection") depSel = true;else if ((((_a$2 = addresses[dep.id]) !== null && _a$2 !== void 0 ? _a$2 : 1) & 1) == 0) depAddrs.push(addresses[dep.id]);
return {
create(state) {
state.values[idx] = getter(state);
return 1;
},
update(state, tr) {
if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state, depAddrs)) {
let newVal = getter(state);
if (multi ? !compareArray(newVal, state.values[idx], compare$2) : !compare$2(newVal, state.values[idx])) {
state.values[idx] = newVal;
return 1;
}
}
return 0;
},
reconfigure: (state, oldState) => {
let newVal,
oldAddr = oldState.config.address[id$1];
if (oldAddr != null) {
let oldVal = getAddr(oldState, oldAddr);
if (this.dependencies.every(dep => {
return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true;
}) || (multi ? compareArray(newVal = getter(state), oldVal, compare$2) : compare$2(newVal = getter(state), oldVal))) {
state.values[idx] = oldVal;
return 0;
}
} else newVal = getter(state);
state.values[idx] = newVal;
return 1;
}
};
}
};
initField = /* @__PURE__ */Facet.define({
static: true
});
/**
Fields can store additional information in an editor state, and
keep it in sync with the rest of the state.
*/
StateField = class StateField {
constructor(id$1, createF, updateF, compareF, spec) {
this.id = id$1;
this.createF = createF;
this.updateF = updateF;
this.compareF = compareF;
this.spec = spec;
/**
@internal
*/
this.provides = void 0;
}
/**
Define a state field.
*/
static define(config$1) {
let field = new StateField(nextID++, config$1.create, config$1.update, config$1.compare || ((a, b) => a === b), config$1);
if (config$1.provide) field.provides = config$1.provide(field);
return field;
}
create(state) {
let init = state.facet(initField).find(i$1 => i$1.field == this);
return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state);
}
/**
@internal
*/
slot(addresses) {
let idx = addresses[this.id] >> 1;
return {
create: state => {
state.values[idx] = this.create(state);
return 1;
},
update: (state, tr) => {
let oldVal = state.values[idx];
let value = this.updateF(oldVal, tr);
if (this.compareF(oldVal, value)) return 0;
state.values[idx] = value;
return 1;
},
reconfigure: (state, oldState) => {
if (oldState.config.address[this.id] != null) {
state.values[idx] = oldState.field(this);
return 0;
}
state.values[idx] = this.create(state);
return 1;
}
};
}
/**
Returns an extension that enables this field and overrides the
way it is initialized. Can be useful when you need to provide a
non-default starting value for the field.
*/
init(create) {
return [this, initField.of({
field: this,
create
})];
}
/**
State field instances can be used as
[`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a
given state.
*/
get extension() {
return this;
}
};
Prec_ = {
lowest: 4,
low: 3,
default: 2,
high: 1,
highest: 0
};
Prec$1 = {
highest: /* @__PURE__ */prec(Prec_.highest),
high: /* @__PURE__ */prec(Prec_.high),
default: /* @__PURE__ */prec(Prec_.default),
low: /* @__PURE__ */prec(Prec_.low),
lowest: /* @__PURE__ */prec(Prec_.lowest)
};
PrecExtension = class {
constructor(inner, prec$2) {
this.inner = inner;
this.prec = prec$2;
}
};
/**
Extension compartments can be used to make a configuration
dynamic. By [wrapping](https://codemirror.net/6/docs/ref/#state.Compartment.of) part of your
configuration in a compartment, you can later
[replace](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure) that part through a
transaction.
*/
Compartment = class Compartment {
/**
Create an instance of this compartment to add to your [state
configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions).
*/
of(ext) {
return new CompartmentInstance(this, ext);
}
/**
Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that
reconfigures this compartment.
*/
reconfigure(content$1) {
return Compartment.reconfigure.of({
compartment: this,
extension: content$1
});
}
/**
Get the current content of the compartment in the state, or
`undefined` if it isn't present.
*/
get(state) {
return state.config.compartments.get(this);
}
};
CompartmentInstance = class {
constructor(compartment, inner) {
this.compartment = compartment;
this.inner = inner;
}
};
Configuration = class Configuration {
constructor(base$1, compartments, dynamicSlots, address, staticValues, facets) {
this.base = base$1;
this.compartments = compartments;
this.dynamicSlots = dynamicSlots;
this.address = address;
this.staticValues = staticValues;
this.facets = facets;
this.statusTemplate = [];
while (this.statusTemplate.length < dynamicSlots.length) this.statusTemplate.push(0);
}
staticFacet(facet) {
let addr = this.address[facet.id];
return addr == null ? facet.default : this.staticValues[addr >> 1];
}
static resolve(base$1, compartments, oldState) {
let fields = [];
let facets = Object.create(null);
let newCompartments = /* @__PURE__ */new Map();
for (let ext of flatten(base$1, compartments, newCompartments)) if (ext instanceof StateField) fields.push(ext);else (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext);
let address = Object.create(null);
let staticValues = [];
let dynamicSlots = [];
for (let field of fields) {
address[field.id] = dynamicSlots.length << 1;
dynamicSlots.push(a => field.slot(a));
}
let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets;
for (let id$1 in facets) {
let providers = facets[id$1],
facet = providers[0].facet;
let oldProviders = oldFacets && oldFacets[id$1] || [];
if (providers.every(p => p.type == 0)) {
address[facet.id] = staticValues.length << 1 | 1;
if (sameArray(oldProviders, providers)) staticValues.push(oldState.facet(facet));else {
let value = facet.combine(providers.map(p => p.value));
staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value);
}
} else {
for (let p of providers) if (p.type == 0) {
address[p.id] = staticValues.length << 1 | 1;
staticValues.push(p.value);
} else {
address[p.id] = dynamicSlots.length << 1;
dynamicSlots.push(a => p.dynamicSlot(a));
}
address[facet.id] = dynamicSlots.length << 1;
dynamicSlots.push(a => dynamicFacetSlot(a, facet, providers));
}
}
return new Configuration(base$1, newCompartments, dynamicSlots.map(f => f(address)), address, staticValues, facets);
}
};
languageData = /* @__PURE__ */Facet.define();
allowMultipleSelections = /* @__PURE__ */Facet.define({
combine: values => values.some(v => v),
static: true
});
lineSeparator = /* @__PURE__ */Facet.define({
combine: values => values.length ? values[0] : void 0,
static: true
});
changeFilter = /* @__PURE__ */Facet.define();
transactionFilter = /* @__PURE__ */Facet.define();
transactionExtender = /* @__PURE__ */Facet.define();
readOnly = /* @__PURE__ */Facet.define({
combine: values => values.length ? values[0] : false
});
/**
Annotations are tagged values that are used to add metadata to
transactions in an extensible way. They should be used to model
things that effect the entire transaction (such as its [time
stamp](https://codemirror.net/6/docs/ref/#state.Transaction^time) or information about its
[origin](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent)). For effects that happen
_alongside_ the other changes made by the transaction, [state
effects](https://codemirror.net/6/docs/ref/#state.StateEffect) are more appropriate.
*/
Annotation$1 = class {
/**
@internal
*/
constructor(type, value) {
this.type = type;
this.value = value;
}
/**
Define a new type of annotation.
*/
static define() {
return new AnnotationType();
}
};
/**
Marker that identifies a type of [annotation](https://codemirror.net/6/docs/ref/#state.Annotation).
*/
AnnotationType = class {
/**
Create an instance of this annotation.
*/
of(value) {
return new Annotation$1(this, value);
}
};
/**
Representation of a type of state effect. Defined with
[`StateEffect.define`](https://codemirror.net/6/docs/ref/#state.StateEffect^define).
*/
StateEffectType = class {
/**
@internal
*/
constructor(map) {
this.map = map;
}
/**
Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this
type.
*/
of(value) {
return new StateEffect(this, value);
}
};
/**
State effects can be used to represent additional effects
associated with a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction.effects). They
are often useful to model changes to custom [state
fields](https://codemirror.net/6/docs/ref/#state.StateField), when those changes aren't implicit in
document or selection changes.
*/
StateEffect = class StateEffect {
/**
@internal
*/
constructor(type, value) {
this.type = type;
this.value = value;
}
/**
Map this effect through a position mapping. Will return
`undefined` when that ends up deleting the effect.
*/
map(mapping) {
let mapped = this.type.map(this.value, mapping);
return mapped === void 0 ? void 0 : mapped == this.value ? this : new StateEffect(this.type, mapped);
}
/**
Tells you whether this effect object is of a given
[type](https://codemirror.net/6/docs/ref/#state.StateEffectType).
*/
is(type) {
return this.type == type;
}
/**
Define a new effect type. The type parameter indicates the type
of values that his effect holds. It should be a type that
doesn't include `undefined`, since that is used in
[mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is
removed.
*/
static define(spec = {}) {
return new StateEffectType(spec.map || (v => v));
}
/**
Map an array of effects through a change set.
*/
static mapEffects(effects, mapping) {
if (!effects.length) return effects;
let result = [];
for (let effect of effects) {
let mapped = effect.map(mapping);
if (mapped) result.push(mapped);
}
return result;
}
};
/**
This effect can be used to reconfigure the root extensions of
the editor. Doing this will discard any extensions
[appended](https://codemirror.net/6/docs/ref/#state.StateEffect^appendConfig), but does not reset
the content of [reconfigured](https://codemirror.net/6/docs/ref/#state.Compartment.reconfigure)
compartments.
*/
StateEffect.reconfigure = /* @__PURE__ */StateEffect.define();
/**
Append extensions to the top-level configuration of the editor.
*/
StateEffect.appendConfig = /* @__PURE__ */StateEffect.define();
/**
Changes to the editor state are grouped into transactions.
Typically, a user action creates a single transaction, which may
contain any number of document changes, may change the selection,
or have other effects. Create a transaction by calling
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update), or immediately
dispatch one by calling
[`EditorView.dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch).
*/
Transaction$1 = class Transaction$1 {
constructor(startState, changes, selection, effects, annotations, scrollIntoView$3) {
this.startState = startState;
this.changes = changes;
this.selection = selection;
this.effects = effects;
this.annotations = annotations;
this.scrollIntoView = scrollIntoView$3;
/**
@internal
*/
this._doc = null;
/**
@internal
*/
this._state = null;
if (selection) checkSelection(selection, changes.newLength);
if (!annotations.some(a => a.type == Transaction$1.time)) this.annotations = annotations.concat(Transaction$1.time.of(Date.now()));
}
/**
@internal
*/
static create(startState, changes, selection, effects, annotations, scrollIntoView$3) {
return new Transaction$1(startState, changes, selection, effects, annotations, scrollIntoView$3);
}
/**
The new document produced by the transaction. Contrary to
[`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't
force the entire new state to be computed right away, so it is
recommended that [transaction
filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter
when they need to look at the new document.
*/
get newDoc() {
return this._doc || (this._doc = this.changes.apply(this.startState.doc));
}
/**
The new selection produced by the transaction. If
[`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined,
this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's
current selection through the changes made by the transaction.
*/
get newSelection() {
return this.selection || this.startState.selection.map(this.changes);
}
/**
The new state created by the transaction. Computed on demand
(but retained for subsequent access), so it is recommended not to
access it in [transaction
filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible.
*/
get state() {
if (!this._state) this.startState.applyTransaction(this);
return this._state;
}
/**
Get the value of the given annotation type, if any.
*/
annotation(type) {
for (let ann of this.annotations) if (ann.type == type) return ann.value;
}
/**
Indicates whether the transaction changed the document.
*/
get docChanged() {
return !this.changes.empty;
}
/**
Indicates whether this transaction reconfigures the state
(through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or
with a top-level configuration
[effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure).
*/
get reconfigured() {
return this.startState.config != this.state.config;
}
/**
Returns true if the transaction has a [user
event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to
or more specific than `event`. For example, if the transaction
has `"select.pointer"` as user event, `"select"` and
`"select.pointer"` will match it.
*/
isUserEvent(event) {
let e = this.annotation(Transaction$1.userEvent);
return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == "."));
}
};
/**
Annotation used to store transaction timestamps. Automatically
added to every transaction, holding `Date.now()`.
*/
Transaction$1.time = /* @__PURE__ */Annotation$1.define();
/**
Annotation used to associate a transaction with a user interface
event. Holds a string identifying the event, using a
dot-separated format to support attaching more specific
information. The events used by the core libraries are:
- `"input"` when content is entered
- `"input.type"` for typed input
- `"input.type.compose"` for composition
- `"input.paste"` for pasted input
- `"input.drop"` when adding content with drag-and-drop
- `"input.complete"` when autocompleting
- `"delete"` when the user deletes content
- `"delete.selection"` when deleting the selection
- `"delete.forward"` when deleting forward from the selection
- `"delete.backward"` when deleting backward from the selection
- `"delete.cut"` when cutting to the clipboard
- `"move"` when content is moved
- `"move.drop"` when content is moved within the editor through drag-and-drop
- `"select"` when explicitly changing the selection
- `"select.pointer"` when selecting with a mouse or other pointing device
- `"undo"` and `"redo"` for history actions
Use [`isUserEvent`](https://codemirror.net/6/docs/ref/#state.Transaction.isUserEvent) to check
whether the annotation matches a given event.
*/
Transaction$1.userEvent = /* @__PURE__ */Annotation$1.define();
/**
Annotation indicating whether a transaction should be added to
the undo history or not.
*/
Transaction$1.addToHistory = /* @__PURE__ */Annotation$1.define();
/**
Annotation indicating (when present and true) that a transaction
represents a change made by some other actor, not the user. This
is used, for example, to tag other people's changes in
collaborative editing.
*/
Transaction$1.remote = /* @__PURE__ */Annotation$1.define();
none = [];
CharCategory$1 = /* @__PURE__ */function (CharCategory$2) {
/**
Word characters.
*/
CharCategory$2[CharCategory$2["Word"] = 0] = "Word";
/**
Whitespace.
*/
CharCategory$2[CharCategory$2["Space"] = 1] = "Space";
/**
Anything else.
*/
CharCategory$2[CharCategory$2["Other"] = 2] = "Other";
return CharCategory$2;
}(CharCategory$1 || (CharCategory$1 = {}));
nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
try {
wordChar = /* @__PURE__ */new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u");
} catch (_) {}
EditorState$1 = class EditorState$1 {
constructor(config$1, doc$2, selection, values, computeSlot, tr) {
this.config = config$1;
this.doc = doc$2;
this.selection = selection;
this.values = values;
this.status = config$1.statusTemplate.slice();
this.computeSlot = computeSlot;
if (tr) tr._state = this;
for (let i$1 = 0; i$1 < this.config.dynamicSlots.length; i$1++) ensureAddr(this, i$1 << 1);
this.computeSlot = null;
}
field(field, require$1 = true) {
let addr = this.config.address[field.id];
if (addr == null) {
if (require$1) throw new RangeError("Field is not present in this state");
return;
}
ensureAddr(this, addr);
return getAddr(this, addr);
}
/**
Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this
state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec)
can be passed. Unless
[`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the
[changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec
are assumed to start in the _current_ document (not the document
produced by previous specs), and its
[selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and
[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer
to the document created by its _own_ changes. The resulting
transaction contains the combined effect of all the different
specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later
specs take precedence over earlier ones.
*/
update(...specs) {
return resolveTransaction(this, specs, true);
}
/**
@internal
*/
applyTransaction(tr) {
let conf = this.config,
{
base: base$1,
compartments
} = conf;
for (let effect of tr.effects) if (effect.is(Compartment.reconfigure)) {
if (conf) {
compartments = /* @__PURE__ */new Map();
conf.compartments.forEach((val, key) => compartments.set(key, val));
conf = null;
}
compartments.set(effect.value.compartment, effect.value.extension);
} else if (effect.is(StateEffect.reconfigure)) {
conf = null;
base$1 = effect.value;
} else if (effect.is(StateEffect.appendConfig)) {
conf = null;
base$1 = asArray(base$1).concat(effect.value);
}
let startValues;
if (!conf) {
conf = Configuration.resolve(base$1, compartments, this);
startValues = new EditorState$1(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null).values;
} else startValues = tr.startState.values.slice();
let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle();
new EditorState$1(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr);
}
/**
Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that
replaces every selection range with the given content.
*/
replaceSelection(text) {
if (typeof text == "string") text = this.toText(text);
return this.changeByRange(range => ({
changes: {
from: range.from,
to: range.to,
insert: text
},
range: EditorSelection$1.cursor(range.from + text.length)
}));
}
/**
Create a set of changes and a new selection by running the given
function for each range in the active selection. The function
can return an optional set of changes (in the coordinate space
of the start document), plus an updated range (in the coordinate
space of the document produced by the call's own changes). This
method will merge all the changes and ranges into a single
changeset and selection, and return it as a [transaction
spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to
[`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update).
*/
changeByRange(f) {
let sel = this.selection;
let result1 = f(sel.ranges[0]);
let changes = this.changes(result1.changes),
ranges = [result1.range];
let effects = asArray(result1.effects);
for (let i$1 = 1; i$1 < sel.ranges.length; i$1++) {
let result = f(sel.ranges[i$1]);
let newChanges = this.changes(result.changes),
newMapped = newChanges.map(changes);
for (let j = 0; j < i$1; j++) ranges[j] = ranges[j].map(newMapped);
let mapBy = changes.mapDesc(newChanges, true);
ranges.push(result.range.map(mapBy));
changes = changes.compose(newMapped);
effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy));
}
return {
changes,
selection: EditorSelection$1.create(ranges, sel.mainIndex),
effects
};
}
/**
Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change
description, taking the state's document length and line
separator into account.
*/
changes(spec = []) {
if (spec instanceof ChangeSet$1) return spec;
return ChangeSet$1.of(spec, this.doc.length, this.facet(EditorState$1.lineSeparator));
}
/**
Using the state's [line
separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a
[`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string.
*/
toText(string$1) {
return Text$1.of(string$1.split(this.facet(EditorState$1.lineSeparator) || DefaultSplit));
}
/**
Return the given range of the document as a string.
*/
sliceDoc(from = 0, to = this.doc.length) {
return this.doc.sliceString(from, to, this.lineBreak);
}
/**
Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet).
*/
facet(facet) {
let addr = this.config.address[facet.id];
if (addr == null) return facet.default;
ensureAddr(this, addr);
return getAddr(this, addr);
}
/**
Convert this state to a JSON-serializable object. When custom
fields should be serialized, you can pass them in as an object
mapping property names (in the resulting object, which should
not use `doc` or `selection`) to fields.
*/
toJSON(fields) {
let result = {
doc: this.sliceDoc(),
selection: this.selection.toJSON()
};
if (fields) for (let prop in fields) {
let value = fields[prop];
if (value instanceof StateField && this.config.address[value.id] != null) result[prop] = value.spec.toJSON(this.field(fields[prop]), this);
}
return result;
}
/**
Deserialize a state from its JSON representation. When custom
fields should be deserialized, pass the same object you passed
to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as
third argument.
*/
static fromJSON(json$1, config$1 = {}, fields) {
if (!json$1 || typeof json$1.doc != "string") throw new RangeError("Invalid JSON representation for EditorState");
let fieldInit = [];
if (fields) {
for (let prop in fields) if (Object.prototype.hasOwnProperty.call(json$1, prop)) {
let field = fields[prop],
value = json$1[prop];
fieldInit.push(field.init(state => field.spec.fromJSON(value, state)));
}
}
return EditorState$1.create({
doc: json$1.doc,
selection: EditorSelection$1.fromJSON(json$1.selection),
extensions: config$1.extensions ? fieldInit.concat([config$1.extensions]) : fieldInit
});
}
/**
Create a new state. You'll usually only need this when
initializing an editor—updated states are created by applying
transactions.
*/
static create(config$1 = {}) {
let configuration = Configuration.resolve(config$1.extensions || [], /* @__PURE__ */new Map());
let doc$2 = config$1.doc instanceof Text$1 ? config$1.doc : Text$1.of((config$1.doc || "").split(configuration.staticFacet(EditorState$1.lineSeparator) || DefaultSplit));
let selection = !config$1.selection ? EditorSelection$1.single(0) : config$1.selection instanceof EditorSelection$1 ? config$1.selection : EditorSelection$1.single(config$1.selection.anchor, config$1.selection.head);
checkSelection(selection, doc$2.length);
if (!configuration.staticFacet(allowMultipleSelections)) selection = selection.asSingle();
return new EditorState$1(configuration, doc$2, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null);
}
/**
The size (in columns) of a tab in the document, determined by
the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet.
*/
get tabSize() {
return this.facet(EditorState$1.tabSize);
}
/**
Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator)
string for this state.
*/
get lineBreak() {
return this.facet(EditorState$1.lineSeparator) || "\n";
}
/**
Returns true when the editor is
[configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only.
*/
get readOnly() {
return this.facet(readOnly);
}
/**
Look up a translation for the given phrase (via the
[`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the
original string if no translation is found.
If additional arguments are passed, they will be inserted in
place of markers like `$1` (for the first value) and `$2`, etc.
A single `$` is equivalent to `$1`, and `$$` will produce a
literal dollar sign.
*/
phrase(phrase$1, ...insert$2) {
for (let map of this.facet(EditorState$1.phrases)) if (Object.prototype.hasOwnProperty.call(map, phrase$1)) {
phrase$1 = map[phrase$1];
break;
}
if (insert$2.length) phrase$1 = phrase$1.replace(/\$(\$|\d*)/g, (m, i$1) => {
if (i$1 == "$") return "$";
let n = +(i$1 || 1);
return !n || n > insert$2.length ? m : insert$2[n - 1];
});
return phrase$1;
}
/**
Find the values for a given language data field, provided by the
the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet.
Examples of language data fields are...
- [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying
comment syntax.
- [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override)
for providing language-specific completion sources.
- [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding
characters that should be considered part of words in this
language.
- [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls
bracket closing behavior.
*/
languageDataAt(name$1, pos, side = -1) {
let values = [];
for (let provider of this.facet(languageData)) for (let result of provider(this, pos, side)) if (Object.prototype.hasOwnProperty.call(result, name$1)) values.push(result[name$1]);
return values;
}
/**
Return a function that can categorize strings (expected to
represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak))
into one of:
- Word (contains an alphanumeric character or a character
explicitly listed in the local language's `"wordChars"`
language data, which should be a string)
- Space (contains only whitespace)
- Other (anything else)
*/
charCategorizer(at) {
return makeCategorizer(this.languageDataAt("wordChars", at).join(""));
}
/**
Find the word at the given position, meaning the range
containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters
around it. If no word characters are adjacent to the position,
this returns null.
*/
wordAt(pos) {
let {
text,
from,
length
} = this.doc.lineAt(pos);
let cat = this.charCategorizer(pos);
let start = pos - from,
end = pos - from;
while (start > 0) {
let prev = findClusterBreak$1(text, start, false);
if (cat(text.slice(prev, start)) != CharCategory$1.Word) break;
start = prev;
}
while (end < length) {
let next = findClusterBreak$1(text, end);
if (cat(text.slice(end, next)) != CharCategory$1.Word) break;
end = next;
}
return start == end ? null : EditorSelection$1.range(start + from, end + from);
}
};
/**
A facet that, when enabled, causes the editor to allow multiple
ranges to be selected. Be careful though, because by default the
editor relies on the native DOM selection, which cannot handle
multiple selections. An extension like
[`drawSelection`](https://codemirror.net/6/docs/ref/#view.drawSelection) can be used to make
secondary selections visible to the user.
*/
EditorState$1.allowMultipleSelections = allowMultipleSelections;
/**
Configures the tab size to use in this state. The first
(highest-precedence) value of the facet is used. If no value is
given, this defaults to 4.
*/
EditorState$1.tabSize = /* @__PURE__ */Facet.define({
combine: values => values.length ? values[0] : 4
});
/**
The line separator to use. By default, any of `"\n"`, `"\r\n"`
and `"\r"` is treated as a separator when splitting lines, and
lines are joined with `"\n"`.
When you configure a value here, only that precise separator
will be used, allowing you to round-trip documents through the
editor without normalizing line separators.
*/
EditorState$1.lineSeparator = lineSeparator;
/**
This facet controls the value of the
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) getter, which is
consulted by commands and extensions that implement editing
functionality to determine whether they should apply. It
defaults to false, but when its highest-precedence value is
`true`, such functionality disables itself.
Not to be confused with
[`EditorView.editable`](https://codemirror.net/6/docs/ref/#view.EditorView^editable), which
controls whether the editor's DOM is set to be editable (and
thus focusable).
*/
EditorState$1.readOnly = readOnly;
/**
Registers translation phrases. The
[`phrase`](https://codemirror.net/6/docs/ref/#state.EditorState.phrase) method will look through
all objects registered with this facet to find translations for
its argument.
*/
EditorState$1.phrases = /* @__PURE__ */Facet.define({
compare(a, b) {
let kA = Object.keys(a),
kB = Object.keys(b);
return kA.length == kB.length && kA.every(k => a[k] == b[k]);
}
});
/**
A facet used to register [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) providers.
*/
EditorState$1.languageData = languageData;
/**
Facet used to register change filters, which are called for each
transaction (unless explicitly
[disabled](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter)), and can suppress
part of the transaction's changes.
Such a function can return `true` to indicate that it doesn't
want to do anything, `false` to completely stop the changes in
the transaction, or a set of ranges in which changes should be
suppressed. Such ranges are represented as an array of numbers,
with each pair of two numbers indicating the start and end of a
range. So for example `[10, 20, 100, 110]` suppresses changes
between 10 and 20, and between 100 and 110.
*/
EditorState$1.changeFilter = changeFilter;
/**
Facet used to register a hook that gets a chance to update or
replace transaction specs before they are applied. This will
only be applied for transactions that don't have
[`filter`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter) set to `false`. You
can either return a single transaction spec (possibly the input
transaction), or an array of specs (which will be combined in
the same way as the arguments to
[`EditorState.update`](https://codemirror.net/6/docs/ref/#state.EditorState.update)).
When possible, it is recommended to avoid accessing
[`Transaction.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state) in a filter,
since it will force creation of a state that will then be
discarded again, if the transaction is actually filtered.
(This functionality should be used with care. Indiscriminately
modifying transaction is likely to break something or degrade
the user experience.)
*/
EditorState$1.transactionFilter = transactionFilter;
/**
This is a more limited form of
[`transactionFilter`](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter),
which can only add
[annotations](https://codemirror.net/6/docs/ref/#state.TransactionSpec.annotations) and
[effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects). _But_, this type
of filter runs even if the transaction has disabled regular
[filtering](https://codemirror.net/6/docs/ref/#state.TransactionSpec.filter), making it suitable
for effects that don't need to touch the changes or selection,
but do want to process every transaction.
Extenders run _after_ filters, when both are present.
*/
EditorState$1.transactionExtender = transactionExtender;
Compartment.reconfigure = /* @__PURE__ */StateEffect.define();
/**
Each range is associated with a value, which must inherit from
this class.
*/
RangeValue$1 = class {
/**
Compare this value with another value. Used when comparing
rangesets. The default implementation compares by identity.
Unless you are only creating a fixed number of unique instances
of your value type, it is a good idea to implement this
properly.
*/
eq(other) {
return this == other;
}
/**
Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value.
*/
range(from, to = from) {
return Range.create(from, to, this);
}
};
RangeValue$1.prototype.startSide = RangeValue$1.prototype.endSide = 0;
RangeValue$1.prototype.point = false;
RangeValue$1.prototype.mapMode = MapMode$1.TrackDel;
/**
A range associates a value with a range of positions.
*/
Range = class Range {
constructor(from, to, value) {
this.from = from;
this.to = to;
this.value = value;
}
/**
@internal
*/
static create(from, to, value) {
return new Range(from, to, value);
}
};
Chunk = class Chunk {
constructor(from, to, value, maxPoint) {
this.from = from;
this.to = to;
this.value = value;
this.maxPoint = maxPoint;
}
get length() {
return this.to[this.to.length - 1];
}
findIndex(pos, side, end, startAt = 0) {
let arr = end ? this.to : this.from;
for (let lo = startAt, hi = arr.length;;) {
if (lo == hi) return lo;
let mid = lo + hi >> 1;
let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side;
if (mid == lo) return diff >= 0 ? lo : hi;
if (diff >= 0) hi = mid;else lo = mid + 1;
}
}
between(offset, from, to, f) {
for (let i$1 = this.findIndex(from, -1e9, true), e = this.findIndex(to, 1e9, false, i$1); i$1 < e; i$1++) if (f(this.from[i$1] + offset, this.to[i$1] + offset, this.value[i$1]) === false) return false;
}
map(offset, changes) {
let value = [],
from = [],
to = [],
newPos = -1,
maxPoint = -1;
for (let i$1 = 0; i$1 < this.value.length; i$1++) {
let val = this.value[i$1],
curFrom = this.from[i$1] + offset,
curTo = this.to[i$1] + offset,
newFrom,
newTo;
if (curFrom == curTo) {
let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode);
if (mapped == null) continue;
newFrom = newTo = mapped;
if (val.startSide != val.endSide) {
newTo = changes.mapPos(curFrom, val.endSide);
if (newTo < newFrom) continue;
}
} else {
newFrom = changes.mapPos(curFrom, val.startSide);
newTo = changes.mapPos(curTo, val.endSide);
if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) continue;
}
if ((newTo - newFrom || val.endSide - val.startSide) < 0) continue;
if (newPos < 0) newPos = newFrom;
if (val.point) maxPoint = Math.max(maxPoint, newTo - newFrom);
value.push(val);
from.push(newFrom - newPos);
to.push(newTo - newPos);
}
return {
mapped: value.length ? new Chunk(from, to, value, maxPoint) : null,
pos: newPos
};
}
};
/**
A range set stores a collection of [ranges](https://codemirror.net/6/docs/ref/#state.Range) in a
way that makes them efficient to [map](https://codemirror.net/6/docs/ref/#state.RangeSet.map) and
[update](https://codemirror.net/6/docs/ref/#state.RangeSet.update). This is an immutable data
structure.
*/
RangeSet = class RangeSet {
constructor(chunkPos, chunk, nextLayer, maxPoint) {
this.chunkPos = chunkPos;
this.chunk = chunk;
this.nextLayer = nextLayer;
this.maxPoint = maxPoint;
}
/**
@internal
*/
static create(chunkPos, chunk, nextLayer, maxPoint) {
return new RangeSet(chunkPos, chunk, nextLayer, maxPoint);
}
/**
@internal
*/
get length() {
let last = this.chunk.length - 1;
return last < 0 ? 0 : Math.max(this.chunkEnd(last), this.nextLayer.length);
}
/**
The number of ranges in the set.
*/
get size() {
if (this.isEmpty) return 0;
let size = this.nextLayer.size;
for (let chunk of this.chunk) size += chunk.value.length;
return size;
}
/**
@internal
*/
chunkEnd(index) {
return this.chunkPos[index] + this.chunk[index].length;
}
/**
Update the range set, optionally adding new ranges or filtering
out existing ones.
(Note: The type parameter is just there as a kludge to work
around TypeScript variance issues that prevented `RangeSet<X>`
from being a subtype of `RangeSet<Y>` when `X` is a subtype of
`Y`.)
*/
update(updateSpec) {
let {
add: add$1 = [],
sort = false,
filterFrom = 0,
filterTo = this.length
} = updateSpec;
let filter = updateSpec.filter;
if (add$1.length == 0 && !filter) return this;
if (sort) add$1 = add$1.slice().sort(cmpRange);
if (this.isEmpty) return add$1.length ? RangeSet.of(add$1) : this;
let cur$1 = new LayerCursor(this, null, -1).goto(0),
i$1 = 0,
spill = [];
let builder = new RangeSetBuilder();
while (cur$1.value || i$1 < add$1.length) if (i$1 < add$1.length && (cur$1.from - add$1[i$1].from || cur$1.startSide - add$1[i$1].value.startSide) >= 0) {
let range = add$1[i$1++];
if (!builder.addInner(range.from, range.to, range.value)) spill.push(range);
} else if (cur$1.rangeIndex == 1 && cur$1.chunkIndex < this.chunk.length && (i$1 == add$1.length || this.chunkEnd(cur$1.chunkIndex) < add$1[i$1].from) && (!filter || filterFrom > this.chunkEnd(cur$1.chunkIndex) || filterTo < this.chunkPos[cur$1.chunkIndex]) && builder.addChunk(this.chunkPos[cur$1.chunkIndex], this.chunk[cur$1.chunkIndex])) cur$1.nextChunk();else {
if (!filter || filterFrom > cur$1.to || filterTo < cur$1.from || filter(cur$1.from, cur$1.to, cur$1.value)) {
if (!builder.addInner(cur$1.from, cur$1.to, cur$1.value)) spill.push(Range.create(cur$1.from, cur$1.to, cur$1.value));
}
cur$1.next();
}
return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? RangeSet.empty : this.nextLayer.update({
add: spill,
filter,
filterFrom,
filterTo
}));
}
/**
Map this range set through a set of changes, return the new set.
*/
map(changes) {
if (changes.empty || this.isEmpty) return this;
let chunks = [],
chunkPos = [],
maxPoint = -1;
for (let i$1 = 0; i$1 < this.chunk.length; i$1++) {
let start = this.chunkPos[i$1],
chunk = this.chunk[i$1];
let touch = changes.touchesRange(start, start + chunk.length);
if (touch === false) {
maxPoint = Math.max(maxPoint, chunk.maxPoint);
chunks.push(chunk);
chunkPos.push(changes.mapPos(start));
} else if (touch === true) {
let {
mapped,
pos
} = chunk.map(start, changes);
if (mapped) {
maxPoint = Math.max(maxPoint, mapped.maxPoint);
chunks.push(mapped);
chunkPos.push(pos);
}
}
}
let next = this.nextLayer.map(changes);
return chunks.length == 0 ? next : new RangeSet(chunkPos, chunks, next || RangeSet.empty, maxPoint);
}
/**
Iterate over the ranges that touch the region `from` to `to`,
calling `f` for each. There is no guarantee that the ranges will
be reported in any specific order. When the callback returns
`false`, iteration stops.
*/
between(from, to, f) {
if (this.isEmpty) return;
for (let i$1 = 0; i$1 < this.chunk.length; i$1++) {
let start = this.chunkPos[i$1],
chunk = this.chunk[i$1];
if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === false) return;
}
this.nextLayer.between(from, to, f);
}
/**
Iterate over the ranges in this set, in order, including all
ranges that end at or after `from`.
*/
iter(from = 0) {
return HeapCursor.from([this]).goto(from);
}
/**
@internal
*/
get isEmpty() {
return this.nextLayer == this;
}
/**
Iterate over the ranges in a collection of sets, in order,
starting from `from`.
*/
static iter(sets, from = 0) {
return HeapCursor.from(sets).goto(from);
}
/**
Iterate over two groups of sets, calling methods on `comparator`
to notify it of possible differences.
*/
static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) {
let a = oldSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
let b = newSets.filter(set => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize);
let sharedChunks = findSharedChunks(a, b, textDiff);
let sideA = new SpanCursor(a, sharedChunks, minPointSize);
let sideB = new SpanCursor(b, sharedChunks, minPointSize);
textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator));
if (textDiff.empty && textDiff.length == 0) compare(sideA, 0, sideB, 0, 0, comparator);
}
/**
Compare the contents of two groups of range sets, returning true
if they are equivalent in the given range.
*/
static eq(oldSets, newSets, from = 0, to) {
if (to == null) to = 999999999;
let a = oldSets.filter(set => !set.isEmpty && newSets.indexOf(set) < 0);
let b = newSets.filter(set => !set.isEmpty && oldSets.indexOf(set) < 0);
if (a.length != b.length) return false;
if (!a.length) return true;
let sharedChunks = findSharedChunks(a, b);
let sideA = new SpanCursor(a, sharedChunks, 0).goto(from),
sideB = new SpanCursor(b, sharedChunks, 0).goto(from);
for (;;) {
if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !sideA.point.eq(sideB.point))) return false;
if (sideA.to > to) return true;
sideA.next();
sideB.next();
}
}
/**
Iterate over a group of range sets at the same time, notifying
the iterator about the ranges covering every given piece of
content. Returns the open count (see
[`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end
of the iteration.
*/
static spans(sets, from, to, iterator, minPointSize = -1) {
let cursor = new SpanCursor(sets, null, minPointSize).goto(from),
pos = from;
let openRanges = cursor.openStart;
for (;;) {
let curTo = Math.min(cursor.to, to);
if (cursor.point) {
let active = cursor.activeForPoint(cursor.to);
let openCount = cursor.pointFrom < from ? active.length + 1 : Math.min(active.length, openRanges);
iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank);
openRanges = Math.min(cursor.openEnd(curTo), active.length);
} else if (curTo > pos) {
iterator.span(pos, curTo, cursor.active, openRanges);
openRanges = cursor.openEnd(curTo);
}
if (cursor.to > to) return openRanges + (cursor.point && cursor.to > to ? 1 : 0);
pos = cursor.to;
cursor.next();
}
}
/**
Create a range set for the given range or array of ranges. By
default, this expects the ranges to be _sorted_ (by start
position and, if two start at the same position,
`value.startSide`). You can pass `true` as second argument to
cause the method to sort them.
*/
static of(ranges, sort = false) {
let build = new RangeSetBuilder();
for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges) build.add(range.from, range.to, range.value);
return build.finish();
}
};
/**
The empty set of ranges.
*/
RangeSet.empty = /* @__PURE__ */new RangeSet([], [], null, -1);
RangeSet.empty.nextLayer = RangeSet.empty;
/**
A range set builder is a data structure that helps build up a
[range set](https://codemirror.net/6/docs/ref/#state.RangeSet) directly, without first allocating
an array of [`Range`](https://codemirror.net/6/docs/ref/#state.Range) objects.
*/
RangeSetBuilder = class RangeSetBuilder {
finishChunk(newArrays) {
this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint));
this.chunkPos.push(this.chunkStart);
this.chunkStart = -1;
this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint);
this.maxPoint = -1;
if (newArrays) {
this.from = [];
this.to = [];
this.value = [];
}
}
/**
Create an empty builder.
*/
constructor() {
this.chunks = [];
this.chunkPos = [];
this.chunkStart = -1;
this.last = null;
this.lastFrom = -1e9;
this.lastTo = -1e9;
this.from = [];
this.to = [];
this.value = [];
this.maxPoint = -1;
this.setMaxPoint = -1;
this.nextLayer = null;
}
/**
Add a range. Ranges should be added in sorted (by `from` and
`value.startSide`) order.
*/
add(from, to, value) {
if (!this.addInner(from, to, value)) (this.nextLayer || (this.nextLayer = new RangeSetBuilder())).add(from, to, value);
}
/**
@internal
*/
addInner(from, to, value) {
let diff = from - this.lastTo || value.startSide - this.last.endSide;
if (diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) throw new Error("Ranges must be added sorted by `from` position and `startSide`");
if (diff < 0) return false;
if (this.from.length == 250) this.finishChunk(true);
if (this.chunkStart < 0) this.chunkStart = from;
this.from.push(from - this.chunkStart);
this.to.push(to - this.chunkStart);
this.last = value;
this.lastFrom = from;
this.lastTo = to;
this.value.push(value);
if (value.point) this.maxPoint = Math.max(this.maxPoint, to - from);
return true;
}
/**
@internal
*/
addChunk(from, chunk) {
if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) return false;
if (this.from.length) this.finishChunk(true);
this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint);
this.chunks.push(chunk);
this.chunkPos.push(from);
let last = chunk.value.length - 1;
this.last = chunk.value[last];
this.lastFrom = chunk.from[last] + from;
this.lastTo = chunk.to[last] + from;
return true;
}
/**
Finish the range set. Returns the new set. The builder can't be
used anymore after this has been called.
*/
finish() {
return this.finishInner(RangeSet.empty);
}
/**
@internal
*/
finishInner(next) {
if (this.from.length) this.finishChunk(false);
if (this.chunks.length == 0) return next;
let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint);
this.from = null;
return result;
}
};
LayerCursor = class {
constructor(layer$1, skip, minPoint, rank = 0) {
this.layer = layer$1;
this.skip = skip;
this.minPoint = minPoint;
this.rank = rank;
}
get startSide() {
return this.value ? this.value.startSide : 0;
}
get endSide() {
return this.value ? this.value.endSide : 0;
}
goto(pos, side = -1e9) {
this.chunkIndex = this.rangeIndex = 0;
this.gotoInner(pos, side, false);
return this;
}
gotoInner(pos, side, forward) {
while (this.chunkIndex < this.layer.chunk.length) {
let next = this.layer.chunk[this.chunkIndex];
if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint)) break;
this.chunkIndex++;
forward = false;
}
if (this.chunkIndex < this.layer.chunk.length) {
let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true);
if (!forward || this.rangeIndex < rangeIndex) this.setRangeIndex(rangeIndex);
}
this.next();
}
forward(pos, side) {
if ((this.to - pos || this.endSide - side) < 0) this.gotoInner(pos, side, true);
}
next() {
for (;;) if (this.chunkIndex == this.layer.chunk.length) {
this.from = this.to = 1e9;
this.value = null;
break;
} else {
let chunkPos = this.layer.chunkPos[this.chunkIndex],
chunk = this.layer.chunk[this.chunkIndex];
this.from = chunkPos + chunk.from[this.rangeIndex];
this.to = chunkPos + chunk.to[this.rangeIndex];
this.value = chunk.value[this.rangeIndex];
this.setRangeIndex(this.rangeIndex + 1);
if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) break;
}
}
setRangeIndex(index) {
if (index == this.layer.chunk[this.chunkIndex].value.length) {
this.chunkIndex++;
if (this.skip) while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) this.chunkIndex++;
this.rangeIndex = 0;
} else this.rangeIndex = index;
}
nextChunk() {
this.chunkIndex++;
this.rangeIndex = 0;
this.next();
}
compare(other) {
return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide;
}
};
HeapCursor = class HeapCursor {
constructor(heap) {
this.heap = heap;
}
static from(sets, skip = null, minPoint = -1) {
let heap = [];
for (let i$1 = 0; i$1 < sets.length; i$1++) for (let cur$1 = sets[i$1]; !cur$1.isEmpty; cur$1 = cur$1.nextLayer) if (cur$1.maxPoint >= minPoint) heap.push(new LayerCursor(cur$1, skip, minPoint, i$1));
return heap.length == 1 ? heap[0] : new HeapCursor(heap);
}
get startSide() {
return this.value ? this.value.startSide : 0;
}
goto(pos, side = -1e9) {
for (let cur$1 of this.heap) cur$1.goto(pos, side);
for (let i$1 = this.heap.length >> 1; i$1 >= 0; i$1--) heapBubble(this.heap, i$1);
this.next();
return this;
}
forward(pos, side) {
for (let cur$1 of this.heap) cur$1.forward(pos, side);
for (let i$1 = this.heap.length >> 1; i$1 >= 0; i$1--) heapBubble(this.heap, i$1);
if ((this.to - pos || this.value.endSide - side) < 0) this.next();
}
next() {
if (this.heap.length == 0) {
this.from = this.to = 1e9;
this.value = null;
this.rank = -1;
} else {
let top$1 = this.heap[0];
this.from = top$1.from;
this.to = top$1.to;
this.value = top$1.value;
this.rank = top$1.rank;
if (top$1.value) top$1.next();
heapBubble(this.heap, 0);
}
}
};
SpanCursor = class {
constructor(sets, skip, minPoint) {
this.minPoint = minPoint;
this.active = [];
this.activeTo = [];
this.activeRank = [];
this.minActive = -1;
this.point = null;
this.pointFrom = 0;
this.pointRank = 0;
this.to = -1e9;
this.endSide = 0;
this.openStart = -1;
this.cursor = HeapCursor.from(sets, skip, minPoint);
}
goto(pos, side = -1e9) {
this.cursor.goto(pos, side);
this.active.length = this.activeTo.length = this.activeRank.length = 0;
this.minActive = -1;
this.to = pos;
this.endSide = side;
this.openStart = -1;
this.next();
return this;
}
forward(pos, side) {
while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) this.removeActive(this.minActive);
this.cursor.forward(pos, side);
}
removeActive(index) {
remove(this.active, index);
remove(this.activeTo, index);
remove(this.activeRank, index);
this.minActive = findMinIndex(this.active, this.activeTo);
}
addActive(trackOpen) {
let i$1 = 0,
{
value,
to,
rank
} = this.cursor;
while (i$1 < this.activeRank.length && this.activeRank[i$1] <= rank) i$1++;
insert(this.active, i$1, value);
insert(this.activeTo, i$1, to);
insert(this.activeRank, i$1, rank);
if (trackOpen) insert(trackOpen, i$1, this.cursor.from);
this.minActive = findMinIndex(this.active, this.activeTo);
}
next() {
let from = this.to,
wasPoint = this.point;
this.point = null;
let trackOpen = this.openStart < 0 ? [] : null;
for (;;) {
let a = this.minActive;
if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) {
if (this.activeTo[a] > from) {
this.to = this.activeTo[a];
this.endSide = this.active[a].endSide;
break;
}
this.removeActive(a);
if (trackOpen) remove(trackOpen, a);
} else if (!this.cursor.value) {
this.to = this.endSide = 1e9;
break;
} else if (this.cursor.from > from) {
this.to = this.cursor.from;
this.endSide = this.cursor.startSide;
break;
} else {
let nextVal = this.cursor.value;
if (!nextVal.point) {
this.addActive(trackOpen);
this.cursor.next();
} else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) this.cursor.next();else {
this.point = nextVal;
this.pointFrom = this.cursor.from;
this.pointRank = this.cursor.rank;
this.to = this.cursor.to;
this.endSide = nextVal.endSide;
this.cursor.next();
this.forward(this.to, this.endSide);
break;
}
}
}
if (trackOpen) {
this.openStart = 0;
for (let i$1 = trackOpen.length - 1; i$1 >= 0 && trackOpen[i$1] < from; i$1--) this.openStart++;
}
}
activeForPoint(to) {
if (!this.active.length) return this.active;
let active = [];
for (let i$1 = this.active.length - 1; i$1 >= 0; i$1--) {
if (this.activeRank[i$1] < this.pointRank) break;
if (this.activeTo[i$1] > to || this.activeTo[i$1] == to && this.active[i$1].endSide >= this.point.endSide) active.push(this.active[i$1]);
}
return active.reverse();
}
openEnd(to) {
let open = 0;
for (let i$1 = this.activeTo.length - 1; i$1 >= 0 && this.activeTo[i$1] > to; i$1--) open++;
return open;
}
};
DOMSelectionState = class {
constructor() {
this.anchorNode = null;
this.anchorOffset = 0;
this.focusNode = null;
this.focusOffset = 0;
}
eq(domSel) {
return this.anchorNode == domSel.anchorNode && this.anchorOffset == domSel.anchorOffset && this.focusNode == domSel.focusNode && this.focusOffset == domSel.focusOffset;
}
setRange(range) {
let {
anchorNode,
focusNode
} = range;
this.set(anchorNode, Math.min(range.anchorOffset, anchorNode ? maxOffset(anchorNode) : 0), focusNode, Math.min(range.focusOffset, focusNode ? maxOffset(focusNode) : 0));
}
set(anchorNode, anchorOffset, focusNode, focusOffset) {
this.anchorNode = anchorNode;
this.anchorOffset = anchorOffset;
this.focusNode = focusNode;
this.focusOffset = focusOffset;
}
};
preventScrollSupported = null;
DOMPos = class DOMPos {
constructor(node, offset, precise = true) {
this.node = node;
this.offset = offset;
this.precise = precise;
}
static before(dom, precise) {
return new DOMPos(dom.parentNode, domIndex(dom), precise);
}
static after(dom, precise) {
return new DOMPos(dom.parentNode, domIndex(dom) + 1, precise);
}
};
noChildren = [];
ContentView = class ContentView {
constructor() {
this.parent = null;
this.dom = null;
this.flags = 2;
}
get overrideDOMText() {
return null;
}
get posAtStart() {
return this.parent ? this.parent.posBefore(this) : 0;
}
get posAtEnd() {
return this.posAtStart + this.length;
}
posBefore(view) {
let pos = this.posAtStart;
for (let child of this.children) {
if (child == view) return pos;
pos += child.length + child.breakAfter;
}
throw new RangeError("Invalid child in posBefore");
}
posAfter(view) {
return this.posBefore(view) + view.length;
}
sync(view, track) {
if (this.flags & 2) {
let parent = this.dom;
let prev = null,
next;
for (let child of this.children) {
if (child.flags & 7) {
if (!child.dom && (next = prev ? prev.nextSibling : parent.firstChild)) {
let contentView = ContentView.get(next);
if (!contentView || !contentView.parent && contentView.canReuseDOM(child)) child.reuseDOM(next);
}
child.sync(view, track);
child.flags &= -8;
}
next = prev ? prev.nextSibling : parent.firstChild;
if (track && !track.written && track.node == parent && next != child.dom) track.written = true;
if (child.dom.parentNode == parent) while (next && next != child.dom) next = rm$1(next);else parent.insertBefore(child.dom, next);
prev = child.dom;
}
next = prev ? prev.nextSibling : parent.firstChild;
if (next && track && track.node == parent) track.written = true;
while (next) next = rm$1(next);
} else if (this.flags & 1) {
for (let child of this.children) if (child.flags & 7) {
child.sync(view, track);
child.flags &= -8;
}
}
}
reuseDOM(_dom) {}
localPosFromDOM(node, offset) {
let after;
if (node == this.dom) after = this.dom.childNodes[offset];else {
let bias = maxOffset(node) == 0 ? 0 : offset == 0 ? -1 : 1;
for (;;) {
let parent = node.parentNode;
if (parent == this.dom) break;
if (bias == 0 && parent.firstChild != parent.lastChild) if (node == parent.firstChild) bias = -1;else bias = 1;
node = parent;
}
if (bias < 0) after = node;else after = node.nextSibling;
}
if (after == this.dom.firstChild) return 0;
while (after && !ContentView.get(after)) after = after.nextSibling;
if (!after) return this.length;
for (let i$1 = 0, pos = 0;; i$1++) {
let child = this.children[i$1];
if (child.dom == after) return pos;
pos += child.length + child.breakAfter;
}
}
domBoundsAround(from, to, offset = 0) {
let fromI = -1,
fromStart = -1,
toI = -1,
toEnd = -1;
for (let i$1 = 0, pos = offset, prevEnd = offset; i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (pos < from && end > to) return child.domBoundsAround(from, to, pos);
if (end >= from && fromI == -1) {
fromI = i$1;
fromStart = pos;
}
if (pos > to && child.dom.parentNode == this.dom) {
toI = i$1;
toEnd = prevEnd;
break;
}
prevEnd = end;
pos = end + child.breakAfter;
}
return {
from: fromStart,
to: toEnd < 0 ? offset + this.length : toEnd,
startDOM: (fromI ? this.children[fromI - 1].dom.nextSibling : null) || this.dom.firstChild,
endDOM: toI < this.children.length && toI >= 0 ? this.children[toI].dom : null
};
}
markDirty(andParent = false) {
this.flags |= 2;
this.markParentsDirty(andParent);
}
markParentsDirty(childList) {
for (let parent = this.parent; parent; parent = parent.parent) {
if (childList) parent.flags |= 2;
if (parent.flags & 1) return;
parent.flags |= 1;
childList = false;
}
}
setParent(parent) {
if (this.parent != parent) {
this.parent = parent;
if (this.flags & 7) this.markParentsDirty(true);
}
}
setDOM(dom) {
if (this.dom == dom) return;
if (this.dom) this.dom.cmView = null;
this.dom = dom;
dom.cmView = this;
}
get rootView() {
for (let v = this;;) {
let parent = v.parent;
if (!parent) return v;
v = parent;
}
}
replaceChildren(from, to, children = noChildren) {
this.markDirty();
for (let i$1 = from; i$1 < to; i$1++) {
let child = this.children[i$1];
if (child.parent == this && children.indexOf(child) < 0) child.destroy();
}
this.children.splice(from, to - from, ...children);
for (let i$1 = 0; i$1 < children.length; i$1++) children[i$1].setParent(this);
}
ignoreMutation(_rec) {
return false;
}
ignoreEvent(_event) {
return false;
}
childCursor(pos = this.length) {
return new ChildCursor(this.children, pos, this.children.length);
}
childPos(pos, bias = 1) {
return this.childCursor().findPos(pos, bias);
}
toString() {
let name$1 = this.constructor.name.replace("View", "");
return name$1 + (this.children.length ? "(" + this.children.join() + ")" : this.length ? "[" + (name$1 == "Text" ? this.text : this.length) + "]" : "") + (this.breakAfter ? "#" : "");
}
static get(node) {
return node.cmView;
}
get isEditable() {
return true;
}
get isWidget() {
return false;
}
get isHidden() {
return false;
}
merge(from, to, source, hasStart, openStart, openEnd) {
return false;
}
become(other) {
return false;
}
canReuseDOM(other) {
return other.constructor == this.constructor && !((this.flags | other.flags) & 8);
}
getSide() {
return 0;
}
destroy() {
for (let child of this.children) if (child.parent == this) child.destroy();
this.parent = null;
}
};
ContentView.prototype.breakAfter = 0;
ChildCursor = class {
constructor(children, pos, i$1) {
this.children = children;
this.pos = pos;
this.i = i$1;
this.off = 0;
}
findPos(pos, bias = 1) {
for (;;) {
if (pos > this.pos || pos == this.pos && (bias > 0 || this.i == 0 || this.children[this.i - 1].breakAfter)) {
this.off = pos - this.pos;
return this;
}
let next = this.children[--this.i];
this.pos -= next.length + next.breakAfter;
}
}
};
nav = typeof navigator != "undefined" ? navigator : {
userAgent: "",
vendor: "",
platform: ""
};
doc = typeof document != "undefined" ? document : {
documentElement: {
style: {}
}
};
ie_edge = /* @__PURE__ *//Edge\/(\d+)/.exec(nav.userAgent);
ie_upto10 = /* @__PURE__ *//MSIE \d/.test(nav.userAgent);
ie_11up = /* @__PURE__ *//Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(nav.userAgent);
ie = !!(ie_upto10 || ie_11up || ie_edge);
gecko = !ie && /* @__PURE__ *//gecko\/(\d+)/i.test(nav.userAgent);
chrome = !ie && /* @__PURE__ *//Chrome\/(\d+)/.exec(nav.userAgent);
webkit = "webkitFontSmoothing" in doc.documentElement.style;
safari = !ie && /* @__PURE__ *//Apple Computer/.test(nav.vendor);
ios = safari && (/* @__PURE__ *//Mobile\/\w+/.test(nav.userAgent) || nav.maxTouchPoints > 2);
browser = {
mac: ios || /* @__PURE__ *//Mac/.test(nav.platform),
windows: /* @__PURE__ *//Win/.test(nav.platform),
linux: /* @__PURE__ *//Linux|X11/.test(nav.platform),
ie,
ie_version: ie_upto10 ? doc.documentMode || 6 : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0,
gecko,
gecko_version: gecko ? +(/* @__PURE__ *//Firefox\/(\d+)/.exec(nav.userAgent) || [0, 0])[1] : 0,
chrome: !!chrome,
chrome_version: chrome ? +chrome[1] : 0,
ios,
android: /* @__PURE__ *//Android\b/.test(nav.userAgent),
webkit,
safari,
webkit_version: webkit ? +(/* @__PURE__ *//\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0,
tabSize: doc.documentElement.style.tabSize != null ? "tab-size" : "-moz-tab-size"
};
MaxJoinLen = 256;
TextView = class TextView extends ContentView {
constructor(text) {
super();
this.text = text;
}
get length() {
return this.text.length;
}
createDOM(textDOM) {
this.setDOM(textDOM || document.createTextNode(this.text));
}
sync(view, track) {
if (!this.dom) this.createDOM();
if (this.dom.nodeValue != this.text) {
if (track && track.node == this.dom) track.written = true;
this.dom.nodeValue = this.text;
}
}
reuseDOM(dom) {
if (dom.nodeType == 3) this.createDOM(dom);
}
merge(from, to, source) {
if (this.flags & 8 || source && (!(source instanceof TextView) || this.length - (to - from) + source.length > MaxJoinLen || source.flags & 8)) return false;
this.text = this.text.slice(0, from) + (source ? source.text : "") + this.text.slice(to);
this.markDirty();
return true;
}
split(from) {
let result = new TextView(this.text.slice(from));
this.text = this.text.slice(0, from);
this.markDirty();
result.flags |= this.flags & 8;
return result;
}
localPosFromDOM(node, offset) {
return node == this.dom ? offset : offset ? this.text.length : 0;
}
domAtPos(pos) {
return new DOMPos(this.dom, pos);
}
domBoundsAround(_from, _to, offset) {
return {
from: offset,
to: offset + this.length,
startDOM: this.dom,
endDOM: this.dom.nextSibling
};
}
coordsAt(pos, side) {
return textCoords(this.dom, pos, side);
}
};
MarkView = class MarkView extends ContentView {
constructor(mark, children = [], length = 0) {
super();
this.mark = mark;
this.children = children;
this.length = length;
for (let ch of children) ch.setParent(this);
}
setAttrs(dom) {
clearAttributes(dom);
if (this.mark.class) dom.className = this.mark.class;
if (this.mark.attrs) for (let name$1 in this.mark.attrs) dom.setAttribute(name$1, this.mark.attrs[name$1]);
return dom;
}
canReuseDOM(other) {
return super.canReuseDOM(other) && !((this.flags | other.flags) & 8);
}
reuseDOM(node) {
if (node.nodeName == this.mark.tagName.toUpperCase()) {
this.setDOM(node);
this.flags |= 6;
}
}
sync(view, track) {
if (!this.dom) this.setDOM(this.setAttrs(document.createElement(this.mark.tagName)));else if (this.flags & 4) this.setAttrs(this.dom);
super.sync(view, track);
}
merge(from, to, source, _hasStart, openStart, openEnd) {
if (source && (!(source instanceof MarkView && source.mark.eq(this.mark)) || from && openStart <= 0 || to < this.length && openEnd <= 0)) return false;
mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart - 1, openEnd - 1);
this.markDirty();
return true;
}
split(from) {
let result = [],
off = 0,
detachFrom = -1,
i$1 = 0;
for (let elt of this.children) {
let end = off + elt.length;
if (end > from) result.push(off < from ? elt.split(from - off) : elt);
if (detachFrom < 0 && off >= from) detachFrom = i$1;
off = end;
i$1++;
}
let length = this.length - from;
this.length = from;
if (detachFrom > -1) {
this.children.length = detachFrom;
this.markDirty();
}
return new MarkView(this.mark, result, length);
}
domAtPos(pos) {
return inlineDOMAtPos(this, pos);
}
coordsAt(pos, side) {
return coordsInChildren(this, pos, side);
}
};
WidgetView = class WidgetView extends ContentView {
static create(widget, length, side) {
return new WidgetView(widget, length, side);
}
constructor(widget, length, side) {
super();
this.widget = widget;
this.length = length;
this.side = side;
this.prevWidget = null;
}
split(from) {
let result = WidgetView.create(this.widget, this.length - from, this.side);
this.length -= from;
return result;
}
sync(view) {
if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
if (this.dom && this.prevWidget) this.prevWidget.destroy(this.dom);
this.prevWidget = null;
this.setDOM(this.widget.toDOM(view));
this.dom.contentEditable = "false";
}
}
getSide() {
return this.side;
}
merge(from, to, source, hasStart, openStart, openEnd) {
if (source && (!(source instanceof WidgetView) || !this.widget.compare(source.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) return false;
this.length = from + (source ? source.length : 0) + (this.length - to);
return true;
}
become(other) {
if (other instanceof WidgetView && other.side == this.side && this.widget.constructor == other.widget.constructor) {
if (!this.widget.compare(other.widget)) this.markDirty(true);
if (this.dom && !this.prevWidget) this.prevWidget = this.widget;
this.widget = other.widget;
this.length = other.length;
return true;
}
return false;
}
ignoreMutation() {
return true;
}
ignoreEvent(event) {
return this.widget.ignoreEvent(event);
}
get overrideDOMText() {
if (this.length == 0) return Text.empty;
let top$1 = this;
while (top$1.parent) top$1 = top$1.parent;
let {
view
} = top$1,
text = view && view.state.doc,
start = this.posAtStart;
return text ? text.slice(start, start + this.length) : Text.empty;
}
domAtPos(pos) {
return (this.length ? pos == 0 : this.side > 0) ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
}
domBoundsAround() {
return null;
}
coordsAt(pos, side) {
let custom = this.widget.coordsAt(this.dom, pos, side);
if (custom) return custom;
let rects = this.dom.getClientRects(),
rect = null;
if (!rects.length) return null;
let fromBack = this.side ? this.side < 0 : pos > 0;
for (let i$1 = fromBack ? rects.length - 1 : 0;; i$1 += fromBack ? -1 : 1) {
rect = rects[i$1];
if (pos > 0 ? i$1 == 0 : i$1 == rects.length - 1 || rect.top < rect.bottom) break;
}
return flattenRect(rect, !fromBack);
}
get isEditable() {
return false;
}
get isWidget() {
return true;
}
get isHidden() {
return this.widget.isHidden;
}
destroy() {
super.destroy();
if (this.dom) this.widget.destroy(this.dom);
}
};
WidgetBufferView = class WidgetBufferView extends ContentView {
constructor(side) {
super();
this.side = side;
}
get length() {
return 0;
}
merge() {
return false;
}
become(other) {
return other instanceof WidgetBufferView && other.side == this.side;
}
split() {
return new WidgetBufferView(this.side);
}
sync() {
if (!this.dom) {
let dom = document.createElement("img");
dom.className = "cm-widgetBuffer";
dom.setAttribute("aria-hidden", "true");
this.setDOM(dom);
}
}
getSide() {
return this.side;
}
domAtPos(pos) {
return this.side > 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom);
}
localPosFromDOM() {
return 0;
}
domBoundsAround() {
return null;
}
coordsAt(pos) {
return this.dom.getBoundingClientRect();
}
get overrideDOMText() {
return Text.empty;
}
get isHidden() {
return true;
}
};
TextView.prototype.children = WidgetView.prototype.children = WidgetBufferView.prototype.children = noChildren;
noAttrs = /* @__PURE__ */Object.create(null);
LineView = class LineView extends ContentView {
constructor() {
super(...arguments);
this.children = [];
this.length = 0;
this.prevAttrs = void 0;
this.attrs = null;
this.breakAfter = 0;
}
merge(from, to, source, hasStart, openStart, openEnd) {
if (source) {
if (!(source instanceof LineView)) return false;
if (!this.dom) source.transferDOM(this);
}
if (hasStart) this.setDeco(source ? source.attrs : null);
mergeChildrenInto(this, from, to, source ? source.children.slice() : [], openStart, openEnd);
return true;
}
split(at) {
let end = new LineView();
end.breakAfter = this.breakAfter;
if (this.length == 0) return end;
let {
i: i$1,
off
} = this.childPos(at);
if (off) {
end.append(this.children[i$1].split(off), 0);
this.children[i$1].merge(off, this.children[i$1].length, null, false, 0, 0);
i$1++;
}
for (let j = i$1; j < this.children.length; j++) end.append(this.children[j], 0);
while (i$1 > 0 && this.children[i$1 - 1].length == 0) this.children[--i$1].destroy();
this.children.length = i$1;
this.markDirty();
this.length = at;
return end;
}
transferDOM(other) {
if (!this.dom) return;
this.markDirty();
other.setDOM(this.dom);
other.prevAttrs = this.prevAttrs === void 0 ? this.attrs : this.prevAttrs;
this.prevAttrs = void 0;
this.dom = null;
}
setDeco(attrs) {
if (!attrsEq(this.attrs, attrs)) {
if (this.dom) {
this.prevAttrs = this.attrs;
this.markDirty();
}
this.attrs = attrs;
}
}
append(child, openStart) {
joinInlineInto(this, child, openStart);
}
addLineDeco(deco) {
let attrs = deco.spec.attributes,
cls = deco.spec.class;
if (attrs) this.attrs = combineAttrs(attrs, this.attrs || {});
if (cls) this.attrs = combineAttrs({
class: cls
}, this.attrs || {});
}
domAtPos(pos) {
return inlineDOMAtPos(this, pos);
}
reuseDOM(node) {
if (node.nodeName == "DIV") {
this.setDOM(node);
this.flags |= 6;
}
}
sync(view, track) {
var _a$2;
if (!this.dom) {
this.setDOM(document.createElement("div"));
this.dom.className = "cm-line";
this.prevAttrs = this.attrs ? null : void 0;
} else if (this.flags & 4) {
clearAttributes(this.dom);
this.dom.className = "cm-line";
this.prevAttrs = this.attrs ? null : void 0;
}
if (this.prevAttrs !== void 0) {
updateAttrs(this.dom, this.prevAttrs, this.attrs);
this.dom.classList.add("cm-line");
this.prevAttrs = void 0;
}
super.sync(view, track);
let last = this.dom.lastChild;
while (last && ContentView.get(last) instanceof MarkView) last = last.lastChild;
if (!last || !this.length || last.nodeName != "BR" && ((_a$2 = ContentView.get(last)) === null || _a$2 === void 0 ? void 0 : _a$2.isEditable) == false && (!browser.ios || !this.children.some(ch => ch instanceof TextView))) {
let hack = document.createElement("BR");
hack.cmIgnore = true;
this.dom.appendChild(hack);
}
}
measureTextSize() {
if (this.children.length == 0 || this.length > 20) return null;
let totalWidth = 0,
textHeight;
for (let child of this.children) {
if (!(child instanceof TextView) || /[^ -~]/.test(child.text)) return null;
let rects = clientRectsFor(child.dom);
if (rects.length != 1) return null;
totalWidth += rects[0].width;
textHeight = rects[0].height;
}
return !totalWidth ? null : {
lineHeight: this.dom.getBoundingClientRect().height,
charWidth: totalWidth / this.length,
textHeight
};
}
coordsAt(pos, side) {
let rect = coordsInChildren(this, pos, side);
if (!this.children.length && rect && this.parent) {
let {
heightOracle
} = this.parent.view.viewState,
height = rect.bottom - rect.top;
if (Math.abs(height - heightOracle.lineHeight) < 2 && heightOracle.textHeight < height) {
let dist$2 = (height - heightOracle.textHeight) / 2;
return {
top: rect.top + dist$2,
bottom: rect.bottom - dist$2,
left: rect.left,
right: rect.left
};
}
}
return rect;
}
become(_other) {
return false;
}
covers() {
return true;
}
static find(docView, pos) {
for (let i$1 = 0, off = 0; i$1 < docView.children.length; i$1++) {
let block = docView.children[i$1],
end = off + block.length;
if (end >= pos) {
if (block instanceof LineView) return block;
if (end > pos) break;
}
off = end + block.breakAfter;
}
return null;
}
};
BlockWidgetView = class BlockWidgetView extends ContentView {
constructor(widget, length, deco) {
super();
this.widget = widget;
this.length = length;
this.deco = deco;
this.breakAfter = 0;
this.prevWidget = null;
}
merge(from, to, source, _takeDeco, openStart, openEnd) {
if (source && (!(source instanceof BlockWidgetView) || !this.widget.compare(source.widget) || from > 0 && openStart <= 0 || to < this.length && openEnd <= 0)) return false;
this.length = from + (source ? source.length : 0) + (this.length - to);
return true;
}
domAtPos(pos) {
return pos == 0 ? DOMPos.before(this.dom) : DOMPos.after(this.dom, pos == this.length);
}
split(at) {
let len = this.length - at;
this.length = at;
let end = new BlockWidgetView(this.widget, len, this.deco);
end.breakAfter = this.breakAfter;
return end;
}
get children() {
return noChildren;
}
sync(view) {
if (!this.dom || !this.widget.updateDOM(this.dom, view)) {
if (this.dom && this.prevWidget) this.prevWidget.destroy(this.dom);
this.prevWidget = null;
this.setDOM(this.widget.toDOM(view));
this.dom.contentEditable = "false";
}
}
get overrideDOMText() {
return this.parent ? this.parent.view.state.doc.slice(this.posAtStart, this.posAtEnd) : Text.empty;
}
domBoundsAround() {
return null;
}
become(other) {
if (other instanceof BlockWidgetView && other.widget.constructor == this.widget.constructor) {
if (!other.widget.compare(this.widget)) this.markDirty(true);
if (this.dom && !this.prevWidget) this.prevWidget = this.widget;
this.widget = other.widget;
this.length = other.length;
this.deco = other.deco;
this.breakAfter = other.breakAfter;
return true;
}
return false;
}
ignoreMutation() {
return true;
}
ignoreEvent(event) {
return this.widget.ignoreEvent(event);
}
get isEditable() {
return false;
}
get isWidget() {
return true;
}
coordsAt(pos, side) {
return this.widget.coordsAt(this.dom, pos, side);
}
destroy() {
super.destroy();
if (this.dom) this.widget.destroy(this.dom);
}
covers(side) {
let {
startSide,
endSide
} = this.deco;
return startSide == endSide ? false : side < 0 ? startSide < 0 : endSide > 0;
}
};
/**
Widgets added to the content are described by subclasses of this
class. Using a description object like that makes it possible to
delay creating of the DOM structure for a widget until it is
needed, and to avoid redrawing widgets even if the decorations
that define them are recreated.
*/
WidgetType = class {
/**
Compare this instance to another instance of the same type.
(TypeScript can't express this, but only instances of the same
specific class will be passed to this method.) This is used to
avoid redrawing widgets when they are replaced by a new
decoration of the same type. The default implementation just
returns `false`, which will cause new instances of the widget to
always be redrawn.
*/
eq(widget) {
return false;
}
/**
Update a DOM element created by a widget of the same type (but
different, non-`eq` content) to reflect this widget. May return
true to indicate that it could update, false to indicate it
couldn't (in which case the widget will be redrawn). The default
implementation just returns false.
*/
updateDOM(dom, view) {
return false;
}
/**
@internal
*/
compare(other) {
return this == other || this.constructor == other.constructor && this.eq(other);
}
/**
The estimated height this widget will have, to be used when
estimating the height of content that hasn't been drawn. May
return -1 to indicate you don't know. The default implementation
returns -1.
*/
get estimatedHeight() {
return -1;
}
/**
For inline widgets that are displayed inline (as opposed to
`inline-block`) and introduce line breaks (through `<br>` tags
or textual newlines), this must indicate the amount of line
breaks they introduce. Defaults to 0.
*/
get lineBreaks() {
return 0;
}
/**
Can be used to configure which kinds of events inside the widget
should be ignored by the editor. The default is to ignore all
events.
*/
ignoreEvent(event) {
return true;
}
/**
Override the way screen coordinates for positions at/in the
widget are found. `pos` will be the offset into the widget, and
`side` the side of the position that is being queried—less than
zero for before, greater than zero for after, and zero for
directly at that position.
*/
coordsAt(dom, pos, side) {
return null;
}
/**
@internal
*/
get isHidden() {
return false;
}
/**
This is called when the an instance of the widget is removed
from the editor view.
*/
destroy(dom) {}
};
/**
The different types of blocks that can occur in an editor view.
*/
BlockType = /* @__PURE__ */function (BlockType$2) {
/**
A line of text.
*/
BlockType$2[BlockType$2["Text"] = 0] = "Text";
/**
A block widget associated with the position after it.
*/
BlockType$2[BlockType$2["WidgetBefore"] = 1] = "WidgetBefore";
/**
A block widget associated with the position before it.
*/
BlockType$2[BlockType$2["WidgetAfter"] = 2] = "WidgetAfter";
/**
A block widget [replacing](https://codemirror.net/6/docs/ref/#view.Decoration^replace) a range of content.
*/
BlockType$2[BlockType$2["WidgetRange"] = 3] = "WidgetRange";
return BlockType$2;
}(BlockType || (BlockType = {}));
/**
A decoration provides information on how to draw or style a piece
of content. You'll usually use it wrapped in a
[`Range`](https://codemirror.net/6/docs/ref/#state.Range), which adds a start and end position.
@nonabstract
*/
Decoration = class extends RangeValue {
constructor(startSide, endSide, widget, spec) {
super();
this.startSide = startSide;
this.endSide = endSide;
this.widget = widget;
this.spec = spec;
}
/**
@internal
*/
get heightRelevant() {
return false;
}
/**
Create a mark decoration, which influences the styling of the
content in its range. Nested mark decorations will cause nested
DOM elements to be created. Nesting order is determined by
precedence of the [facet](https://codemirror.net/6/docs/ref/#view.EditorView^decorations), with
the higher-precedence decorations creating the inner DOM nodes.
Such elements are split on line boundaries and on the boundaries
of lower-precedence decorations.
*/
static mark(spec) {
return new MarkDecoration(spec);
}
/**
Create a widget decoration, which displays a DOM element at the
given position.
*/
static widget(spec) {
let side = Math.max(-1e4, Math.min(1e4, spec.side || 0)),
block = !!spec.block;
side += block && !spec.inlineOrder ? side > 0 ? 3e8 : -4e8 : side > 0 ? 1e8 : -1e8;
return new PointDecoration(spec, side, side, block, spec.widget || null, false);
}
/**
Create a replace decoration which replaces the given range with
a widget, or simply hides it.
*/
static replace(spec) {
let block = !!spec.block,
startSide,
endSide;
if (spec.isBlockGap) {
startSide = -5e8;
endSide = 4e8;
} else {
let {
start,
end
} = getInclusive(spec, block);
startSide = (start ? block ? -3e8 : -1 : 5e8) - 1;
endSide = (end ? block ? 2e8 : 1 : -6e8) + 1;
}
return new PointDecoration(spec, startSide, endSide, block, spec.widget || null, true);
}
/**
Create a line decoration, which can add DOM attributes to the
line starting at the given position.
*/
static line(spec) {
return new LineDecoration(spec);
}
/**
Build a [`DecorationSet`](https://codemirror.net/6/docs/ref/#view.DecorationSet) from the given
decorated range or ranges. If the ranges aren't already sorted,
pass `true` for `sort` to make the library sort them for you.
*/
static set(of, sort = false) {
return RangeSet$1.of(of, sort);
}
/**
@internal
*/
hasHeight() {
return this.widget ? this.widget.estimatedHeight > -1 : false;
}
};
/**
The empty set of decorations.
*/
Decoration.none = RangeSet$1.empty;
MarkDecoration = class MarkDecoration extends Decoration {
constructor(spec) {
let {
start,
end
} = getInclusive(spec);
super(start ? -1 : 5e8, end ? 1 : -6e8, null, spec);
this.tagName = spec.tagName || "span";
this.class = spec.class || "";
this.attrs = spec.attributes || null;
}
eq(other) {
var _a$2, _b;
return this == other || other instanceof MarkDecoration && this.tagName == other.tagName && (this.class || ((_a$2 = this.attrs) === null || _a$2 === void 0 ? void 0 : _a$2.class)) == (other.class || ((_b = other.attrs) === null || _b === void 0 ? void 0 : _b.class)) && attrsEq(this.attrs, other.attrs, "class");
}
range(from, to = from) {
if (from >= to) throw new RangeError("Mark decorations may not be empty");
return super.range(from, to);
}
};
MarkDecoration.prototype.point = false;
LineDecoration = class LineDecoration extends Decoration {
constructor(spec) {
super(-2e8, -2e8, null, spec);
}
eq(other) {
return other instanceof LineDecoration && this.spec.class == other.spec.class && attrsEq(this.spec.attributes, other.spec.attributes);
}
range(from, to = from) {
if (to != from) throw new RangeError("Line decoration ranges must be zero-length");
return super.range(from, to);
}
};
LineDecoration.prototype.mapMode = MapMode.TrackBefore;
LineDecoration.prototype.point = true;
PointDecoration = class PointDecoration extends Decoration {
constructor(spec, startSide, endSide, block, widget, isReplace) {
super(startSide, endSide, widget, spec);
this.block = block;
this.isReplace = isReplace;
this.mapMode = !block ? MapMode.TrackDel : startSide <= 0 ? MapMode.TrackBefore : MapMode.TrackAfter;
}
get type() {
return this.startSide != this.endSide ? BlockType.WidgetRange : this.startSide <= 0 ? BlockType.WidgetBefore : BlockType.WidgetAfter;
}
get heightRelevant() {
return this.block || !!this.widget && (this.widget.estimatedHeight >= 5 || this.widget.lineBreaks > 0);
}
eq(other) {
return other instanceof PointDecoration && widgetsEq(this.widget, other.widget) && this.block == other.block && this.startSide == other.startSide && this.endSide == other.endSide;
}
range(from, to = from) {
if (this.isReplace && (from > to || from == to && this.startSide > 0 && this.endSide <= 0)) throw new RangeError("Invalid range for replacement decoration");
if (!this.isReplace && to != from) throw new RangeError("Widget decorations can only have zero-length ranges");
return super.range(from, to);
}
};
PointDecoration.prototype.point = true;
ContentBuilder = class ContentBuilder {
constructor(doc$2, pos, end, disallowBlockEffectsFor) {
this.doc = doc$2;
this.pos = pos;
this.end = end;
this.disallowBlockEffectsFor = disallowBlockEffectsFor;
this.content = [];
this.curLine = null;
this.breakAtStart = 0;
this.pendingBuffer = 0;
this.bufferMarks = [];
this.atCursorPos = true;
this.openStart = -1;
this.openEnd = -1;
this.text = "";
this.textOff = 0;
this.cursor = doc$2.iter();
this.skip = pos;
}
posCovered() {
if (this.content.length == 0) return !this.breakAtStart && this.doc.lineAt(this.pos).from != this.pos;
let last = this.content[this.content.length - 1];
return !(last.breakAfter || last instanceof BlockWidgetView && last.deco.endSide < 0);
}
getLine() {
if (!this.curLine) {
this.content.push(this.curLine = new LineView());
this.atCursorPos = true;
}
return this.curLine;
}
flushBuffer(active = this.bufferMarks) {
if (this.pendingBuffer) {
this.curLine.append(wrapMarks(new WidgetBufferView(-1), active), active.length);
this.pendingBuffer = 0;
}
}
addBlockWidget(view) {
this.flushBuffer();
this.curLine = null;
this.content.push(view);
}
finish(openEnd) {
if (this.pendingBuffer && openEnd <= this.bufferMarks.length) this.flushBuffer();else this.pendingBuffer = 0;
if (!this.posCovered() && !(openEnd && this.content.length && this.content[this.content.length - 1] instanceof BlockWidgetView)) this.getLine();
}
buildText(length, active, openStart) {
while (length > 0) {
if (this.textOff == this.text.length) {
let {
value,
lineBreak,
done
} = this.cursor.next(this.skip);
this.skip = 0;
if (done) throw new Error("Ran out of text content when drawing inline views");
if (lineBreak) {
if (!this.posCovered()) this.getLine();
if (this.content.length) this.content[this.content.length - 1].breakAfter = 1;else this.breakAtStart = 1;
this.flushBuffer();
this.curLine = null;
this.atCursorPos = true;
length--;
continue;
} else {
this.text = value;
this.textOff = 0;
}
}
let take = Math.min(this.text.length - this.textOff, length, 512);
this.flushBuffer(active.slice(active.length - openStart));
this.getLine().append(wrapMarks(new TextView(this.text.slice(this.textOff, this.textOff + take)), active), openStart);
this.atCursorPos = true;
this.textOff += take;
length -= take;
openStart = 0;
}
}
span(from, to, active, openStart) {
this.buildText(to - from, active, openStart);
this.pos = to;
if (this.openStart < 0) this.openStart = openStart;
}
point(from, to, deco, active, openStart, index) {
if (this.disallowBlockEffectsFor[index] && deco instanceof PointDecoration) {
if (deco.block) throw new RangeError("Block decorations may not be specified via plugins");
if (to > this.doc.lineAt(this.pos).to) throw new RangeError("Decorations that replace line breaks may not be specified via plugins");
}
let len = to - from;
if (deco instanceof PointDecoration) {
if (deco.block) {
if (deco.startSide > 0 && !this.posCovered()) this.getLine();
this.addBlockWidget(new BlockWidgetView(deco.widget || new NullWidget("div"), len, deco));
} else {
let view = WidgetView.create(deco.widget || new NullWidget("span"), len, len ? 0 : deco.startSide);
let cursorBefore = this.atCursorPos && !view.isEditable && openStart <= active.length && (from < to || deco.startSide > 0);
let cursorAfter = !view.isEditable && (from < to || openStart > active.length || deco.startSide <= 0);
let line = this.getLine();
if (this.pendingBuffer == 2 && !cursorBefore && !view.isEditable) this.pendingBuffer = 0;
this.flushBuffer(active);
if (cursorBefore) {
line.append(wrapMarks(new WidgetBufferView(1), active), openStart);
openStart = active.length + Math.max(0, openStart - active.length);
}
line.append(wrapMarks(view, active), openStart);
this.atCursorPos = cursorAfter;
this.pendingBuffer = !cursorAfter ? 0 : from < to || openStart > active.length ? 1 : 2;
if (this.pendingBuffer) this.bufferMarks = active.slice();
}
} else if (this.doc.lineAt(this.pos).from == this.pos) this.getLine().addLineDeco(deco);
if (len) {
if (this.textOff + len <= this.text.length) this.textOff += len;else {
this.skip += len - (this.text.length - this.textOff);
this.text = "";
this.textOff = 0;
}
this.pos = to;
}
if (this.openStart < 0) this.openStart = openStart;
}
static build(text, from, to, decorations$2, dynamicDecorationMap) {
let builder = new ContentBuilder(text, from, to, dynamicDecorationMap);
builder.openEnd = RangeSet$1.spans(decorations$2, from, to, builder);
if (builder.openStart < 0) builder.openStart = builder.openEnd;
builder.finish(builder.openEnd);
return builder;
}
};
NullWidget = class extends WidgetType {
constructor(tag) {
super();
this.tag = tag;
}
eq(other) {
return other.tag == this.tag;
}
toDOM() {
return document.createElement(this.tag);
}
updateDOM(elt) {
return elt.nodeName.toLowerCase() == this.tag;
}
get isHidden() {
return true;
}
};
clickAddsSelectionRange = /* @__PURE__ */Facet$1.define();
dragMovesSelection$1 = /* @__PURE__ */Facet$1.define();
mouseSelectionStyle = /* @__PURE__ */Facet$1.define();
exceptionSink = /* @__PURE__ */Facet$1.define();
updateListener = /* @__PURE__ */Facet$1.define();
inputHandler = /* @__PURE__ */Facet$1.define();
focusChangeEffect = /* @__PURE__ */Facet$1.define();
perLineTextDirection = /* @__PURE__ */Facet$1.define({
combine: values => values.some(x => x)
});
nativeSelectionHidden = /* @__PURE__ */Facet$1.define({
combine: values => values.some(x => x)
});
ScrollTarget = class ScrollTarget {
constructor(range, y = "nearest", x = "nearest", yMargin = 5, xMargin = 5, isSnapshot = false) {
this.range = range;
this.y = y;
this.x = x;
this.yMargin = yMargin;
this.xMargin = xMargin;
this.isSnapshot = isSnapshot;
}
map(changes) {
return changes.empty ? this : new ScrollTarget(this.range.map(changes), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
}
clip(state) {
return this.range.to <= state.doc.length ? this : new ScrollTarget(EditorSelection.cursor(state.doc.length), this.y, this.x, this.yMargin, this.xMargin, this.isSnapshot);
}
};
scrollIntoView = /* @__PURE__ */StateEffect$1.define({
map: (t$1, ch) => t$1.map(ch)
});
editable = /* @__PURE__ */Facet$1.define({
combine: values => values.length ? values[0] : true
});
nextPluginID = 0;
viewPlugin = /* @__PURE__ */Facet$1.define();
/**
View plugins associate stateful values with a view. They can
influence the way the content is drawn, and are notified of things
that happen in the view.
*/
ViewPlugin = class ViewPlugin {
constructor(id$1, create, domEventHandlers, domEventObservers, buildExtensions) {
this.id = id$1;
this.create = create;
this.domEventHandlers = domEventHandlers;
this.domEventObservers = domEventObservers;
this.extension = buildExtensions(this);
}
/**
Define a plugin from a constructor function that creates the
plugin's value, given an editor view.
*/
static define(create, spec) {
const {
eventHandlers,
eventObservers,
provide,
decorations: deco
} = spec || {};
return new ViewPlugin(nextPluginID++, create, eventHandlers, eventObservers, plugin => {
let ext = [viewPlugin.of(plugin)];
if (deco) ext.push(decorations.of(view => {
let pluginInst = view.plugin(plugin);
return pluginInst ? deco(pluginInst) : Decoration.none;
}));
if (provide) ext.push(provide(plugin));
return ext;
});
}
/**
Create a plugin for a class whose constructor takes a single
editor view as argument.
*/
static fromClass(cls, spec) {
return ViewPlugin.define(view => new cls(view), spec);
}
};
PluginInstance = class {
constructor(spec) {
this.spec = spec;
this.mustUpdate = null;
this.value = null;
}
update(view) {
if (!this.value) {
if (this.spec) try {
this.value = this.spec.create(view);
} catch (e) {
logException(view.state, e, "CodeMirror plugin crashed");
this.deactivate();
}
} else if (this.mustUpdate) {
let update = this.mustUpdate;
this.mustUpdate = null;
if (this.value.update) try {
this.value.update(update);
} catch (e) {
logException(update.state, e, "CodeMirror plugin crashed");
if (this.value.destroy) try {
this.value.destroy();
} catch (_) {}
this.deactivate();
}
}
return this;
}
destroy(view) {
var _a$2;
if ((_a$2 = this.value) === null || _a$2 === void 0 ? void 0 : _a$2.destroy) try {
this.value.destroy();
} catch (e) {
logException(view.state, e, "CodeMirror plugin crashed");
}
}
deactivate() {
this.spec = this.value = null;
}
};
editorAttributes = /* @__PURE__ */Facet$1.define();
contentAttributes = /* @__PURE__ */Facet$1.define();
decorations = /* @__PURE__ */Facet$1.define();
atomicRanges = /* @__PURE__ */Facet$1.define();
bidiIsolatedRanges = /* @__PURE__ */Facet$1.define();
scrollMargins = /* @__PURE__ */Facet$1.define();
styleModule = /* @__PURE__ */Facet$1.define();
ChangedRange = class ChangedRange {
constructor(fromA, toA, fromB, toB) {
this.fromA = fromA;
this.toA = toA;
this.fromB = fromB;
this.toB = toB;
}
join(other) {
return new ChangedRange(Math.min(this.fromA, other.fromA), Math.max(this.toA, other.toA), Math.min(this.fromB, other.fromB), Math.max(this.toB, other.toB));
}
addToSet(set) {
let i$1 = set.length,
me = this;
for (; i$1 > 0; i$1--) {
let range = set[i$1 - 1];
if (range.fromA > me.toA) continue;
if (range.toA < me.fromA) break;
me = me.join(range);
set.splice(i$1 - 1, 1);
}
set.splice(i$1, 0, me);
return set;
}
static extendWithRanges(diff, ranges) {
if (ranges.length == 0) return diff;
let result = [];
for (let dI = 0, rI = 0, posA = 0, posB = 0;; dI++) {
let next = dI == diff.length ? null : diff[dI],
off = posA - posB;
let end = next ? next.fromB : 1e9;
while (rI < ranges.length && ranges[rI] < end) {
let from = ranges[rI],
to = ranges[rI + 1];
let fromB = Math.max(posB, from),
toB = Math.min(end, to);
if (fromB <= toB) new ChangedRange(fromB + off, toB + off, fromB, toB).addToSet(result);
if (to > end) break;else rI += 2;
}
if (!next) return result;
new ChangedRange(next.fromA, next.toA, next.fromB, next.toB).addToSet(result);
posA = next.toA;
posB = next.toB;
}
}
};
/**
View [plugins](https://codemirror.net/6/docs/ref/#view.ViewPlugin) are given instances of this
class, which describe what happened, whenever the view is updated.
*/
ViewUpdate = class ViewUpdate {
constructor(view, state, transactions) {
this.view = view;
this.state = state;
this.transactions = transactions;
/**
@internal
*/
this.flags = 0;
this.startState = view.state;
this.changes = ChangeSet.empty(this.startState.doc.length);
for (let tr of transactions) this.changes = this.changes.compose(tr.changes);
let changedRanges = [];
this.changes.iterChangedRanges((fromA, toA, fromB, toB) => changedRanges.push(new ChangedRange(fromA, toA, fromB, toB)));
this.changedRanges = changedRanges;
}
/**
@internal
*/
static create(view, state, transactions) {
return new ViewUpdate(view, state, transactions);
}
/**
Tells you whether the [viewport](https://codemirror.net/6/docs/ref/#view.EditorView.viewport) or
[visible ranges](https://codemirror.net/6/docs/ref/#view.EditorView.visibleRanges) changed in this
update.
*/
get viewportChanged() {
return (this.flags & 4) > 0;
}
/**
Indicates whether the height of a block element in the editor
changed in this update.
*/
get heightChanged() {
return (this.flags & 2) > 0;
}
/**
Returns true when the document was modified or the size of the
editor, or elements within the editor, changed.
*/
get geometryChanged() {
return this.docChanged || (this.flags & 10) > 0;
}
/**
True when this update indicates a focus change.
*/
get focusChanged() {
return (this.flags & 1) > 0;
}
/**
Whether the document changed in this update.
*/
get docChanged() {
return !this.changes.empty;
}
/**
Whether the selection was explicitly set in this update.
*/
get selectionSet() {
return this.transactions.some(tr => tr.selection);
}
/**
@internal
*/
get empty() {
return this.flags == 0 && this.transactions.length == 0;
}
};
/**
Used to indicate [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
*/
Direction = /* @__PURE__ */function (Direction$2) {
/**
Left-to-right.
*/
Direction$2[Direction$2["LTR"] = 0] = "LTR";
/**
Right-to-left.
*/
Direction$2[Direction$2["RTL"] = 1] = "RTL";
return Direction$2;
}(Direction || (Direction = {}));
LTR = Direction.LTR, RTL = Direction.RTL;
LowTypes = /* @__PURE__ */dec("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008");
ArabicTypes = /* @__PURE__ */dec("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333");
Brackets = /* @__PURE__ */Object.create(null), BracketStack = [];
for (let p of ["()", "[]", "{}"]) {
let l = /* @__PURE__ */p.charCodeAt(0),
r = /* @__PURE__ */p.charCodeAt(1);
Brackets[l] = r;
Brackets[r] = -l;
}
BidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;
/**
Represents a contiguous range of text that has a single direction
(as in left-to-right or right-to-left).
*/
BidiSpan = class {
/**
The direction of this span.
*/
get dir() {
return this.level % 2 ? RTL : LTR;
}
/**
@internal
*/
constructor(from, to, level) {
this.from = from;
this.to = to;
this.level = level;
}
/**
@internal
*/
side(end, dir) {
return this.dir == dir == end ? this.to : this.from;
}
/**
@internal
*/
static find(order, index, level, assoc) {
let maybe = -1;
for (let i$1 = 0; i$1 < order.length; i$1++) {
let span = order[i$1];
if (span.from <= index && span.to >= index) {
if (span.level == level) return i$1;
if (maybe < 0 || (assoc != 0 ? assoc < 0 ? span.from < index : span.to > index : order[maybe].level > span.level)) maybe = i$1;
}
}
if (maybe < 0) throw new RangeError("Index out of range");
return maybe;
}
};
types = [];
movedOver = "";
DocView = class extends ContentView {
get length() {
return this.view.state.doc.length;
}
constructor(view) {
super();
this.view = view;
this.decorations = [];
this.dynamicDecorationMap = [];
this.domChanged = null;
this.hasComposition = null;
this.markedForComposition = /* @__PURE__ */new Set();
this.minWidth = 0;
this.minWidthFrom = 0;
this.minWidthTo = 0;
this.impreciseAnchor = null;
this.impreciseHead = null;
this.forceSelection = false;
this.lastUpdate = Date.now();
this.setDOM(view.contentDOM);
this.children = [new LineView()];
this.children[0].setParent(this);
this.updateDeco();
this.updateInner([new ChangedRange(0, 0, 0, view.state.doc.length)], 0, null);
}
update(update) {
var _a$2;
let changedRanges = update.changedRanges;
if (this.minWidth > 0 && changedRanges.length) if (!changedRanges.every(({
fromA,
toA
}) => toA < this.minWidthFrom || fromA > this.minWidthTo)) this.minWidth = this.minWidthFrom = this.minWidthTo = 0;else {
this.minWidthFrom = update.changes.mapPos(this.minWidthFrom, 1);
this.minWidthTo = update.changes.mapPos(this.minWidthTo, 1);
}
let readCompositionAt = -1;
if (this.view.inputState.composing >= 0) {
if ((_a$2 = this.domChanged) === null || _a$2 === void 0 ? void 0 : _a$2.newSel) readCompositionAt = this.domChanged.newSel.head;else if (!touchesComposition(update.changes, this.hasComposition) && !update.selectionSet) readCompositionAt = update.state.selection.main.head;
}
let composition = readCompositionAt > -1 ? findCompositionRange(this.view, update.changes, readCompositionAt) : null;
this.domChanged = null;
if (this.hasComposition) {
this.markedForComposition.clear();
let {
from,
to
} = this.hasComposition;
changedRanges = new ChangedRange(from, to, update.changes.mapPos(from, -1), update.changes.mapPos(to, 1)).addToSet(changedRanges.slice());
}
this.hasComposition = composition ? {
from: composition.range.fromB,
to: composition.range.toB
} : null;
if ((browser.ie || browser.chrome) && !composition && update && update.state.doc.lines != update.startState.doc.lines) this.forceSelection = true;
let prevDeco = this.decorations;
let decoDiff = findChangedDeco(prevDeco, this.updateDeco(), update.changes);
changedRanges = ChangedRange.extendWithRanges(changedRanges, decoDiff);
if (!(this.flags & 7) && changedRanges.length == 0) return false;else {
this.updateInner(changedRanges, update.startState.doc.length, composition);
if (update.transactions.length) this.lastUpdate = Date.now();
return true;
}
}
updateInner(changes, oldLength, composition) {
this.view.viewState.mustMeasureContent = true;
this.updateChildren(changes, oldLength, composition);
let {
observer
} = this.view;
observer.ignore(() => {
this.dom.style.height = this.view.viewState.contentHeight / this.view.scaleY + "px";
this.dom.style.flexBasis = this.minWidth ? this.minWidth + "px" : "";
let track = browser.chrome || browser.ios ? {
node: observer.selectionRange.focusNode,
written: false
} : void 0;
this.sync(this.view, track);
this.flags &= -8;
if (track && (track.written || observer.selectionRange.focusNode != track.node)) this.forceSelection = true;
this.dom.style.height = "";
});
this.markedForComposition.forEach(cView => cView.flags &= -9);
let gaps = [];
if (this.view.viewport.from || this.view.viewport.to < this.view.state.doc.length) {
for (let child of this.children) if (child instanceof BlockWidgetView && child.widget instanceof BlockGapWidget) gaps.push(child.dom);
}
observer.updateGaps(gaps);
}
updateChildren(changes, oldLength, composition) {
let ranges = composition ? composition.range.addToSet(changes.slice()) : changes;
let cursor = this.childCursor(oldLength);
for (let i$1 = ranges.length - 1;; i$1--) {
let next = i$1 >= 0 ? ranges[i$1] : null;
if (!next) break;
let {
fromA,
toA,
fromB,
toB
} = next,
content$1,
breakAtStart,
openStart,
openEnd;
if (composition && composition.range.fromB < toB && composition.range.toB > fromB) {
let before = ContentBuilder.build(this.view.state.doc, fromB, composition.range.fromB, this.decorations, this.dynamicDecorationMap);
let after = ContentBuilder.build(this.view.state.doc, composition.range.toB, toB, this.decorations, this.dynamicDecorationMap);
breakAtStart = before.breakAtStart;
openStart = before.openStart;
openEnd = after.openEnd;
let compLine = this.compositionView(composition);
if (after.breakAtStart) compLine.breakAfter = 1;else if (after.content.length && compLine.merge(compLine.length, compLine.length, after.content[0], false, after.openStart, 0)) {
compLine.breakAfter = after.content[0].breakAfter;
after.content.shift();
}
if (before.content.length && compLine.merge(0, 0, before.content[before.content.length - 1], true, 0, before.openEnd)) before.content.pop();
content$1 = before.content.concat(compLine).concat(after.content);
} else ({
content: content$1,
breakAtStart,
openStart,
openEnd
} = ContentBuilder.build(this.view.state.doc, fromB, toB, this.decorations, this.dynamicDecorationMap));
let {
i: toI,
off: toOff
} = cursor.findPos(toA, 1);
let {
i: fromI,
off: fromOff
} = cursor.findPos(fromA, -1);
replaceRange(this, fromI, fromOff, toI, toOff, content$1, breakAtStart, openStart, openEnd);
}
if (composition) this.fixCompositionDOM(composition);
}
compositionView(composition) {
let cur$1 = new TextView(composition.text.nodeValue);
cur$1.flags |= 8;
for (let {
deco
} of composition.marks) cur$1 = new MarkView(deco, [cur$1], cur$1.length);
let line = new LineView();
line.append(cur$1, 0);
return line;
}
fixCompositionDOM(composition) {
let fix = (dom, cView$1) => {
cView$1.flags |= 8 | (cView$1.children.some(c => c.flags & 7) ? 1 : 0);
this.markedForComposition.add(cView$1);
let prev = ContentView.get(dom);
if (prev && prev != cView$1) prev.dom = null;
cView$1.setDOM(dom);
};
let pos = this.childPos(composition.range.fromB, 1);
let cView = this.children[pos.i];
fix(composition.line, cView);
for (let i$1 = composition.marks.length - 1; i$1 >= -1; i$1--) {
pos = cView.childPos(pos.off, 1);
cView = cView.children[pos.i];
fix(i$1 >= 0 ? composition.marks[i$1].node : composition.text, cView);
}
}
updateSelection(mustRead = false, fromPointer = false) {
if (mustRead || !this.view.observer.selectionRange.focusNode) this.view.observer.readSelectionRange();
let activeElt = this.view.root.activeElement,
focused = activeElt == this.dom;
let selectionNotFocus = !focused && hasSelection(this.dom, this.view.observer.selectionRange) && !(activeElt && this.dom.contains(activeElt));
if (!(focused || fromPointer || selectionNotFocus)) return;
let force = this.forceSelection;
this.forceSelection = false;
let main = this.view.state.selection.main;
let anchor = this.moveToLine(this.domAtPos(main.anchor));
let head = main.empty ? anchor : this.moveToLine(this.domAtPos(main.head));
if (browser.gecko && main.empty && !this.hasComposition && betweenUneditable(anchor)) {
let dummy = document.createTextNode("");
this.view.observer.ignore(() => anchor.node.insertBefore(dummy, anchor.node.childNodes[anchor.offset] || null));
anchor = head = new DOMPos(dummy, 0);
force = true;
}
let domSel = this.view.observer.selectionRange;
if (force || !domSel.focusNode || !isEquivalentPosition(anchor.node, anchor.offset, domSel.anchorNode, domSel.anchorOffset) || !isEquivalentPosition(head.node, head.offset, domSel.focusNode, domSel.focusOffset)) {
this.view.observer.ignore(() => {
if (browser.android && browser.chrome && this.dom.contains(domSel.focusNode) && inUneditable(domSel.focusNode, this.dom)) {
this.dom.blur();
this.dom.focus({
preventScroll: true
});
}
let rawSel = getSelection(this.view.root);
if (!rawSel) ;else if (main.empty) {
if (browser.gecko) {
let nextTo = nextToUneditable(anchor.node, anchor.offset);
if (nextTo && nextTo != 3) {
let text = nearbyTextNode(anchor.node, anchor.offset, nextTo == 1 ? 1 : -1);
if (text) anchor = new DOMPos(text.node, text.offset);
}
}
rawSel.collapse(anchor.node, anchor.offset);
if (main.bidiLevel != null && rawSel.caretBidiLevel !== void 0) rawSel.caretBidiLevel = main.bidiLevel;
} else if (rawSel.extend) {
rawSel.collapse(anchor.node, anchor.offset);
try {
rawSel.extend(head.node, head.offset);
} catch (_) {}
} else {
let range = document.createRange();
if (main.anchor > main.head) [anchor, head] = [head, anchor];
range.setEnd(head.node, head.offset);
range.setStart(anchor.node, anchor.offset);
rawSel.removeAllRanges();
rawSel.addRange(range);
}
if (selectionNotFocus && this.view.root.activeElement == this.dom) {
this.dom.blur();
if (activeElt) activeElt.focus();
}
});
this.view.observer.setSelectionRange(anchor, head);
}
this.impreciseAnchor = anchor.precise ? null : new DOMPos(domSel.anchorNode, domSel.anchorOffset);
this.impreciseHead = head.precise ? null : new DOMPos(domSel.focusNode, domSel.focusOffset);
}
enforceCursorAssoc() {
if (this.hasComposition) return;
let {
view
} = this,
cursor = view.state.selection.main;
let sel = getSelection(view.root);
let {
anchorNode,
anchorOffset
} = view.observer.selectionRange;
if (!sel || !cursor.empty || !cursor.assoc || !sel.modify) return;
let line = LineView.find(this, cursor.head);
if (!line) return;
let lineStart = line.posAtStart;
if (cursor.head == lineStart || cursor.head == lineStart + line.length) return;
let before = this.coordsAt(cursor.head, -1),
after = this.coordsAt(cursor.head, 1);
if (!before || !after || before.bottom > after.top) return;
let dom = this.domAtPos(cursor.head + cursor.assoc);
sel.collapse(dom.node, dom.offset);
sel.modify("move", cursor.assoc < 0 ? "forward" : "backward", "lineboundary");
view.observer.readSelectionRange();
let newRange = view.observer.selectionRange;
if (view.docView.posFromDOM(newRange.anchorNode, newRange.anchorOffset) != cursor.from) sel.collapse(anchorNode, anchorOffset);
}
moveToLine(pos) {
let dom = this.dom,
newPos;
if (pos.node != dom) return pos;
for (let i$1 = pos.offset; !newPos && i$1 < dom.childNodes.length; i$1++) {
let view = ContentView.get(dom.childNodes[i$1]);
if (view instanceof LineView) newPos = view.domAtPos(0);
}
for (let i$1 = pos.offset - 1; !newPos && i$1 >= 0; i$1--) {
let view = ContentView.get(dom.childNodes[i$1]);
if (view instanceof LineView) newPos = view.domAtPos(view.length);
}
return newPos ? new DOMPos(newPos.node, newPos.offset, true) : pos;
}
nearest(dom) {
for (let cur$1 = dom; cur$1;) {
let domView = ContentView.get(cur$1);
if (domView && domView.rootView == this) return domView;
cur$1 = cur$1.parentNode;
}
return null;
}
posFromDOM(node, offset) {
let view = this.nearest(node);
if (!view) throw new RangeError("Trying to find position for a DOM position outside of the document");
return view.localPosFromDOM(node, offset) + view.posAtStart;
}
domAtPos(pos) {
let {
i: i$1,
off
} = this.childCursor().findPos(pos, -1);
for (; i$1 < this.children.length - 1;) {
let child = this.children[i$1];
if (off < child.length || child instanceof LineView) break;
i$1++;
off = 0;
}
return this.children[i$1].domAtPos(off);
}
coordsAt(pos, side) {
let best = null,
bestPos = 0;
for (let off = this.length, i$1 = this.children.length - 1; i$1 >= 0; i$1--) {
let child = this.children[i$1],
end = off - child.breakAfter,
start = end - child.length;
if (end < pos) break;
if (start <= pos && (start < pos || child.covers(-1)) && (end > pos || child.covers(1)) && (!best || child instanceof LineView && !(best instanceof LineView && side >= 0))) {
best = child;
bestPos = start;
}
off = start;
}
return best ? best.coordsAt(pos - bestPos, side) : null;
}
coordsForChar(pos) {
let {
i: i$1,
off
} = this.childPos(pos, 1),
child = this.children[i$1];
if (!(child instanceof LineView)) return null;
while (child.children.length) {
let {
i: i$2,
off: childOff
} = child.childPos(off, 1);
for (;; i$2++) {
if (i$2 == child.children.length) return null;
if ((child = child.children[i$2]).length) break;
}
off = childOff;
}
if (!(child instanceof TextView)) return null;
let end = findClusterBreak(child.text, off);
if (end == off) return null;
let rects = textRange(child.dom, off, end).getClientRects();
for (let i$2 = 0; i$2 < rects.length; i$2++) {
let rect = rects[i$2];
if (i$2 == rects.length - 1 || rect.top < rect.bottom && rect.left < rect.right) return rect;
}
return null;
}
measureVisibleLineHeights(viewport) {
let result = [],
{
from,
to
} = viewport;
let contentWidth = this.view.contentDOM.clientWidth;
let isWider = contentWidth > Math.max(this.view.scrollDOM.clientWidth, this.minWidth) + 1;
let widest = -1,
ltr = this.view.textDirection == Direction.LTR;
for (let pos = 0, i$1 = 0; i$1 < this.children.length; i$1++) {
let child = this.children[i$1],
end = pos + child.length;
if (end > to) break;
if (pos >= from) {
let childRect = child.dom.getBoundingClientRect();
result.push(childRect.height);
if (isWider) {
let last = child.dom.lastChild;
let rects = last ? clientRectsFor(last) : [];
if (rects.length) {
let rect = rects[rects.length - 1];
let width = ltr ? rect.right - childRect.left : childRect.right - rect.left;
if (width > widest) {
widest = width;
this.minWidth = contentWidth;
this.minWidthFrom = pos;
this.minWidthTo = end;
}
}
}
}
pos = end + child.breakAfter;
}
return result;
}
textDirectionAt(pos) {
let {
i: i$1
} = this.childPos(pos, 1);
return getComputedStyle(this.children[i$1].dom).direction == "rtl" ? Direction.RTL : Direction.LTR;
}
measureTextSize() {
for (let child of this.children) if (child instanceof LineView) {
let measure = child.measureTextSize();
if (measure) return measure;
}
let dummy = document.createElement("div"),
lineHeight,
charWidth,
textHeight;
dummy.className = "cm-line";
dummy.style.width = "99999px";
dummy.style.position = "absolute";
dummy.textContent = "abc def ghi jkl mno pqr stu";
this.view.observer.ignore(() => {
this.dom.appendChild(dummy);
let rect = clientRectsFor(dummy.firstChild)[0];
lineHeight = dummy.getBoundingClientRect().height;
charWidth = rect ? rect.width / 27 : 7;
textHeight = rect ? rect.height : lineHeight;
dummy.remove();
});
return {
lineHeight,
charWidth,
textHeight
};
}
childCursor(pos = this.length) {
let i$1 = this.children.length;
if (i$1) pos -= this.children[--i$1].length;
return new ChildCursor(this.children, pos, i$1);
}
computeBlockGapDeco() {
let deco = [],
vs = this.view.viewState;
for (let pos = 0, i$1 = 0;; i$1++) {
let next = i$1 == vs.viewports.length ? null : vs.viewports[i$1];
let end = next ? next.from - 1 : this.length;
if (end > pos) {
let height = (vs.lineBlockAt(end).bottom - vs.lineBlockAt(pos).top) / this.view.scaleY;
deco.push(Decoration.replace({
widget: new BlockGapWidget(height),
block: true,
inclusive: true,
isBlockGap: true
}).range(pos, end));
}
if (!next) break;
pos = next.to + 1;
}
return Decoration.set(deco);
}
updateDeco() {
let allDeco = this.view.state.facet(decorations).map((d, i$1) => {
return (this.dynamicDecorationMap[i$1] = typeof d == "function") ? d(this.view) : d;
});
for (let i$1 = allDeco.length; i$1 < allDeco.length + 3; i$1++) this.dynamicDecorationMap[i$1] = false;
return this.decorations = [...allDeco, this.computeBlockGapDeco(), this.view.viewState.lineGapDeco];
}
scrollIntoView(target) {
if (target.isSnapshot) {
let ref$1 = this.view.viewState.lineBlockAt(target.range.head);
this.view.scrollDOM.scrollTop = ref$1.top - target.yMargin;
this.view.scrollDOM.scrollLeft = target.xMargin;
return;
}
let {
range
} = target;
let rect = this.coordsAt(range.head, range.empty ? range.assoc : range.head > range.anchor ? -1 : 1),
other;
if (!rect) return;
if (!range.empty && (other = this.coordsAt(range.anchor, range.anchor > range.head ? -1 : 1))) rect = {
left: Math.min(rect.left, other.left),
top: Math.min(rect.top, other.top),
right: Math.max(rect.right, other.right),
bottom: Math.max(rect.bottom, other.bottom)
};
let margins = getScrollMargins(this.view);
let targetRect = {
left: rect.left - margins.left,
top: rect.top - margins.top,
right: rect.right + margins.right,
bottom: rect.bottom + margins.bottom
};
let {
offsetWidth,
offsetHeight
} = this.view.scrollDOM;
scrollRectIntoView(this.view.scrollDOM, targetRect, range.head < range.anchor ? -1 : 1, target.x, target.y, Math.max(Math.min(target.xMargin, offsetWidth), -offsetWidth), Math.max(Math.min(target.yMargin, offsetHeight), -offsetHeight), this.view.textDirection == Direction.LTR);
}
};
BlockGapWidget = class extends WidgetType {
constructor(height) {
super();
this.height = height;
}
toDOM() {
let elt = document.createElement("div");
this.updateDOM(elt);
return elt;
}
eq(other) {
return other.height == this.height;
}
updateDOM(elt) {
elt.style.height = this.height + "px";
return true;
}
get estimatedHeight() {
return this.height;
}
};
DecorationComparator$1 = class DecorationComparator$3 {
constructor() {
this.changes = [];
}
compareRange(from, to) {
addRange(from, to, this.changes);
}
comparePoint(from, to) {
addRange(from, to, this.changes);
}
};
InputState = class {
setSelectionOrigin(origin) {
this.lastSelectionOrigin = origin;
this.lastSelectionTime = Date.now();
}
constructor(view) {
this.view = view;
this.lastKeyCode = 0;
this.lastKeyTime = 0;
this.lastTouchTime = 0;
this.lastFocusTime = 0;
this.lastScrollTop = 0;
this.lastScrollLeft = 0;
this.pendingIOSKey = void 0;
this.lastSelectionOrigin = null;
this.lastSelectionTime = 0;
this.lastEscPress = 0;
this.lastContextMenu = 0;
this.scrollHandlers = [];
this.handlers = Object.create(null);
this.composing = -1;
this.compositionFirstChange = null;
this.compositionEndedAt = 0;
this.compositionPendingKey = false;
this.compositionPendingChange = false;
this.mouseSelection = null;
this.draggedContent = null;
this.handleEvent = this.handleEvent.bind(this);
this.notifiedFocused = view.hasFocus;
if (browser.safari) view.contentDOM.addEventListener("input", () => null);
if (browser.gecko) firefoxCopyCutHack(view.contentDOM.ownerDocument);
}
handleEvent(event) {
if (!eventBelongsToEditor(this.view, event) || this.ignoreDuringComposition(event)) return;
if (event.type == "keydown" && this.keydown(event)) return;
this.runHandlers(event.type, event);
}
runHandlers(type, event) {
let handlers$2 = this.handlers[type];
if (handlers$2) {
for (let observer of handlers$2.observers) observer(this.view, event);
for (let handler of handlers$2.handlers) {
if (event.defaultPrevented) break;
if (handler(this.view, event)) {
event.preventDefault();
break;
}
}
}
}
ensureHandlers(plugins) {
let handlers$2 = computeHandlers(plugins),
prev = this.handlers,
dom = this.view.contentDOM;
for (let type in handlers$2) if (type != "scroll") {
let passive = !handlers$2[type].handlers.length;
let exists = prev[type];
if (exists && passive != !exists.handlers.length) {
dom.removeEventListener(type, this.handleEvent);
exists = null;
}
if (!exists) dom.addEventListener(type, this.handleEvent, {
passive
});
}
for (let type in prev) if (type != "scroll" && !handlers$2[type]) dom.removeEventListener(type, this.handleEvent);
this.handlers = handlers$2;
}
keydown(event) {
this.lastKeyCode = event.keyCode;
this.lastKeyTime = Date.now();
if (event.keyCode == 9 && Date.now() < this.lastEscPress + 2e3) return true;
if (event.keyCode != 27 && modifierCodes.indexOf(event.keyCode) < 0) this.view.inputState.lastEscPress = 0;
if (browser.android && browser.chrome && !event.synthetic && (event.keyCode == 13 || event.keyCode == 8)) {
this.view.observer.delayAndroidKey(event.key, event.keyCode);
return true;
}
let pending;
if (browser.ios && !event.synthetic && !event.altKey && !event.metaKey && ((pending = PendingKeys.find(key => key.keyCode == event.keyCode)) && !event.ctrlKey || EmacsyPendingKeys.indexOf(event.key) > -1 && event.ctrlKey && !event.shiftKey)) {
this.pendingIOSKey = pending || event;
setTimeout(() => this.flushIOSKey(), 250);
return true;
}
if (event.keyCode != 229) this.view.observer.forceFlush();
return false;
}
flushIOSKey() {
let key = this.pendingIOSKey;
if (!key) return false;
this.pendingIOSKey = void 0;
return dispatchKey(this.view.contentDOM, key.key, key.keyCode);
}
ignoreDuringComposition(event) {
if (!/^key/.test(event.type)) return false;
if (this.composing > 0) return true;
if (browser.safari && !browser.ios && this.compositionPendingKey && Date.now() - this.compositionEndedAt < 100) {
this.compositionPendingKey = false;
return true;
}
return false;
}
startMouseSelection(mouseSelection) {
if (this.mouseSelection) this.mouseSelection.destroy();
this.mouseSelection = mouseSelection;
}
update(update) {
if (this.mouseSelection) this.mouseSelection.update(update);
if (this.draggedContent && update.docChanged) this.draggedContent = this.draggedContent.map(update.changes);
if (update.transactions.length) this.lastKeyCode = this.lastSelectionTime = 0;
}
destroy() {
if (this.mouseSelection) this.mouseSelection.destroy();
}
};
PendingKeys = [{
key: "Backspace",
keyCode: 8,
inputType: "deleteContentBackward"
}, {
key: "Enter",
keyCode: 13,
inputType: "insertParagraph"
}, {
key: "Enter",
keyCode: 13,
inputType: "insertLineBreak"
}, {
key: "Delete",
keyCode: 46,
inputType: "deleteContentForward"
}];
EmacsyPendingKeys = "dthko";
modifierCodes = [16, 17, 18, 20, 91, 92, 224, 225];
dragScrollMargin = 6;
MouseSelection = class {
constructor(view, startEvent, style, mustSelect) {
this.view = view;
this.startEvent = startEvent;
this.style = style;
this.mustSelect = mustSelect;
this.scrollSpeed = {
x: 0,
y: 0
};
this.scrolling = -1;
this.lastEvent = startEvent;
this.scrollParent = scrollableParent(view.contentDOM);
this.atoms = view.state.facet(atomicRanges).map(f => f(view));
let doc$2 = view.contentDOM.ownerDocument;
doc$2.addEventListener("mousemove", this.move = this.move.bind(this));
doc$2.addEventListener("mouseup", this.up = this.up.bind(this));
this.extend = startEvent.shiftKey;
this.multiple = view.state.facet(EditorState.allowMultipleSelections) && addsSelectionRange(view, startEvent);
this.dragging = isInPrimarySelection(view, startEvent) && getClickType(startEvent) == 1 ? null : false;
}
start(event) {
if (this.dragging === false) this.select(event);
}
move(event) {
var _a$2;
if (event.buttons == 0) return this.destroy();
if (this.dragging || this.dragging == null && dist(this.startEvent, event) < 10) return;
this.select(this.lastEvent = event);
let sx = 0,
sy = 0;
let rect = ((_a$2 = this.scrollParent) === null || _a$2 === void 0 ? void 0 : _a$2.getBoundingClientRect()) || {
left: 0,
top: 0,
right: this.view.win.innerWidth,
bottom: this.view.win.innerHeight
};
let margins = getScrollMargins(this.view);
if (event.clientX - margins.left <= rect.left + dragScrollMargin) sx = -dragScrollSpeed(rect.left - event.clientX);else if (event.clientX + margins.right >= rect.right - dragScrollMargin) sx = dragScrollSpeed(event.clientX - rect.right);
if (event.clientY - margins.top <= rect.top + dragScrollMargin) sy = -dragScrollSpeed(rect.top - event.clientY);else if (event.clientY + margins.bottom >= rect.bottom - dragScrollMargin) sy = dragScrollSpeed(event.clientY - rect.bottom);
this.setScrollSpeed(sx, sy);
}
up(event) {
if (this.dragging == null) this.select(this.lastEvent);
if (!this.dragging) event.preventDefault();
this.destroy();
}
destroy() {
this.setScrollSpeed(0, 0);
let doc$2 = this.view.contentDOM.ownerDocument;
doc$2.removeEventListener("mousemove", this.move);
doc$2.removeEventListener("mouseup", this.up);
this.view.inputState.mouseSelection = this.view.inputState.draggedContent = null;
}
setScrollSpeed(sx, sy) {
this.scrollSpeed = {
x: sx,
y: sy
};
if (sx || sy) {
if (this.scrolling < 0) this.scrolling = setInterval(() => this.scroll(), 50);
} else if (this.scrolling > -1) {
clearInterval(this.scrolling);
this.scrolling = -1;
}
}
scroll() {
if (this.scrollParent) {
this.scrollParent.scrollLeft += this.scrollSpeed.x;
this.scrollParent.scrollTop += this.scrollSpeed.y;
} else this.view.win.scrollBy(this.scrollSpeed.x, this.scrollSpeed.y);
if (this.dragging === false) this.select(this.lastEvent);
}
skipAtoms(sel) {
let ranges = null;
for (let i$1 = 0; i$1 < sel.ranges.length; i$1++) {
let range = sel.ranges[i$1],
updated = null;
if (range.empty) {
let pos = skipAtomicRanges(this.atoms, range.from, 0);
if (pos != range.from) updated = EditorSelection.cursor(pos, -1);
} else {
let from = skipAtomicRanges(this.atoms, range.from, -1);
let to = skipAtomicRanges(this.atoms, range.to, 1);
if (from != range.from || to != range.to) updated = EditorSelection.range(range.from == range.anchor ? from : to, range.from == range.head ? from : to);
}
if (updated) {
if (!ranges) ranges = sel.ranges.slice();
ranges[i$1] = updated;
}
}
return ranges ? EditorSelection.create(ranges, sel.mainIndex) : sel;
}
select(event) {
let {
view
} = this,
selection = this.skipAtoms(this.style.get(event, this.extend, this.multiple));
if (this.mustSelect || !selection.eq(view.state.selection) || selection.main.assoc != view.state.selection.main.assoc && this.dragging === false) this.view.dispatch({
selection,
userEvent: "select.pointer"
});
this.mustSelect = false;
}
update(update) {
if (this.style.update(update)) setTimeout(() => this.select(this.lastEvent), 20);
}
};
handlers = /* @__PURE__ */Object.create(null);
observers = /* @__PURE__ */Object.create(null);
brokenClipboardAPI = browser.ie && browser.ie_version < 15 || browser.ios && browser.webkit_version < 604;
observers.scroll = view => {
view.inputState.lastScrollTop = view.scrollDOM.scrollTop;
view.inputState.lastScrollLeft = view.scrollDOM.scrollLeft;
};
handlers.keydown = (view, event) => {
view.inputState.setSelectionOrigin("select");
if (event.keyCode == 27) view.inputState.lastEscPress = Date.now();
return false;
};
observers.touchstart = (view, e) => {
view.inputState.lastTouchTime = Date.now();
view.inputState.setSelectionOrigin("select.pointer");
};
observers.touchmove = view => {
view.inputState.setSelectionOrigin("select.pointer");
};
handlers.mousedown = (view, event) => {
view.observer.flush();
if (view.inputState.lastTouchTime > Date.now() - 2e3) return false;
let style = null;
for (let makeStyle of view.state.facet(mouseSelectionStyle)) {
style = makeStyle(view, event);
if (style) break;
}
if (!style && event.button == 0) style = basicMouseSelection(view, event);
if (style) {
let mustFocus = !view.hasFocus;
view.inputState.startMouseSelection(new MouseSelection(view, event, style, mustFocus));
if (mustFocus) view.observer.ignore(() => focusPreventScroll(view.contentDOM));
let mouseSel = view.inputState.mouseSelection;
if (mouseSel) {
mouseSel.start(event);
return mouseSel.dragging === false;
}
}
return false;
};
insideY = (y, rect) => y >= rect.top && y <= rect.bottom;
inside = (x, y, rect) => insideY(y, rect) && x >= rect.left && x <= rect.right;
BadMouseDetail = browser.ie && browser.ie_version <= 11;
lastMouseDown = null, lastMouseDownCount = 0, lastMouseDownTime = 0;
handlers.dragstart = (view, event) => {
let {
selection: {
main: range
}
} = view.state;
if (event.target.draggable) {
let cView = view.docView.nearest(event.target);
if (cView && cView.isWidget) {
let from = cView.posAtStart,
to = from + cView.length;
if (from >= range.to || to <= range.from) range = EditorSelection.range(from, to);
}
}
let {
inputState
} = view;
if (inputState.mouseSelection) inputState.mouseSelection.dragging = true;
inputState.draggedContent = range;
if (event.dataTransfer) {
event.dataTransfer.setData("Text", view.state.sliceDoc(range.from, range.to));
event.dataTransfer.effectAllowed = "copyMove";
}
return false;
};
handlers.dragend = view => {
view.inputState.draggedContent = null;
return false;
};
handlers.drop = (view, event) => {
if (!event.dataTransfer) return false;
if (view.state.readOnly) return true;
let files = event.dataTransfer.files;
if (files && files.length) {
let text = Array(files.length),
read$1 = 0;
let finishFile = () => {
if (++read$1 == files.length) dropText(view, event, text.filter(s => s != null).join(view.state.lineBreak), false);
};
for (let i$1 = 0; i$1 < files.length; i$1++) {
let reader = new FileReader();
reader.onerror = finishFile;
reader.onload = () => {
if (!/[\x00-\x08\x0e-\x1f]{2}/.test(reader.result)) text[i$1] = reader.result;
finishFile();
};
reader.readAsText(files[i$1]);
}
return true;
} else {
let text = event.dataTransfer.getData("Text");
if (text) {
dropText(view, event, text, true);
return true;
}
}
return false;
};
handlers.paste = (view, event) => {
if (view.state.readOnly) return true;
view.observer.flush();
let data = brokenClipboardAPI ? null : event.clipboardData;
if (data) {
doPaste(view, data.getData("text/plain") || data.getData("text/uri-text"));
return true;
} else {
capturePaste(view);
return false;
}
};
lastLinewiseCopy = null;
handlers.copy = handlers.cut = (view, event) => {
let {
text,
ranges,
linewise
} = copiedRange(view.state);
if (!text && !linewise) return false;
lastLinewiseCopy = linewise ? text : null;
if (event.type == "cut" && !view.state.readOnly) view.dispatch({
changes: ranges,
scrollIntoView: true,
userEvent: "delete.cut"
});
let data = brokenClipboardAPI ? null : event.clipboardData;
if (data) {
data.clearData();
data.setData("text/plain", text);
return true;
} else {
captureCopy(view, text);
return false;
}
};
isFocusChange = /* @__PURE__ */Annotation.define();
observers.focus = view => {
view.inputState.lastFocusTime = Date.now();
if (!view.scrollDOM.scrollTop && (view.inputState.lastScrollTop || view.inputState.lastScrollLeft)) {
view.scrollDOM.scrollTop = view.inputState.lastScrollTop;
view.scrollDOM.scrollLeft = view.inputState.lastScrollLeft;
}
updateForFocusChange(view);
};
observers.blur = view => {
view.observer.clearSelectionRange();
updateForFocusChange(view);
};
observers.compositionstart = observers.compositionupdate = view => {
if (view.inputState.compositionFirstChange == null) view.inputState.compositionFirstChange = true;
if (view.inputState.composing < 0) view.inputState.composing = 0;
};
observers.compositionend = view => {
view.inputState.composing = -1;
view.inputState.compositionEndedAt = Date.now();
view.inputState.compositionPendingKey = true;
view.inputState.compositionPendingChange = view.observer.pendingRecords().length > 0;
view.inputState.compositionFirstChange = null;
if (browser.chrome && browser.android) view.observer.flushSoon();else if (view.inputState.compositionPendingChange) Promise.resolve().then(() => view.observer.flush());else setTimeout(() => {
if (view.inputState.composing < 0 && view.docView.hasComposition) view.update([]);
}, 50);
};
observers.contextmenu = view => {
view.inputState.lastContextMenu = Date.now();
};
handlers.beforeinput = (view, event) => {
var _a$2;
let pending;
if (browser.chrome && browser.android && (pending = PendingKeys.find(key => key.inputType == event.inputType))) {
view.observer.delayAndroidKey(pending.key, pending.keyCode);
if (pending.key == "Backspace" || pending.key == "Delete") {
let startViewHeight = ((_a$2 = window.visualViewport) === null || _a$2 === void 0 ? void 0 : _a$2.height) || 0;
setTimeout(() => {
var _a$3;
if ((((_a$3 = window.visualViewport) === null || _a$3 === void 0 ? void 0 : _a$3.height) || 0) > startViewHeight + 10 && view.hasFocus) {
view.contentDOM.blur();
view.focus();
}
}, 100);
}
}
return false;
};
appliedFirefoxHack = /* @__PURE__ */new Set();
wrappingWhiteSpace = ["pre-wrap", "normal", "pre-line", "break-spaces"];
HeightOracle = class {
constructor(lineWrapping) {
this.lineWrapping = lineWrapping;
this.doc = Text.empty;
this.heightSamples = {};
this.lineHeight = 14;
this.charWidth = 7;
this.textHeight = 14;
this.lineLength = 30;
this.heightChanged = false;
}
heightForGap(from, to) {
let lines = this.doc.lineAt(to).number - this.doc.lineAt(from).number + 1;
if (this.lineWrapping) lines += Math.max(0, Math.ceil((to - from - lines * this.lineLength * .5) / this.lineLength));
return this.lineHeight * lines;
}
heightForLine(length) {
if (!this.lineWrapping) return this.lineHeight;
return (1 + Math.max(0, Math.ceil((length - this.lineLength) / (this.lineLength - 5)))) * this.lineHeight;
}
setDoc(doc$2) {
this.doc = doc$2;
return this;
}
mustRefreshForWrapping(whiteSpace) {
return wrappingWhiteSpace.indexOf(whiteSpace) > -1 != this.lineWrapping;
}
mustRefreshForHeights(lineHeights) {
let newHeight = false;
for (let i$1 = 0; i$1 < lineHeights.length; i$1++) {
let h = lineHeights[i$1];
if (h < 0) i$1++;else if (!this.heightSamples[Math.floor(h * 10)]) {
newHeight = true;
this.heightSamples[Math.floor(h * 10)] = true;
}
}
return newHeight;
}
refresh(whiteSpace, lineHeight, charWidth, textHeight, lineLength, knownHeights) {
let lineWrapping = wrappingWhiteSpace.indexOf(whiteSpace) > -1;
let changed = Math.round(lineHeight) != Math.round(this.lineHeight) || this.lineWrapping != lineWrapping;
this.lineWrapping = lineWrapping;
this.lineHeight = lineHeight;
this.charWidth = charWidth;
this.textHeight = textHeight;
this.lineLength = lineLength;
if (changed) {
this.heightSamples = {};
for (let i$1 = 0; i$1 < knownHeights.length; i$1++) {
let h = knownHeights[i$1];
if (h < 0) i$1++;else this.heightSamples[Math.floor(h * 10)] = true;
}
}
return changed;
}
};
MeasuredHeights = class {
constructor(from, heights) {
this.from = from;
this.heights = heights;
this.index = 0;
}
get more() {
return this.index < this.heights.length;
}
};
/**
Record used to represent information about a block-level element
in the editor view.
*/
BlockInfo = class BlockInfo {
/**
@internal
*/
constructor(from, length, top$1, height, _content) {
this.from = from;
this.length = length;
this.top = top$1;
this.height = height;
this._content = _content;
}
/**
The type of element this is. When querying lines, this may be
an array of all the blocks that make up the line.
*/
get type() {
return typeof this._content == "number" ? BlockType.Text : Array.isArray(this._content) ? this._content : this._content.type;
}
/**
The end of the element as a document position.
*/
get to() {
return this.from + this.length;
}
/**
The bottom position of the element.
*/
get bottom() {
return this.top + this.height;
}
/**
If this is a widget block, this will return the widget
associated with it.
*/
get widget() {
return this._content instanceof PointDecoration ? this._content.widget : null;
}
/**
If this is a textblock, this holds the number of line breaks
that appear in widgets inside the block.
*/
get widgetLineBreaks() {
return typeof this._content == "number" ? this._content : 0;
}
/**
@internal
*/
join(other) {
let content$1 = (Array.isArray(this._content) ? this._content : [this]).concat(Array.isArray(other._content) ? other._content : [other]);
return new BlockInfo(this.from, this.length + other.length, this.top, this.height + other.height, content$1);
}
};
QueryType = /* @__PURE__ */function (QueryType$3) {
QueryType$3[QueryType$3["ByPos"] = 0] = "ByPos";
QueryType$3[QueryType$3["ByHeight"] = 1] = "ByHeight";
QueryType$3[QueryType$3["ByPosNoHeight"] = 2] = "ByPosNoHeight";
return QueryType$3;
}(QueryType || (QueryType = {}));
Epsilon = .001;
HeightMap = class HeightMap {
constructor(length, height, flags = 2) {
this.length = length;
this.height = height;
this.flags = flags;
}
get outdated() {
return (this.flags & 2) > 0;
}
set outdated(value) {
this.flags = (value ? 2 : 0) | this.flags & -3;
}
setHeight(oracle, height) {
if (this.height != height) {
if (Math.abs(this.height - height) > Epsilon) oracle.heightChanged = true;
this.height = height;
}
}
replace(_from, _to, nodes) {
return HeightMap.of(nodes);
}
decomposeLeft(_to, result) {
result.push(this);
}
decomposeRight(_from, result) {
result.push(this);
}
applyChanges(decorations$2, oldDoc, oracle, changes) {
let me = this,
doc$2 = oracle.doc;
for (let i$1 = changes.length - 1; i$1 >= 0; i$1--) {
let {
fromA,
toA,
fromB,
toB
} = changes[i$1];
let start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle.setDoc(oldDoc), 0, 0);
let end = start.to >= toA ? start : me.lineAt(toA, QueryType.ByPosNoHeight, oracle, 0, 0);
toB += end.to - toA;
toA = end.to;
while (i$1 > 0 && start.from <= changes[i$1 - 1].toA) {
fromA = changes[i$1 - 1].fromA;
fromB = changes[i$1 - 1].fromB;
i$1--;
if (fromA < start.from) start = me.lineAt(fromA, QueryType.ByPosNoHeight, oracle, 0, 0);
}
fromB += start.from - fromA;
fromA = start.from;
let nodes = NodeBuilder.build(oracle.setDoc(doc$2), decorations$2, fromB, toB);
me = me.replace(fromA, toA, nodes);
}
return me.updateHeight(oracle, 0);
}
static empty() {
return new HeightMapText(0, 0);
}
static of(nodes) {
if (nodes.length == 1) return nodes[0];
let i$1 = 0,
j = nodes.length,
before = 0,
after = 0;
for (;;) if (i$1 == j) {
if (before > after * 2) {
let split = nodes[i$1 - 1];
if (split.break) nodes.splice(--i$1, 1, split.left, null, split.right);else nodes.splice(--i$1, 1, split.left, split.right);
j += 1 + split.break;
before -= split.size;
} else if (after > before * 2) {
let split = nodes[j];
if (split.break) nodes.splice(j, 1, split.left, null, split.right);else nodes.splice(j, 1, split.left, split.right);
j += 2 + split.break;
after -= split.size;
} else break;
} else if (before < after) {
let next = nodes[i$1++];
if (next) before += next.size;
} else {
let next = nodes[--j];
if (next) after += next.size;
}
let brk = 0;
if (nodes[i$1 - 1] == null) {
brk = 1;
i$1--;
} else if (nodes[i$1] == null) {
brk = 1;
j++;
}
return new HeightMapBranch(HeightMap.of(nodes.slice(0, i$1)), brk, HeightMap.of(nodes.slice(j)));
}
};
HeightMap.prototype.size = 1;
HeightMapBlock = class extends HeightMap {
constructor(length, height, deco) {
super(length, height);
this.deco = deco;
}
blockAt(_height, _oracle, top$1, offset) {
return new BlockInfo(offset, this.length, top$1, this.height, this.deco || 0);
}
lineAt(_value, _type, oracle, top$1, offset) {
return this.blockAt(0, oracle, top$1, offset);
}
forEachLine(from, to, oracle, top$1, offset, f) {
if (from <= offset + this.length && to >= offset) f(this.blockAt(0, oracle, top$1, offset));
}
updateHeight(oracle, offset = 0, _force = false, measured) {
if (measured && measured.from <= offset && measured.more) this.setHeight(oracle, measured.heights[measured.index++]);
this.outdated = false;
return this;
}
toString() {
return `block(${this.length})`;
}
};
HeightMapText = class HeightMapText extends HeightMapBlock {
constructor(length, height) {
super(length, height, null);
this.collapsed = 0;
this.widgetHeight = 0;
this.breaks = 0;
}
blockAt(_height, _oracle, top$1, offset) {
return new BlockInfo(offset, this.length, top$1, this.height, this.breaks);
}
replace(_from, _to, nodes) {
let node = nodes[0];
if (nodes.length == 1 && (node instanceof HeightMapText || node instanceof HeightMapGap && node.flags & 4) && Math.abs(this.length - node.length) < 10) {
if (node instanceof HeightMapGap) node = new HeightMapText(node.length, this.height);else node.height = this.height;
if (!this.outdated) node.outdated = false;
return node;
} else return HeightMap.of(nodes);
}
updateHeight(oracle, offset = 0, force = false, measured) {
if (measured && measured.from <= offset && measured.more) this.setHeight(oracle, measured.heights[measured.index++]);else if (force || this.outdated) this.setHeight(oracle, Math.max(this.widgetHeight, oracle.heightForLine(this.length - this.collapsed)) + this.breaks * oracle.lineHeight);
this.outdated = false;
return this;
}
toString() {
return `line(${this.length}${this.collapsed ? -this.collapsed : ""}${this.widgetHeight ? ":" + this.widgetHeight : ""})`;
}
};
HeightMapGap = class HeightMapGap extends HeightMap {
constructor(length) {
super(length, 0);
}
heightMetrics(oracle, offset) {
let firstLine = oracle.doc.lineAt(offset).number,
lastLine = oracle.doc.lineAt(offset + this.length).number;
let lines = lastLine - firstLine + 1;
let perLine,
perChar = 0;
if (oracle.lineWrapping) {
let totalPerLine = Math.min(this.height, oracle.lineHeight * lines);
perLine = totalPerLine / lines;
if (this.length > lines + 1) perChar = (this.height - totalPerLine) / (this.length - lines - 1);
} else perLine = this.height / lines;
return {
firstLine,
lastLine,
perLine,
perChar
};
}
blockAt(height, oracle, top$1, offset) {
let {
firstLine,
lastLine,
perLine,
perChar
} = this.heightMetrics(oracle, offset);
if (oracle.lineWrapping) {
let guess = offset + Math.round(Math.max(0, Math.min(1, (height - top$1) / this.height)) * this.length);
let line = oracle.doc.lineAt(guess),
lineHeight = perLine + line.length * perChar;
let lineTop = Math.max(top$1, height - lineHeight / 2);
return new BlockInfo(line.from, line.length, lineTop, lineHeight, 0);
} else {
let line = Math.max(0, Math.min(lastLine - firstLine, Math.floor((height - top$1) / perLine)));
let {
from,
length
} = oracle.doc.line(firstLine + line);
return new BlockInfo(from, length, top$1 + perLine * line, perLine, 0);
}
}
lineAt(value, type, oracle, top$1, offset) {
if (type == QueryType.ByHeight) return this.blockAt(value, oracle, top$1, offset);
if (type == QueryType.ByPosNoHeight) {
let {
from,
to
} = oracle.doc.lineAt(value);
return new BlockInfo(from, to - from, 0, 0, 0);
}
let {
firstLine,
perLine,
perChar
} = this.heightMetrics(oracle, offset);
let line = oracle.doc.lineAt(value),
lineHeight = perLine + line.length * perChar;
let linesAbove = line.number - firstLine;
let lineTop = top$1 + perLine * linesAbove + perChar * (line.from - offset - linesAbove);
return new BlockInfo(line.from, line.length, Math.max(top$1, Math.min(lineTop, top$1 + this.height - lineHeight)), lineHeight, 0);
}
forEachLine(from, to, oracle, top$1, offset, f) {
from = Math.max(from, offset);
to = Math.min(to, offset + this.length);
let {
firstLine,
perLine,
perChar
} = this.heightMetrics(oracle, offset);
for (let pos = from, lineTop = top$1; pos <= to;) {
let line = oracle.doc.lineAt(pos);
if (pos == from) {
let linesAbove = line.number - firstLine;
lineTop += perLine * linesAbove + perChar * (from - offset - linesAbove);
}
let lineHeight = perLine + perChar * line.length;
f(new BlockInfo(line.from, line.length, lineTop, lineHeight, 0));
lineTop += lineHeight;
pos = line.to + 1;
}
}
replace(from, to, nodes) {
let after = this.length - to;
if (after > 0) {
let last = nodes[nodes.length - 1];
if (last instanceof HeightMapGap) nodes[nodes.length - 1] = new HeightMapGap(last.length + after);else nodes.push(null, new HeightMapGap(after - 1));
}
if (from > 0) {
let first = nodes[0];
if (first instanceof HeightMapGap) nodes[0] = new HeightMapGap(from + first.length);else nodes.unshift(new HeightMapGap(from - 1), null);
}
return HeightMap.of(nodes);
}
decomposeLeft(to, result) {
result.push(new HeightMapGap(to - 1), null);
}
decomposeRight(from, result) {
result.push(null, new HeightMapGap(this.length - from - 1));
}
updateHeight(oracle, offset = 0, force = false, measured) {
let end = offset + this.length;
if (measured && measured.from <= offset + this.length && measured.more) {
let nodes = [],
pos = Math.max(offset, measured.from),
singleHeight = -1;
if (measured.from > offset) nodes.push(new HeightMapGap(measured.from - offset - 1).updateHeight(oracle, offset));
while (pos <= end && measured.more) {
let len = oracle.doc.lineAt(pos).length;
if (nodes.length) nodes.push(null);
let height = measured.heights[measured.index++];
if (singleHeight == -1) singleHeight = height;else if (Math.abs(height - singleHeight) >= Epsilon) singleHeight = -2;
let line = new HeightMapText(len, height);
line.outdated = false;
nodes.push(line);
pos += len + 1;
}
if (pos <= end) nodes.push(null, new HeightMapGap(end - pos).updateHeight(oracle, pos));
let result = HeightMap.of(nodes);
if (singleHeight < 0 || Math.abs(result.height - this.height) >= Epsilon || Math.abs(singleHeight - this.heightMetrics(oracle, offset).perLine) >= Epsilon) oracle.heightChanged = true;
return result;
} else if (force || this.outdated) {
this.setHeight(oracle, oracle.heightForGap(offset, offset + this.length));
this.outdated = false;
}
return this;
}
toString() {
return `gap(${this.length})`;
}
};
HeightMapBranch = class extends HeightMap {
constructor(left, brk, right) {
super(left.length + brk + right.length, left.height + right.height, brk | (left.outdated || right.outdated ? 2 : 0));
this.left = left;
this.right = right;
this.size = left.size + right.size;
}
get break() {
return this.flags & 1;
}
blockAt(height, oracle, top$1, offset) {
let mid = top$1 + this.left.height;
return height < mid ? this.left.blockAt(height, oracle, top$1, offset) : this.right.blockAt(height, oracle, mid, offset + this.left.length + this.break);
}
lineAt(value, type, oracle, top$1, offset) {
let rightTop = top$1 + this.left.height,
rightOffset = offset + this.left.length + this.break;
let left = type == QueryType.ByHeight ? value < rightTop : value < rightOffset;
let base$1 = left ? this.left.lineAt(value, type, oracle, top$1, offset) : this.right.lineAt(value, type, oracle, rightTop, rightOffset);
if (this.break || (left ? base$1.to < rightOffset : base$1.from > rightOffset)) return base$1;
let subQuery = type == QueryType.ByPosNoHeight ? QueryType.ByPosNoHeight : QueryType.ByPos;
if (left) return base$1.join(this.right.lineAt(rightOffset, subQuery, oracle, rightTop, rightOffset));else return this.left.lineAt(rightOffset, subQuery, oracle, top$1, offset).join(base$1);
}
forEachLine(from, to, oracle, top$1, offset, f) {
let rightTop = top$1 + this.left.height,
rightOffset = offset + this.left.length + this.break;
if (this.break) {
if (from < rightOffset) this.left.forEachLine(from, to, oracle, top$1, offset, f);
if (to >= rightOffset) this.right.forEachLine(from, to, oracle, rightTop, rightOffset, f);
} else {
let mid = this.lineAt(rightOffset, QueryType.ByPos, oracle, top$1, offset);
if (from < mid.from) this.left.forEachLine(from, mid.from - 1, oracle, top$1, offset, f);
if (mid.to >= from && mid.from <= to) f(mid);
if (to > mid.to) this.right.forEachLine(mid.to + 1, to, oracle, rightTop, rightOffset, f);
}
}
replace(from, to, nodes) {
let rightStart = this.left.length + this.break;
if (to < rightStart) return this.balanced(this.left.replace(from, to, nodes), this.right);
if (from > this.left.length) return this.balanced(this.left, this.right.replace(from - rightStart, to - rightStart, nodes));
let result = [];
if (from > 0) this.decomposeLeft(from, result);
let left = result.length;
for (let node of nodes) result.push(node);
if (from > 0) mergeGaps(result, left - 1);
if (to < this.length) {
let right = result.length;
this.decomposeRight(to, result);
mergeGaps(result, right);
}
return HeightMap.of(result);
}
decomposeLeft(to, result) {
let left = this.left.length;
if (to <= left) return this.left.decomposeLeft(to, result);
result.push(this.left);
if (this.break) {
left++;
if (to >= left) result.push(null);
}
if (to > left) this.right.decomposeLeft(to - left, result);
}
decomposeRight(from, result) {
let left = this.left.length,
right = left + this.break;
if (from >= right) return this.right.decomposeRight(from - right, result);
if (from < left) this.left.decomposeRight(from, result);
if (this.break && from < right) result.push(null);
result.push(this.right);
}
balanced(left, right) {
if (left.size > 2 * right.size || right.size > 2 * left.size) return HeightMap.of(this.break ? [left, null, right] : [left, right]);
this.left = left;
this.right = right;
this.height = left.height + right.height;
this.outdated = left.outdated || right.outdated;
this.size = left.size + right.size;
this.length = left.length + this.break + right.length;
return this;
}
updateHeight(oracle, offset = 0, force = false, measured) {
let {
left,
right
} = this,
rightStart = offset + left.length + this.break,
rebalance = null;
if (measured && measured.from <= offset + left.length && measured.more) rebalance = left = left.updateHeight(oracle, offset, force, measured);else left.updateHeight(oracle, offset, force);
if (measured && measured.from <= rightStart + right.length && measured.more) rebalance = right = right.updateHeight(oracle, rightStart, force, measured);else right.updateHeight(oracle, rightStart, force);
if (rebalance) return this.balanced(left, right);
this.height = this.left.height + this.right.height;
this.outdated = false;
return this;
}
toString() {
return this.left + (this.break ? " " : "-") + this.right;
}
};
relevantWidgetHeight = 5;
NodeBuilder = class NodeBuilder {
constructor(pos, oracle) {
this.pos = pos;
this.oracle = oracle;
this.nodes = [];
this.lineStart = -1;
this.lineEnd = -1;
this.covering = null;
this.writtenTo = pos;
}
get isCovered() {
return this.covering && this.nodes[this.nodes.length - 1] == this.covering;
}
span(_from, to) {
if (this.lineStart > -1) {
let end = Math.min(to, this.lineEnd),
last = this.nodes[this.nodes.length - 1];
if (last instanceof HeightMapText) last.length += end - this.pos;else if (end > this.pos || !this.isCovered) this.nodes.push(new HeightMapText(end - this.pos, -1));
this.writtenTo = end;
if (to > end) {
this.nodes.push(null);
this.writtenTo++;
this.lineStart = -1;
}
}
this.pos = to;
}
point(from, to, deco) {
if (from < to || deco.heightRelevant) {
let height = deco.widget ? deco.widget.estimatedHeight : 0;
let breaks = deco.widget ? deco.widget.lineBreaks : 0;
if (height < 0) height = this.oracle.lineHeight;
let len = to - from;
if (deco.block) this.addBlock(new HeightMapBlock(len, height, deco));else if (len || breaks || height >= relevantWidgetHeight) this.addLineDeco(height, breaks, len);
} else if (to > from) this.span(from, to);
if (this.lineEnd > -1 && this.lineEnd < this.pos) this.lineEnd = this.oracle.doc.lineAt(this.pos).to;
}
enterLine() {
if (this.lineStart > -1) return;
let {
from,
to
} = this.oracle.doc.lineAt(this.pos);
this.lineStart = from;
this.lineEnd = to;
if (this.writtenTo < from) {
if (this.writtenTo < from - 1 || this.nodes[this.nodes.length - 1] == null) this.nodes.push(this.blankContent(this.writtenTo, from - 1));
this.nodes.push(null);
}
if (this.pos > from) this.nodes.push(new HeightMapText(this.pos - from, -1));
this.writtenTo = this.pos;
}
blankContent(from, to) {
let gap = new HeightMapGap(to - from);
if (this.oracle.doc.lineAt(from).to == to) gap.flags |= 4;
return gap;
}
ensureLine() {
this.enterLine();
let last = this.nodes.length ? this.nodes[this.nodes.length - 1] : null;
if (last instanceof HeightMapText) return last;
let line = new HeightMapText(0, -1);
this.nodes.push(line);
return line;
}
addBlock(block) {
this.enterLine();
let deco = block.deco;
if (deco && deco.startSide > 0 && !this.isCovered) this.ensureLine();
this.nodes.push(block);
this.writtenTo = this.pos = this.pos + block.length;
if (deco && deco.endSide > 0) this.covering = block;
}
addLineDeco(height, breaks, length) {
let line = this.ensureLine();
line.length += length;
line.collapsed += length;
line.widgetHeight = Math.max(line.widgetHeight, height);
line.breaks += breaks;
this.writtenTo = this.pos = this.pos + length;
}
finish(from) {
let last = this.nodes.length == 0 ? null : this.nodes[this.nodes.length - 1];
if (this.lineStart > -1 && !(last instanceof HeightMapText) && !this.isCovered) this.nodes.push(new HeightMapText(0, -1));else if (this.writtenTo < this.pos || last == null) this.nodes.push(this.blankContent(this.writtenTo, this.pos));
let pos = from;
for (let node of this.nodes) {
if (node instanceof HeightMapText) node.updateHeight(this.oracle, pos);
pos += node ? node.length : 1;
}
return this.nodes;
}
static build(oracle, decorations$2, from, to) {
let builder = new NodeBuilder(from, oracle);
RangeSet$1.spans(decorations$2, from, to, builder, 0);
return builder.finish(from);
}
};
DecorationComparator = class {
constructor() {
this.changes = [];
}
compareRange() {}
comparePoint(from, to, a, b) {
if (from < to || a && a.heightRelevant || b && b.heightRelevant) addRange(from, to, this.changes, 5);
}
};
LineGap = class {
constructor(from, to, size) {
this.from = from;
this.to = to;
this.size = size;
}
static same(a, b) {
if (a.length != b.length) return false;
for (let i$1 = 0; i$1 < a.length; i$1++) {
let gA = a[i$1],
gB = b[i$1];
if (gA.from != gB.from || gA.to != gB.to || gA.size != gB.size) return false;
}
return true;
}
draw(viewState, wrapping) {
return Decoration.replace({
widget: new LineGapWidget(this.size * (wrapping ? viewState.scaleY : viewState.scaleX), wrapping)
}).range(this.from, this.to);
}
};
LineGapWidget = class extends WidgetType {
constructor(size, vertical) {
super();
this.size = size;
this.vertical = vertical;
}
eq(other) {
return other.size == this.size && other.vertical == this.vertical;
}
toDOM() {
let elt = document.createElement("div");
if (this.vertical) elt.style.height = this.size + "px";else {
elt.style.width = this.size + "px";
elt.style.height = "2px";
elt.style.display = "inline-block";
}
return elt;
}
get estimatedHeight() {
return this.vertical ? this.size : -1;
}
};
ViewState = class {
constructor(state) {
this.state = state;
this.pixelViewport = {
left: 0,
right: window.innerWidth,
top: 0,
bottom: 0
};
this.inView = true;
this.paddingTop = 0;
this.paddingBottom = 0;
this.contentDOMWidth = 0;
this.contentDOMHeight = 0;
this.editorHeight = 0;
this.editorWidth = 0;
this.scrollTop = 0;
this.scrolledToBottom = true;
this.scaleX = 1;
this.scaleY = 1;
this.scrollAnchorPos = 0;
this.scrollAnchorHeight = -1;
this.scaler = IdScaler;
this.scrollTarget = null;
this.printing = false;
this.mustMeasureContent = true;
this.defaultTextDirection = Direction.LTR;
this.visibleRanges = [];
this.mustEnforceCursorAssoc = false;
this.heightOracle = new HeightOracle(state.facet(contentAttributes).some(v => typeof v != "function" && v.class == "cm-lineWrapping"));
this.stateDeco = state.facet(decorations).filter(d => typeof d != "function");
this.heightMap = HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle.setDoc(state.doc), [new ChangedRange(0, 0, 0, state.doc.length)]);
this.viewport = this.getViewport(0, null);
this.updateViewportLines();
this.updateForViewport();
this.lineGaps = this.ensureLineGaps([]);
this.lineGapDeco = Decoration.set(this.lineGaps.map(gap => gap.draw(this, false)));
this.computeVisibleRanges();
}
updateForViewport() {
let viewports = [this.viewport],
{
main
} = this.state.selection;
for (let i$1 = 0; i$1 <= 1; i$1++) {
let pos = i$1 ? main.head : main.anchor;
if (!viewports.some(({
from,
to
}) => pos >= from && pos <= to)) {
let {
from,
to
} = this.lineBlockAt(pos);
viewports.push(new Viewport(from, to));
}
}
this.viewports = viewports.sort((a, b) => a.from - b.from);
this.scaler = this.heightMap.height <= 7e6 ? IdScaler : new BigScaler(this.heightOracle, this.heightMap, this.viewports);
}
updateViewportLines() {
this.viewportLines = [];
this.heightMap.forEachLine(this.viewport.from, this.viewport.to, this.heightOracle.setDoc(this.state.doc), 0, 0, block => {
this.viewportLines.push(this.scaler.scale == 1 ? block : scaleBlock(block, this.scaler));
});
}
update(update, scrollTarget = null) {
this.state = update.state;
let prevDeco = this.stateDeco;
this.stateDeco = this.state.facet(decorations).filter(d => typeof d != "function");
let contentChanges = update.changedRanges;
let heightChanges = ChangedRange.extendWithRanges(contentChanges, heightRelevantDecoChanges(prevDeco, this.stateDeco, update ? update.changes : ChangeSet.empty(this.state.doc.length)));
let prevHeight = this.heightMap.height;
let scrollAnchor = this.scrolledToBottom ? null : this.scrollAnchorAt(this.scrollTop);
this.heightMap = this.heightMap.applyChanges(this.stateDeco, update.startState.doc, this.heightOracle.setDoc(this.state.doc), heightChanges);
if (this.heightMap.height != prevHeight) update.flags |= 2;
if (scrollAnchor) {
this.scrollAnchorPos = update.changes.mapPos(scrollAnchor.from, -1);
this.scrollAnchorHeight = scrollAnchor.top;
} else {
this.scrollAnchorPos = -1;
this.scrollAnchorHeight = this.heightMap.height;
}
let viewport = heightChanges.length ? this.mapViewport(this.viewport, update.changes) : this.viewport;
if (scrollTarget && (scrollTarget.range.head < viewport.from || scrollTarget.range.head > viewport.to) || !this.viewportIsAppropriate(viewport)) viewport = this.getViewport(0, scrollTarget);
let updateLines = !update.changes.empty || update.flags & 2 || viewport.from != this.viewport.from || viewport.to != this.viewport.to;
this.viewport = viewport;
this.updateForViewport();
if (updateLines) this.updateViewportLines();
if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps, update.changes)));
update.flags |= this.computeVisibleRanges();
if (scrollTarget) this.scrollTarget = scrollTarget;
if (!this.mustEnforceCursorAssoc && update.selectionSet && update.view.lineWrapping && update.state.selection.main.empty && update.state.selection.main.assoc && !update.state.facet(nativeSelectionHidden)) this.mustEnforceCursorAssoc = true;
}
measure(view) {
let dom = view.contentDOM,
style = window.getComputedStyle(dom);
let oracle = this.heightOracle;
let whiteSpace = style.whiteSpace;
this.defaultTextDirection = style.direction == "rtl" ? Direction.RTL : Direction.LTR;
let refresh = this.heightOracle.mustRefreshForWrapping(whiteSpace);
let domRect = dom.getBoundingClientRect();
let measureContent = refresh || this.mustMeasureContent || this.contentDOMHeight != domRect.height;
this.contentDOMHeight = domRect.height;
this.mustMeasureContent = false;
let result = 0,
bias = 0;
if (domRect.width && domRect.height) {
let {
scaleX,
scaleY
} = getScale(dom, domRect);
if (this.scaleX != scaleX || this.scaleY != scaleY) {
this.scaleX = scaleX;
this.scaleY = scaleY;
result |= 8;
refresh = measureContent = true;
}
}
let paddingTop = (parseInt(style.paddingTop) || 0) * this.scaleY;
let paddingBottom = (parseInt(style.paddingBottom) || 0) * this.scaleY;
if (this.paddingTop != paddingTop || this.paddingBottom != paddingBottom) {
this.paddingTop = paddingTop;
this.paddingBottom = paddingBottom;
result |= 10;
}
if (this.editorWidth != view.scrollDOM.clientWidth) {
if (oracle.lineWrapping) measureContent = true;
this.editorWidth = view.scrollDOM.clientWidth;
result |= 8;
}
let scrollTop = view.scrollDOM.scrollTop * this.scaleY;
if (this.scrollTop != scrollTop) {
this.scrollAnchorHeight = -1;
this.scrollTop = scrollTop;
}
this.scrolledToBottom = isScrolledToBottom(view.scrollDOM);
let pixelViewport = (this.printing ? fullPixelRange : visiblePixelRange)(dom, this.paddingTop);
let dTop = pixelViewport.top - this.pixelViewport.top,
dBottom = pixelViewport.bottom - this.pixelViewport.bottom;
this.pixelViewport = pixelViewport;
let inView = this.pixelViewport.bottom > this.pixelViewport.top && this.pixelViewport.right > this.pixelViewport.left;
if (inView != this.inView) {
this.inView = inView;
if (inView) measureContent = true;
}
if (!this.inView && !this.scrollTarget) return 0;
let contentWidth = domRect.width;
if (this.contentDOMWidth != contentWidth || this.editorHeight != view.scrollDOM.clientHeight) {
this.contentDOMWidth = domRect.width;
this.editorHeight = view.scrollDOM.clientHeight;
result |= 8;
}
if (measureContent) {
let lineHeights = view.docView.measureVisibleLineHeights(this.viewport);
if (oracle.mustRefreshForHeights(lineHeights)) refresh = true;
if (refresh || oracle.lineWrapping && Math.abs(contentWidth - this.contentDOMWidth) > oracle.charWidth) {
let {
lineHeight,
charWidth,
textHeight
} = view.docView.measureTextSize();
refresh = lineHeight > 0 && oracle.refresh(whiteSpace, lineHeight, charWidth, textHeight, contentWidth / charWidth, lineHeights);
if (refresh) {
view.docView.minWidth = 0;
result |= 8;
}
}
if (dTop > 0 && dBottom > 0) bias = Math.max(dTop, dBottom);else if (dTop < 0 && dBottom < 0) bias = Math.min(dTop, dBottom);
oracle.heightChanged = false;
for (let vp of this.viewports) {
let heights = vp.from == this.viewport.from ? lineHeights : view.docView.measureVisibleLineHeights(vp);
this.heightMap = (refresh ? HeightMap.empty().applyChanges(this.stateDeco, Text.empty, this.heightOracle, [new ChangedRange(0, 0, 0, view.state.doc.length)]) : this.heightMap).updateHeight(oracle, 0, refresh, new MeasuredHeights(vp.from, heights));
}
if (oracle.heightChanged) result |= 2;
}
let viewportChange = !this.viewportIsAppropriate(this.viewport, bias) || this.scrollTarget && (this.scrollTarget.range.head < this.viewport.from || this.scrollTarget.range.head > this.viewport.to);
if (viewportChange) this.viewport = this.getViewport(bias, this.scrollTarget);
this.updateForViewport();
if (result & 2 || viewportChange) this.updateViewportLines();
if (this.lineGaps.length || this.viewport.to - this.viewport.from > 4e3) this.updateLineGaps(this.ensureLineGaps(refresh ? [] : this.lineGaps, view));
result |= this.computeVisibleRanges();
if (this.mustEnforceCursorAssoc) {
this.mustEnforceCursorAssoc = false;
view.docView.enforceCursorAssoc();
}
return result;
}
get visibleTop() {
return this.scaler.fromDOM(this.pixelViewport.top);
}
get visibleBottom() {
return this.scaler.fromDOM(this.pixelViewport.bottom);
}
getViewport(bias, scrollTarget) {
let marginTop = .5 - Math.max(-.5, Math.min(.5, bias / 1e3 / 2));
let map = this.heightMap,
oracle = this.heightOracle;
let {
visibleTop,
visibleBottom
} = this;
let viewport = new Viewport(map.lineAt(visibleTop - marginTop * 1e3, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(visibleBottom + (1 - marginTop) * 1e3, QueryType.ByHeight, oracle, 0, 0).to);
if (scrollTarget) {
let {
head
} = scrollTarget.range;
if (head < viewport.from || head > viewport.to) {
let viewHeight = Math.min(this.editorHeight, this.pixelViewport.bottom - this.pixelViewport.top);
let block = map.lineAt(head, QueryType.ByPos, oracle, 0, 0),
topPos;
if (scrollTarget.y == "center") topPos = (block.top + block.bottom) / 2 - viewHeight / 2;else if (scrollTarget.y == "start" || scrollTarget.y == "nearest" && head < viewport.from) topPos = block.top;else topPos = block.bottom - viewHeight;
viewport = new Viewport(map.lineAt(topPos - 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).from, map.lineAt(topPos + viewHeight + 1e3 / 2, QueryType.ByHeight, oracle, 0, 0).to);
}
}
return viewport;
}
mapViewport(viewport, changes) {
let from = changes.mapPos(viewport.from, -1),
to = changes.mapPos(viewport.to, 1);
return new Viewport(this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0).from, this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0).to);
}
viewportIsAppropriate({
from,
to
}, bias = 0) {
if (!this.inView) return true;
let {
top: top$1
} = this.heightMap.lineAt(from, QueryType.ByPos, this.heightOracle, 0, 0);
let {
bottom
} = this.heightMap.lineAt(to, QueryType.ByPos, this.heightOracle, 0, 0);
let {
visibleTop,
visibleBottom
} = this;
return (from == 0 || top$1 <= visibleTop - Math.max(10, Math.min(-bias, 250))) && (to == this.state.doc.length || bottom >= visibleBottom + Math.max(10, Math.min(bias, 250))) && top$1 > visibleTop - 2 * 1e3 && bottom < visibleBottom + 2 * 1e3;
}
mapLineGaps(gaps, changes) {
if (!gaps.length || changes.empty) return gaps;
let mapped = [];
for (let gap of gaps) if (!changes.touchesRange(gap.from, gap.to)) mapped.push(new LineGap(changes.mapPos(gap.from), changes.mapPos(gap.to), gap.size));
return mapped;
}
ensureLineGaps(current, mayMeasure) {
let wrapping = this.heightOracle.lineWrapping;
let margin = wrapping ? 1e4 : 2e3,
halfMargin = margin >> 1,
doubleMargin = margin << 1;
if (this.defaultTextDirection != Direction.LTR && !wrapping) return [];
let gaps = [];
let addGap = (from, to, line, structure) => {
if (to - from < halfMargin) return;
let sel = this.state.selection.main,
avoid = [sel.from];
if (!sel.empty) avoid.push(sel.to);
for (let pos of avoid) if (pos > from && pos < to) {
addGap(from, pos - 10, line, structure);
addGap(pos + 10, to, line, structure);
return;
}
let gap = find(current, gap$1 => gap$1.from >= line.from && gap$1.to <= line.to && Math.abs(gap$1.from - from) < halfMargin && Math.abs(gap$1.to - to) < halfMargin && !avoid.some(pos => gap$1.from < pos && gap$1.to > pos));
if (!gap) {
if (to < line.to && mayMeasure && wrapping && mayMeasure.visibleRanges.some(r => r.from <= to && r.to >= to)) {
let lineStart = mayMeasure.moveToLineBoundary(EditorSelection.cursor(to), false, true).head;
if (lineStart > from) to = lineStart;
}
gap = new LineGap(from, to, this.gapSize(line, from, to, structure));
}
gaps.push(gap);
};
for (let line of this.viewportLines) {
if (line.length < doubleMargin) continue;
let structure = lineStructure(line.from, line.to, this.stateDeco);
if (structure.total < doubleMargin) continue;
let target = this.scrollTarget ? this.scrollTarget.range.head : null;
let viewFrom, viewTo;
if (wrapping) {
let marginHeight = margin / this.heightOracle.lineLength * this.heightOracle.lineHeight;
let top$1, bot;
if (target != null) {
let targetFrac = findFraction(structure, target);
let spaceFrac = ((this.visibleBottom - this.visibleTop) / 2 + marginHeight) / line.height;
top$1 = targetFrac - spaceFrac;
bot = targetFrac + spaceFrac;
} else {
top$1 = (this.visibleTop - line.top - marginHeight) / line.height;
bot = (this.visibleBottom - line.top + marginHeight) / line.height;
}
viewFrom = findPosition(structure, top$1);
viewTo = findPosition(structure, bot);
} else {
let totalWidth = structure.total * this.heightOracle.charWidth;
let marginWidth = margin * this.heightOracle.charWidth;
let left, right;
if (target != null) {
let targetFrac = findFraction(structure, target);
let spaceFrac = ((this.pixelViewport.right - this.pixelViewport.left) / 2 + marginWidth) / totalWidth;
left = targetFrac - spaceFrac;
right = targetFrac + spaceFrac;
} else {
left = (this.pixelViewport.left - marginWidth) / totalWidth;
right = (this.pixelViewport.right + marginWidth) / totalWidth;
}
viewFrom = findPosition(structure, left);
viewTo = findPosition(structure, right);
}
if (viewFrom > line.from) addGap(line.from, viewFrom, line, structure);
if (viewTo < line.to) addGap(viewTo, line.to, line, structure);
}
return gaps;
}
gapSize(line, from, to, structure) {
let fraction = findFraction(structure, to) - findFraction(structure, from);
if (this.heightOracle.lineWrapping) return line.height * fraction;else return structure.total * this.heightOracle.charWidth * fraction;
}
updateLineGaps(gaps) {
if (!LineGap.same(gaps, this.lineGaps)) {
this.lineGaps = gaps;
this.lineGapDeco = Decoration.set(gaps.map(gap => gap.draw(this, this.heightOracle.lineWrapping)));
}
}
computeVisibleRanges() {
let deco = this.stateDeco;
if (this.lineGaps.length) deco = deco.concat(this.lineGapDeco);
let ranges = [];
RangeSet$1.spans(deco, this.viewport.from, this.viewport.to, {
span(from, to) {
ranges.push({
from,
to
});
},
point() {}
}, 20);
let changed = ranges.length != this.visibleRanges.length || this.visibleRanges.some((r, i$1) => r.from != ranges[i$1].from || r.to != ranges[i$1].to);
this.visibleRanges = ranges;
return changed ? 4 : 0;
}
lineBlockAt(pos) {
return pos >= this.viewport.from && pos <= this.viewport.to && this.viewportLines.find(b => b.from <= pos && b.to >= pos) || scaleBlock(this.heightMap.lineAt(pos, QueryType.ByPos, this.heightOracle, 0, 0), this.scaler);
}
lineBlockAtHeight(height) {
return scaleBlock(this.heightMap.lineAt(this.scaler.fromDOM(height), QueryType.ByHeight, this.heightOracle, 0, 0), this.scaler);
}
scrollAnchorAt(scrollTop) {
let block = this.lineBlockAtHeight(scrollTop + 8);
return block.from >= this.viewport.from || this.viewportLines[0].top - scrollTop > 200 ? block : this.viewportLines[0];
}
elementAtHeight(height) {
return scaleBlock(this.heightMap.blockAt(this.scaler.fromDOM(height), this.heightOracle, 0, 0), this.scaler);
}
get docHeight() {
return this.scaler.toDOM(this.heightMap.height);
}
get contentHeight() {
return this.docHeight + this.paddingTop + this.paddingBottom;
}
};
Viewport = class {
constructor(from, to) {
this.from = from;
this.to = to;
}
};
IdScaler = {
toDOM(n) {
return n;
},
fromDOM(n) {
return n;
},
scale: 1
};
BigScaler = class {
constructor(oracle, heightMap, viewports) {
let vpHeight = 0,
base$1 = 0,
domBase = 0;
this.viewports = viewports.map(({
from,
to
}) => {
let top$1 = heightMap.lineAt(from, QueryType.ByPos, oracle, 0, 0).top;
let bottom = heightMap.lineAt(to, QueryType.ByPos, oracle, 0, 0).bottom;
vpHeight += bottom - top$1;
return {
from,
to,
top: top$1,
bottom,
domTop: 0,
domBottom: 0
};
});
this.scale = (7e6 - vpHeight) / (heightMap.height - vpHeight);
for (let obj of this.viewports) {
obj.domTop = domBase + (obj.top - base$1) * this.scale;
domBase = obj.domBottom = obj.domTop + (obj.bottom - obj.top);
base$1 = obj.bottom;
}
}
toDOM(n) {
for (let i$1 = 0, base$1 = 0, domBase = 0;; i$1++) {
let vp = i$1 < this.viewports.length ? this.viewports[i$1] : null;
if (!vp || n < vp.top) return domBase + (n - base$1) * this.scale;
if (n <= vp.bottom) return vp.domTop + (n - vp.top);
base$1 = vp.bottom;
domBase = vp.domBottom;
}
}
fromDOM(n) {
for (let i$1 = 0, base$1 = 0, domBase = 0;; i$1++) {
let vp = i$1 < this.viewports.length ? this.viewports[i$1] : null;
if (!vp || n < vp.domTop) return base$1 + (n - domBase) / this.scale;
if (n <= vp.domBottom) return vp.top + (n - vp.domTop);
base$1 = vp.bottom;
domBase = vp.domBottom;
}
}
};
theme = /* @__PURE__ */Facet$1.define({
combine: strs => strs.join(" ")
});
darkTheme = /* @__PURE__ */Facet$1.define({
combine: values => values.indexOf(true) > -1
});
baseThemeID = /* @__PURE__ */StyleModule.newName(), baseLightID = /* @__PURE__ */StyleModule.newName(), baseDarkID = /* @__PURE__ */StyleModule.newName();
lightDarkIDs = {
"&light": "." + baseLightID,
"&dark": "." + baseDarkID
};
baseTheme$1 = /* @__PURE__ */buildTheme("." + baseThemeID, {
"&": {
position: "relative !important",
boxSizing: "border-box",
"&.cm-focused": {
outline: "1px dotted #212121"
},
display: "flex !important",
flexDirection: "column"
},
".cm-scroller": {
display: "flex !important",
alignItems: "flex-start !important",
fontFamily: "monospace",
lineHeight: 1.4,
height: "100%",
overflowX: "auto",
position: "relative",
zIndex: 0
},
".cm-content": {
margin: 0,
flexGrow: 2,
flexShrink: 0,
display: "block",
whiteSpace: "pre",
wordWrap: "normal",
boxSizing: "border-box",
minHeight: "100%",
padding: "4px 0",
outline: "none",
"&[contenteditable=true]": {
WebkitUserModify: "read-write-plaintext-only"
}
},
".cm-lineWrapping": {
whiteSpace_fallback: "pre-wrap",
whiteSpace: "break-spaces",
wordBreak: "break-word",
overflowWrap: "anywhere",
flexShrink: 1
},
"&light .cm-content": {
caretColor: "black"
},
"&dark .cm-content": {
caretColor: "white"
},
".cm-line": {
display: "block",
padding: "0 2px 0 6px"
},
".cm-layer": {
position: "absolute",
left: 0,
top: 0,
contain: "size style",
"& > *": {
position: "absolute"
}
},
"&light .cm-selectionBackground": {
background: "#d9d9d9"
},
"&dark .cm-selectionBackground": {
background: "#222"
},
"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
background: "#d7d4f0"
},
"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground": {
background: "#233"
},
".cm-cursorLayer": {
pointerEvents: "none"
},
"&.cm-focused > .cm-scroller > .cm-cursorLayer": {
animation: "steps(1) cm-blink 1.2s infinite"
},
"@keyframes cm-blink": {
"0%": {},
"50%": {
opacity: 0
},
"100%": {}
},
"@keyframes cm-blink2": {
"0%": {},
"50%": {
opacity: 0
},
"100%": {}
},
".cm-cursor, .cm-dropCursor": {
borderLeft: "1.2px solid black",
marginLeft: "-0.6px",
pointerEvents: "none"
},
".cm-cursor": {
display: "none"
},
"&dark .cm-cursor": {
borderLeftColor: "#444"
},
".cm-dropCursor": {
position: "absolute"
},
"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor": {
display: "block"
},
".cm-announced": {
position: "fixed",
top: "-10000px"
},
"@media print": {
".cm-announced": {
display: "none"
}
},
"&light .cm-activeLine": {
backgroundColor: "#cceeff44"
},
"&dark .cm-activeLine": {
backgroundColor: "#99eeff33"
},
"&light .cm-specialChar": {
color: "red"
},
"&dark .cm-specialChar": {
color: "#f78"
},
".cm-gutters": {
flexShrink: 0,
display: "flex",
height: "100%",
boxSizing: "border-box",
insetInlineStart: 0,
zIndex: 200
},
"&light .cm-gutters": {
backgroundColor: "#f5f5f5",
color: "#6c6c6c",
borderRight: "1px solid #ddd"
},
"&dark .cm-gutters": {
backgroundColor: "#333338",
color: "#ccc"
},
".cm-gutter": {
display: "flex !important",
flexDirection: "column",
flexShrink: 0,
boxSizing: "border-box",
minHeight: "100%",
overflow: "hidden"
},
".cm-gutterElement": {
boxSizing: "border-box"
},
".cm-lineNumbers .cm-gutterElement": {
padding: "0 3px 0 5px",
minWidth: "20px",
textAlign: "right",
whiteSpace: "nowrap"
},
"&light .cm-activeLineGutter": {
backgroundColor: "#e2f2ff"
},
"&dark .cm-activeLineGutter": {
backgroundColor: "#222227"
},
".cm-panels": {
boxSizing: "border-box",
position: "sticky",
left: 0,
right: 0
},
"&light .cm-panels": {
backgroundColor: "#f5f5f5",
color: "black"
},
"&light .cm-panels-top": {
borderBottom: "1px solid #ddd"
},
"&light .cm-panels-bottom": {
borderTop: "1px solid #ddd"
},
"&dark .cm-panels": {
backgroundColor: "#333338",
color: "white"
},
".cm-tab": {
display: "inline-block",
overflow: "hidden",
verticalAlign: "bottom"
},
".cm-widgetBuffer": {
verticalAlign: "text-top",
height: "1em",
width: 0,
display: "inline"
},
".cm-placeholder": {
color: "#888",
display: "inline-block",
verticalAlign: "top"
},
".cm-highlightSpace:before": {
content: "attr(data-display)",
position: "absolute",
pointerEvents: "none",
color: "#888"
},
".cm-highlightTab": {
backgroundImage: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,
backgroundSize: "auto 100%",
backgroundPosition: "right 90%",
backgroundRepeat: "no-repeat"
},
".cm-trailingSpace": {
backgroundColor: "#ff332255"
},
".cm-button": {
verticalAlign: "middle",
color: "inherit",
fontSize: "70%",
padding: ".2em 1em",
borderRadius: "1px"
},
"&light .cm-button": {
backgroundImage: "linear-gradient(#eff1f5, #d9d9df)",
border: "1px solid #888",
"&:active": {
backgroundImage: "linear-gradient(#b4b4b4, #d0d3d6)"
}
},
"&dark .cm-button": {
backgroundImage: "linear-gradient(#393939, #111)",
border: "1px solid #888",
"&:active": {
backgroundImage: "linear-gradient(#111, #333)"
}
},
".cm-textfield": {
verticalAlign: "middle",
color: "inherit",
fontSize: "70%",
border: "1px solid silver",
padding: ".2em .5em"
},
"&light .cm-textfield": {
backgroundColor: "white"
},
"&dark .cm-textfield": {
border: "1px solid #555",
backgroundColor: "inherit"
}
}, lightDarkIDs);
LineBreakPlaceholder = "";
DOMReader = class {
constructor(points, state) {
this.points = points;
this.text = "";
this.lineSeparator = state.facet(EditorState.lineSeparator);
}
append(text) {
this.text += text;
}
lineBreak() {
this.text += LineBreakPlaceholder;
}
readRange(start, end) {
if (!start) return this;
let parent = start.parentNode;
for (let cur$1 = start;;) {
this.findPointBefore(parent, cur$1);
let oldLen = this.text.length;
this.readNode(cur$1);
let next = cur$1.nextSibling;
if (next == end) break;
let view = ContentView.get(cur$1),
nextView = ContentView.get(next);
if (view && nextView ? view.breakAfter : (view ? view.breakAfter : isBlockElement(cur$1)) || isBlockElement(next) && (cur$1.nodeName != "BR" || cur$1.cmIgnore) && this.text.length > oldLen) this.lineBreak();
cur$1 = next;
}
this.findPointBefore(parent, end);
return this;
}
readTextNode(node) {
let text = node.nodeValue;
for (let point of this.points) if (point.node == node) point.pos = this.text.length + Math.min(point.offset, text.length);
for (let off = 0, re = this.lineSeparator ? null : /\r\n?|\n/g;;) {
let nextBreak = -1,
breakSize = 1,
m;
if (this.lineSeparator) {
nextBreak = text.indexOf(this.lineSeparator, off);
breakSize = this.lineSeparator.length;
} else if (m = re.exec(text)) {
nextBreak = m.index;
breakSize = m[0].length;
}
this.append(text.slice(off, nextBreak < 0 ? text.length : nextBreak));
if (nextBreak < 0) break;
this.lineBreak();
if (breakSize > 1) {
for (let point of this.points) if (point.node == node && point.pos > this.text.length) point.pos -= breakSize - 1;
}
off = nextBreak + breakSize;
}
}
readNode(node) {
if (node.cmIgnore) return;
let view = ContentView.get(node);
let fromView = view && view.overrideDOMText;
if (fromView != null) {
this.findPointInside(node, fromView.length);
for (let i$1 = fromView.iter(); !i$1.next().done;) if (i$1.lineBreak) this.lineBreak();else this.append(i$1.value);
} else if (node.nodeType == 3) this.readTextNode(node);else if (node.nodeName == "BR") {
if (node.nextSibling) this.lineBreak();
} else if (node.nodeType == 1) this.readRange(node.firstChild, null);
}
findPointBefore(node, next) {
for (let point of this.points) if (point.node == node && node.childNodes[point.offset] == next) point.pos = this.text.length;
}
findPointInside(node, length) {
for (let point of this.points) if (node.nodeType == 3 ? point.node == node : node.contains(point.node)) point.pos = this.text.length + (isAtEnd(node, point.node, point.offset) ? length : 0);
}
};
DOMPoint = class {
constructor(node, offset) {
this.node = node;
this.offset = offset;
this.pos = -1;
}
};
DOMChange = class {
constructor(view, start, end, typeOver) {
this.typeOver = typeOver;
this.bounds = null;
this.text = "";
let {
impreciseHead: iHead,
impreciseAnchor: iAnchor
} = view.docView;
if (view.state.readOnly && start > -1) this.newSel = null;else if (start > -1 && (this.bounds = view.docView.domBoundsAround(start, end, 0))) {
let selPoints = iHead || iAnchor ? [] : selectionPoints(view);
let reader = new DOMReader(selPoints, view.state);
reader.readRange(this.bounds.startDOM, this.bounds.endDOM);
this.text = reader.text;
this.newSel = selectionFromPoints(selPoints, this.bounds.from);
} else {
let domSel = view.observer.selectionRange;
let head = iHead && iHead.node == domSel.focusNode && iHead.offset == domSel.focusOffset || !contains(view.contentDOM, domSel.focusNode) ? view.state.selection.main.head : view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset);
let anchor = iAnchor && iAnchor.node == domSel.anchorNode && iAnchor.offset == domSel.anchorOffset || !contains(view.contentDOM, domSel.anchorNode) ? view.state.selection.main.anchor : view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset);
this.newSel = EditorSelection.single(anchor, head);
}
}
};
observeOptions = {
childList: true,
characterData: true,
subtree: true,
attributes: true,
characterDataOldValue: true
};
useCharData = browser.ie && browser.ie_version <= 11;
DOMObserver = class {
constructor(view) {
this.view = view;
this.active = false;
this.selectionRange = new DOMSelectionState();
this.selectionChanged = false;
this.delayedFlush = -1;
this.resizeTimeout = -1;
this.queue = [];
this.delayedAndroidKey = null;
this.flushingAndroidKey = -1;
this.lastChange = 0;
this.scrollTargets = [];
this.intersection = null;
this.resizeScroll = null;
this.intersecting = false;
this.gapIntersection = null;
this.gaps = [];
this.parentCheck = -1;
this.dom = view.contentDOM;
this.observer = new MutationObserver(mutations => {
for (let mut of mutations) this.queue.push(mut);
if ((browser.ie && browser.ie_version <= 11 || browser.ios && view.composing) && mutations.some(m => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) this.flushSoon();else this.flush();
});
if (useCharData) this.onCharData = event => {
this.queue.push({
target: event.target,
type: "characterData",
oldValue: event.prevValue
});
this.flushSoon();
};
this.onSelectionChange = this.onSelectionChange.bind(this);
this.onResize = this.onResize.bind(this);
this.onPrint = this.onPrint.bind(this);
this.onScroll = this.onScroll.bind(this);
if (typeof ResizeObserver == "function") {
this.resizeScroll = new ResizeObserver(() => {
var _a$2;
if (((_a$2 = this.view.docView) === null || _a$2 === void 0 ? void 0 : _a$2.lastUpdate) < Date.now() - 75) this.onResize();
});
this.resizeScroll.observe(view.scrollDOM);
}
this.addWindowListeners(this.win = view.win);
this.start();
if (typeof IntersectionObserver == "function") {
this.intersection = new IntersectionObserver(entries => {
if (this.parentCheck < 0) this.parentCheck = setTimeout(this.listenForScroll.bind(this), 1e3);
if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0 != this.intersecting) {
this.intersecting = !this.intersecting;
if (this.intersecting != this.view.inView) this.onScrollChanged(document.createEvent("Event"));
}
}, {
threshold: [0, .001]
});
this.intersection.observe(this.dom);
this.gapIntersection = new IntersectionObserver(entries => {
if (entries.length > 0 && entries[entries.length - 1].intersectionRatio > 0) this.onScrollChanged(document.createEvent("Event"));
}, {});
}
this.listenForScroll();
this.readSelectionRange();
}
onScrollChanged(e) {
this.view.inputState.runHandlers("scroll", e);
if (this.intersecting) this.view.measure();
}
onScroll(e) {
if (this.intersecting) this.flush(false);
this.onScrollChanged(e);
}
onResize() {
if (this.resizeTimeout < 0) this.resizeTimeout = setTimeout(() => {
this.resizeTimeout = -1;
this.view.requestMeasure();
}, 50);
}
onPrint() {
this.view.viewState.printing = true;
this.view.measure();
setTimeout(() => {
this.view.viewState.printing = false;
this.view.requestMeasure();
}, 500);
}
updateGaps(gaps) {
if (this.gapIntersection && (gaps.length != this.gaps.length || this.gaps.some((g, i$1) => g != gaps[i$1]))) {
this.gapIntersection.disconnect();
for (let gap of gaps) this.gapIntersection.observe(gap);
this.gaps = gaps;
}
}
onSelectionChange(event) {
let wasChanged = this.selectionChanged;
if (!this.readSelectionRange() || this.delayedAndroidKey) return;
let {
view
} = this,
sel = this.selectionRange;
if (view.state.facet(editable) ? view.root.activeElement != this.dom : !hasSelection(view.dom, sel)) return;
let context = sel.anchorNode && view.docView.nearest(sel.anchorNode);
if (context && context.ignoreEvent(event)) {
if (!wasChanged) this.selectionChanged = false;
return;
}
if ((browser.ie && browser.ie_version <= 11 || browser.android && browser.chrome) && !view.state.selection.main.empty && sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) this.flushSoon();else this.flush(false);
}
readSelectionRange() {
let {
view
} = this;
let range = browser.safari && view.root.nodeType == 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariSelectionRangeHack(this.view) || getSelection(view.root);
if (!range || this.selectionRange.eq(range)) return false;
let local = hasSelection(this.dom, range);
if (local && !this.selectionChanged && view.inputState.lastFocusTime > Date.now() - 200 && view.inputState.lastTouchTime < Date.now() - 300 && atElementStart(this.dom, range)) {
this.view.inputState.lastFocusTime = 0;
view.docView.updateSelection();
return false;
}
this.selectionRange.setRange(range);
if (local) this.selectionChanged = true;
return true;
}
setSelectionRange(anchor, head) {
this.selectionRange.set(anchor.node, anchor.offset, head.node, head.offset);
this.selectionChanged = false;
}
clearSelectionRange() {
this.selectionRange.set(null, 0, null, 0);
}
listenForScroll() {
this.parentCheck = -1;
let i$1 = 0,
changed = null;
for (let dom = this.dom; dom;) if (dom.nodeType == 1) {
if (!changed && i$1 < this.scrollTargets.length && this.scrollTargets[i$1] == dom) i$1++;else if (!changed) changed = this.scrollTargets.slice(0, i$1);
if (changed) changed.push(dom);
dom = dom.assignedSlot || dom.parentNode;
} else if (dom.nodeType == 11) dom = dom.host;else break;
if (i$1 < this.scrollTargets.length && !changed) changed = this.scrollTargets.slice(0, i$1);
if (changed) {
for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll);
for (let dom of this.scrollTargets = changed) dom.addEventListener("scroll", this.onScroll);
}
}
ignore(f) {
if (!this.active) return f();
try {
this.stop();
return f();
} finally {
this.start();
this.clear();
}
}
start() {
if (this.active) return;
this.observer.observe(this.dom, observeOptions);
if (useCharData) this.dom.addEventListener("DOMCharacterDataModified", this.onCharData);
this.active = true;
}
stop() {
if (!this.active) return;
this.active = false;
this.observer.disconnect();
if (useCharData) this.dom.removeEventListener("DOMCharacterDataModified", this.onCharData);
}
clear() {
this.processRecords();
this.queue.length = 0;
this.selectionChanged = false;
}
delayAndroidKey(key, keyCode) {
var _a$2;
if (!this.delayedAndroidKey) {
let flush = () => {
let key$1 = this.delayedAndroidKey;
if (key$1) {
this.clearDelayedAndroidKey();
this.view.inputState.lastKeyCode = key$1.keyCode;
this.view.inputState.lastKeyTime = Date.now();
if (!this.flush() && key$1.force) dispatchKey(this.dom, key$1.key, key$1.keyCode);
}
};
this.flushingAndroidKey = this.view.win.requestAnimationFrame(flush);
}
if (!this.delayedAndroidKey || key == "Enter") this.delayedAndroidKey = {
key,
keyCode,
force: this.lastChange < Date.now() - 50 || !!((_a$2 = this.delayedAndroidKey) === null || _a$2 === void 0 ? void 0 : _a$2.force)
};
}
clearDelayedAndroidKey() {
this.win.cancelAnimationFrame(this.flushingAndroidKey);
this.delayedAndroidKey = null;
this.flushingAndroidKey = -1;
}
flushSoon() {
if (this.delayedFlush < 0) this.delayedFlush = this.view.win.requestAnimationFrame(() => {
this.delayedFlush = -1;
this.flush();
});
}
forceFlush() {
if (this.delayedFlush >= 0) {
this.view.win.cancelAnimationFrame(this.delayedFlush);
this.delayedFlush = -1;
}
this.flush();
}
pendingRecords() {
for (let mut of this.observer.takeRecords()) this.queue.push(mut);
return this.queue;
}
processRecords() {
let records = this.pendingRecords();
if (records.length) this.queue = [];
let from = -1,
to = -1,
typeOver = false;
for (let record of records) {
let range = this.readMutation(record);
if (!range) continue;
if (range.typeOver) typeOver = true;
if (from == -1) ({
from,
to
} = range);else {
from = Math.min(range.from, from);
to = Math.max(range.to, to);
}
}
return {
from,
to,
typeOver
};
}
readChange() {
let {
from,
to,
typeOver
} = this.processRecords();
let newSel = this.selectionChanged && hasSelection(this.dom, this.selectionRange);
if (from < 0 && !newSel) return null;
if (from > -1) this.lastChange = Date.now();
this.view.inputState.lastFocusTime = 0;
this.selectionChanged = false;
let change = new DOMChange(this.view, from, to, typeOver);
this.view.docView.domChanged = {
newSel: change.newSel ? change.newSel.main : null
};
return change;
}
flush(readSelection = true) {
if (this.delayedFlush >= 0 || this.delayedAndroidKey) return false;
if (readSelection) this.readSelectionRange();
let domChange = this.readChange();
if (!domChange) {
this.view.requestMeasure();
return false;
}
let startState = this.view.state;
let handled = applyDOMChange(this.view, domChange);
if (this.view.state == startState) this.view.update([]);
return handled;
}
readMutation(rec) {
let cView = this.view.docView.nearest(rec.target);
if (!cView || cView.ignoreMutation(rec)) return null;
cView.markDirty(rec.type == "attributes");
if (rec.type == "attributes") cView.flags |= 4;
if (rec.type == "childList") {
let childBefore = findChild(cView, rec.previousSibling || rec.target.previousSibling, -1);
let childAfter = findChild(cView, rec.nextSibling || rec.target.nextSibling, 1);
return {
from: childBefore ? cView.posAfter(childBefore) : cView.posAtStart,
to: childAfter ? cView.posBefore(childAfter) : cView.posAtEnd,
typeOver: false
};
} else if (rec.type == "characterData") return {
from: cView.posAtStart,
to: cView.posAtEnd,
typeOver: rec.target.nodeValue == rec.oldValue
};else return null;
}
setWindow(win) {
if (win != this.win) {
this.removeWindowListeners(this.win);
this.win = win;
this.addWindowListeners(this.win);
}
}
addWindowListeners(win) {
win.addEventListener("resize", this.onResize);
win.addEventListener("beforeprint", this.onPrint);
win.addEventListener("scroll", this.onScroll);
win.document.addEventListener("selectionchange", this.onSelectionChange);
}
removeWindowListeners(win) {
win.removeEventListener("scroll", this.onScroll);
win.removeEventListener("resize", this.onResize);
win.removeEventListener("beforeprint", this.onPrint);
win.document.removeEventListener("selectionchange", this.onSelectionChange);
}
destroy() {
var _a$2, _b, _c;
this.stop();
(_a$2 = this.intersection) === null || _a$2 === void 0 || _a$2.disconnect();
(_b = this.gapIntersection) === null || _b === void 0 || _b.disconnect();
(_c = this.resizeScroll) === null || _c === void 0 || _c.disconnect();
for (let dom of this.scrollTargets) dom.removeEventListener("scroll", this.onScroll);
this.removeWindowListeners(this.win);
clearTimeout(this.parentCheck);
clearTimeout(this.resizeTimeout);
this.win.cancelAnimationFrame(this.delayedFlush);
this.win.cancelAnimationFrame(this.flushingAndroidKey);
}
};
EditorView$1 = class EditorView$1 {
/**
The current editor state.
*/
get state() {
return this.viewState.state;
}
/**
To be able to display large documents without consuming too much
memory or overloading the browser, CodeMirror only draws the
code that is visible (plus a margin around it) to the DOM. This
property tells you the extent of the current drawn viewport, in
document positions.
*/
get viewport() {
return this.viewState.viewport;
}
/**
When there are, for example, large collapsed ranges in the
viewport, its size can be a lot bigger than the actual visible
content. Thus, if you are doing something like styling the
content in the viewport, it is preferable to only do so for
these ranges, which are the subset of the viewport that is
actually drawn.
*/
get visibleRanges() {
return this.viewState.visibleRanges;
}
/**
Returns false when the editor is entirely scrolled out of view
or otherwise hidden.
*/
get inView() {
return this.viewState.inView;
}
/**
Indicates whether the user is currently composing text via
[IME](https://en.wikipedia.org/wiki/Input_method), and at least
one change has been made in the current composition.
*/
get composing() {
return this.inputState.composing > 0;
}
/**
Indicates whether the user is currently in composing state. Note
that on some platforms, like Android, this will be the case a
lot, since just putting the cursor on a word starts a
composition there.
*/
get compositionStarted() {
return this.inputState.composing >= 0;
}
/**
The document or shadow root that the view lives in.
*/
get root() {
return this._root;
}
/**
@internal
*/
get win() {
return this.dom.ownerDocument.defaultView || window;
}
/**
Construct a new view. You'll want to either provide a `parent`
option, or put `view.dom` into your document after creating a
view, so that the user can see the editor.
*/
constructor(config$1 = {}) {
this.plugins = [];
this.pluginMap = /* @__PURE__ */new Map();
this.editorAttrs = {};
this.contentAttrs = {};
this.bidiCache = [];
this.destroyed = false;
/**
@internal
*/
this.updateState = 2;
/**
@internal
*/
this.measureScheduled = -1;
/**
@internal
*/
this.measureRequests = [];
this.contentDOM = document.createElement("div");
this.scrollDOM = document.createElement("div");
this.scrollDOM.tabIndex = -1;
this.scrollDOM.className = "cm-scroller";
this.scrollDOM.appendChild(this.contentDOM);
this.announceDOM = document.createElement("div");
this.announceDOM.className = "cm-announced";
this.announceDOM.setAttribute("aria-live", "polite");
this.dom = document.createElement("div");
this.dom.appendChild(this.announceDOM);
this.dom.appendChild(this.scrollDOM);
if (config$1.parent) config$1.parent.appendChild(this.dom);
let {
dispatch
} = config$1;
this.dispatchTransactions = config$1.dispatchTransactions || dispatch && (trs => trs.forEach(tr => dispatch(tr, this))) || (trs => this.update(trs));
this.dispatch = this.dispatch.bind(this);
this._root = config$1.root || getRoot(config$1.parent) || document;
this.viewState = new ViewState(config$1.state || EditorState.create(config$1));
if (config$1.scrollTo && config$1.scrollTo.is(scrollIntoView)) this.viewState.scrollTarget = config$1.scrollTo.value.clip(this.viewState.state);
this.plugins = this.state.facet(viewPlugin).map(spec => new PluginInstance(spec));
for (let plugin of this.plugins) plugin.update(this);
this.observer = new DOMObserver(this);
this.inputState = new InputState(this);
this.inputState.ensureHandlers(this.plugins);
this.docView = new DocView(this);
this.mountStyles();
this.updateAttrs();
this.updateState = 0;
this.requestMeasure();
}
dispatch(...input) {
let trs = input.length == 1 && input[0] instanceof Transaction ? input : input.length == 1 && Array.isArray(input[0]) ? input[0] : [this.state.update(...input)];
this.dispatchTransactions(trs, this);
}
/**
Update the view for the given array of transactions. This will
update the visible document and selection to match the state
produced by the transactions, and notify view plugins of the
change. You should usually call
[`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead, which uses this
as a primitive.
*/
update(transactions) {
if (this.updateState != 0) throw new Error("Calls to EditorView.update are not allowed while an update is in progress");
let redrawn = false,
attrsChanged = false,
update;
let state = this.state;
for (let tr of transactions) {
if (tr.startState != state) throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");
state = tr.state;
}
if (this.destroyed) {
this.viewState.state = state;
return;
}
let focus = this.hasFocus,
focusFlag = 0,
dispatchFocus = null;
if (transactions.some(tr => tr.annotation(isFocusChange))) {
this.inputState.notifiedFocused = focus;
focusFlag = 1;
} else if (focus != this.inputState.notifiedFocused) {
this.inputState.notifiedFocused = focus;
dispatchFocus = focusChangeTransaction(state, focus);
if (!dispatchFocus) focusFlag = 1;
}
let pendingKey = this.observer.delayedAndroidKey,
domChange = null;
if (pendingKey) {
this.observer.clearDelayedAndroidKey();
domChange = this.observer.readChange();
if (domChange && !this.state.doc.eq(state.doc) || !this.state.selection.eq(state.selection)) domChange = null;
} else this.observer.clear();
if (state.facet(EditorState.phrases) != this.state.facet(EditorState.phrases)) return this.setState(state);
update = ViewUpdate.create(this, state, transactions);
update.flags |= focusFlag;
let scrollTarget = this.viewState.scrollTarget;
try {
this.updateState = 2;
for (let tr of transactions) {
if (scrollTarget) scrollTarget = scrollTarget.map(tr.changes);
if (tr.scrollIntoView) {
let {
main
} = tr.state.selection;
scrollTarget = new ScrollTarget(main.empty ? main : EditorSelection.cursor(main.head, main.head > main.anchor ? -1 : 1));
}
for (let e of tr.effects) if (e.is(scrollIntoView)) scrollTarget = e.value.clip(this.state);
}
this.viewState.update(update, scrollTarget);
this.bidiCache = CachedOrder.update(this.bidiCache, update.changes);
if (!update.empty) {
this.updatePlugins(update);
this.inputState.update(update);
}
redrawn = this.docView.update(update);
if (this.state.facet(styleModule) != this.styleModules) this.mountStyles();
attrsChanged = this.updateAttrs();
this.showAnnouncements(transactions);
this.docView.updateSelection(redrawn, transactions.some(tr => tr.isUserEvent("select.pointer")));
} finally {
this.updateState = 0;
}
if (update.startState.facet(theme) != update.state.facet(theme)) this.viewState.mustMeasureContent = true;
if (redrawn || attrsChanged || scrollTarget || this.viewState.mustEnforceCursorAssoc || this.viewState.mustMeasureContent) this.requestMeasure();
if (!update.empty) for (let listener of this.state.facet(updateListener)) try {
listener(update);
} catch (e) {
logException(this.state, e, "update listener");
}
if (dispatchFocus || domChange) Promise.resolve().then(() => {
if (dispatchFocus && this.state == dispatchFocus.startState) this.dispatch(dispatchFocus);
if (domChange) {
if (!applyDOMChange(this, domChange) && pendingKey.force) dispatchKey(this.contentDOM, pendingKey.key, pendingKey.keyCode);
}
});
}
/**
Reset the view to the given state. (This will cause the entire
document to be redrawn and all view plugins to be reinitialized,
so you should probably only use it when the new state isn't
derived from the old state. Otherwise, use
[`dispatch`](https://codemirror.net/6/docs/ref/#view.EditorView.dispatch) instead.)
*/
setState(newState) {
if (this.updateState != 0) throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");
if (this.destroyed) {
this.viewState.state = newState;
return;
}
this.updateState = 2;
let hadFocus = this.hasFocus;
try {
for (let plugin of this.plugins) plugin.destroy(this);
this.viewState = new ViewState(newState);
this.plugins = newState.facet(viewPlugin).map(spec => new PluginInstance(spec));
this.pluginMap.clear();
for (let plugin of this.plugins) plugin.update(this);
this.docView.destroy();
this.docView = new DocView(this);
this.inputState.ensureHandlers(this.plugins);
this.mountStyles();
this.updateAttrs();
this.bidiCache = [];
} finally {
this.updateState = 0;
}
if (hadFocus) this.focus();
this.requestMeasure();
}
updatePlugins(update) {
let prevSpecs = update.startState.facet(viewPlugin),
specs = update.state.facet(viewPlugin);
if (prevSpecs != specs) {
let newPlugins = [];
for (let spec of specs) {
let found = prevSpecs.indexOf(spec);
if (found < 0) newPlugins.push(new PluginInstance(spec));else {
let plugin = this.plugins[found];
plugin.mustUpdate = update;
newPlugins.push(plugin);
}
}
for (let plugin of this.plugins) if (plugin.mustUpdate != update) plugin.destroy(this);
this.plugins = newPlugins;
this.pluginMap.clear();
} else for (let p of this.plugins) p.mustUpdate = update;
for (let i$1 = 0; i$1 < this.plugins.length; i$1++) this.plugins[i$1].update(this);
if (prevSpecs != specs) this.inputState.ensureHandlers(this.plugins);
}
/**
@internal
*/
measure(flush = true) {
if (this.destroyed) return;
if (this.measureScheduled > -1) this.win.cancelAnimationFrame(this.measureScheduled);
if (this.observer.delayedAndroidKey) {
this.measureScheduled = -1;
this.requestMeasure();
return;
}
this.measureScheduled = 0;
if (flush) this.observer.forceFlush();
let updated = null;
let sDOM = this.scrollDOM,
scrollTop = sDOM.scrollTop * this.scaleY;
let {
scrollAnchorPos,
scrollAnchorHeight
} = this.viewState;
if (Math.abs(scrollTop - this.viewState.scrollTop) > 1) scrollAnchorHeight = -1;
this.viewState.scrollAnchorHeight = -1;
try {
for (let i$1 = 0;; i$1++) {
if (scrollAnchorHeight < 0) if (isScrolledToBottom(sDOM)) {
scrollAnchorPos = -1;
scrollAnchorHeight = this.viewState.heightMap.height;
} else {
let block = this.viewState.scrollAnchorAt(scrollTop);
scrollAnchorPos = block.from;
scrollAnchorHeight = block.top;
}
this.updateState = 1;
let changed = this.viewState.measure(this);
if (!changed && !this.measureRequests.length && this.viewState.scrollTarget == null) break;
if (i$1 > 5) {
console.warn(this.measureRequests.length ? "Measure loop restarted more than 5 times" : "Viewport failed to stabilize");
break;
}
let measuring = [];
if (!(changed & 4)) [this.measureRequests, measuring] = [measuring, this.measureRequests];
let measured = measuring.map(m => {
try {
return m.read(this);
} catch (e) {
logException(this.state, e);
return BadMeasure;
}
});
let update = ViewUpdate.create(this, this.state, []),
redrawn = false;
update.flags |= changed;
if (!updated) updated = update;else updated.flags |= changed;
this.updateState = 2;
if (!update.empty) {
this.updatePlugins(update);
this.inputState.update(update);
this.updateAttrs();
redrawn = this.docView.update(update);
}
for (let i$2 = 0; i$2 < measuring.length; i$2++) if (measured[i$2] != BadMeasure) try {
let m = measuring[i$2];
if (m.write) m.write(measured[i$2], this);
} catch (e) {
logException(this.state, e);
}
if (redrawn) this.docView.updateSelection(true);
if (!update.viewportChanged && this.measureRequests.length == 0) {
if (this.viewState.editorHeight) if (this.viewState.scrollTarget) {
this.docView.scrollIntoView(this.viewState.scrollTarget);
this.viewState.scrollTarget = null;
scrollAnchorHeight = -1;
continue;
} else {
let diff = (scrollAnchorPos < 0 ? this.viewState.heightMap.height : this.viewState.lineBlockAt(scrollAnchorPos).top) - scrollAnchorHeight;
if (diff > 1 || diff < -1) {
scrollTop = scrollTop + diff;
sDOM.scrollTop = scrollTop / this.scaleY;
scrollAnchorHeight = -1;
continue;
}
}
break;
}
}
} finally {
this.updateState = 0;
this.measureScheduled = -1;
}
if (updated && !updated.empty) for (let listener of this.state.facet(updateListener)) listener(updated);
}
/**
Get the CSS classes for the currently active editor themes.
*/
get themeClasses() {
return baseThemeID + " " + (this.state.facet(darkTheme) ? baseDarkID : baseLightID) + " " + this.state.facet(theme);
}
updateAttrs() {
let editorAttrs = attrsFromFacet(this, editorAttributes, {
class: "cm-editor" + (this.hasFocus ? " cm-focused " : " ") + this.themeClasses
});
let contentAttrs = {
spellcheck: "false",
autocorrect: "off",
autocapitalize: "off",
translate: "no",
contenteditable: !this.state.facet(editable) ? "false" : "true",
class: "cm-content",
style: `${browser.tabSize}: ${this.state.tabSize}`,
role: "textbox",
"aria-multiline": "true"
};
if (this.state.readOnly) contentAttrs["aria-readonly"] = "true";
attrsFromFacet(this, contentAttributes, contentAttrs);
let changed = this.observer.ignore(() => {
let changedContent = updateAttrs(this.contentDOM, this.contentAttrs, contentAttrs);
let changedEditor = updateAttrs(this.dom, this.editorAttrs, editorAttrs);
return changedContent || changedEditor;
});
this.editorAttrs = editorAttrs;
this.contentAttrs = contentAttrs;
return changed;
}
showAnnouncements(trs) {
let first = true;
for (let tr of trs) for (let effect of tr.effects) if (effect.is(EditorView$1.announce)) {
if (first) this.announceDOM.textContent = "";
first = false;
let div = this.announceDOM.appendChild(document.createElement("div"));
div.textContent = effect.value;
}
}
mountStyles() {
this.styleModules = this.state.facet(styleModule);
let nonce = this.state.facet(EditorView$1.cspNonce);
StyleModule.mount(this.root, this.styleModules.concat(baseTheme$1).reverse(), nonce ? {
nonce
} : void 0);
}
readMeasured() {
if (this.updateState == 2) throw new Error("Reading the editor layout isn't allowed during an update");
if (this.updateState == 0 && this.measureScheduled > -1) this.measure(false);
}
/**
Schedule a layout measurement, optionally providing callbacks to
do custom DOM measuring followed by a DOM write phase. Using
this is preferable reading DOM layout directly from, for
example, an event handler, because it'll make sure measuring and
drawing done by other components is synchronized, avoiding
unnecessary DOM layout computations.
*/
requestMeasure(request) {
if (this.measureScheduled < 0) this.measureScheduled = this.win.requestAnimationFrame(() => this.measure());
if (request) {
if (this.measureRequests.indexOf(request) > -1) return;
if (request.key != null) {
for (let i$1 = 0; i$1 < this.measureRequests.length; i$1++) if (this.measureRequests[i$1].key === request.key) {
this.measureRequests[i$1] = request;
return;
}
}
this.measureRequests.push(request);
}
}
/**
Get the value of a specific plugin, if present. Note that
plugins that crash can be dropped from a view, so even when you
know you registered a given plugin, it is recommended to check
the return value of this method.
*/
plugin(plugin) {
let known = this.pluginMap.get(plugin);
if (known === void 0 || known && known.spec != plugin) this.pluginMap.set(plugin, known = this.plugins.find(p => p.spec == plugin) || null);
return known && known.update(this).value;
}
/**
The top position of the document, in screen coordinates. This
may be negative when the editor is scrolled down. Points
directly to the top of the first line, not above the padding.
*/
get documentTop() {
return this.contentDOM.getBoundingClientRect().top + this.viewState.paddingTop;
}
/**
Reports the padding above and below the document.
*/
get documentPadding() {
return {
top: this.viewState.paddingTop,
bottom: this.viewState.paddingBottom
};
}
/**
If the editor is transformed with CSS, this provides the scale
along the X axis. Otherwise, it will just be 1. Note that
transforms other than translation and scaling are not supported.
*/
get scaleX() {
return this.viewState.scaleX;
}
/**
Provide the CSS transformed scale along the Y axis.
*/
get scaleY() {
return this.viewState.scaleY;
}
/**
Find the text line or block widget at the given vertical
position (which is interpreted as relative to the [top of the
document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop)).
*/
elementAtHeight(height) {
this.readMeasured();
return this.viewState.elementAtHeight(height);
}
/**
Find the line block (see
[`lineBlockAt`](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) at the given
height, again interpreted relative to the [top of the
document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop).
*/
lineBlockAtHeight(height) {
this.readMeasured();
return this.viewState.lineBlockAtHeight(height);
}
/**
Get the extent and vertical position of all [line
blocks](https://codemirror.net/6/docs/ref/#view.EditorView.lineBlockAt) in the viewport. Positions
are relative to the [top of the
document](https://codemirror.net/6/docs/ref/#view.EditorView.documentTop);
*/
get viewportLineBlocks() {
return this.viewState.viewportLines;
}
/**
Find the line block around the given document position. A line
block is a range delimited on both sides by either a
non-[hidden](https://codemirror.net/6/docs/ref/#view.Decoration^replace) line breaks, or the
start/end of the document. It will usually just hold a line of
text, but may be broken into multiple textblocks by block
widgets.
*/
lineBlockAt(pos) {
return this.viewState.lineBlockAt(pos);
}
/**
The editor's total content height.
*/
get contentHeight() {
return this.viewState.contentHeight;
}
/**
Move a cursor position by [grapheme
cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak). `forward` determines whether
the motion is away from the line start, or towards it. In
bidirectional text, the line is traversed in visual order, using
the editor's [text direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection).
When the start position was the last one on the line, the
returned position will be across the line break. If there is no
further line, the original position is returned.
By default, this method moves over a single cluster. The
optional `by` argument can be used to move across more. It will
be called with the first cluster as argument, and should return
a predicate that determines, for each subsequent cluster,
whether it should also be moved over.
*/
moveByChar(start, forward, by) {
return skipAtoms(this, start, moveByChar(this, start, forward, by));
}
/**
Move a cursor position across the next group of either
[letters](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) or non-letter
non-whitespace characters.
*/
moveByGroup(start, forward) {
return skipAtoms(this, start, moveByChar(this, start, forward, initial => byGroup(this, start.head, initial)));
}
/**
Move to the next line boundary in the given direction. If
`includeWrap` is true, line wrapping is on, and there is a
further wrap point on the current line, the wrap point will be
returned. Otherwise this function will return the start or end
of the line.
*/
moveToLineBoundary(start, forward, includeWrap = true) {
return moveToLineBoundary(this, start, forward, includeWrap);
}
/**
Move a cursor position vertically. When `distance` isn't given,
it defaults to moving to the next line (including wrapped
lines). Otherwise, `distance` should provide a positive distance
in pixels.
When `start` has a
[`goalColumn`](https://codemirror.net/6/docs/ref/#state.SelectionRange.goalColumn), the vertical
motion will use that as a target horizontal position. Otherwise,
the cursor's own horizontal position is used. The returned
cursor will have its goal column set to whichever column was
used.
*/
moveVertically(start, forward, distance) {
return skipAtoms(this, start, moveVertically(this, start, forward, distance));
}
/**
Find the DOM parent node and offset (child offset if `node` is
an element, character offset when it is a text node) at the
given document position.
Note that for positions that aren't currently in
`visibleRanges`, the resulting DOM position isn't necessarily
meaningful (it may just point before or after a placeholder
element).
*/
domAtPos(pos) {
return this.docView.domAtPos(pos);
}
/**
Find the document position at the given DOM node. Can be useful
for associating positions with DOM events. Will raise an error
when `node` isn't part of the editor content.
*/
posAtDOM(node, offset = 0) {
return this.docView.posFromDOM(node, offset);
}
posAtCoords(coords, precise = true) {
this.readMeasured();
return posAtCoords(this, coords, precise);
}
/**
Get the screen coordinates at the given document position.
`side` determines whether the coordinates are based on the
element before (-1) or after (1) the position (if no element is
available on the given side, the method will transparently use
another strategy to get reasonable coordinates).
*/
coordsAtPos(pos, side = 1) {
this.readMeasured();
let rect = this.docView.coordsAt(pos, side);
if (!rect || rect.left == rect.right) return rect;
let line = this.state.doc.lineAt(pos),
order = this.bidiSpans(line);
let span = order[BidiSpan.find(order, pos - line.from, -1, side)];
return flattenRect(rect, span.dir == Direction.LTR == side > 0);
}
/**
Return the rectangle around a given character. If `pos` does not
point in front of a character that is in the viewport and
rendered (i.e. not replaced, not a line break), this will return
null. For space characters that are a line wrap point, this will
return the position before the line break.
*/
coordsForChar(pos) {
this.readMeasured();
return this.docView.coordsForChar(pos);
}
/**
The default width of a character in the editor. May not
accurately reflect the width of all characters (given variable
width fonts or styling of invididual ranges).
*/
get defaultCharacterWidth() {
return this.viewState.heightOracle.charWidth;
}
/**
The default height of a line in the editor. May not be accurate
for all lines.
*/
get defaultLineHeight() {
return this.viewState.heightOracle.lineHeight;
}
/**
The text direction
([`direction`](https://developer.mozilla.org/en-US/docs/Web/CSS/direction)
CSS property) of the editor's content element.
*/
get textDirection() {
return this.viewState.defaultTextDirection;
}
/**
Find the text direction of the block at the given position, as
assigned by CSS. If
[`perLineTextDirection`](https://codemirror.net/6/docs/ref/#view.EditorView^perLineTextDirection)
isn't enabled, or the given position is outside of the viewport,
this will always return the same as
[`textDirection`](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection). Note that
this may trigger a DOM layout.
*/
textDirectionAt(pos) {
if (!this.state.facet(perLineTextDirection) || pos < this.viewport.from || pos > this.viewport.to) return this.textDirection;
this.readMeasured();
return this.docView.textDirectionAt(pos);
}
/**
Whether this editor [wraps lines](https://codemirror.net/6/docs/ref/#view.EditorView.lineWrapping)
(as determined by the
[`white-space`](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space)
CSS property of its content element).
*/
get lineWrapping() {
return this.viewState.heightOracle.lineWrapping;
}
/**
Returns the bidirectional text structure of the given line
(which should be in the current document) as an array of span
objects. The order of these spans matches the [text
direction](https://codemirror.net/6/docs/ref/#view.EditorView.textDirection)—if that is
left-to-right, the leftmost spans come first, otherwise the
rightmost spans come first.
*/
bidiSpans(line) {
if (line.length > MaxBidiLine) return trivialOrder(line.length);
let dir = this.textDirectionAt(line.from),
isolates;
for (let entry of this.bidiCache) if (entry.from == line.from && entry.dir == dir && (entry.fresh || isolatesEq(entry.isolates, isolates = getIsolatedRanges(this, line.from, line.to)))) return entry.order;
if (!isolates) isolates = getIsolatedRanges(this, line.from, line.to);
let order = computeOrder(line.text, dir, isolates);
this.bidiCache.push(new CachedOrder(line.from, line.to, dir, isolates, true, order));
return order;
}
/**
Check whether the editor has focus.
*/
get hasFocus() {
var _a$2;
return (this.dom.ownerDocument.hasFocus() || browser.safari && ((_a$2 = this.inputState) === null || _a$2 === void 0 ? void 0 : _a$2.lastContextMenu) > Date.now() - 3e4) && this.root.activeElement == this.contentDOM;
}
/**
Put focus on the editor.
*/
focus() {
this.observer.ignore(() => {
focusPreventScroll(this.contentDOM);
this.docView.updateSelection();
});
}
/**
Update the [root](https://codemirror.net/6/docs/ref/##view.EditorViewConfig.root) in which the editor lives. This is only
necessary when moving the editor's existing DOM to a new window or shadow root.
*/
setRoot(root) {
if (this._root != root) {
this._root = root;
this.observer.setWindow((root.nodeType == 9 ? root : root.ownerDocument).defaultView || window);
this.mountStyles();
}
}
/**
Clean up this editor view, removing its element from the
document, unregistering event handlers, and notifying
plugins. The view instance can no longer be used after
calling this.
*/
destroy() {
for (let plugin of this.plugins) plugin.destroy(this);
this.plugins = [];
this.inputState.destroy();
this.docView.destroy();
this.dom.remove();
this.observer.destroy();
if (this.measureScheduled > -1) this.win.cancelAnimationFrame(this.measureScheduled);
this.destroyed = true;
}
/**
Returns an effect that can be
[added](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) to a transaction to
cause it to scroll the given position or range into view.
*/
static scrollIntoView(pos, options = {}) {
return scrollIntoView.of(new ScrollTarget(typeof pos == "number" ? EditorSelection.cursor(pos) : pos, options.y, options.x, options.yMargin, options.xMargin));
}
/**
Return an effect that resets the editor to its current (at the
time this method was called) scroll position. Note that this
only affects the editor's own scrollable element, not parents.
See also
[`EditorViewConfig.scrollTo`](https://codemirror.net/6/docs/ref/#view.EditorViewConfig.scrollTo).
The effect should be used with a document identical to the one
it was created for. Failing to do so is not an error, but may
not scroll to the expected position. You can
[map](https://codemirror.net/6/docs/ref/#state.StateEffect.map) the effect to account for changes.
*/
scrollSnapshot() {
let {
scrollTop,
scrollLeft
} = this.scrollDOM;
let ref$1 = this.viewState.scrollAnchorAt(scrollTop);
return scrollIntoView.of(new ScrollTarget(EditorSelection.cursor(ref$1.from), "start", "start", ref$1.top - scrollTop, scrollLeft, true));
}
/**
Returns an extension that can be used to add DOM event handlers.
The value should be an object mapping event names to handler
functions. For any given event, such functions are ordered by
extension precedence, and the first handler to return true will
be assumed to have handled that event, and no other handlers or
built-in behavior will be activated for it. These are registered
on the [content element](https://codemirror.net/6/docs/ref/#view.EditorView.contentDOM), except
for `scroll` handlers, which will be called any time the
editor's [scroll element](https://codemirror.net/6/docs/ref/#view.EditorView.scrollDOM) or one of
its parent nodes is scrolled.
*/
static domEventHandlers(handlers$2) {
return ViewPlugin.define(() => ({}), {
eventHandlers: handlers$2
});
}
/**
Create an extension that registers DOM event observers. Contrary
to event [handlers](https://codemirror.net/6/docs/ref/#view.EditorView^domEventHandlers),
observers can't be prevented from running by a higher-precedence
handler returning true. They also don't prevent other handlers
and observers from running when they return true, and should not
call `preventDefault`.
*/
static domEventObservers(observers$2) {
return ViewPlugin.define(() => ({}), {
eventObservers: observers$2
});
}
/**
Create a theme extension. The first argument can be a
[`style-mod`](https://github.com/marijnh/style-mod#documentation)
style spec providing the styles for the theme. These will be
prefixed with a generated class for the style.
Because the selectors will be prefixed with a scope class, rule
that directly match the editor's [wrapper
element](https://codemirror.net/6/docs/ref/#view.EditorView.dom)—to which the scope class will be
added—need to be explicitly differentiated by adding an `&` to
the selector for that element—for example
`&.cm-focused`.
When `dark` is set to true, the theme will be marked as dark,
which will cause the `&dark` rules from [base
themes](https://codemirror.net/6/docs/ref/#view.EditorView^baseTheme) to be used (as opposed to
`&light` when a light theme is active).
*/
static theme(spec, options) {
let prefix = StyleModule.newName();
let result = [theme.of(prefix), styleModule.of(buildTheme(`.${prefix}`, spec))];
if (options && options.dark) result.push(darkTheme.of(true));
return result;
}
/**
Create an extension that adds styles to the base theme. Like
with [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme), use `&` to indicate the
place of the editor wrapper element when directly targeting
that. You can also use `&dark` or `&light` instead to only
target editors with a dark or light theme.
*/
static baseTheme(spec) {
return Prec.lowest(styleModule.of(buildTheme("." + baseThemeID, spec, lightDarkIDs)));
}
/**
Retrieve an editor view instance from the view's DOM
representation.
*/
static findFromDOM(dom) {
var _a$2;
let content$1 = dom.querySelector(".cm-content");
let cView = content$1 && ContentView.get(content$1) || ContentView.get(dom);
return ((_a$2 = cView === null || cView === void 0 ? void 0 : cView.rootView) === null || _a$2 === void 0 ? void 0 : _a$2.view) || null;
}
};
/**
Facet to add a [style
module](https://github.com/marijnh/style-mod#documentation) to
an editor view. The view will ensure that the module is
mounted in its [document
root](https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root).
*/
EditorView$1.styleModule = styleModule;
/**
An input handler can override the way changes to the editable
DOM content are handled. Handlers are passed the document
positions between which the change was found, and the new
content. When one returns true, no further input handlers are
called and the default behavior is prevented.
The `insert` argument can be used to get the default transaction
that would be applied for this input. This can be useful when
dispatching the custom behavior as a separate transaction.
*/
EditorView$1.inputHandler = inputHandler;
/**
This facet can be used to provide functions that create effects
to be dispatched when the editor's focus state changes.
*/
EditorView$1.focusChangeEffect = focusChangeEffect;
/**
By default, the editor assumes all its content has the same
[text direction](https://codemirror.net/6/docs/ref/#view.Direction). Configure this with a `true`
value to make it read the text direction of every (rendered)
line separately.
*/
EditorView$1.perLineTextDirection = perLineTextDirection;
/**
Allows you to provide a function that should be called when the
library catches an exception from an extension (mostly from view
plugins, but may be used by other extensions to route exceptions
from user-code-provided callbacks). This is mostly useful for
debugging and logging. See [`logException`](https://codemirror.net/6/docs/ref/#view.logException).
*/
EditorView$1.exceptionSink = exceptionSink;
/**
A facet that can be used to register a function to be called
every time the view updates.
*/
EditorView$1.updateListener = updateListener;
/**
Facet that controls whether the editor content DOM is editable.
When its highest-precedence value is `false`, the element will
not have its `contenteditable` attribute set. (Note that this
doesn't affect API calls that change the editor content, even
when those are bound to keys or buttons. See the
[`readOnly`](https://codemirror.net/6/docs/ref/#state.EditorState.readOnly) facet for that.)
*/
EditorView$1.editable = editable;
/**
Allows you to influence the way mouse selection happens. The
functions in this facet will be called for a `mousedown` event
on the editor, and can return an object that overrides the way a
selection is computed from that mouse click or drag.
*/
EditorView$1.mouseSelectionStyle = mouseSelectionStyle;
/**
Facet used to configure whether a given selection drag event
should move or copy the selection. The given predicate will be
called with the `mousedown` event, and can return `true` when
the drag should move the content.
*/
EditorView$1.dragMovesSelection = dragMovesSelection$1;
/**
Facet used to configure whether a given selecting click adds a
new range to the existing selection or replaces it entirely. The
default behavior is to check `event.metaKey` on macOS, and
`event.ctrlKey` elsewhere.
*/
EditorView$1.clickAddsSelectionRange = clickAddsSelectionRange;
/**
A facet that determines which [decorations](https://codemirror.net/6/docs/ref/#view.Decoration)
are shown in the view. Decorations can be provided in two
ways—directly, or via a function that takes an editor view.
Only decoration sets provided directly are allowed to influence
the editor's vertical layout structure. The ones provided as
functions are called _after_ the new viewport has been computed,
and thus **must not** introduce block widgets or replacing
decorations that cover line breaks.
If you want decorated ranges to behave like atomic units for
cursor motion and deletion purposes, also provide the range set
containing the decorations to
[`EditorView.atomicRanges`](https://codemirror.net/6/docs/ref/#view.EditorView^atomicRanges).
*/
EditorView$1.decorations = decorations;
/**
Used to provide ranges that should be treated as atoms as far as
cursor motion is concerned. This causes methods like
[`moveByChar`](https://codemirror.net/6/docs/ref/#view.EditorView.moveByChar) and
[`moveVertically`](https://codemirror.net/6/docs/ref/#view.EditorView.moveVertically) (and the
commands built on top of them) to skip across such regions when
a selection endpoint would enter them. This does _not_ prevent
direct programmatic [selection
updates](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) from moving into such
regions.
*/
EditorView$1.atomicRanges = atomicRanges;
/**
When range decorations add a `unicode-bidi: isolate` style, they
should also include a
[`bidiIsolate`](https://codemirror.net/6/docs/ref/#view.MarkDecorationSpec.bidiIsolate) property
in their decoration spec, and be exposed through this facet, so
that the editor can compute the proper text order. (Other values
for `unicode-bidi`, except of course `normal`, are not
supported.)
*/
EditorView$1.bidiIsolatedRanges = bidiIsolatedRanges;
/**
Facet that allows extensions to provide additional scroll
margins (space around the sides of the scrolling element that
should be considered invisible). This can be useful when the
plugin introduces elements that cover part of that element (for
example a horizontally fixed gutter).
*/
EditorView$1.scrollMargins = scrollMargins;
/**
This facet records whether a dark theme is active. The extension
returned by [`theme`](https://codemirror.net/6/docs/ref/#view.EditorView^theme) automatically
includes an instance of this when the `dark` option is set to
true.
*/
EditorView$1.darkTheme = darkTheme;
/**
Provides a Content Security Policy nonce to use when creating
the style sheets for the editor. Holds the empty string when no
nonce has been provided.
*/
EditorView$1.cspNonce = /* @__PURE__ */Facet$1.define({
combine: values => values.length ? values[0] : ""
});
/**
Facet that provides additional DOM attributes for the editor's
editable DOM element.
*/
EditorView$1.contentAttributes = contentAttributes;
/**
Facet that provides DOM attributes for the editor's outer
element.
*/
EditorView$1.editorAttributes = editorAttributes;
/**
An extension that enables line wrapping in the editor (by
setting CSS `white-space` to `pre-wrap` in the content).
*/
EditorView$1.lineWrapping = /* @__PURE__ */EditorView$1.contentAttributes.of({
"class": "cm-lineWrapping"
});
/**
State effect used to include screen reader announcements in a
transaction. These will be added to the DOM in a visually hidden
element with `aria-live="polite"` set, and should be used to
describe effects that are visually obvious but may not be
noticed by screen reader users (such as moving to the next
search match).
*/
EditorView$1.announce = /* @__PURE__ */StateEffect$1.define();
MaxBidiLine = 4096;
BadMeasure = {};
CachedOrder = class CachedOrder {
constructor(from, to, dir, isolates, fresh, order) {
this.from = from;
this.to = to;
this.dir = dir;
this.isolates = isolates;
this.fresh = fresh;
this.order = order;
}
static update(cache$1, changes) {
if (changes.empty && !cache$1.some(c => c.fresh)) return cache$1;
let result = [],
lastDir = cache$1.length ? cache$1[cache$1.length - 1].dir : Direction.LTR;
for (let i$1 = Math.max(0, cache$1.length - 10); i$1 < cache$1.length; i$1++) {
let entry = cache$1[i$1];
if (entry.dir == lastDir && !changes.touchesRange(entry.from, entry.to)) result.push(new CachedOrder(changes.mapPos(entry.from, 1), changes.mapPos(entry.to, -1), entry.dir, entry.isolates, false, entry.order));
}
return result;
}
};
currentPlatform = browser.mac ? "mac" : browser.windows ? "win" : browser.linux ? "linux" : "key";
CanHidePrimary = !browser.ios;
themeSpec = {
".cm-line": {
"& ::selection": {
backgroundColor: "transparent !important"
},
"&::selection": {
backgroundColor: "transparent !important"
}
}
};
if (CanHidePrimary) {
themeSpec[".cm-line"].caretColor = "transparent !important";
themeSpec[".cm-content"] = {
caretColor: "transparent !important"
};
}
UnicodeRegexpSupport = /x/.unicode != null ? "gu" : "g";
/**
A gutter marker represents a bit of information attached to a line
in a specific gutter. Your own custom markers have to extend this
class.
*/
GutterMarker = class extends RangeValue {
/**
@internal
*/
compare(other) {
return this == other || this.constructor == other.constructor && this.eq(other);
}
/**
Compare this marker to another marker of the same type.
*/
eq(other) {
return false;
}
/**
Called if the marker has a `toDOM` method and its representation
was removed from a gutter.
*/
destroy(dom) {}
};
GutterMarker.prototype.elementClass = "";
GutterMarker.prototype.toDOM = void 0;
GutterMarker.prototype.mapMode = MapMode.TrackBefore;
GutterMarker.prototype.startSide = GutterMarker.prototype.endSide = -1;
GutterMarker.prototype.point = true;
//#endregion
//#region ../../../node_modules/.pnpm/@codemirror+language@6.9.3/node_modules/@codemirror/language/dist/index.js
/**
Node prop stored in a parser's top syntax node to provide the
facet that stores language-specific data for that language.
*/
languageDataProp = /* @__PURE__ */new NodeProp();
sublanguageProp = /* @__PURE__ */new NodeProp();
/**
A language object manages parsing and per-language
[metadata](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt). Parse data is
managed as a [Lezer](https://lezer.codemirror.net) tree. The class
can be used directly, via the [`LRLanguage`](https://codemirror.net/6/docs/ref/#language.LRLanguage)
subclass for [Lezer](https://lezer.codemirror.net/) LR parsers, or
via the [`StreamLanguage`](https://codemirror.net/6/docs/ref/#language.StreamLanguage) subclass
for stream parsers.
*/
Language = class {
/**
Construct a language object. If you need to invoke this
directly, first define a data facet with
[`defineLanguageFacet`](https://codemirror.net/6/docs/ref/#language.defineLanguageFacet), and then
configure your parser to [attach](https://codemirror.net/6/docs/ref/#language.languageDataProp) it
to the language's outer syntax node.
*/
constructor(data, parser$3, extraExtensions = [], name$1 = "") {
this.data = data;
this.name = name$1;
if (!EditorState$1.prototype.hasOwnProperty("tree")) Object.defineProperty(EditorState$1.prototype, "tree", {
get() {
return syntaxTree(this);
}
});
this.parser = parser$3;
this.extension = [language.of(this), EditorState$1.languageData.of((state, pos, side) => {
let top$1 = topNodeAt(state, pos, side),
data$1 = top$1.type.prop(languageDataProp);
if (!data$1) return [];
let base$1 = state.facet(data$1),
sub = top$1.type.prop(sublanguageProp);
if (sub) {
let innerNode = top$1.resolve(pos - top$1.from, side);
for (let sublang of sub) if (sublang.test(innerNode, state)) {
let data$2 = state.facet(sublang.facet);
return sublang.type == "replace" ? data$2 : data$2.concat(base$1);
}
}
return base$1;
})].concat(extraExtensions);
}
/**
Query whether this language is active at the given position.
*/
isActiveAt(state, pos, side = -1) {
return topNodeAt(state, pos, side).type.prop(languageDataProp) == this.data;
}
/**
Find the document regions that were parsed using this language.
The returned regions will _include_ any nested languages rooted
in this language, when those exist.
*/
findRegions(state) {
let lang = state.facet(language);
if ((lang === null || lang === void 0 ? void 0 : lang.data) == this.data) return [{
from: 0,
to: state.doc.length
}];
if (!lang || !lang.allowsNesting) return [];
let result = [];
let explore = (tree, from) => {
if (tree.prop(languageDataProp) == this.data) {
result.push({
from,
to: from + tree.length
});
return;
}
let mount = tree.prop(NodeProp.mounted);
if (mount) {
if (mount.tree.prop(languageDataProp) == this.data) {
if (mount.overlay) for (let r of mount.overlay) result.push({
from: r.from + from,
to: r.to + from
});else result.push({
from,
to: from + tree.length
});
return;
} else if (mount.overlay) {
let size = result.length;
explore(mount.tree, mount.overlay[0].from + from);
if (result.length > size) return;
}
}
for (let i$1 = 0; i$1 < tree.children.length; i$1++) {
let ch = tree.children[i$1];
if (ch instanceof Tree) explore(ch, tree.positions[i$1] + from);
}
};
explore(syntaxTree(state), 0);
return result;
}
/**
Indicates whether this language allows nested languages. The
default implementation returns true.
*/
get allowsNesting() {
return true;
}
};
/**
@internal
*/
Language.setState = /* @__PURE__ */StateEffect.define();
LRLanguage$1 = class LRLanguage$1 extends Language {
constructor(data, parser$3, name$1) {
super(data, parser$3, [], name$1);
this.parser = parser$3;
}
/**
Define a language from a parser.
*/
static define(spec) {
let data = defineLanguageFacet(spec.languageData);
return new LRLanguage$1(data, spec.parser.configure({
props: [languageDataProp.add(type => type.isTop ? data : void 0)]
}), spec.name);
}
/**
Create a new instance of this language with a reconfigured
version of its parser and optionally a new name.
*/
configure(options, name$1) {
return new LRLanguage$1(this.data, this.parser.configure(options), name$1 || this.name);
}
get allowsNesting() {
return this.parser.hasWrappers();
}
};
DocInput = class {
/**
Create an input object for the given document.
*/
constructor(doc$2) {
this.doc = doc$2;
this.cursorPos = 0;
this.string = "";
this.cursor = doc$2.iter();
}
get length() {
return this.doc.length;
}
syncTo(pos) {
this.string = this.cursor.next(pos - this.cursorPos).value;
this.cursorPos = pos + this.string.length;
return this.cursorPos - this.string.length;
}
chunk(pos) {
this.syncTo(pos);
return this.string;
}
get lineChunks() {
return true;
}
read(from, to) {
let stringStart = this.cursorPos - this.string.length;
if (from < stringStart || to >= this.cursorPos) return this.doc.sliceString(from, to);else return this.string.slice(from - stringStart, to - stringStart);
}
};
currentContext = null;
/**
A parse context provided to parsers working on the editor content.
*/
ParseContext = class ParseContext {
constructor(parser$3, state, fragments = [], tree, treeLen, viewport, skipped, scheduleOn) {
this.parser = parser$3;
this.state = state;
this.fragments = fragments;
this.tree = tree;
this.treeLen = treeLen;
this.viewport = viewport;
this.skipped = skipped;
this.scheduleOn = scheduleOn;
this.parse = null;
/**
@internal
*/
this.tempSkipped = [];
}
/**
@internal
*/
static create(parser$3, state, viewport) {
return new ParseContext(parser$3, state, [], Tree.empty, 0, viewport, [], null);
}
startParse() {
return this.parser.startParse(new DocInput(this.state.doc), this.fragments);
}
/**
@internal
*/
work(until, upto) {
if (upto != null && upto >= this.state.doc.length) upto = void 0;
if (this.tree != Tree.empty && this.isDone(upto !== null && upto !== void 0 ? upto : this.state.doc.length)) {
this.takeTree();
return true;
}
return this.withContext(() => {
var _a$2;
if (typeof until == "number") {
let endTime = Date.now() + until;
until = () => Date.now() > endTime;
}
if (!this.parse) this.parse = this.startParse();
if (upto != null && (this.parse.stoppedAt == null || this.parse.stoppedAt > upto) && upto < this.state.doc.length) this.parse.stopAt(upto);
for (;;) {
let done = this.parse.advance();
if (done) {
this.fragments = this.withoutTempSkipped(TreeFragment.addTree(done, this.fragments, this.parse.stoppedAt != null));
this.treeLen = (_a$2 = this.parse.stoppedAt) !== null && _a$2 !== void 0 ? _a$2 : this.state.doc.length;
this.tree = done;
this.parse = null;
if (this.treeLen < (upto !== null && upto !== void 0 ? upto : this.state.doc.length)) this.parse = this.startParse();else return true;
}
if (until()) return false;
}
});
}
/**
@internal
*/
takeTree() {
let pos, tree;
if (this.parse && (pos = this.parse.parsedPos) >= this.treeLen) {
if (this.parse.stoppedAt == null || this.parse.stoppedAt > pos) this.parse.stopAt(pos);
this.withContext(() => {
while (!(tree = this.parse.advance()));
});
this.treeLen = pos;
this.tree = tree;
this.fragments = this.withoutTempSkipped(TreeFragment.addTree(this.tree, this.fragments, true));
this.parse = null;
}
}
withContext(f) {
let prev = currentContext;
currentContext = this;
try {
return f();
} finally {
currentContext = prev;
}
}
withoutTempSkipped(fragments) {
for (let r; r = this.tempSkipped.pop();) fragments = cutFragments(fragments, r.from, r.to);
return fragments;
}
/**
@internal
*/
changes(changes, newState) {
let {
fragments,
tree,
treeLen,
viewport,
skipped
} = this;
this.takeTree();
if (!changes.empty) {
let ranges = [];
changes.iterChangedRanges((fromA, toA, fromB, toB) => ranges.push({
fromA,
toA,
fromB,
toB
}));
fragments = TreeFragment.applyChanges(fragments, ranges);
tree = Tree.empty;
treeLen = 0;
viewport = {
from: changes.mapPos(viewport.from, -1),
to: changes.mapPos(viewport.to, 1)
};
if (this.skipped.length) {
skipped = [];
for (let r of this.skipped) {
let from = changes.mapPos(r.from, 1),
to = changes.mapPos(r.to, -1);
if (from < to) skipped.push({
from,
to
});
}
}
}
return new ParseContext(this.parser, newState, fragments, tree, treeLen, viewport, skipped, this.scheduleOn);
}
/**
@internal
*/
updateViewport(viewport) {
if (this.viewport.from == viewport.from && this.viewport.to == viewport.to) return false;
this.viewport = viewport;
let startLen = this.skipped.length;
for (let i$1 = 0; i$1 < this.skipped.length; i$1++) {
let {
from,
to
} = this.skipped[i$1];
if (from < viewport.to && to > viewport.from) {
this.fragments = cutFragments(this.fragments, from, to);
this.skipped.splice(i$1--, 1);
}
}
if (this.skipped.length >= startLen) return false;
this.reset();
return true;
}
/**
@internal
*/
reset() {
if (this.parse) {
this.takeTree();
this.parse = null;
}
}
/**
Notify the parse scheduler that the given region was skipped
because it wasn't in view, and the parse should be restarted
when it comes into view.
*/
skipUntilInView(from, to) {
this.skipped.push({
from,
to
});
}
/**
Returns a parser intended to be used as placeholder when
asynchronously loading a nested parser. It'll skip its input and
mark it as not-really-parsed, so that the next update will parse
it again.
When `until` is given, a reparse will be scheduled when that
promise resolves.
*/
static getSkippingParser(until) {
return new class extends Parser {
createParse(input, fragments, ranges) {
let from = ranges[0].from,
to = ranges[ranges.length - 1].to;
return {
parsedPos: from,
advance() {
let cx = currentContext;
if (cx) {
for (let r of ranges) cx.tempSkipped.push(r);
if (until) cx.scheduleOn = cx.scheduleOn ? Promise.all([cx.scheduleOn, until]) : until;
}
this.parsedPos = to;
return new Tree(NodeType.none, [], [], to - from);
},
stoppedAt: null,
stopAt() {}
};
}
}();
}
/**
@internal
*/
isDone(upto) {
upto = Math.min(upto, this.state.doc.length);
let frags = this.fragments;
return this.treeLen >= upto && frags.length && frags[0].from == 0 && frags[0].to >= upto;
}
/**
Get the context for the current parse, or `null` if no editor
parse is in progress.
*/
static get() {
return currentContext;
}
};
LanguageState = class LanguageState {
constructor(context) {
this.context = context;
this.tree = context.tree;
}
apply(tr) {
if (!tr.docChanged && this.tree == this.context.tree) return this;
let newCx = this.context.changes(tr.changes, tr.state);
let upto = this.context.treeLen == tr.startState.doc.length ? void 0 : Math.max(tr.changes.mapPos(this.context.treeLen), newCx.viewport.to);
if (!newCx.work(20, upto)) newCx.takeTree();
return new LanguageState(newCx);
}
static init(state) {
let vpTo = Math.min(3e3, state.doc.length);
let parseState = ParseContext.create(state.facet(language).parser, state, {
from: 0,
to: vpTo
});
if (!parseState.work(20, vpTo)) parseState.takeTree();
return new LanguageState(parseState);
}
};
Language.state = /* @__PURE__ */StateField.define({
create: LanguageState.init,
update(value, tr) {
for (let e of tr.effects) if (e.is(Language.setState)) return e.value;
if (tr.startState.facet(language) != tr.state.facet(language)) return LanguageState.init(tr.state);
return value.apply(tr);
}
});
requestIdle = callback => {
let timeout = setTimeout(() => callback(), 500);
return () => clearTimeout(timeout);
};
if (typeof requestIdleCallback != "undefined") requestIdle = callback => {
let idle = -1,
timeout = setTimeout(() => {
idle = requestIdleCallback(callback, {
timeout: 400
});
}, 100);
return () => idle < 0 ? clearTimeout(timeout) : cancelIdleCallback(idle);
};
isInputPending = typeof navigator != "undefined" && ((_a = navigator.scheduling) === null || _a === void 0 ? void 0 : _a.isInputPending) ? () => navigator.scheduling.isInputPending() : null;
parseWorker = /* @__PURE__ */ViewPlugin.fromClass(class ParseWorker {
constructor(view) {
this.view = view;
this.working = null;
this.workScheduled = 0;
this.chunkEnd = -1;
this.chunkBudget = -1;
this.work = this.work.bind(this);
this.scheduleWork();
}
update(update) {
let cx = this.view.state.field(Language.state).context;
if (cx.updateViewport(update.view.viewport) || this.view.viewport.to > cx.treeLen) this.scheduleWork();
if (update.docChanged || update.selectionSet) {
if (this.view.hasFocus) this.chunkBudget += 50;
this.scheduleWork();
}
this.checkAsyncSchedule(cx);
}
scheduleWork() {
if (this.working) return;
let {
state
} = this.view,
field = state.field(Language.state);
if (field.tree != field.context.tree || !field.context.isDone(state.doc.length)) this.working = requestIdle(this.work);
}
work(deadline) {
this.working = null;
let now = Date.now();
if (this.chunkEnd < now && (this.chunkEnd < 0 || this.view.hasFocus)) {
this.chunkEnd = now + 3e4;
this.chunkBudget = 3e3;
}
if (this.chunkBudget <= 0) return;
let {
state,
viewport: {
to: vpTo
}
} = this.view,
field = state.field(Language.state);
if (field.tree == field.context.tree && field.context.isDone(vpTo + 1e5)) return;
let endTime = Date.now() + Math.min(this.chunkBudget, 100, deadline && !isInputPending ? Math.max(25, deadline.timeRemaining() - 5) : 1e9);
let viewportFirst = field.context.treeLen < vpTo && state.doc.length > vpTo + 1e3;
let done = field.context.work(() => {
return isInputPending && isInputPending() || Date.now() > endTime;
}, vpTo + (viewportFirst ? 0 : 1e5));
this.chunkBudget -= Date.now() - now;
if (done || this.chunkBudget <= 0) {
field.context.takeTree();
this.view.dispatch({
effects: Language.setState.of(new LanguageState(field.context))
});
}
if (this.chunkBudget > 0 && !(done && !viewportFirst)) this.scheduleWork();
this.checkAsyncSchedule(field.context);
}
checkAsyncSchedule(cx) {
if (cx.scheduleOn) {
this.workScheduled++;
cx.scheduleOn.then(() => this.scheduleWork()).catch(err => logException(this.view.state, err)).then(() => this.workScheduled--);
cx.scheduleOn = null;
}
}
destroy() {
if (this.working) this.working();
}
isWorking() {
return !!(this.working || this.workScheduled > 0);
}
}, {
eventHandlers: {
focus() {
this.scheduleWork();
}
}
});
/**
The facet used to associate a language with an editor state. Used
by `Language` object's `extension` property (so you don't need to
manually wrap your languages in this). Can be used to access the
current language on a state.
*/
language = /* @__PURE__ */Facet.define({
combine(languages) {
return languages.length ? languages[0] : null;
},
enables: language$2 => [Language.state, parseWorker, EditorView$1.contentAttributes.compute([language$2], state => {
let lang = state.facet(language$2);
return lang && lang.name ? {
"data-language": lang.name
} : {};
})]
});
/**
This node prop is used to associate folding information with
syntax node types. Given a syntax node, it should check whether
that tree is foldable and return the range that can be collapsed
when it is.
*/
foldNodeProp$1 = /* @__PURE__ */new NodeProp();
HighlightStyle$1 = class HighlightStyle$1 {
constructor(specs, options) {
this.specs = specs;
let modSpec;
function def(spec) {
let cls = StyleModule.newName();
(modSpec || (modSpec = Object.create(null)))["." + cls] = spec;
return cls;
}
const all = typeof options.all == "string" ? options.all : options.all ? def(options.all) : void 0;
const scopeOpt = options.scope;
this.scope = scopeOpt instanceof Language ? type => type.prop(languageDataProp) == scopeOpt.data : scopeOpt ? type => type == scopeOpt : void 0;
this.style = tagHighlighter(specs.map(style => ({
tag: style.tag,
class: style.class || def(Object.assign({}, style, {
tag: null
}))
})), {
all
}).style;
this.module = modSpec ? new StyleModule(modSpec) : null;
this.themeType = options.themeType;
}
/**
Create a highlighter style that associates the given styles to
the given tags. The specs must be objects that hold a style tag
or array of tags in their `tag` property, and either a single
`class` property providing a static CSS class (for highlighter
that rely on external styling), or a
[`style-mod`](https://github.com/marijnh/style-mod#documentation)-style
set of CSS properties (which define the styling for those tags).
The CSS rules created for a highlighter will be emitted in the
order of the spec's properties. That means that for elements that
have multiple tags associated with them, styles defined further
down in the list will have a higher CSS precedence than styles
defined earlier.
*/
static define(specs, options) {
return new HighlightStyle$1(specs, options || {});
}
};
/**
A default highlight style (works well with light themes).
*/
defaultHighlightStyle = /* @__PURE__ */HighlightStyle$1.define([{
tag: tags.meta,
color: "#404740"
}, {
tag: tags.link,
textDecoration: "underline"
}, {
tag: tags.heading,
textDecoration: "underline",
fontWeight: "bold"
}, {
tag: tags.emphasis,
fontStyle: "italic"
}, {
tag: tags.strong,
fontWeight: "bold"
}, {
tag: tags.strikethrough,
textDecoration: "line-through"
}, {
tag: tags.keyword,
color: "#708"
}, {
tag: [tags.atom, tags.bool, tags.url, tags.contentSeparator, tags.labelName],
color: "#219"
}, {
tag: [tags.literal, tags.inserted],
color: "#164"
}, {
tag: [tags.string, tags.deleted],
color: "#a11"
}, {
tag: [tags.regexp, tags.escape, /* @__PURE__ */tags.special(tags.string)],
color: "#e40"
}, {
tag: /* @__PURE__ */tags.definition(tags.variableName),
color: "#00f"
}, {
tag: /* @__PURE__ */tags.local(tags.variableName),
color: "#30a"
}, {
tag: [tags.typeName, tags.namespace],
color: "#085"
}, {
tag: tags.className,
color: "#167"
}, {
tag: [/* @__PURE__ */tags.special(tags.variableName), tags.macroName],
color: "#256"
}, {
tag: /* @__PURE__ */tags.definition(tags.propertyName),
color: "#00c"
}, {
tag: tags.comment,
color: "#940"
}, {
tag: tags.invalid,
color: "#f00"
}]);
noTokens = /* @__PURE__ */Object.create(null);
typeArray = [NodeType.none];
warned = [];
byTag = /* @__PURE__ */Object.create(null);
defaultTable = /* @__PURE__ */Object.create(null);
for (let [legacyName, name$1] of [["variable", "variableName"], ["variable-2", "variableName.special"], ["string-2", "string.special"], ["def", "variableName.definition"], ["tag", "tagName"], ["attribute", "attributeName"], ["type", "typeName"], ["builtin", "variableName.standard"], ["qualifier", "modifier"], ["error", "invalid"], ["header", "heading"], ["property", "propertyName"]]) defaultTable[legacyName] = /* @__PURE__ */createTokenType(noTokens, name$1);
parser$1 = LRParser.deserialize({
version: 14,
states: "nQQOPOOOOOO'#Cb'#CbOOOO'#C`'#C`QQOPOOOOOO-E6^-E6^",
stateData: "Y~OQPORPO~O",
goto: "bVPPPPWP^QRORSRTQOR",
nodeNames: "⚠ Program Plaintext Resolvable",
maxTerm: 6,
skippedNodes: [0],
repeatNodeCount: 1,
tokenData: "%o~RTO#ob#o#p!h#p;'Sb;'S;=`!]<%lOb~gTQ~O#ob#o#pv#p;'Sb;'S;=`!]<%lOb~yUO#ob#p;'Sb;'S;=`!]<%l~b~Ob~~!c~!`P;=`<%lb~!hOQ~~!kVO#ob#o#p#Q#p;'Sb;'S;=`!]<%l~b~Ob~~!c~#TVO#O#Q#O#P#j#P#q#Q#q#r%Q#r;'S#Q;'S;=`%i<%lO#Q~#mVO#O#Q#O#P#j#P#q#Q#q#r$S#r;'S#Q;'S;=`%i<%lO#Q~$VTO#q#Q#q#r$f#r;'S#Q;'S;=`%i<%lO#Q~$kVR~O#O#Q#O#P#j#P#q#Q#q#r%Q#r;'S#Q;'S;=`%i<%lO#Q~%TTO#q#Q#q#r%d#r;'S#Q;'S;=`%i<%lO#Q~%iOR~~%lP;=`<%l#Q",
tokenizers: [0],
topRules: {
Program: [0, 1]
},
tokenPrec: 0
}); //#endregion
//#region ../../@n8n/codemirror-lang/src/expressions/index.ts
_export("m", expressionParser = parser$1);
parserWithMetaData = parser$1.configure({
props: [foldNodeProp$1.add({
Application: foldInside$1
}), styleTags({
OpenMarker: tags.brace,
CloseMarker: tags.brace,
Plaintext: tags.content,
Resolvable: tags.string
})]
});
n8nLanguage$1 = LRLanguage$1.define({
parser: parserWithMetaData,
languageData: {
commentTokens: {
line: ";"
}
}
}); //#endregion
//#region src/features/shared/editors/plugins/codemirror/n8nLang.ts
isResolvable = node => node.type.name === "Resolvable";
n8nParserWithNestedJsParser = parserWithMetaData.configure({
wrap: parseMixed(node => {
if (node.type.isTop) return null;
return node.name === "Resolvable" ? {
parser: javascriptLanguage.parser,
overlay: isResolvable
} : null;
})
});
n8nLanguage = LRLanguage.define({
parser: n8nParserWithNestedJsParser
});
_export("f", n8nAutocompletion = () => autocompletion({
icons: false,
aboveCursor: true,
closeOnBlur: false,
optionClass: completion => completion.type ?? ""
})); //#endregion
//#region src/features/shared/editors/components/CodeNodeEditor/theme.ts
/**
* Light theme based on Tomorrow theme by Chris Kempson
* https://github.com/vadimdemedes/thememirror/blob/main/source/themes/tomorrow.ts
*
* Dark theme based on Dracula theme by Zeno Rocha
* https://github.com/vadimdemedes/thememirror/blob/main/source/themes/dracula.ts
*/
BASE_STYLING = {
fontSize: "0.8em",
fontFamily: "var(--font-family--monospace)",
maxHeight: "400px",
tooltip: {
maxWidth: "250px",
lineHeight: "1.3em"
},
diagnosticButton: {
backgroundColor: "inherit",
lineHeight: "1em",
textDecoration: "underline",
marginLeft: "0.2em",
cursor: "pointer"
}
};
codeEditorSyntaxHighlighting = syntaxHighlighting(HighlightStyle.define([{
tag: tags.keyword,
color: "var(--code-tags--keyword--color)"
}, {
tag: [tags.deleted, tags.character, tags.macroName, tags.definition(tags.name), tags.definition(tags.variableName), tags.atom, tags.bool],
color: "var(--code-tags--variable--color)"
}, {
tag: [tags.name, tags.propertyName],
color: "var(--code-tags--property--color)"
}, {
tag: [tags.processingInstruction, tags.string, tags.inserted, tags.special(tags.string)],
color: "var(--code-tags--string--color)"
}, {
tag: [tags.function(tags.variableName), tags.labelName],
color: "var(--code-tags--function--color)"
}, {
tag: [tags.color, tags.constant(tags.name), tags.standard(tags.name)],
color: "var(--code-tags--constant--color)"
}, {
tag: [tags.className],
color: "var(--code-tags--class--color)"
}, {
tag: [tags.number, tags.changed, tags.annotation, tags.modifier, tags.self, tags.namespace],
color: "var(--code-tags--primitive--color)"
}, {
tag: [tags.typeName],
color: "var(--code-tags--type--color)"
}, {
tag: [tags.operator, tags.operatorKeyword],
color: "var(--code-tags--keyword--color)"
}, {
tag: [tags.url, tags.escape, tags.regexp, tags.link],
color: "var(--code-tags--keyword--color)"
}, {
tag: [tags.meta, tags.comment, tags.lineComment],
color: "var(--code-tags--comment--color)"
}, {
tag: tags.strong,
fontWeight: "bold"
}, {
tag: tags.emphasis,
fontStyle: "italic"
}, {
tag: tags.link,
textDecoration: "underline"
}, {
tag: tags.heading,
fontWeight: "bold",
color: "var(--code-tags--heading--color)"
}, {
tag: tags.invalid,
color: "var(--code-tags--invalid--color)"
}, {
tag: tags.strikethrough,
textDecoration: "line-through"
}, {
tag: [tags.derefOperator, tags.special(tags.variableName), tags.variableName, tags.separator],
color: "var(--code--color--foreground)"
}]));
_export("d", codeEditorTheme = ({
isReadOnly,
minHeight,
maxHeight,
rows
}) => [EditorView.theme({
"&": {
"font-size": BASE_STYLING.fontSize,
border: "var(--border)",
borderRadius: "var(--radius)",
backgroundColor: "var(--code--color--background)",
color: "var(--code--color--foreground)",
height: "100%"
},
".cm-content": {
fontFamily: BASE_STYLING.fontFamily,
caretColor: isReadOnly ? "transparent" : "var(--code--caret--color)",
lineHeight: "var(--line-height--xl)",
paddingTop: "var(--spacing--2xs)",
paddingBottom: "var(--spacing--sm)"
},
".cm-cursor, .cm-dropCursor": {
borderLeftColor: "var(--code--caret--color)"
},
"&.cm-focused > .cm-scroller .cm-selectionLayer > .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection": {
background: "var(--code--selection--color)"
},
"&.cm-editor": {
...(isReadOnly ? {
backgroundColor: "var(--code--color--background--readonly)"
} : {}),
borderColor: "var(--border-color)",
overflow: "hidden"
},
"&.cm-editor.cm-focused": {
outline: "none",
borderColor: "var(--color--secondary)"
},
".cm-activeLine": {
backgroundColor: "var(--code--line-highlight--color)"
},
".cm-activeLineGutter": {
backgroundColor: "var(--code--line-highlight--color)"
},
".cm-lineNumbers .cm-activeLineGutter": {
color: "var(--code--gutter--color--foreground--active)"
},
".cm-gutters": {
backgroundColor: isReadOnly ? "var(--code--color--background--readonly)" : "var(--code--gutter--color--background)",
color: "var(--code--gutter--color--foreground)",
border: "0",
borderRadius: "var(--radius)"
},
".cm-gutterElement": {
padding: 0
},
".cm-tooltip": {
maxWidth: BASE_STYLING.tooltip.maxWidth,
lineHeight: BASE_STYLING.tooltip.lineHeight
},
".cm-scroller": {
overflow: "auto",
maxHeight: maxHeight ?? "100%",
...(isReadOnly ? {} : {
minHeight: rows && rows !== -1 ? `${Number(rows + 1) * 1.3}em` : "auto"
})
},
".cm-lineNumbers .cm-gutterElement": {
padding: "0 var(--spacing--5xs) 0 var(--spacing--2xs)"
},
".cm-gutter,.cm-content": {
minHeight: rows && rows !== -1 ? "auto" : minHeight ?? "calc(35vh - var(--spacing--2xl))"
},
".cm-foldGutter": {
width: "16px"
},
".cm-fold-marker": {
display: "flex",
alignItems: "center",
justifyContent: "center",
height: "100%",
opacity: 0,
transition: "opacity 0.3s ease"
},
".cm-activeLineGutter .cm-fold-marker, .cm-gutters:hover .cm-fold-marker": {
opacity: 1
},
".cm-diagnosticAction": {
backgroundColor: BASE_STYLING.diagnosticButton.backgroundColor,
color: "var(--color--primary)",
lineHeight: BASE_STYLING.diagnosticButton.lineHeight,
textDecoration: BASE_STYLING.diagnosticButton.textDecoration,
marginLeft: BASE_STYLING.diagnosticButton.marginLeft,
cursor: BASE_STYLING.diagnosticButton.cursor
},
".cm-diagnostic-error": {
backgroundColor: "var(--autocomplete--infobox--color--background)"
},
".cm-diagnosticText": {
fontSize: "var(--font-size--xs)",
color: "var(--color--text)"
},
".cm-diagnosticDocs": {
fontSize: "var(--font-size--2xs)"
},
".cm-foldPlaceholder": {
color: "var(--color--text)",
backgroundColor: "var(--color--background)",
border: "var(--border)"
},
".cm-lintRange-error": {
backgroundImage: "url(\"data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='6' height='3'%3e%3cpath d='m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0' stroke='%23F56565' fill='none' stroke-width='.7'/%3e%3c/svg%3e\") !important"
},
".cm-selectionMatch": {
background: "var(--code--selection--color--highlight)"
},
".cm-selectionMatch-main": {
background: "var(--code--selection--color--highlight)"
},
".cm-matchingBracket": {
background: "var(--code--selection--color)"
},
".cm-completionMatchedText": {
textDecoration: "none",
fontWeight: "600",
color: "var(--autocomplete--item--color--selected)"
},
".cm-faded > span": {
opacity: .6
},
".cm-panel.cm-search": {
padding: "var(--spacing--4xs) var(--spacing--2xs)"
},
".cm-panels": {
background: "var(--color--background--light-2)",
color: "var(--color--text)"
},
".cm-panels-bottom": {
borderTop: "var(--border)"
},
".cm-textfield": {
color: "var(--color--text--shade-1)",
background: "var(--color--foreground--tint-2)",
borderRadius: "var(--radius)",
border: "var(--border)",
fontSize: "90%"
},
".cm-textfield:focus": {
outline: "none",
borderColor: "var(--color--secondary)"
},
".cm-panel button": {
color: "var(--color--text)"
},
".cm-panel input[type=\"checkbox\"]": {
border: "var(--border)",
outline: "none"
},
".cm-panel input[type=\"checkbox\"]:hover": {
border: "var(--border)",
outline: "none"
},
".cm-panel.cm-search label": {
fontSize: "90%",
display: "inline"
},
".cm-button": {
outline: "none",
border: "var(--border)",
color: "var(--color--text--shade-1)",
backgroundColor: "var(--color--foreground--tint-2)",
backgroundImage: "none",
borderRadius: "var(--radius)",
fontSize: "90%"
}
}), codeEditorSyntaxHighlighting, tooltips({
parent: document.getElementById("cm-tooltip-container") ?? void 0
})]); //#endregion
//#region ../../../node_modules/.pnpm/@lezer+json@1.0.0/node_modules/@lezer/json/dist/index.es.js
jsonHighlighting = styleTags({
String: tags.string,
Number: tags.number,
"True False": tags.bool,
PropertyName: tags.propertyName,
Null: tags.null,
",": tags.separator,
"[ ]": tags.squareBracket,
"{ }": tags.brace
});
parser = LRParser.deserialize({
version: 14,
states: "$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#CjOOQO'#Cp'#CpQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CrOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59U,59UO!iQPO,59UOVQPO,59QOqQPO'#CkO!nQPO,59^OOQO1G.k1G.kOVQPO'#ClO!vQPO,59aOOQO1G.p1G.pOOQO1G.l1G.lOOQO,59V,59VOOQO-E6i-E6iOOQO,59W,59WOOQO-E6j-E6j",
stateData: "#O~OcOS~OQSORSOSSOTSOWQO]ROePO~OVXOeUO~O[[O~PVOg^O~Oh_OVfX~OVaO~OhbO[iX~O[dO~Oh_OVfa~OhbO[ia~O",
goto: "!kjPPPPPPkPPkqwPPk{!RPPP!XP!ePP!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",
nodeNames: "⚠ JsonText True False Null Number String } { Object Property PropertyName ] [ Array",
maxTerm: 25,
nodeProps: [["openedBy", 7, "{", 12, "["], ["closedBy", 8, "}", 13, "]"]],
propSources: [jsonHighlighting],
skippedNodes: [0],
repeatNodeCount: 2,
tokenData: "(p~RaXY!WYZ!W]^!Wpq!Wrs!]|}$i}!O$n!Q!R$w!R![&V![!]&h!}#O&m#P#Q&r#Y#Z&w#b#c'f#h#i'}#o#p(f#q#r(k~!]Oc~~!`Upq!]qr!]rs!rs#O!]#O#P!w#P~!]~!wOe~~!zXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#g~#jR!Q![#s!c!i#s#T#Z#s~#vR!Q![$P!c!i$P#T#Z$P~$SR!Q![$]!c!i$]#T#Z$]~$`R!Q![!]!c!i!]#T#Z!]~$nOh~~$qQ!Q!R$w!R![&V~$|RT~!O!P%V!g!h%k#X#Y%k~%YP!Q![%]~%bRT~!Q![%]!g!h%k#X#Y%k~%nR{|%w}!O%w!Q![%}~%zP!Q![%}~&SPT~!Q![%}~&[ST~!O!P%V!Q![&V!g!h%k#X#Y%k~&mOg~~&rO]~~&wO[~~&zP#T#U&}~'QP#`#a'T~'WP#g#h'Z~'^P#X#Y'a~'fOR~~'iP#i#j'l~'oP#`#a'r~'uP#`#a'x~'}OS~~(QP#f#g(T~(WP#i#j(Z~(^P#X#Y(a~(fOQ~~(kOW~~(pOV~",
tokenizers: [0],
topRules: {
"JsonText": [0, 1]
},
tokenPrec: 0
}); //#endregion
//#region ../../../node_modules/.pnpm/@codemirror+lang-json@6.0.1/node_modules/@codemirror/lang-json/dist/index.js
/**
Calls
[`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)
on the document and, if that throws an error, reports it as a
single diagnostic.
*/
jsonParseLinter = () => view => {
try {
JSON.parse(view.state.doc.toString());
} catch (e) {
if (!(e instanceof SyntaxError)) throw e;
const pos = getErrorPosition(e, view.state.doc);
return [{
from: pos,
message: e.message,
severity: "error",
to: pos
}];
}
return [];
};
jsonLanguage = /* @__PURE__ */LRLanguage.define({
name: "json",
parser: /* @__PURE__ */parser.configure({
props: [/* @__PURE__ */indentNodeProp.add({
Object: /* @__PURE__ */continuedIndent({
except: /^\s*\}/
}),
Array: /* @__PURE__ */continuedIndent({
except: /^\s*\]/
})
}), /* @__PURE__ */foldNodeProp.add({
"Object Array": foldInside
})]
}),
languageData: {
closeBrackets: {
brackets: ["[", "{", "\""]
},
indentOnInput: /^\s*[\}\]]$/
}
});
_hoisted_1$9 = {
viewBox: "0 0 24 24",
width: "1.2em",
height: "1.2em"
};
_export("l", close_default = {
name: "mdi-close",
render
}); //#endregion
//#region src/features/shared/editors/components/JsonEditor/JsonEditor.vue?vue&type=script&setup=true&lang.ts
JsonEditor_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "JsonEditor",
props: {
modelValue: {},
isReadOnly: {
type: Boolean,
default: false
},
fillParent: {
type: Boolean,
default: false
},
rows: {
default: 4
}
},
emits: ["update:modelValue"],
setup(__props, {
expose: __expose,
emit: __emit
}) {
const props = __props;
const emit = __emit;
const jsonEditorRef = ref();
const editor = ref(null);
const editorState = ref(null);
const extensions$1 = computed(() => {
const extensionsToApply = [json(), lineNumbers(), EditorView.lineWrapping, EditorState.readOnly.of(props.isReadOnly), codeEditorTheme({
isReadOnly: props.isReadOnly,
maxHeight: props.fillParent ? "100%" : "40vh",
minHeight: "20vh",
rows: props.rows
})];
if (!props.isReadOnly) extensionsToApply.push(history(), Prec.highest(keymap.of(editorKeymap)), linter(jsonParseLinter()), lintGutter(), n8nAutocompletion(), indentOnInput(), highlightActiveLine(), highlightActiveLineGutter(), foldGutter(), dropCursor(), bracketMatching(), mappingDropCursor(), EditorView.updateListener.of(viewUpdate => {
if (!viewUpdate.docChanged || !editor.value) return;
emit("update:modelValue", editor.value?.state.doc.toString());
}));
return extensionsToApply;
});
onMounted(() => {
createEditor();
});
onBeforeUnmount(() => {
if (!editor.value) return;
editor.value.destroy();
});
watch(() => props.modelValue, newValue => {
const editorValue = editor.value?.state?.doc.toString();
if (editorValue && editorValue.length !== newValue.length && editorValue !== newValue) {
destroyEditor();
createEditor();
}
});
function createEditor() {
const state = EditorState.create({
doc: props.modelValue,
extensions: extensions$1.value
});
const parent = jsonEditorRef.value;
editor.value = new EditorView({
parent,
state
});
editorState.value = editor.value.state;
}
function destroyEditor() {
editor.value?.destroy();
}
const focus = () => {
const view = editor.value;
if (view && typeof view.focus === "function") view.focus();
};
__expose({
focus
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
class: normalizeClass([_ctx.$style["editor-container"], _ctx.$style.fillHeight])
}, [createBaseVNode("div", {
ref_key: "jsonEditorRef",
ref: jsonEditorRef,
class: normalizeClass(["ph-no-capture", _ctx.$style.fillHeight])
}, null, 2), renderSlot(_ctx.$slots, "suffix")], 2);
};
}
}); //#endregion
//#region src/features/shared/editors/components/JsonEditor/JsonEditor.vue?vue&type=style&index=0&lang.module.scss
fillHeight = "_fillHeight_uiiyw_127";
JsonEditor_vue_vue_type_style_index_0_lang_module_default = {
"editor-container": "_editor-container_uiiyw_123",
fillHeight
}; //#endregion
//#region src/features/shared/editors/components/JsonEditor/JsonEditor.vue
cssModules$7 = {
"$style": JsonEditor_vue_vue_type_style_index_0_lang_module_default
};
_export("c", JsonEditor_default = /* @__PURE__ */__plugin_vue_export_helper_default(JsonEditor_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules$7]])); //#endregion
//#region src/app/constants/samples.ts
DUMMY_PIN_DATA = [{
name: "First item",
code: 1
}, {
name: "Second item",
code: 2
}];
_export("o", SAMPLE_SUBWORKFLOW_TRIGGER_ID = "c055762a-8fe7-4141-a639-df2372f30060");
_export("s", SAMPLE_SUBWORKFLOW_WORKFLOW = {
name: "My Sub-Workflow",
nodes: [{
id: SAMPLE_SUBWORKFLOW_TRIGGER_ID,
typeVersion: 1.1,
name: "When Executed by Another Workflow",
type: "n8n-nodes-base.executeWorkflowTrigger",
position: [260, 340],
parameters: {}
}, {
id: "b5942df6-0160-4ef7-965d-57583acdc8aa",
name: "Replace me with your logic",
type: "n8n-nodes-base.noOp",
position: [520, 340],
parameters: {}
}],
connections: {
"When Executed by Another Workflow": {
main: [[{
node: "Replace me with your logic",
type: NodeConnectionTypes.Main,
index: 0
}]]
}
},
settings: {
executionOrder: "v1"
},
pinData: {}
});
SAMPLE_EVALUATION_WORKFLOW = {
name: "My Evaluation Sub-Workflow",
nodes: [{
parameters: {
inputSource: "passthrough"
},
id: "c20c82d6-5f71-4fb6-a398-a10a6e6944c5",
name: "When called by a test run",
type: "n8n-nodes-base.executeWorkflowTrigger",
typeVersion: 1.1,
position: [80, 440]
}, {
parameters: {},
id: "4e14d09a-2699-4659-9a20-e4f4965f473e",
name: "Replace me",
type: "n8n-nodes-base.noOp",
typeVersion: 1,
position: [340, 440]
}, {
parameters: {
metrics: {
assignments: [{
name: "latency",
value: "={{(() => {\n const newExecutionRuns = Object.values($json.newExecution)\n .reduce((acc, node) => {\n acc.push(node.runs.filter(run => run.output.main !== undefined))\n return acc\n }, []).flat()\n\n const latency = newExecutionRuns.reduce((acc, run) => acc + run.executionTime, 0)\n\n return latency\n})()}}",
type: "number",
id: "1ebc15e9-f079-4d1f-a08d-d4880ea0ddb5"
}]
}
},
type: "n8n-nodes-base.evaluationMetrics",
id: "33e2e94a-ec48-4e7b-b750-f56718d5105c",
name: "Return metric(s)",
typeVersion: 1,
position: [600, 440]
}, {
parameters: {
content: "### 1. Receive execution data\n\nThis workflow will be passed:\n- The benchmark execution (`$json.originalExecution`)\n- The evaluation execution (`$json.newExecution`) produced by re-running the workflow using trigger data from benchmark execution\n\n\nWe've pinned some example data to get you started",
height: 458,
width: 257,
color: 7
},
id: "55e5e311-e285-4000-bd1e-900bc3a07da3",
name: "Sticky Note",
type: "n8n-nodes-base.stickyNote",
typeVersion: 1,
position: [0, 140]
}, {
parameters: {
content: "### 2. Evaluation logic\n\nReplace with logic to perform the tests you want to perform.\n\nE.g. compare against benchmark data, use LLMs to evaluate sentiment, compare token usage, and more.",
height: 459,
width: 237,
color: 7
},
id: "ea74e341-ff9c-456a-83f0-c10758f0844a",
name: "Sticky Note1",
type: "n8n-nodes-base.stickyNote",
typeVersion: 1,
position: [280, 140]
}, {
parameters: {
content: "### 3. Return metrics\n\nDefine evaluation metrics you want to show on your report.\n\n__Note:__ Metrics need to be numeric",
height: 459,
width: 217,
color: 7
},
id: "9b3c3408-19e1-43d5-b2bb-29d61bd129b8",
name: "Sticky Note2",
type: "n8n-nodes-base.stickyNote",
typeVersion: 1,
position: [540, 140]
}, {
parameters: {
content: "## Evaluation workflow\nThis workflow is used to define evaluation logic and calculate metrics. You can compare against benchmark executions, use LLMs to evaluate, or write any other logic you choose.",
height: 105,
width: 754
},
id: "0fc1356e-6238-4557-a920-e50806c1ec13",
name: "Sticky Note3",
type: "n8n-nodes-base.stickyNote",
typeVersion: 1,
position: [0, 0]
}],
connections: {
"When called by a test run": {
main: [[{
node: "Replace me",
type: NodeConnectionTypes.Main,
index: 0
}]]
},
"Replace me": {
main: [[{
node: "Return metric(s)",
type: NodeConnectionTypes.Main,
index: 0
}]]
}
},
pinData: {
"When called by a test run": [{
json: {
newExecution: {},
originalExecution: {}
}
}]
},
settings: {
executionOrder: "v1"
}
}; //#endregion
//#region src/features/ndv/settings/components/NodeSettingsHint.vue?vue&type=script&setup=true&lang.ts
NodeSettingsHint_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "NodeSettingsHint",
props: {
node: {}
},
setup(__props) {
const props = __props;
const i18n$1 = useI18n();
const activeSettings = computed(() => {
if (!props.node || props.node.disabled) return props.node?.disabled ? [{
key: "disabled",
message: i18n$1.baseText("ndv.nodeHints.disabled"),
icon: "power-off"
}] : [];
const settings = [];
if (props.node.alwaysOutputData) settings.push({
key: "alwaysOutputData",
message: i18n$1.baseText("ndv.nodeHints.alwaysOutputData"),
icon: "always-output-data"
});
if (props.node.executeOnce) settings.push({
key: "executeOnce",
message: i18n$1.baseText("ndv.nodeHints.executeOnce"),
icon: "execute-once"
});
if (props.node.retryOnFail) settings.push({
key: "retryOnFail",
message: i18n$1.baseText("ndv.nodeHints.retryOnFail"),
icon: "retry-on-fail"
});
if (props.node.onError === "continueRegularOutput" || props.node.onError === "continueErrorOutput") settings.push({
key: "continueOnError",
message: i18n$1.baseText("ndv.nodeHints.continueOnError"),
icon: "continue-on-error"
});
return settings;
});
return (_ctx, _cache) => {
return activeSettings.value.length > 0 ? (openBlock(), createElementBlock("div", {
key: 0,
class: normalizeClass(_ctx.$style.settingsHint)
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(activeSettings.value, setting => {
return openBlock(), createElementBlock("div", {
key: setting.key,
class: normalizeClass(_ctx.$style.settingItem)
}, [createBaseVNode("div", {
class: normalizeClass(_ctx.$style.iconWrapper)
}, [createVNode(unref(N8nIcon_default), {
icon: setting.icon,
class: normalizeClass(_ctx.$style.icon)
}, null, 8, ["icon", "class"])], 2), createVNode(unref(N8nText_default), {
size: "small",
class: normalizeClass(_ctx.$style.message)
}, {
default: withCtx(() => [createTextVNode(toDisplayString(setting.message), 1)]),
_: 2
}, 1032, ["class"])], 2);
}), 128))], 2)) : createCommentVNode("", true);
};
}
}); //#endregion
//#region src/features/ndv/settings/components/NodeSettingsHint.vue?vue&type=style&index=0&lang.module.scss
settingsHint = "_settingsHint_1m3ps_123";
settingItem = "_settingItem_1m3ps_136";
iconWrapper = "_iconWrapper_1m3ps_145";
icon$1 = "_icon_1m3ps_145";
message = "_message_1m3ps_158";
NodeSettingsHint_vue_vue_type_style_index_0_lang_module_default = {
settingsHint,
settingItem,
iconWrapper,
icon: icon$1,
message
}; //#endregion
//#region src/features/ndv/settings/components/NodeSettingsHint.vue
cssModules$6 = {
"$style": NodeSettingsHint_vue_vue_type_style_index_0_lang_module_default
};
NodeSettingsHint_default = /* @__PURE__ */__plugin_vue_export_helper_default(NodeSettingsHint_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules$6]]); //#endregion
//#region src/features/ndv/runData/components/BinaryDataDisplayEmbed.vue?vue&type=script&setup=true&lang.ts
_hoisted_1$8 = {
key: 0
};
_hoisted_2$5 = {
key: 1
};
_hoisted_3$3 = {
key: 2
};
_hoisted_4$3 = {
key: 0,
controls: "",
autoplay: ""
};
_hoisted_5$3 = ["src", "type"];
_hoisted_6$2 = {
key: 1,
controls: "",
autoplay: ""
};
_hoisted_7$1 = ["src", "type"];
_hoisted_8$1 = ["src"];
_hoisted_9$1 = ["src"];
BinaryDataDisplayEmbed_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "BinaryDataDisplayEmbed",
props: {
binaryData: {}
},
setup(__props) {
const props = __props;
const isLoading = ref(true);
const embedSource = ref("");
const error = ref(false);
const data = ref("");
const workflowsStore = useWorkflowsStore();
const i18n$1 = useI18n();
const embedClass = computed(() => {
return [props.binaryData.fileType ?? "other"];
});
onMounted(async () => {
const {
id: id$1,
data: binaryData,
fileName,
fileType,
mimeType
} = props.binaryData;
const isJSONData = fileType === "json";
const isHTMLData = fileType === "html";
if (!id$1) {
if (isJSONData || isHTMLData) data.value = isJSONData ? jsonParse(base64DecodeUTF8(binaryData)) : base64DecodeUTF8(binaryData);else embedSource.value = `data:${mimeType};charset=utf-8;base64,${binaryData}`;
} else try {
const binaryUrl = workflowsStore.getBinaryUrl(id$1, "view", fileName ?? "", mimeType);
if (isJSONData || isHTMLData) {
const fetchedData = await fetch(binaryUrl, {
credentials: "include"
});
data.value = await (isJSONData ? fetchedData.json() : fetchedData.text());
} else embedSource.value = binaryUrl;
} catch (e) {
error.value = true;
}
isLoading.value = false;
});
return (_ctx, _cache) => {
return openBlock(), createElementBlock("span", null, [isLoading.value ? (openBlock(), createElementBlock("div", _hoisted_1$8, "Loading binary data...")) : error.value ? (openBlock(), createElementBlock("div", _hoisted_2$5, "Error loading binary data")) : (openBlock(), createElementBlock("span", _hoisted_3$3, [_ctx.binaryData.fileType === "video" ? (openBlock(), createElementBlock("video", _hoisted_4$3, [createBaseVNode("source", {
src: embedSource.value,
type: _ctx.binaryData.mimeType
}, null, 8, _hoisted_5$3), createTextVNode(" " + toDisplayString(unref(i18n$1).baseText("binaryDataDisplay.yourBrowserDoesNotSupport")), 1)])) : _ctx.binaryData.fileType === "audio" ? (openBlock(), createElementBlock("audio", _hoisted_6$2, [createBaseVNode("source", {
src: embedSource.value,
type: _ctx.binaryData.mimeType
}, null, 8, _hoisted_7$1), createTextVNode(" " + toDisplayString(unref(i18n$1).baseText("binaryDataDisplay.yourBrowserDoesNotSupport")), 1)])) : _ctx.binaryData.fileType === "image" ? (openBlock(), createElementBlock("img", {
key: 2,
src: embedSource.value
}, null, 8, _hoisted_8$1)) : _ctx.binaryData.fileType === "json" ? (openBlock(), createBlock(unref(P), {
key: 3,
data: data.value,
deep: 3,
"show-length": true
}, null, 8, ["data"])) : _ctx.binaryData.fileType === "html" ? (openBlock(), createBlock(RunDataHtml_default, {
key: 4,
"input-html": data.value
}, null, 8, ["input-html"])) : (openBlock(), createElementBlock("embed", {
key: 5,
src: embedSource.value,
class: normalizeClass(["binary-data", embedClass.value])
}, null, 10, _hoisted_9$1))]))]);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/BinaryDataDisplayEmbed.vue
BinaryDataDisplayEmbed_default = BinaryDataDisplayEmbed_vue_vue_type_script_setup_true_lang_default; //#endregion
//#region src/features/ndv/runData/components/BinaryDataDisplay.vue?vue&type=script&setup=true&lang.ts
_hoisted_1$7 = {
class: "binary-data-window-wrapper"
};
_hoisted_2$4 = {
key: 0
};
BinaryDataDisplay_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "BinaryDataDisplay",
props: {
displayData: {},
windowVisible: {
type: Boolean
}
},
emits: ["close"],
setup(__props, {
emit: __emit
}) {
const props = __props;
const emit = __emit;
const nodeHelpers = useNodeHelpers();
const workflowsStore = useWorkflowsStore();
const i18n$1 = useI18n();
const workflowRunData = computed(() => {
const workflowExecution = workflowsStore.getWorkflowExecution;
if (workflowExecution === null) return null;
const executionData = workflowExecution.data;
return executionData ? executionData.resultData.runData : null;
});
const binaryData = computed(() => {
if (typeof props.displayData.node !== "string" || typeof props.displayData.key !== "string" || typeof props.displayData.runIndex !== "number" || typeof props.displayData.index !== "number" || typeof props.displayData.outputIndex !== "number") return null;
const binaryDataLocal = nodeHelpers.getBinaryData(workflowRunData.value, props.displayData.node, props.displayData.runIndex, props.displayData.outputIndex);
if (binaryDataLocal.length === 0) return null;
if (props.displayData.index >= binaryDataLocal.length || binaryDataLocal[props.displayData.index][props.displayData.key] === void 0) return null;
return binaryDataLocal[props.displayData.index][props.displayData.key];
});
function closeWindow() {
emit("close");
return false;
}
return (_ctx, _cache) => {
return _ctx.windowVisible ? (openBlock(), createElementBlock("div", {
key: 0,
class: normalizeClass(["binary-data-window", binaryData.value?.fileType])
}, [createVNode(unref(N8nButton_default), {
size: "small",
class: "binary-data-window-back",
title: unref(i18n$1).baseText("binaryDataDisplay.backToOverviewPage"),
icon: "arrow-left",
label: unref(i18n$1).baseText("binaryDataDisplay.backToList"),
onClick: withModifiers(closeWindow, ["stop"])
}, null, 8, ["title", "label"]), createBaseVNode("div", _hoisted_1$7, [!binaryData.value ? (openBlock(), createElementBlock("div", _hoisted_2$4, toDisplayString(unref(i18n$1).baseText("binaryDataDisplay.noDataFoundToDisplay")), 1)) : (openBlock(), createBlock(BinaryDataDisplayEmbed_default, {
key: 1,
"binary-data": binaryData.value
}, null, 8, ["binary-data"]))])], 2)) : createCommentVNode("", true);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/BinaryDataDisplay.vue
BinaryDataDisplay_default = BinaryDataDisplay_vue_vue_type_script_setup_true_lang_default; //#endregion
//#region src/features/ndv/runData/components/error/NodeErrorView.vue?vue&type=script&setup=true&lang.ts
_hoisted_1$6 = {
class: "node-error-view__header"
};
_hoisted_2$3 = {
class: "node-error-view__header-message",
"data-test-id": "node-error-message"
};
_hoisted_3$2 = {
key: 0,
"data-test-id": "node-error-description",
class: "node-error-view__header-description"
};
_hoisted_4$2 = {
key: 1
};
_hoisted_5$2 = {
key: 2,
class: "node-error-view__button",
"data-test-id": "node-error-view-ask-assistant-button"
};
_hoisted_6$1 = {
key: 0,
class: "node-error-view__info"
};
_hoisted_7 = {
class: "node-error-view__info-header"
};
_hoisted_8 = {
class: "node-error-view__info-title"
};
_hoisted_9 = {
class: "copy-button"
};
_hoisted_10 = {
class: "node-error-view__info-content"
};
_hoisted_11 = {
key: 0,
class: "node-error-view__details"
};
_hoisted_12 = {
class: "node-error-view__details-summary"
};
_hoisted_13 = {
class: "node-error-view__details-content"
};
_hoisted_14 = {
key: 0,
class: "node-error-view__details-row"
};
_hoisted_15 = {
class: "node-error-view__details-label"
};
_hoisted_16 = {
class: "node-error-view__details-value"
};
_hoisted_17 = {
key: 1,
class: "node-error-view__details-row"
};
_hoisted_18 = {
class: "node-error-view__details-label"
};
_hoisted_19 = {
class: "node-error-view__details-value"
};
_hoisted_20 = {
key: 2,
class: "node-error-view__details-row"
};
_hoisted_21 = {
class: "node-error-view__details-label"
};
_hoisted_22 = {
class: "node-error-view__details-value"
};
_hoisted_23 = {
key: 3,
class: "node-error-view__details-row"
};
_hoisted_24 = {
class: "node-error-view__details-label"
};
_hoisted_25 = {
class: "node-error-view__details-value"
};
_hoisted_26 = {
key: 4,
class: "node-error-view__details-row"
};
_hoisted_27 = {
class: "node-error-view__details-label"
};
_hoisted_28 = {
class: "node-error-view__details-value"
};
_hoisted_29 = {
class: "node-error-view__details"
};
_hoisted_30 = {
class: "node-error-view__details-summary"
};
_hoisted_31 = {
class: "node-error-view__details-content"
};
_hoisted_32 = {
key: 0,
class: "node-error-view__details-row"
};
_hoisted_33 = {
class: "node-error-view__details-label"
};
_hoisted_34 = {
class: "node-error-view__details-value"
};
_hoisted_35 = {
key: 1,
class: "node-error-view__details-row"
};
_hoisted_36 = {
class: "node-error-view__details-label"
};
_hoisted_37 = {
class: "node-error-view__details-value"
};
_hoisted_38 = {
key: 2,
class: "node-error-view__details-row"
};
_hoisted_39 = {
class: "node-error-view__details-label"
};
_hoisted_40 = {
class: "node-error-view__details-value"
};
_hoisted_41 = {
key: 3,
class: "node-error-view__details-row"
};
_hoisted_42 = {
class: "node-error-view__details-label"
};
_hoisted_43 = {
class: "node-error-view__details-value"
};
_hoisted_44 = {
key: 4,
class: "node-error-view__details-row"
};
_hoisted_45 = {
class: "node-error-view__details-label"
};
_hoisted_46 = {
class: "node-error-view__details-value"
};
_hoisted_47 = {
class: "node-error-view__details-row"
};
_hoisted_48 = {
class: "node-error-view__details-label"
};
_hoisted_49 = {
class: "node-error-view__details-value"
};
_hoisted_50 = {
key: 5,
class: "node-error-view__details-row"
};
_hoisted_51 = {
class: "node-error-view__details-label"
};
_hoisted_52 = {
class: "node-error-view__details-value"
};
_hoisted_53 = {
key: 6,
class: "node-error-view__details-row"
};
_hoisted_54 = {
class: "node-error-view__details-label"
};
_hoisted_55 = {
class: "node-error-view__details-value"
};
_hoisted_56 = {
key: 7,
class: "node-error-view__details-row"
};
_hoisted_57 = {
class: "node-error-view__details-label"
};
_hoisted_58 = {
class: "node-error-view__details-value"
};
_hoisted_59 = {
key: 8,
class: "node-error-view__details-row"
};
_hoisted_60 = {
class: "node-error-view__details-label"
};
_hoisted_61 = {
class: "node-error-view__details-value"
};
NodeErrorView_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "NodeErrorView",
props: {
error: {},
showDetails: {
type: Boolean
},
compact: {
type: Boolean
}
},
setup(__props) {
const props = __props;
const router = useRouter();
const clipboard = useClipboard();
const toast = useToast();
const i18n$1 = useI18n();
const assistantHelpers = useAIAssistantHelpers();
const nodeTypesStore = useNodeTypesStore();
const ndvStore = useNDVStore();
const workflowsStore = useWorkflowsStore();
const rootStore = useRootStore();
const assistantStore = useAssistantStore();
const chatPanelStore = useChatPanelStore();
const uiStore = useUIStore();
const workflowId = computed(() => workflowsStore.workflowId);
const executionId = computed(() => workflowsStore.getWorkflowExecution?.id);
const displayCause = computed(() => {
return JSON.stringify(props.error.cause ?? "").length < MAX_DISPLAY_DATA_SIZE;
});
const node = computed(() => {
return props.error.node || ndvStore.activeNode;
});
const parameters = computed(() => {
if (!node.value) return [];
const nodeType = nodeTypesStore.getNodeType(node.value.type, node.value.typeVersion);
if (nodeType === null) return [];
return nodeType.properties;
});
const n8nVersion = computed(() => {
const baseUrl = rootStore.urlBaseEditor;
let instanceType = "Self Hosted";
if (baseUrl.includes("n8n.cloud")) instanceType = "Cloud";
return rootStore.versionCli + ` (${instanceType})`;
});
const hasManyInputItems = computed(() => {
return ndvStore.ndvInputData.length > 1;
});
const nodeDefaultName = computed(() => {
if (!node.value) return "Node";
return nodeTypesStore.getNodeType(node.value.type, node.value.typeVersion)?.defaults?.name || node.value.name;
});
const prepareRawMessages = computed(() => {
const returnData = [];
if (!props.error.messages?.length) return [];
const errorMessage = getErrorMessage();
Array.from(new Set(props.error.messages)).forEach(message$1 => {
const parts = /^\d{3} - \{/.test(message$1) ? message$1.split(" - ").map(part => part.trim()) : [];
for (const part of parts) try {
const parsed = JSON.parse(part);
if (typeof parsed === "object") {
returnData.push(parsed);
return;
}
} catch (error) {}
if (message$1 === errorMessage) return;
returnData.push(message$1);
});
return returnData;
});
const isAskAssistantAvailable = computed(() => {
if (!node.value || isSubNodeError.value) return false;
const isCustomNode = node.value.type === void 0 || isCommunityPackageName(node.value.type);
return chatPanelStore.canShowAiButtonOnCanvas && !isCustomNode && !nodeIsHidden();
});
const assistantAlreadyAsked = computed(() => {
return assistantStore.isNodeErrorActive({
error: assistantHelpers.simplifyErrorForAssistant(props.error),
node: props.error.node || ndvStore.activeNode
});
});
const isSubNodeError = computed(() => {
return props.error.name === "NodeOperationError" && props.error.functionality === "configuration-node";
});
function nodeVersionTag(nodeType) {
if (!nodeType || "hidden" in nodeType && nodeType.hidden) return i18n$1.baseText("nodeSettings.deprecated");
const latestNodeVersion = Math.max(...nodeTypesStore.getNodeVersions(nodeType.type));
if (latestNodeVersion === nodeType.typeVersion) return i18n$1.baseText("nodeSettings.latest");
return i18n$1.baseText("nodeSettings.latestVersion", {
interpolate: {
version: latestNodeVersion.toString()
}
});
}
function prepareDescription(description) {
return sanitizeHtml(description.replace(/`(.*?)`/g, "<code>$1</code>"));
}
function getErrorDescription() {
if (props.error.context?.descriptionKey) {
const interpolate = {
nodeCause: props.error.context.nodeCause,
runIndex: props.error.context.runIndex ?? "0",
itemIndex: props.error.context.itemIndex ?? "0"
};
return prepareDescription(i18n$1.baseText(`nodeErrorView.description.${props.error.context.descriptionKey}`, {
interpolate
}));
}
if (!props.error.context?.descriptionTemplate) return prepareDescription(props.error.description ?? "");
const parameterName = parameterDisplayName(props.error.context.parameter);
return prepareDescription(props.error.context.descriptionTemplate.replace(/%%PARAMETER%%/g, parameterName));
}
function addItemIndexSuffix(message$1) {
let itemIndexSuffix = "";
if (hasManyInputItems.value && props.error?.context?.itemIndex !== void 0) itemIndexSuffix = `item ${props.error.context.itemIndex}`;
if (message$1.includes(itemIndexSuffix)) return message$1;
return `${message$1} [${itemIndexSuffix}]`;
}
function getErrorMessage() {
let message$1 = "";
const isNonEmptyString = value => !!value && typeof value === "string";
if (isSubNodeError.value) message$1 = i18n$1.baseText("nodeErrorView.errorSubNode", {
interpolate: {
node: props.error.node?.name ?? ""
}
});else if (isNonEmptyString(props.error.message) && (props.error.message === props.error.description || !props.error.context?.messageTemplate)) message$1 = props.error.message;else if (isNonEmptyString(props.error.context?.messageTemplate) && isNonEmptyString(props.error.context?.parameter)) {
const parameterName = parameterDisplayName(props.error.context.parameter);
message$1 = props.error.context.messageTemplate.replace(/%%PARAMETER%%/g, parameterName);
} else if (Array.isArray(props.error.messages) && props.error.messages.length > 0) message$1 = props.error.messages[0];
return addItemIndexSuffix(message$1);
}
function parameterDisplayName(path, fullPath = true) {
try {
const params = getParameterName(parameters.value, path.split("."));
if (!params.length) throw new Error();
if (!fullPath) return params.pop().displayName;
return params.map(parameter => parameter.displayName).join(" > ");
} catch (error) {
return `Could not find parameter "${path}"`;
}
}
function getParameterName(params, pathParts) {
let currentParameterName = pathParts.shift();
if (currentParameterName === void 0) return [];
const arrayMatch = currentParameterName.match(/(.*)\[([\d])\]$/);
if (arrayMatch !== null && arrayMatch.length > 0) currentParameterName = arrayMatch[1];
const currentParameter = params.find(parameter => parameter.name === currentParameterName);
if (currentParameter === void 0) throw new Error(`Could not find parameter "${currentParameterName}"`);
if (pathParts.length === 0) return [currentParameter];
if (currentParameter.hasOwnProperty("options")) return [currentParameter, ...getParameterName(currentParameter.options, pathParts)];
if (currentParameter.hasOwnProperty("values")) return [currentParameter, ...getParameterName(currentParameter.values, pathParts)];
return [currentParameter];
}
function copyErrorDetails() {
const error = props.error;
const errorInfo = {
errorMessage: getErrorMessage()
};
if (error.description) errorInfo.errorDescription = error.description;
const errorDetails = {};
if (error?.messages?.length) errorDetails.rawErrorMessage = error.messages;
if ("httpCode" in error && error.httpCode) errorDetails.httpCode = error.httpCode;
if (error.context && error.context.data) errorDetails.errorData = error.context.data;
if (error.extra) errorDetails.errorExtra = error.extra;
errorInfo.errorDetails = errorDetails;
const n8nDetails = {};
if (error.node) {
n8nDetails.nodeName = error.node.name;
n8nDetails.nodeType = error.node.type;
n8nDetails.nodeVersion = error.node.typeVersion;
if (error.node?.parameters?.resource) n8nDetails.resource = error.node.parameters.resource;
if (error?.node?.parameters?.operation) n8nDetails.operation = error.node.parameters.operation;
}
if (error.context) {
if (error.context.itemIndex !== void 0) n8nDetails.itemIndex = error.context.itemIndex;
if (error.context.runIndex !== void 0) n8nDetails.runIndex = error.context.runIndex;
if (error.context.parameter !== void 0) n8nDetails.parameter = error.context.parameter;
if (error.context.causeDetailed) n8nDetails.causeDetailed = error.context.causeDetailed;
}
if (error.timestamp) n8nDetails.time = new Date(error.timestamp).toLocaleString();
n8nDetails.n8nVersion = n8nVersion.value;
n8nDetails.binaryDataMode = rootStore.binaryDataMode;
if (error.cause) n8nDetails.cause = error.cause;
n8nDetails.stackTrace = error.stack?.split("\n");
errorInfo.n8nDetails = n8nDetails;
clipboard.copy(JSON.stringify(errorInfo, null, 2));
copySuccess();
}
function copySuccess() {
toast.showMessage({
title: i18n$1.baseText("nodeErrorView.showMessage.title"),
type: "info"
});
}
function nodeIsHidden() {
return nodeTypesStore.getNodeType(node?.value.type)?.hidden ?? false;
}
const onOpenErrorNodeDetailClick = () => {
if (!props.error.node) return;
if ("workflowId" in props.error && workflowId.value && typeof props.error.workflowId === "string" && workflowId.value !== props.error.workflowId && "executionId" in props.error && executionId.value && typeof props.error.executionId === "string" && executionId.value !== props.error.executionId) {
const link = router.resolve({
name: VIEWS.EXECUTION_PREVIEW,
params: {
name: props.error.workflowId,
executionId: props.error.executionId,
nodeId: props.error.node.id
}
});
window.open(link.href, "_blank");
} else ndvStore.setActiveNodeName(props.error.node.name, "other");
};
async function onAskAssistantClick() {
const {
message: message$1,
lineNumber,
description
} = props.error;
const sessionInProgress = !assistantStore.isSessionEnded;
const errorHelp = {
error: {
name: props.error.name,
message: message$1,
lineNumber,
description: description ?? getErrorDescription(),
type: "type" in props.error ? props.error.type : void 0
},
node: node.value
};
if (sessionInProgress) {
uiStore.openModalWithData({
name: NEW_ASSISTANT_SESSION_MODAL,
data: {
context: {
errorHelp
}
}
});
return;
}
await chatPanelStore.openWithErrorHelper(errorHelp);
assistantStore.trackUserOpenedAssistant({
source: "error",
task: "error",
has_existing_session: false
});
}
return (_ctx, _cache) => {
const _directive_n8n_html = resolveDirective("n8n-html");
return openBlock(), createElementBlock("div", {
class: normalizeClass(["node-error-view", props.compact ? "node-error-view_compact" : ""])
}, [createBaseVNode("div", _hoisted_1$6, [createBaseVNode("div", _hoisted_2$3, [createBaseVNode("div", null, toDisplayString(getErrorMessage()), 1)]), (_ctx.error.description || _ctx.error.context?.descriptionKey) && !isSubNodeError.value ? withDirectives((openBlock(), createElementBlock("div", _hoisted_3$2, null, 512)), [[_directive_n8n_html, getErrorDescription()]]) : createCommentVNode("", true), isSubNodeError.value ? (openBlock(), createElementBlock("div", _hoisted_4$2, [createVNode(unref(N8nButton_default), {
icon: "arrow-right",
type: "secondary",
label: unref(i18n$1).baseText("pushConnection.executionError.openNode"),
class: "node-error-view__button",
"data-test-id": "node-error-view-open-node-button",
onClick: onOpenErrorNodeDetailClick
}, null, 8, ["label"])])) : createCommentVNode("", true), isAskAssistantAvailable.value ? (openBlock(), createElementBlock("div", _hoisted_5$2, [createVNode(unref(InlineAskAssistantButton_default), {
asked: assistantAlreadyAsked.value,
onClick: onAskAssistantClick
}, null, 8, ["asked"])])) : createCommentVNode("", true)]), _ctx.showDetails ? (openBlock(), createElementBlock("div", _hoisted_6$1, [createBaseVNode("div", _hoisted_7, [createBaseVNode("p", _hoisted_8, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.title")), 1), createVNode(unref(N8nTooltip_default), {
class: "item",
content: unref(i18n$1).baseText("nodeErrorView.copyToClipboard.tooltip"),
placement: "left"
}, {
default: withCtx(() => [createBaseVNode("div", _hoisted_9, [createVNode(unref(N8nIconButton_default), {
icon: "files",
type: "secondary",
size: "small",
text: true,
"transparent-background": "transparent",
onClick: copyErrorDetails
})])]),
_: 1
}, 8, ["content"])]), createBaseVNode("div", _hoisted_10, ["httpCode" in _ctx.error && _ctx.error.httpCode || prepareRawMessages.value.length || _ctx.error?.context?.data || _ctx.error.extra ? (openBlock(), createElementBlock("details", _hoisted_11, [createBaseVNode("summary", _hoisted_12, [createVNode(unref(N8nIcon_default), {
class: "node-error-view__details-icon",
icon: "chevron-right"
}), createTextVNode(" " + toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.from", {
interpolate: {
node: `${nodeDefaultName.value}`
}
})), 1)]), createBaseVNode("div", _hoisted_13, ["httpCode" in _ctx.error && _ctx.error.httpCode ? (openBlock(), createElementBlock("div", _hoisted_14, [createBaseVNode("p", _hoisted_15, toDisplayString(unref(i18n$1).baseText("nodeErrorView.errorCode")), 1), createBaseVNode("p", _hoisted_16, [createBaseVNode("code", null, toDisplayString(_ctx.error.httpCode), 1)])])) : createCommentVNode("", true), prepareRawMessages.value.length ? (openBlock(), createElementBlock("div", _hoisted_17, [createBaseVNode("p", _hoisted_18, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.rawMessages")), 1), createBaseVNode("div", _hoisted_19, [(openBlock(true), createElementBlock(Fragment, null, renderList(prepareRawMessages.value, (msg, index) => {
return openBlock(), createElementBlock("div", {
key: index
}, [createBaseVNode("pre", null, [createBaseVNode("code", null, toDisplayString(msg), 1)])]);
}), 128))])])) : createCommentVNode("", true), _ctx.error?.context?.data ? (openBlock(), createElementBlock("div", _hoisted_20, [createBaseVNode("p", _hoisted_21, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.errorData")), 1), createBaseVNode("div", _hoisted_22, [createBaseVNode("pre", null, [createBaseVNode("code", null, toDisplayString(_ctx.error.context.data), 1)])])])) : createCommentVNode("", true), _ctx.error.extra ? (openBlock(), createElementBlock("div", _hoisted_23, [createBaseVNode("p", _hoisted_24, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.errorExtra")), 1), createBaseVNode("div", _hoisted_25, [createBaseVNode("pre", null, [createBaseVNode("code", null, toDisplayString(_ctx.error.extra), 1)])])])) : createCommentVNode("", true), _ctx.error.context && _ctx.error.context.request ? (openBlock(), createElementBlock("div", _hoisted_26, [createBaseVNode("p", _hoisted_27, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.request")), 1), createBaseVNode("div", _hoisted_28, [createBaseVNode("pre", null, [createBaseVNode("code", null, toDisplayString(_ctx.error.context.request), 1)])])])) : createCommentVNode("", true)])])) : createCommentVNode("", true), createBaseVNode("details", _hoisted_29, [createBaseVNode("summary", _hoisted_30, [createVNode(unref(N8nIcon_default), {
class: "node-error-view__details-icon",
icon: "chevron-right"
}), createTextVNode(" " + toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.info")), 1)]), createBaseVNode("div", _hoisted_31, [_ctx.error.context && _ctx.error.context.itemIndex !== void 0 ? (openBlock(), createElementBlock("div", _hoisted_32, [createBaseVNode("p", _hoisted_33, toDisplayString(unref(i18n$1).baseText("nodeErrorView.itemIndex")), 1), createBaseVNode("p", _hoisted_34, [createBaseVNode("code", null, toDisplayString(_ctx.error.context.itemIndex), 1)])])) : createCommentVNode("", true), _ctx.error.context && _ctx.error.context.runIndex !== void 0 ? (openBlock(), createElementBlock("div", _hoisted_35, [createBaseVNode("p", _hoisted_36, toDisplayString(unref(i18n$1).baseText("nodeErrorView.runIndex")), 1), createBaseVNode("p", _hoisted_37, [createBaseVNode("code", null, toDisplayString(_ctx.error.context.runIndex), 1)])])) : createCommentVNode("", true), _ctx.error.context && _ctx.error.context.parameter !== void 0 ? (openBlock(), createElementBlock("div", _hoisted_38, [createBaseVNode("p", _hoisted_39, toDisplayString(unref(i18n$1).baseText("nodeErrorView.inParameter")), 1), createBaseVNode("p", _hoisted_40, [createBaseVNode("code", null, toDisplayString(parameterDisplayName(`${_ctx.error.context.parameter}`)), 1)])])) : createCommentVNode("", true), _ctx.error.node && _ctx.error.node.type ? (openBlock(), createElementBlock("div", _hoisted_41, [createBaseVNode("p", _hoisted_42, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.nodeType")), 1), createBaseVNode("p", _hoisted_43, [createBaseVNode("code", null, toDisplayString(_ctx.error.node.type), 1)])])) : createCommentVNode("", true), _ctx.error.node && _ctx.error.node.typeVersion ? (openBlock(), createElementBlock("div", _hoisted_44, [createBaseVNode("p", _hoisted_45, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.nodeVersion")), 1), createBaseVNode("p", _hoisted_46, [createBaseVNode("code", null, [createBaseVNode("span", null, toDisplayString(_ctx.error.node.typeVersion + " "), 1), createBaseVNode("span", null, "(" + toDisplayString(nodeVersionTag(_ctx.error.node)) + ")", 1)])])])) : createCommentVNode("", true), createBaseVNode("div", _hoisted_47, [createBaseVNode("p", _hoisted_48, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.n8nVersion")), 1), createBaseVNode("p", _hoisted_49, [createBaseVNode("code", null, toDisplayString(n8nVersion.value), 1)])]), _ctx.error.timestamp ? (openBlock(), createElementBlock("div", _hoisted_50, [createBaseVNode("p", _hoisted_51, toDisplayString(unref(i18n$1).baseText("nodeErrorView.time")), 1), createBaseVNode("p", _hoisted_52, [createBaseVNode("code", null, toDisplayString(new Date(_ctx.error.timestamp).toLocaleString()), 1)])])) : createCommentVNode("", true), _ctx.error.cause && displayCause.value ? (openBlock(), createElementBlock("div", _hoisted_53, [createBaseVNode("p", _hoisted_54, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.errorCause")), 1), createBaseVNode("pre", _hoisted_55, [createBaseVNode("code", null, toDisplayString(_ctx.error.cause), 1)])])) : createCommentVNode("", true), _ctx.error.context && _ctx.error.context.causeDetailed ? (openBlock(), createElementBlock("div", _hoisted_56, [createBaseVNode("p", _hoisted_57, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.causeDetailed")), 1), createBaseVNode("pre", _hoisted_58, [createBaseVNode("code", null, toDisplayString(_ctx.error.context.causeDetailed), 1)])])) : createCommentVNode("", true), _ctx.error.stack ? (openBlock(), createElementBlock("div", _hoisted_59, [createBaseVNode("p", _hoisted_60, toDisplayString(unref(i18n$1).baseText("nodeErrorView.details.stackTrace")), 1), createBaseVNode("pre", _hoisted_61, [createBaseVNode("code", null, toDisplayString(_ctx.error.stack), 1)])])) : createCommentVNode("", true)])])])])) : createCommentVNode("", true)], 2);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/error/NodeErrorView.vue
_export("a", NodeErrorView_default = NodeErrorView_vue_vue_type_script_setup_true_lang_default); //#endregion
//#region src/features/ndv/runData/components/RunDataPinButton.vue?vue&type=script&setup=true&lang.ts
_hoisted_1$5 = {
key: 0
};
_hoisted_2$2 = {
key: 1
};
_hoisted_3$1 = {
key: 2
};
_hoisted_4$1 = {
key: 0
};
_hoisted_5$1 = {
key: 1
};
RunDataPinButton_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "RunDataPinButton",
props: {
tooltipContentsVisibility: {},
dataPinningDocsUrl: {},
pinnedData: {},
disabled: {
type: Boolean
}
},
emits: ["togglePinData"],
setup(__props, {
emit: __emit
}) {
const locale = useI18n();
const props = __props;
const emit = __emit;
const visible = computed(() => props.tooltipContentsVisibility.pinDataDiscoveryTooltipContent ? true : void 0);
return (_ctx, _cache) => {
return openBlock(), createBlock(unref(N8nTooltip_default), {
placement: "bottom-end",
visible: visible.value
}, {
content: withCtx(() => [props.tooltipContentsVisibility.binaryDataTooltipContent ? (openBlock(), createElementBlock("div", _hoisted_1$5, toDisplayString(unref(locale).baseText("ndv.pinData.pin.binary")), 1)) : props.tooltipContentsVisibility.pinDataDiscoveryTooltipContent ? (openBlock(), createElementBlock("div", _hoisted_2$2, toDisplayString(unref(locale).baseText("node.discovery.pinData.ndv")), 1)) : (openBlock(), createElementBlock("div", _hoisted_3$1, [_ctx.pinnedData.hasData.value ? (openBlock(), createElementBlock("div", _hoisted_4$1, [createBaseVNode("strong", null, toDisplayString(unref(locale).baseText("ndv.pinData.unpin.title")), 1)])) : (openBlock(), createElementBlock("div", _hoisted_5$1, [createBaseVNode("strong", null, toDisplayString(unref(locale).baseText("ndv.pinData.pin.title")), 1), createVNode(unref(N8nText_default), {
size: "small",
tag: "p"
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(locale).baseText("ndv.pinData.pin.description")) + " ", 1), createVNode(unref(N8nLink_default), {
to: props.dataPinningDocsUrl,
size: "small"
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(locale).baseText("ndv.pinData.pin.link")), 1)]),
_: 1
}, 8, ["to"])]),
_: 1
})]))]))]),
default: withCtx(() => [createVNode(unref(N8nIconButton_default), {
class: normalizeClass(_ctx.$style.pinDataButton),
type: "tertiary",
active: props.pinnedData.hasData.value,
icon: "pin",
disabled: props.disabled,
"data-test-id": "ndv-pin-data",
onClick: _cache[0] || (_cache[0] = $event => emit("togglePinData"))
}, null, 8, ["class", "active", "disabled"])]),
_: 1
}, 8, ["visible"]);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/RunDataPinButton.vue?vue&type=style&index=0&lang.module.scss
pinDataButton = "_pinDataButton_12tk2_123";
RunDataPinButton_vue_vue_type_style_index_0_lang_module_default = {
pinDataButton
}; //#endregion
//#region src/features/ndv/runData/components/RunDataPinButton.vue
cssModules$5 = {
"$style": RunDataPinButton_vue_vue_type_style_index_0_lang_module_default
};
RunDataPinButton_default = /* @__PURE__ */__plugin_vue_export_helper_default(RunDataPinButton_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules$5]]); //#endregion
//#region src/features/execution/executions/components/ViewSubExecution.vue?vue&type=script&setup=true&lang.ts
_hoisted_1$4 = ["href"];
ViewSubExecution_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "ViewSubExecution",
props: {
taskMetadata: {},
displayMode: {},
inline: {
type: Boolean,
default: false
}
},
setup(__props) {
const {
trackOpeningRelatedExecution,
resolveRelatedExecutionUrl
} = useExecutionHelpers();
const i18n$1 = useI18n();
const props = __props;
const hasRelatedExecution = computed(() => {
return Boolean(props.taskMetadata.subExecution ?? props.taskMetadata.parentExecution);
});
function getExecutionLinkLabel(task) {
if (task.parentExecution) return i18n$1.baseText("runData.openParentExecution", {
interpolate: {
id: task.parentExecution.executionId
}
});
if (task.subExecution) if (props.taskMetadata.subExecutionsCount === 1) return i18n$1.baseText("runData.openSubExecutionSingle");else return i18n$1.baseText("runData.openSubExecutionWithId", {
interpolate: {
id: task.subExecution.executionId
}
});
}
return (_ctx, _cache) => {
return hasRelatedExecution.value ? (openBlock(), createElementBlock("a", {
key: 0,
class: normalizeClass({
[_ctx.$style.relatedExecutionInfo]: !_ctx.inline
}),
"data-test-id": "related-execution-link",
href: unref(resolveRelatedExecutionUrl)(_ctx.taskMetadata),
target: "_blank",
onClick: _cache[0] || (_cache[0] = withModifiers($event => unref(trackOpeningRelatedExecution)(_ctx.taskMetadata, _ctx.displayMode), ["stop"]))
}, [createVNode(unref(N8nIcon_default), {
icon: "external-link",
size: "xsmall"
}), createTextVNode(" " + toDisplayString(getExecutionLinkLabel(_ctx.taskMetadata)), 1)], 10, _hoisted_1$4)) : createCommentVNode("", true);
};
}
}); //#endregion
//#region src/features/execution/executions/components/ViewSubExecution.vue?vue&type=style&index=0&lang.module.scss
relatedExecutionInfo = "_relatedExecutionInfo_1d0kf_123";
ViewSubExecution_vue_vue_type_style_index_0_lang_module_default = {
relatedExecutionInfo
}; //#endregion
//#region src/features/execution/executions/components/ViewSubExecution.vue
cssModules$4 = {
"$style": ViewSubExecution_vue_vue_type_style_index_0_lang_module_default
};
_export("i", ViewSubExecution_default = /* @__PURE__ */__plugin_vue_export_helper_default(ViewSubExecution_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules$4]])); //#endregion
//#region src/features/ndv/runData/components/RunDataItemCount.vue?vue&type=script&setup=true&lang.ts
_hoisted_1$3 = {
key: 0
};
RunDataItemCount_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "RunDataItemCount",
props: {
dataCount: {},
unfilteredDataCount: {},
subExecutionsCount: {
default: 0
},
search: {}
},
setup(__props) {
const i18n$1 = useI18n();
return (_ctx, _cache) => {
return _ctx.search ? (openBlock(), createBlock(unref(N8nText_default), {
key: 0,
class: normalizeClass(_ctx.$style.itemsText),
"data-test-id": "run-data-item-count"
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("ndv.search.items", {
adjustToNumber: _ctx.unfilteredDataCount,
interpolate: {
matched: _ctx.dataCount,
count: _ctx.unfilteredDataCount
}
})), 1)]),
_: 1
}, 8, ["class"])) : (openBlock(), createBlock(unref(N8nText_default), {
key: 1,
class: normalizeClass(_ctx.$style.itemsText),
"data-test-id": "run-data-item-count"
}, {
default: withCtx(() => [createBaseVNode("span", null, toDisplayString(unref(i18n$1).baseText("ndv.output.items", {
adjustToNumber: _ctx.dataCount,
interpolate: {
count: _ctx.dataCount
}
})), 1), _ctx.subExecutionsCount > 0 ? (openBlock(), createElementBlock("span", _hoisted_1$3, toDisplayString(unref(i18n$1).baseText("ndv.output.andSubExecutions", {
adjustToNumber: _ctx.subExecutionsCount,
interpolate: {
count: _ctx.subExecutionsCount
}
})), 1)) : createCommentVNode("", true)]),
_: 1
}, 8, ["class"]));
};
}
}); //#endregion
//#region src/features/ndv/runData/components/RunDataItemCount.vue?vue&type=style&index=0&lang.module.scss
itemsText = "_itemsText_1uijj_123";
RunDataItemCount_vue_vue_type_style_index_0_lang_module_default = {
itemsText
}; //#endregion
//#region src/features/ndv/runData/components/RunDataItemCount.vue
cssModules$3 = {
"$style": RunDataItemCount_vue_vue_type_style_index_0_lang_module_default
};
_export("r", RunDataItemCount_default = /* @__PURE__ */__plugin_vue_export_helper_default(RunDataItemCount_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules$3]])); //#endregion
//#region src/features/ndv/runData/components/RunDataDisplayModeSelect.vue?vue&type=script&setup=true&lang.ts
_hoisted_1$2 = {
key: 6
};
RunDataDisplayModeSelect_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "RunDataDisplayModeSelect",
props: {
compact: {
type: Boolean
},
value: {},
hasBinaryData: {
type: Boolean
},
paneType: {},
nodeGeneratesHtml: {
type: Boolean
},
hasRenderableData: {
type: Boolean
}
},
emits: ["change"],
setup(__props, {
emit: __emit
}) {
const emit = __emit;
const i18n$1 = useI18n();
const options = computed(() => {
const defaults$2 = [{
label: i18n$1.baseText("runData.schema"),
value: "schema"
}, {
label: i18n$1.baseText("runData.table"),
value: "table"
}, {
label: i18n$1.baseText("runData.json"),
value: "json"
}];
if (__props.hasBinaryData) defaults$2.push({
label: i18n$1.baseText("runData.binary"),
value: "binary"
});
if (__props.paneType === "output" && __props.nodeGeneratesHtml) defaults$2.unshift({
label: "HTML",
value: "html"
});
if (__props.hasRenderableData) defaults$2.unshift({
label: i18n$1.baseText("runData.rendered"),
value: "ai"
});
return defaults$2;
});
watch([() => __props.value, options], ([val, opts]) => {
if (opts.length > 0 && opts.every(opt => opt.value !== val)) emit("change", opts[0].value);
}, {
immediate: true
});
return (_ctx, _cache) => {
return openBlock(), createBlock(unref(N8nRadioButtons_default), {
"model-value": _ctx.value,
options: options.value,
"data-test-id": "ndv-run-data-display-mode",
size: _ctx.compact ? "small-medium" : "medium",
"square-buttons": _ctx.compact,
"onUpdate:modelValue": _cache[0] || (_cache[0] = selected => emit("change", selected))
}, createSlots({
_: 2
}, [_ctx.compact ? {
name: "option",
fn: withCtx(option => [option.value === "table" ? (openBlock(), createBlock(unref(N8nIcon_default), {
key: 0,
icon: "table",
size: "small"
})) : option.value === "json" ? (openBlock(), createBlock(unref(N8nIcon_default), {
key: 1,
icon: "json",
size: "small"
})) : option.value === "binary" ? (openBlock(), createBlock(unref(N8nIcon_default), {
key: 2,
icon: "binary",
size: "small"
})) : option.value === "schema" ? (openBlock(), createBlock(unref(N8nIcon_default), {
key: 3,
icon: "schema",
size: "small"
})) : option.value === "html" ? (openBlock(), createBlock(unref(N8nIcon_default), {
key: 4,
icon: "file-code",
size: "small"
})) : option.value === "ai" ? (openBlock(), createBlock(unref(N8nIcon_default), {
key: 5,
icon: "text",
size: "small"
})) : (openBlock(), createElementBlock("span", _hoisted_1$2, toDisplayString(option.label), 1))]),
key: "0"
} : void 0]), 1032, ["model-value", "options", "size", "square-buttons"]);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/RunDataDisplayModeSelect.vue
RunDataDisplayModeSelect_default = RunDataDisplayModeSelect_vue_vue_type_script_setup_true_lang_default; //#endregion
//#region src/features/ndv/runData/components/RunDataPaginationBar.vue?vue&type=script&setup=true&lang.ts
RunDataPaginationBar_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "RunDataPaginationBar",
props: {
pageSize: {},
total: {},
currentPage: {}
},
emits: ["update:current-page", "update:page-size"],
setup(__props, {
emit: __emit
}) {
const emit = __emit;
const i18n$1 = useI18n();
const pageSizes = [1, 10, 25, 50, 100];
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
class: normalizeClass(_ctx.$style.pagination),
"data-test-id": "ndv-data-pagination"
}, [createVNode(unref(ElPagination), {
background: "",
"hide-on-single-page": true,
"current-page": _ctx.currentPage,
"pager-count": 5,
"page-size": _ctx.pageSize,
layout: "prev, pager, next",
total: _ctx.total,
"onUpdate:currentPage": _cache[0] || (_cache[0] = value => emit("update:current-page", value))
}, null, 8, ["current-page", "page-size", "total"]), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.pageSizeSelector)
}, [createVNode(unref(N8nSelect_default), {
size: "mini",
"model-value": _ctx.pageSize,
teleported: "",
"onUpdate:modelValue": _cache[1] || (_cache[1] = value => emit("update:page-size", value))
}, {
prepend: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("ndv.output.pageSize")), 1)]),
default: withCtx(() => [(openBlock(), createElementBlock(Fragment, null, renderList(pageSizes, size => {
return createVNode(unref(N8nOption_default), {
key: size,
label: size,
value: size
}, null, 8, ["label", "value"]);
}), 64)), createVNode(unref(N8nOption_default), {
label: unref(i18n$1).baseText("ndv.output.all"),
value: _ctx.total
}, null, 8, ["label", "value"])]),
_: 1
}, 8, ["model-value"])], 2)], 2);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/RunDataPaginationBar.vue?vue&type=style&index=0&lang.module.scss
pagination = "_pagination_1hlvz_123";
pageSizeSelector = "_pageSizeSelector_1hlvz_134";
RunDataPaginationBar_vue_vue_type_style_index_0_lang_module_default = {
pagination,
pageSizeSelector
}; //#endregion
//#region src/features/ndv/runData/components/RunDataPaginationBar.vue
cssModules$2 = {
"$style": RunDataPaginationBar_vue_vue_type_style_index_0_lang_module_default
};
RunDataPaginationBar_default = /* @__PURE__ */__plugin_vue_export_helper_default(RunDataPaginationBar_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules$2]]); //#endregion
//#region src/features/ndv/runData/components/RunDataBinary.vue?vue&type=script&setup=true&lang.ts
import_FileSaver_min$1 = /* @__PURE__ */__toESM(require_FileSaver_min());
_hoisted_1$1 = ["data-test-id"];
_hoisted_2$1 = {
key: 0
};
_hoisted_3 = {
key: 1
};
_hoisted_4 = {
key: 2
};
_hoisted_5 = {
key: 3
};
_hoisted_6 = {
key: 4
};
RunDataBinary_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "RunDataBinary",
props: {
binaryData: {}
},
emits: ["preview"],
setup(__props, {
emit: __emit
}) {
const emit = __emit;
const i18n$1 = useI18n();
const workflowsStore = useWorkflowsStore();
function isViewable(index, key) {
const {
mimeType
} = __props.binaryData[index][key];
return ViewableMimeTypes.includes(mimeType);
}
function isDownloadable(index, key) {
const {
mimeType,
fileName
} = __props.binaryData[index][key];
return !!(mimeType && fileName);
}
async function downloadBinaryData(index, key) {
const {
id: id$1,
data,
fileName,
fileExtension,
mimeType
} = __props.binaryData[index][key];
if (id$1) {
(0, import_FileSaver_min$1.saveAs)(workflowsStore.getBinaryUrl(id$1, "download", fileName ?? "", mimeType), [fileName, fileExtension].join("."));
return;
} else {
const bufferString = "data:" + mimeType + ";base64," + data;
(0, import_FileSaver_min$1.saveAs)(await fetch(bufferString).then(async d => await d.blob()), fileName);
}
}
return (_ctx, _cache) => {
return openBlock(), createElementBlock("div", {
class: normalizeClass(_ctx.$style.component)
}, [_ctx.binaryData.length === 0 ? (openBlock(), createBlock(unref(N8nText_default), {
key: 0,
align: "center",
tag: "div"
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.noBinaryDataFound")), 1)]),
_: 1
})) : createCommentVNode("", true), (openBlock(true), createElementBlock(Fragment, null, renderList(_ctx.binaryData, (binaryDataEntry, index) => {
return openBlock(), createElementBlock("div", {
key: index
}, [_ctx.binaryData.length > 1 ? (openBlock(), createElementBlock("div", {
key: 0,
class: normalizeClass(_ctx.$style.binaryIndex)
}, [createBaseVNode("div", null, toDisplayString(index + 1), 1)], 2)) : createCommentVNode("", true), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryRow)
}, [(openBlock(true), createElementBlock(Fragment, null, renderList(binaryDataEntry, (data, key) => {
return openBlock(), createElementBlock("div", {
key: index + "_" + key,
class: normalizeClass(_ctx.$style.binaryCell)
}, [createBaseVNode("div", {
"data-test-id": "ndv-binary-data_" + index
}, [createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryHeader)
}, toDisplayString(key), 3), data.fileName ? (openBlock(), createElementBlock("div", _hoisted_2$1, [createBaseVNode("div", null, [createVNode(unref(N8nText_default), {
size: "small",
bold: true
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.fileName")) + ": ", 1)]),
_: 1
})]), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryValue)
}, toDisplayString(data.fileName), 3)])) : createCommentVNode("", true), data.directory ? (openBlock(), createElementBlock("div", _hoisted_3, [createBaseVNode("div", null, [createVNode(unref(N8nText_default), {
size: "small",
bold: true
}, {
default: withCtx(() => [createTextVNode(toDisplayString(data.directory.startsWith("http://") || data.directory.startsWith("https://") ? unref(i18n$1).baseText("runData.url") : unref(i18n$1).baseText("runData.directory")) + ": ", 1)]),
_: 2
}, 1024)]), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryValue)
}, toDisplayString(data.directory), 3)])) : createCommentVNode("", true), data.fileExtension ? (openBlock(), createElementBlock("div", _hoisted_4, [createBaseVNode("div", null, [createVNode(unref(N8nText_default), {
size: "small",
bold: true
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.fileExtension")) + ": ", 1)]),
_: 1
})]), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryValue)
}, toDisplayString(data.fileExtension), 3)])) : createCommentVNode("", true), data.mimeType ? (openBlock(), createElementBlock("div", _hoisted_5, [createBaseVNode("div", null, [createVNode(unref(N8nText_default), {
size: "small",
bold: true
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.mimeType")) + ": ", 1)]),
_: 1
})]), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryValue)
}, toDisplayString(data.mimeType), 3)])) : createCommentVNode("", true), data.fileSize ? (openBlock(), createElementBlock("div", _hoisted_6, [createBaseVNode("div", null, [createVNode(unref(N8nText_default), {
size: "small",
bold: true
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.fileSize")) + ": ", 1)]),
_: 1
})]), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryValue)
}, toDisplayString(data.fileSize), 3)])) : createCommentVNode("", true), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.binaryButtonContainer)
}, [isViewable(index, key) ? (openBlock(), createBlock(unref(N8nButton_default), {
key: 0,
size: "small",
label: unref(i18n$1).baseText("runData.showBinaryData"),
"data-test-id": "ndv-view-binary-data",
onClick: $event => emit("preview", index, key)
}, null, 8, ["label", "onClick"])) : createCommentVNode("", true), isDownloadable(index, key) ? (openBlock(), createBlock(unref(N8nButton_default), {
key: 1,
size: "small",
type: "secondary",
label: unref(i18n$1).baseText("runData.downloadBinaryData"),
"data-test-id": "ndv-download-binary-data",
onClick: $event => downloadBinaryData(index, key)
}, null, 8, ["label", "onClick"])) : createCommentVNode("", true)], 2)], 8, _hoisted_1$1)], 2);
}), 128))], 2)]);
}), 128))], 2);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/RunDataBinary.vue?vue&type=style&index=0&lang.module.scss
component = "_component_1e3w0_123";
binaryIndex = "_binaryIndex_1e3w0_135";
binaryRow = "_binaryRow_1e3w0_152";
binaryCell = "_binaryCell_1e3w0_157";
binaryHeader = "_binaryHeader_1e3w0_169";
binaryButtonContainer = "_binaryButtonContainer_1e3w0_178";
binaryValue = "_binaryValue_1e3w0_189";
RunDataBinary_vue_vue_type_style_index_0_lang_module_default = {
component,
binaryIndex,
binaryRow,
binaryCell,
binaryHeader,
binaryButtonContainer,
binaryValue
}; //#endregion
//#region src/features/ndv/runData/components/RunDataBinary.vue
cssModules$1 = {
"$style": RunDataBinary_vue_vue_type_style_index_0_lang_module_default
};
RunDataBinary_default = /* @__PURE__ */__plugin_vue_export_helper_default(RunDataBinary_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules$1]]); //#endregion
//#region src/features/ndv/runData/components/RunData.vue?vue&type=script&setup=true&lang.ts
import_FileSaver_min = /* @__PURE__ */__toESM(require_FileSaver_min());
import_isEqual = /* @__PURE__ */__toESM(require_isEqual());
import_isObject = /* @__PURE__ */__toESM(require_isObject());
_hoisted_1 = {
key: 0,
class: "ml-4xs"
};
_hoisted_2 = {
key: 1
};
RunData_vue_vue_type_script_setup_true_lang_default = /* @__PURE__ */defineComponent({
__name: "RunData",
props: {
workflowObject: {},
workflowExecution: {
default: void 0
},
runIndex: {},
executingMessage: {},
pushRef: {},
paneType: {},
displayMode: {},
noDataInBranchMessage: {},
node: {
default: null
},
nodes: {
default: () => []
},
linkedRuns: {
type: Boolean
},
canLinkRuns: {
type: Boolean
},
isExecuting: {
type: Boolean,
default: false
},
overrideOutputs: {
default: void 0
},
mappingEnabled: {
type: Boolean,
default: false
},
distanceFromActive: {
default: 0
},
blockUI: {
type: Boolean,
default: false
},
isProductionExecutionPreview: {
type: Boolean,
default: false
},
searchShortcut: {
default: void 0
},
hidePagination: {
type: Boolean,
default: false
},
calloutMessage: {
default: void 0
},
disableRunIndexSelection: {
type: Boolean,
default: false
},
disableDisplayModeSelection: {
type: Boolean,
default: false
},
disableEdit: {
type: Boolean,
default: false
},
disablePin: {
type: Boolean,
default: false
},
compact: {
type: Boolean,
default: false
},
showActionsOnHover: {
type: Boolean,
default: false
},
tableHeaderBgColor: {
default: "base"
},
disableHoverHighlight: {
type: Boolean,
default: false
},
disableSettingsHint: {
type: Boolean,
default: false
},
disableAiContent: {
type: Boolean,
default: false
},
collapsingTableColumnName: {},
truncateLimit: {}
},
emits: ["search", "runChange", "itemHover", "linkRun", "unlinkRun", "activatePane", "tableMounted", "displayModeChange", "collapsingTableColumnChanged", "captureWheelDataContainer"],
setup(__props, {
expose: __expose,
emit: __emit
}) {
const LazyRunDataTable = defineAsyncComponent(async () => await __vitePreload(() => _context.import("./RunDataTable-legacy-DEjcTLS6.js"), true ? void 0 : void 0));
const LazyRunDataJson = defineAsyncComponent(async () => await __vitePreload(() => _context.import("./RunDataJson-legacy-C33VaI-_.js"), true ? void 0 : void 0));
const LazyRunDataSchema = defineAsyncComponent(async () => await __vitePreload(() => _context.import("./VirtualSchema-legacy-Dj_jut97.js"), true ? void 0 : void 0));
const LazyRunDataHtml = defineAsyncComponent(async () => await __vitePreload(() => _context.import("./RunDataHtml-legacy-BByK4_Xp.js"), true ? void 0 : void 0));
const LazyRunDataAi = defineAsyncComponent(async () => await __vitePreload(() => _context.import("./RunDataParsedAiContent-legacy-CzOBQxDZ.js"), true ? void 0 : void 0));
const LazyRunDataSearch = defineAsyncComponent(async () => await __vitePreload(() => _context.import("./RunDataSearch-legacy-CCeKJkRO.js"), true ? void 0 : void 0));
const props = __props;
const emit = __emit;
const connectionType = ref(NodeConnectionTypes.Main);
const dataSize = ref(0);
const showData = ref(false);
const userEnabledShowData = ref(false);
const outputIndex = ref(0);
const binaryDataDisplayData = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const previousExecutionDataUsedInEditMode = ref(false);
const pinDataDiscoveryTooltipVisible = ref(false);
const isControlledPinDataTooltip = ref(false);
const search$1 = ref("");
const dataContainerRef = ref();
const nodeTypesStore = useNodeTypesStore();
const ndvStore = useNDVStore();
const workflowsStore = useWorkflowsStore();
const workflowState = injectWorkflowState();
const sourceControlStore = useSourceControlStore();
const rootStore = useRootStore();
const schemaPreviewStore = useSchemaPreviewStore();
const posthogStore = usePostHog();
const toast = useToast();
const route = useRoute();
const nodeHelpers = useNodeHelpers();
const externalHooks = useExternalHooks();
const telemetry = useTelemetry();
const i18n$1 = useI18n();
const {
runWorkflow
} = useRunWorkflow({
router: useRouter()
});
const node = toRef(props, "node");
const pinnedData = usePinnedData(node, {
runIndex: props.runIndex,
displayMode: props.displayMode
});
const {
isSubNodeType
} = useNodeType({
node
});
const isArchivedWorkflow = computed(() => workflowsStore.workflow.isArchived);
const isReadOnlyRoute = computed(() => route.meta.readOnlyCanvas === true);
const isWaitNodeWaiting = computed(() => {
return node.value?.name && workflowExecution.value?.resultData?.runData?.[node.value?.name]?.[props.runIndex]?.executionStatus === "waiting";
});
const {
activeNode
} = storeToRefs(ndvStore);
const nodeType = computed(() => {
if (!node.value) return null;
return nodeTypesStore.getNodeType(node.value.type, node.value.typeVersion);
});
const isPaneTypeInput = computed(() => props.paneType === "input");
const isPaneTypeOutput = computed(() => props.paneType === "output");
const isSchemaView = computed(() => props.displayMode === "schema");
const isSearchInSchemaView = computed(() => isSchemaView.value && !!search$1.value);
const hasMultipleInputNodes = computed(() => isPaneTypeInput.value && props.nodes.length > 0);
const displaysMultipleNodes = computed(() => isSchemaView.value && hasMultipleInputNodes.value);
const hasAnyUpstreamExecuted = computed(() => {
return hasMultipleInputNodes.value && props.nodes.some(inputNode => nodeHelpers.hasNodeExecuted(inputNode.name));
});
const hasAnyDataAvailable = computed(() => {
return node.value?.disabled || hasPreviewSchema.value || hasAnyUpstreamExecuted.value || !!workflowsStore.lastSuccessfulExecution;
});
const isSingleNodeView = computed(() => !displaysMultipleNodes.value);
const hasBinaryData = computed(() => binaryData.value?.length > 0);
const hasNoData = computed(() => !rawInputData.value.length && !pinnedData.hasData.value);
const isReadOnly = computed(() => isReadOnlyRoute.value || readOnlyEnv.value || isArchivedWorkflow.value);
const shouldShowSchemaView = computed(() => {
if (!isSchemaView.value) return false;
return hasNodeRun.value || hasPreviewSchema.value || !hasNodeRun.value && (hasAnyUpstreamExecuted.value || workflowsStore.lastSuccessfulExecution);
});
const currentNodeRunData = computed(() => {
if (!node.value || !workflowRunData.value) return null;
const nodeName = node.value.name;
return workflowRunData.value.hasOwnProperty(nodeName) ? workflowRunData.value[nodeName] : null;
});
const shouldShowNodeNotRunState = computed(() => {
return !hasNodeRun.value && !(displaysMultipleNodes.value && hasAnyDataAvailable.value);
});
const shouldShowDisabledNodeHint = computed(() => {
return isPaneTypeInput.value && isSingleNodeView.value && node.value?.disabled;
});
const shouldShowNoDataInBranch = computed(() => {
return hasNodeRun.value && (!unfilteredDataCount.value || search$1.value && !dataCount.value) && isSingleNodeView.value && branches.value.length > 1;
});
const shouldShowNoOutputData = computed(() => {
return hasNodeRun.value && !inputData.value.length && isSingleNodeView.value && !search$1.value;
});
const shouldShowBinaryOnlyHint = computed(() => {
return hasNodeRun.value && props.displayMode === "table" && binaryData.value.length > 0 && inputData.value.length === 1 && Object.keys(jsonData.value[0] || {}).length === 0;
});
const isTriggerNode = computed(() => node.value && nodeTypesStore.isTriggerNode(node.value.type));
const canPinData = computed(() => node.value && pinnedData.canPinNode(false, currentOutputIndex.value) && !isPaneTypeInput.value && pinnedData.isValidNodeType.value && !hasBinaryData.value);
const hasNodeRun = computed(() => Boolean(!props.isExecuting && node.value && (workflowRunData.value && workflowRunData.value.hasOwnProperty(node.value.name) || pinnedData.hasData.value)));
const isArtificialRecoveredEventItem = computed(() => rawInputData.value?.[0]?.json?.isArtificialRecoveredEventItem);
const subworkflowExecutionError = computed(() => {
if (!node.value) return null;
return {
node: node.value,
messages: [workflowsStore.subWorkflowExecutionError?.message ?? ""]
};
});
const hasSubworkflowExecutionError = computed(() => !!workflowsStore.subWorkflowExecutionError);
const parentNodeError = computed(() => {
const parentNode = props.workflowObject.getChildNodes(node.value?.name ?? "", "ALL_NON_MAIN")[0];
return workflowRunData.value?.[parentNode]?.[props.runIndex]?.error;
});
const workflowRunErrorAsNodeError = computed(() => {
if (!node.value) return null;
if (isSubNodeType.value && isPaneTypeInput.value) return parentNodeError.value;
return workflowRunData.value?.[node.value.name]?.[props.runIndex]?.error;
});
const hasRunError = computed(() => node.value && !!workflowRunErrorAsNodeError.value);
const executionHints = computed(() => {
if (hasNodeRun.value) {
const hints = node.value && workflowRunData.value?.[node.value.name]?.[props.runIndex]?.hints;
if (hints) return hints;
}
return [];
});
const workflowExecution = computed(() => props.workflowExecution ?? workflowsStore.getWorkflowExecution?.data ?? void 0);
const workflowRunData = computed(() => {
if (workflowExecution.value === void 0) return null;
const executionData = workflowExecution.value;
if (executionData?.resultData) return executionData.resultData.runData;
return null;
});
const dataCount = computed(() => getDataCount(props.runIndex, currentOutputIndex.value, connectionType.value));
const isTrimmedManualExecutionDataItem = computed(() => workflowRunData.value ? hasTrimmedRunData(workflowRunData.value) : false);
const unfilteredDataCount = computed(() => pinnedData.data.value ? pinnedData.data.value.length : rawInputData.value.length);
const dataSizeInMB = computed(() => (dataSize.value / (1024 * 1024)).toFixed(1));
const maxOutputIndex = computed(() => {
if (!node.value || props.runIndex === void 0) return 0;
const nodeRunData = currentNodeRunData.value;
if (!nodeRunData || nodeRunData.length <= props.runIndex) return 0;
const taskData = nodeRunData[props.runIndex]?.data;
return taskData?.main ? taskData.main.length - 1 : 0;
});
const currentPageOffset = computed(() => pageSize.value * (currentPage.value - 1));
const showBranchSwitch = computed(() => maxOutputIndex.value > 0 && branches.value.length > 1 && isSingleNodeView.value);
const maxRunIndex = computed(() => {
const nodeRunData = currentNodeRunData.value;
return nodeRunData?.length ? nodeRunData.length - 1 : 0;
});
const runSelectorOptionsCount = computed(() => {
const nodeRunData = currentNodeRunData.value;
if (!nodeRunData) return 0;
if (showBranchSwitch.value) return maxRunIndex.value + 1;
return nodeRunData.filter(nodeRun => {
const nodeOutput = nodeRun?.data?.[connectionType.value]?.[currentOutputIndex.value];
return nodeOutput && nodeOutput.length > 0;
}).length;
});
const rawInputData = computed(() => getRawInputData(props.runIndex, currentOutputIndex.value, connectionType.value));
const unfilteredInputData = computed(() => getPinDataOrLiveData(rawInputData.value));
const inputData = computed(() => getFilteredData(unfilteredInputData.value));
const inputDataPage = computed(() => {
const offset = pageSize.value * (currentPage.value - 1);
return inputData.value.slice(offset, offset + pageSize.value);
});
const jsonData = computed(() => executionDataToJson(inputData.value));
const binaryData = computed(() => {
if (!node.value) return [];
return nodeHelpers.getBinaryData(workflowRunData.value, node.value.name, props.runIndex, currentOutputIndex.value).filter(data => Boolean(data && Object.keys(data).length));
});
const inputHtml = computed(() => String(inputData.value[0]?.json?.html ?? ""));
const currentOutputIndex = computed(() => {
if (props.overrideOutputs?.length && !props.overrideOutputs.includes(outputIndex.value)) return props.overrideOutputs[0];
return Math.min(outputIndex.value, maxOutputIndex.value);
});
const branches = computed(() => {
const capitalize = name$1 => name$1.charAt(0).toLocaleUpperCase() + name$1.slice(1);
const result = [];
for (let i$1 = 0; i$1 <= maxOutputIndex.value; i$1++) {
if (props.overrideOutputs && !props.overrideOutputs.includes(i$1)) continue;
const totalItemsCount = getRawInputData(props.runIndex, i$1).length;
const itemsCount$1 = getDataCount(props.runIndex, i$1);
const items = search$1.value ? i18n$1.baseText("ndv.search.items", {
adjustToNumber: totalItemsCount,
interpolate: {
matched: itemsCount$1,
total: totalItemsCount
}
}) : i18n$1.baseText("ndv.output.items", {
adjustToNumber: itemsCount$1,
interpolate: {
count: itemsCount$1
}
});
let outputName = getOutputName(i$1);
if (`${outputName}` === `${i$1}`) outputName = `${i18n$1.baseText("ndv.output")} ${outputName}`;else {
const appendBranchWord = NODE_TYPES_EXCLUDED_FROM_OUTPUT_NAME_APPEND.includes(node.value?.type ?? "") ? "" : ` ${i18n$1.baseText("ndv.output.branch")}`;
outputName = capitalize(`${getOutputName(i$1)}${appendBranchWord}`);
}
result.push({
label: search$1.value && itemsCount$1 || totalItemsCount ? `${outputName} (${items})` : outputName,
value: i$1
});
}
return result;
});
const editMode$1 = computed(() => {
return isPaneTypeInput.value ? {
enabled: false,
value: ""
} : ndvStore.outputPanelEditMode;
});
const readOnlyEnv = computed(() => sourceControlStore.preferences.branchReadOnly);
const showIOSearch = computed(() => hasNodeRun.value && !hasRunError.value && (unfilteredInputData.value.length > 0 || displaysMultipleNodes.value));
const inputSelectLocation = computed(() => {
if (isSchemaView.value) return "none";
if (!hasNodeRun.value) return "header";
if (maxRunIndex.value > 0) return "runs";
if (maxOutputIndex.value > 0 && branches.value.length > 1) return "outputs";
return "items";
});
const showIoSearchNoMatchContent = computed(() => hasNodeRun.value && !inputData.value.length && !!search$1.value && isSingleNodeView.value);
const shouldShowDisplayModeSelect = computed(() => {
if (editMode$1.value.enabled) return false;
return hasAnyDataAvailable.value || hasNodeRun.value && (inputData.value.length || binaryData.value.length || search$1.value || hasMultipleInputNodes.value);
});
const parentNodeOutputData = computed(() => {
const parentNode = props.workflowObject.getParentNodesByDepth(node.value?.name ?? "")[0];
let parentNodeData = [];
if (parentNode?.name) parentNodeData = nodeHelpers.getNodeInputData(props.workflowObject.getNode(parentNode?.name), props.runIndex, outputIndex.value, "input", connectionType.value);
return parentNodeData;
});
const parentNodePinnedData = computed(() => {
const parentNode = props.workflowObject.getParentNodesByDepth(node.value?.name ?? "")[0];
return props.workflowObject.pinData?.[parentNode?.name || ""] ?? [];
});
const showPinButton = computed(() => !props.disablePin && !hasNoData.value && !editMode$1.value.enabled && (hasBinaryData.value ? isPaneTypeOutput.value : canPinData.value));
const pinButtonDisabled = computed(() => hasNoData.value || hasBinaryData.value || isReadOnly.value);
const activeTaskMetadata = computed(() => {
if (!node.value) return null;
const errorMetadata = parseErrorMetadata(workflowRunErrorAsNodeError.value);
if (errorMetadata !== void 0) return errorMetadata;
if (parentNodeError.value) {
const subNodeMetadata = parseErrorMetadata(parentNodeError.value);
if (subNodeMetadata !== void 0) return subNodeMetadata;
}
return workflowRunData.value?.[node.value.name]?.[props.runIndex]?.metadata ?? null;
});
const hasInputOverwrite = computed(() => {
if (!node.value) return false;
const taskData = nodeHelpers.getNodeTaskData(node.value.name, props.runIndex);
return Boolean(taskData?.inputOverride);
});
const isSchemaPreviewEnabled = computed(() => props.paneType === "input" && !(nodeType.value?.codex?.categories ?? []).some(category => category === "Core Nodes"));
const isNDVV2 = computed(() => posthogStore.isVariantEnabled(NDV_UI_OVERHAUL_EXPERIMENT.name, NDV_UI_OVERHAUL_EXPERIMENT.variant));
const hasPreviewSchema = computedAsync(async () => {
if (!isSchemaPreviewEnabled.value || props.nodes.length === 0) return false;
const nodes = props.nodes.filter(n => n.depth === 1).map(n => workflowsStore.getNodeByName(n.name)).filter(isPresent);
for (const connectedNode of nodes) {
const {
type,
typeVersion,
parameters
} = connectedNode;
if ((await schemaPreviewStore.getSchemaPreview({
nodeType: type,
version: typeVersion,
resource: parameters.resource,
operation: parameters.operation
})).ok) return true;
}
return false;
}, false);
const itemsCountProps = computed(() => ({
search: search$1.value,
dataCount: dataCount.value,
unfilteredDataCount: unfilteredDataCount.value,
subExecutionsCount: activeTaskMetadata.value?.subExecutionsCount
}));
const parsedAiContent = computed(() => props.disableAiContent ? [] : parseAiContent(rawInputData.value, connectionType.value));
const hasParsedAiContent = computed(() => parsedAiContent.value.some(prr => prr.parsedContent?.parsed));
const binaryDataDisplayVisible = computed(() => binaryDataDisplayData.value !== null && props.displayMode === "binary");
function setInputBranchIndex(value) {
if (props.paneType === "input") outputIndex.value = value;
}
watch(node, (newNode, prevNode) => {
if (newNode?.id === prevNode?.id) return;
init();
});
watch([hasNodeRun, isTrimmedManualExecutionDataItem], () => {
if (props.paneType === "output") setDisplayMode();else outputIndex.value = determineInitialOutputIndex();
});
watch(inputDataPage, data => {
if (props.paneType && data) ndvStore.setNDVPanelDataIsEmpty({
panel: props.paneType,
isEmpty: data.every(item => isEmpty$1(item.json))
});
}, {
immediate: true,
deep: true
});
watch(jsonData, (data, prevData) => {
if ((0, import_isEqual.default)(data, prevData)) return;
refreshDataSize();
if (dataCount.value) resetCurrentPageIfTooFar();
showPinDataDiscoveryTooltip(data);
});
watch(binaryData, (newData, prevData) => {
if (newData.length && !prevData.length && props.displayMode !== "binary") switchToBinary();else if (!newData.length && props.displayMode === "binary") onDisplayModeChange("table");
});
watch(currentOutputIndex, branchIndex => {
ndvStore.setNDVBranchIndex({
pane: props.paneType,
branchIndex
});
});
watch(search$1, newSearch => {
emit("search", newSearch);
});
watch(hasParsedAiContent, hasAiContent => {
if (hasAiContent && props.displayMode !== "ai") emit("displayModeChange", "ai");
}, {
immediate: true
});
onMounted(() => {
init();
ndvEventBus.on("setInputBranchIndex", setInputBranchIndex);
if (!isPaneTypeInput.value) showPinDataDiscoveryTooltip(jsonData.value);
ndvStore.setNDVBranchIndex({
pane: props.paneType,
branchIndex: currentOutputIndex.value
});
if (props.paneType === "output") activatePane();
if (hasRunError.value && node.value) {
const error = workflowRunData.value?.[node.value.name]?.[props.runIndex]?.error;
if (error && ["unknown error"].some(e => error.message?.toLowerCase().includes(e))) telemetry.track("User encountered an error", {
node: node.value.type,
errorMessage: error.message,
nodeVersion: node.value.typeVersion,
n8nVersion: rootStore.versionCli
});
}
});
onBeforeUnmount(() => {
hidePinDataDiscoveryTooltip();
ndvEventBus.off("setInputBranchIndex", setInputBranchIndex);
});
function getResolvedNodeOutputs() {
if (node.value && nodeType.value) {
const workflowNode = props.workflowObject.getNode(node.value.name);
if (workflowNode) return getNodeOutputs(props.workflowObject, workflowNode, nodeType.value);
}
return [];
}
function shouldHintBeDisplayed(hint) {
const {
location,
whenToDisplay
} = hint;
if (location) {
if (location === "ndv" && !["input", "output"].includes(props.paneType)) return false;
if (location === "inputPane" && props.paneType !== "input") return false;
if (location === "outputPane" && props.paneType !== "output") return false;
}
if (whenToDisplay === "afterExecution" && !hasNodeRun.value) return false;
if (whenToDisplay === "beforeExecution" && hasNodeRun.value) return false;
return true;
}
const nodeHints = computed(() => {
try {
if (node.value && nodeType.value) {
const workflowNode = props.workflowObject.getNode(node.value.name);
if (workflowNode) {
const hints = nodeHelpers.getNodeHints(props.workflowObject, workflowNode, nodeType.value, {
runExecutionData: workflowExecution.value ?? null,
runIndex: props.runIndex,
connectionInputData: parentNodeOutputData.value
});
const hasMultipleInputItems = parentNodeOutputData.value.length > 1 || parentNodePinnedData.value.length > 1;
const nodeOutputData = workflowRunData.value?.[node.value.name]?.[props.runIndex]?.data?.main?.[0] ?? [];
const genericHints = getGenericHints({
workflowNode,
node: node.value,
nodeType: nodeType.value,
nodeOutputData,
nodes: props.workflowObject.nodes,
connections: props.workflowObject.connectionsBySourceNode,
hasNodeRun: hasNodeRun.value,
hasMultipleInputItems
});
return executionHints.value.concat(hints, genericHints).filter(shouldHintBeDisplayed);
}
}
} catch (error) {
console.error("Error while getting node hints", error);
}
return [];
});
function onItemHover(itemIndex) {
if (itemIndex === null) {
emit("itemHover", null);
return;
}
emit("itemHover", {
outputIndex: currentOutputIndex.value,
itemIndex
});
}
function onClickDataPinningDocsLink() {
telemetry.track("User clicked ndv link", {
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
node_type: activeNode.value?.type,
pane: "output",
type: "data-pinning-docs"
});
}
function showPinDataDiscoveryTooltip(value) {
if (!isTriggerNode.value) return;
const pinDataDiscoveryFlag = useStorage(LOCAL_STORAGE_PIN_DATA_DISCOVERY_NDV_FLAG).value;
if (value && value.length > 0 && !isReadOnlyRoute.value && !isArchivedWorkflow.value && !pinDataDiscoveryFlag) {
pinDataDiscoveryComplete();
setTimeout(() => {
isControlledPinDataTooltip.value = true;
pinDataDiscoveryTooltipVisible.value = true;
dataPinningEventBus.emit("data-pinning-discovery", {
isTooltipVisible: true
});
}, 500);
}
}
function hidePinDataDiscoveryTooltip() {
if (pinDataDiscoveryTooltipVisible.value) {
isControlledPinDataTooltip.value = false;
pinDataDiscoveryTooltipVisible.value = false;
dataPinningEventBus.emit("data-pinning-discovery", {
isTooltipVisible: false
});
}
}
function pinDataDiscoveryComplete() {
useStorage(LOCAL_STORAGE_PIN_DATA_DISCOVERY_NDV_FLAG).value = "true";
useStorage(LOCAL_STORAGE_PIN_DATA_DISCOVERY_CANVAS_FLAG).value = "true";
}
function enterEditMode({
origin
}) {
const inputData$1 = pinnedData.data.value ? clearJsonKey(pinnedData.data.value) : executionDataToJson(rawInputData.value);
const inputDataLength = Array.isArray(inputData$1) ? inputData$1.length : Object.keys(inputData$1 ?? {}).length;
const lastSuccessfulExecutionItems = getOutputtedNodeItems(workflowsStore.lastSuccessfulExecution, node.value);
previousExecutionDataUsedInEditMode.value = inputDataLength === 0 && Boolean(lastSuccessfulExecutionItems.length);
const mockData = lastSuccessfulExecutionItems.length ? executionDataToJson(lastSuccessfulExecutionItems) : DUMMY_PIN_DATA;
const data = inputDataLength > 0 ? inputData$1 : mockData;
ndvStore.setOutputPanelEditModeEnabled(true);
ndvStore.setOutputPanelEditModeValue(JSON.stringify(data, null, 2));
telemetry.track("User opened ndv edit state", {
node_type: activeNode.value?.type,
click_type: origin === "editIconButton" ? "button" : "link",
push_ref: props.pushRef,
run_index: props.runIndex,
is_output_present: hasNodeRun.value || pinnedData.hasData.value,
view: !hasNodeRun.value && !pinnedData.hasData.value ? "undefined" : props.displayMode,
is_data_pinned: pinnedData.hasData.value
});
}
function getOutputtedNodeItems(execution, node$1, runIndex = 0, outputIndex$1 = 0, connectionType$1 = "main") {
if (!node$1) return [];
return execution?.data?.resultData.runData?.[node$1?.name]?.[runIndex]?.data?.[connectionType$1]?.[outputIndex$1] ?? [];
}
function onClickCancelEdit() {
ndvStore.setOutputPanelEditModeEnabled(false);
ndvStore.setOutputPanelEditModeValue("");
onExitEditMode({
type: "cancel"
});
}
function onClickSaveEdit() {
if (!node.value) return;
const {
value
} = editMode$1.value;
toast.clearAllStickyNotifications();
try {
const clearedValue = clearJsonKey(value);
try {
pinnedData.setData(clearedValue, "save-edit");
} catch (error) {
return;
}
} catch (error) {
toast.showError(error, i18n$1.baseText("ndv.pinData.error.syntaxError.title"));
return;
}
ndvStore.setOutputPanelEditModeEnabled(false);
onExitEditMode({
type: "save"
});
}
function onExitEditMode({
type
}) {
telemetry.track("User closed ndv edit state", {
node_type: activeNode.value?.type,
push_ref: props.pushRef,
run_index: props.runIndex,
view: props.displayMode,
type
});
}
async function onTogglePinData({
source
}) {
if (!node.value) return;
if (source === "pin-icon-click") {
const telemetryPayload = {
node_type: activeNode.value?.type,
push_ref: props.pushRef,
run_index: props.runIndex,
view: !hasNodeRun.value && !pinnedData.hasData.value ? "none" : props.displayMode
};
externalHooks.run("runData.onTogglePinData", telemetryPayload);
telemetry.track("User clicked pin data icon", telemetryPayload);
}
nodeHelpers.updateNodeParameterIssues(node.value);
if (pinnedData.hasData.value) {
pinnedData.unsetData(source);
return;
}
try {
pinnedData.setData(rawInputData.value, "pin-icon-click");
} catch (error) {
console.error(error);
return;
}
if (maxRunIndex.value > 0) toast.showToast({
title: i18n$1.baseText("ndv.pinData.pin.multipleRuns.title", {
interpolate: {
index: `${props.runIndex}`
}
}),
message: i18n$1.baseText("ndv.pinData.pin.multipleRuns.description"),
type: "success",
duration: 2e3
});
hidePinDataDiscoveryTooltip();
pinDataDiscoveryComplete();
}
function switchToBinary() {
onDisplayModeChange("binary");
}
function onBranchChange(value) {
outputIndex.value = value;
telemetry.track("User changed ndv branch", {
push_ref: props.pushRef,
branch_index: value,
node_type: activeNode.value?.type,
node_type_input_selection: nodeType.value ? nodeType.value.name : "",
pane: props.paneType
});
}
function showTooMuchData() {
showData.value = true;
userEnabledShowData.value = true;
telemetry.track("User clicked ndv button", {
node_type: activeNode.value?.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: props.paneType,
type: "showTooMuchData"
});
}
function toggleLinkRuns() {
if (props.linkedRuns) unlinkRun();else linkRun();
}
function linkRun() {
emit("linkRun");
}
function unlinkRun() {
emit("unlinkRun");
}
function onCurrentPageChange(value) {
currentPage.value = value;
telemetry.track("User changed ndv page", {
node_type: activeNode.value?.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: props.paneType,
page_selected: currentPage.value,
page_size: pageSize.value,
items_total: dataCount.value
});
}
function resetCurrentPageIfTooFar() {
const maxPage = Math.ceil(dataCount.value / pageSize.value);
if (maxPage < currentPage.value) currentPage.value = maxPage;
}
function onPageSizeChange(newPageSize) {
pageSize.value = newPageSize;
resetCurrentPageIfTooFar();
telemetry.track("User changed ndv page size", {
node_type: activeNode.value?.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: props.paneType,
page_selected: currentPage.value,
page_size: pageSize.value,
items_total: dataCount.value
});
}
function onDisplayModeChange(newDisplayMode) {
const previous = props.displayMode;
emit("displayModeChange", newDisplayMode);
if (!userEnabledShowData.value) updateShowData();
if (dataContainerRef.value) {
const dataDisplay$1 = dataContainerRef.value.children[0];
if (dataDisplay$1) dataDisplay$1.scrollTo(0, 0);
}
closeBinaryDataDisplay();
externalHooks.run("runData.displayModeChanged", {
newValue: newDisplayMode,
oldValue: previous
});
if (activeNode.value) telemetry.track("User changed ndv item view", {
previous_view: previous,
new_view: newDisplayMode,
node_type: activeNode.value.type,
workflow_id: workflowsStore.workflowId,
push_ref: props.pushRef,
pane: props.paneType
});
}
function getRunLabel(option) {
if (!node.value) return;
let itemsCount$1 = 0;
for (let i$1 = 0; i$1 <= maxOutputIndex.value; i$1++) itemsCount$1 += getPinDataOrLiveData(getRawInputData(option - 1, i$1)).length;
const items = i18n$1.baseText("ndv.output.items", {
adjustToNumber: itemsCount$1,
interpolate: {
count: itemsCount$1
}
});
const metadata = workflowRunData.value?.[node.value.name]?.[option - 1]?.metadata ?? null;
const subexecutions = metadata?.subExecutionsCount ? i18n$1.baseText("ndv.output.andSubExecutions", {
adjustToNumber: metadata.subExecutionsCount,
interpolate: {
count: metadata.subExecutionsCount
}
}) : "";
const itemsLabel = itemsCount$1 > 0 ? ` (${items}${subexecutions})` : "";
return option + i18n$1.baseText("ndv.output.of") + runSelectorOptionsCount.value + itemsLabel;
}
function getRawInputData(runIndex, outputIndex$1, connectionType$1 = NodeConnectionTypes.Main) {
let inputData$1 = [];
if (node.value) inputData$1 = nodeHelpers.getNodeInputData(node.value, runIndex, outputIndex$1, props.paneType, connectionType$1, workflowExecution.value);
if (inputData$1.length === 0 || !Array.isArray(inputData$1)) return [];
return inputData$1;
}
function getPinDataOrLiveData(data) {
if (pinnedData.data.value && !props.isProductionExecutionPreview) return Array.isArray(pinnedData.data.value) ? pinnedData.data.value.map(value => ({
json: value
})) : [{
json: pinnedData.data.value
}];
return data;
}
function getFilteredData(data) {
if (!search$1.value || isSchemaView.value) return data;
currentPage.value = 1;
return data.filter(({
json: json$1
}) => searchInObject(json$1, search$1.value));
}
function getDataCount(runIndex, outputIndex$1, connectionType$1 = NodeConnectionTypes.Main) {
if (!node.value) return 0;
if (workflowRunData.value?.[node.value.name]?.[runIndex]?.hasOwnProperty("error")) return 1;
return getFilteredData(getPinDataOrLiveData(getRawInputData(runIndex, outputIndex$1, connectionType$1))).length;
}
function determineInitialOutputIndex() {
for (let i$1 = 0; i$1 <= maxOutputIndex.value; i$1++) if (getRawInputData(props.runIndex, i$1).length) return i$1;
return 0;
}
function init() {
outputIndex.value = determineInitialOutputIndex();
refreshDataSize();
closeBinaryDataDisplay();
let outputTypes = [];
if (node.value && nodeType.value) {
const outputs$1 = getResolvedNodeOutputs();
outputTypes = getConnectionTypes(outputs$1);
}
connectionType.value = outputTypes.length === 0 ? NodeConnectionTypes.Main : outputTypes[0];
if (binaryData.value.length > 0) emit("displayModeChange", "binary");else if (props.displayMode === "binary") emit("displayModeChange", "schema");
if (isNDVV2.value) pageSize.value = 25;
if (props.paneType === "output") setDisplayMode();
}
function closeBinaryDataDisplay() {
binaryDataDisplayData.value = null;
}
function downloadJsonData() {
const fileName = (node.value?.name ?? "").replace(/[^\w\d]/g, "_");
(0, import_FileSaver_min.saveAs)(new Blob([JSON.stringify(rawInputData.value, null, 2)], {
type: "application/json"
}), `${fileName}.json`);
}
function displayBinaryData(index, key) {
const {
data,
mimeType
} = binaryData.value[index][key];
binaryDataDisplayData.value = {
node: node.value?.name,
runIndex: props.runIndex,
outputIndex: currentOutputIndex.value,
index,
key,
data,
mimeType
};
}
function getOutputName(outputIndex$1) {
if (node.value === null) return outputIndex$1 + 1;
const outputConfiguration = getResolvedNodeOutputs()?.[outputIndex$1];
if (outputConfiguration && (0, import_isObject.default)(outputConfiguration)) return outputConfiguration?.displayName;
if (!nodeType.value?.outputNames || nodeType.value.outputNames.length <= outputIndex$1) return outputIndex$1 + 1;
return nodeType.value.outputNames[outputIndex$1];
}
function refreshDataSize() {
showData.value = false;
const jsonItems = inputDataPage.value.map(item => item.json);
dataSize.value = new Blob([JSON.stringify(jsonItems)]).size;
updateShowData();
}
function updateShowData() {
showData.value = isSchemaView.value && dataSize.value < 4194304 || dataSize.value < 1048576;
}
function onRunIndexChange(run) {
emit("runChange", run);
}
function enableNode() {
if (node.value) {
const updateInformation = {
name: node.value.name,
properties: {
disabled: !node.value.disabled
}
};
workflowState.updateNodeProperties(updateInformation);
}
}
const shouldDisplayHtml = computed(() => node.value?.type === "n8n-nodes-base.html" && node.value.parameters.operation === "generateHtmlTemplate");
function setDisplayMode() {
if (shouldDisplayHtml.value) emit("displayModeChange", "html");
}
function activatePane() {
emit("activatePane");
}
function onSearchClear() {
search$1.value = "";
document.dispatchEvent(new KeyboardEvent("keyup", {
key: "/"
}));
}
function executeNode(nodeName) {
runWorkflow({
destinationNode: {
nodeName,
mode: "inclusive"
},
source: "schema-preview"
});
}
__expose({
enterEditMode
});
return (_ctx, _cache) => {
const _directive_n8n_html = resolveDirective("n8n-html");
return openBlock(), createElementBlock("div", {
class: normalizeClass(["run-data", _ctx.$style.container, {
[_ctx.$style["ndv-v2"]]: isNDVV2.value,
[_ctx.$style.compact]: _ctx.compact,
[_ctx.$style.showActionsOnHover]: _ctx.showActionsOnHover && !search$1.value
}]),
onMouseover: activatePane
}, [!isPaneTypeInput.value && unref(pinnedData).hasData.value && !editMode$1.value.enabled && !_ctx.isProductionExecutionPreview ? (openBlock(), createBlock(unref(N8nCallout_default), {
key: 0,
theme: "secondary",
icon: "pin",
class: normalizeClass(_ctx.$style.pinnedDataCallout),
"data-test-id": "ndv-pinned-data-callout"
}, {
trailingContent: withCtx(() => [createVNode(unref(N8nLink_default), {
to: unref(DATA_PINNING_DOCS_URL),
size: "small",
theme: "secondary",
bold: "",
underline: "",
onClick: onClickDataPinningDocsLink
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.pindata.learnMore")), 1)]),
_: 1
}, 8, ["to"])]),
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.pindata.thisDataIsPinned")) + " ", 1), !isReadOnlyRoute.value && !isArchivedWorkflow.value && !readOnlyEnv.value ? (openBlock(), createElementBlock("span", _hoisted_1, [createVNode(unref(N8nLink_default), {
theme: "secondary",
size: "small",
underline: "",
bold: "",
"data-test-id": "ndv-unpin-data",
onClick: _cache[0] || (_cache[0] = withModifiers($event => onTogglePinData({
source: "banner-link"
}), ["stop"]))
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.pindata.unpin")), 1)]),
_: 1
})])) : createCommentVNode("", true)]),
_: 1
}, 8, ["class"])) : createCommentVNode("", true), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.header)
}, [createBaseVNode("div", {
class: normalizeClass(_ctx.$style.title)
}, [renderSlot(_ctx.$slots, "header", {}, void 0, true)], 2), withDirectives(createBaseVNode("div", {
class: normalizeClass(_ctx.$style.displayModes),
"data-test-id": "run-data-pane-header",
onClick: _cache[5] || (_cache[5] = withModifiers(() => {}, ["stop"]))
}, [(openBlock(), createBlock(Suspense, null, {
default: withCtx(() => [showIOSearch.value ? (openBlock(), createBlock(unref(LazyRunDataSearch), {
key: 0,
modelValue: search$1.value,
"onUpdate:modelValue": _cache[1] || (_cache[1] = $event => search$1.value = $event),
class: normalizeClass(_ctx.$style.search),
"pane-type": _ctx.paneType,
"display-mode": _ctx.displayMode,
shortcut: _ctx.searchShortcut,
onFocus: activatePane
}, null, 8, ["modelValue", "class", "pane-type", "display-mode", "shortcut"])) : createCommentVNode("", true)]),
_: 1
})), _ctx.displayMode === "table" && _ctx.collapsingTableColumnName !== null ? (openBlock(), createBlock(unref(N8nIconButton_default), {
key: 0,
class: normalizeClass(_ctx.$style.resetCollapseButton),
text: "",
icon: "chevrons-up-down",
size: "xmini",
type: "tertiary",
onClick: _cache[2] || (_cache[2] = $event => emit("collapsingTableColumnChanged", null))
}, null, 8, ["class"])) : createCommentVNode("", true), !_ctx.disableDisplayModeSelection ? withDirectives((openBlock(), createBlock(RunDataDisplayModeSelect_default, {
key: 1,
compact: props.compact,
value: _ctx.displayMode,
"has-binary-data": binaryData.value.length > 0,
"pane-type": _ctx.paneType,
"node-generates-html": shouldDisplayHtml.value,
"has-renderable-data": hasParsedAiContent.value,
onChange: onDisplayModeChange
}, null, 8, ["compact", "value", "has-binary-data", "pane-type", "node-generates-html", "has-renderable-data"])), [[vShow, shouldShowDisplayModeSelect.value]]) : createCommentVNode("", true), !props.disableEdit && canPinData.value && !isReadOnlyRoute.value && !readOnlyEnv.value ? withDirectives((openBlock(), createBlock(unref(N8nIconButton_default), {
key: 2,
title: unref(i18n$1).baseText("runData.editOutput"),
circle: false,
disabled: node.value?.disabled,
icon: "pencil",
type: "tertiary",
"data-test-id": "ndv-edit-pinned-data",
onClick: _cache[3] || (_cache[3] = $event => enterEditMode({
origin: "editIconButton"
}))
}, null, 8, ["title", "disabled"])), [[vShow, !editMode$1.value.enabled]]) : createCommentVNode("", true), showPinButton.value ? (openBlock(), createBlock(RunDataPinButton_default, {
key: 3,
disabled: pinButtonDisabled.value,
"tooltip-contents-visibility": {
binaryDataTooltipContent: !!binaryData.value?.length,
pinDataDiscoveryTooltipContent: isControlledPinDataTooltip.value && pinDataDiscoveryTooltipVisible.value
},
"data-pinning-docs-url": unref(DATA_PINNING_DOCS_URL),
"pinned-data": unref(pinnedData),
onTogglePinData: _cache[4] || (_cache[4] = $event => onTogglePinData({
source: "pin-icon-click"
}))
}, null, 8, ["disabled", "tooltip-contents-visibility", "data-pinning-docs-url", "pinned-data"])) : createCommentVNode("", true), !props.disableEdit ? withDirectives((openBlock(), createElementBlock("div", {
key: 4,
class: normalizeClass(_ctx.$style.editModeActions)
}, [createVNode(unref(N8nButton_default), {
type: "tertiary",
label: unref(i18n$1).baseText("runData.editor.cancel"),
onClick: onClickCancelEdit
}, null, 8, ["label"]), createVNode(unref(N8nButton_default), {
class: "ml-2xs",
type: "primary",
label: unref(i18n$1).baseText("runData.editor.save"),
onClick: onClickSaveEdit
}, null, 8, ["label"])], 2)), [[vShow, editMode$1.value.enabled]]) : createCommentVNode("", true)], 2), [[vShow, !hasRunError.value && !isTrimmedManualExecutionDataItem.value]]), renderSlot(_ctx.$slots, "header-end", normalizeProps(guardReactiveProps(itemsCountProps.value)), void 0, true)], 2), withDirectives(createBaseVNode("div", null, [inputSelectLocation.value === "header" ? (openBlock(), createElementBlock("div", {
key: 0,
class: normalizeClass(_ctx.$style.inputSelect)
}, [renderSlot(_ctx.$slots, "input-select", {}, void 0, true)], 2)) : createCommentVNode("", true), maxRunIndex.value > 0 && !displaysMultipleNodes.value && !props.disableRunIndexSelection ? withDirectives((openBlock(), createElementBlock("div", {
key: 1,
class: normalizeClass(_ctx.$style.runSelector)
}, [createBaseVNode("div", {
class: normalizeClass(_ctx.$style.runSelectorInner)
}, [inputSelectLocation.value === "runs" ? renderSlot(_ctx.$slots, "input-select", {
key: 0
}, void 0, true) : createCommentVNode("", true), createVNode(unref(N8nSelect_default), {
"model-value": _ctx.runIndex,
class: normalizeClass(_ctx.$style.runSelectorSelect),
size: "small",
teleported: "",
"data-test-id": "run-selector",
"onUpdate:modelValue": onRunIndexChange,
onClick: _cache[6] || (_cache[6] = withModifiers(() => {}, ["stop"]))
}, {
prepend: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("ndv.output.run")), 1)]),
default: withCtx(() => [(openBlock(true), createElementBlock(Fragment, null, renderList(runSelectorOptionsCount.value, option => {
return openBlock(), createBlock(unref(N8nOption_default), {
key: option,
label: getRunLabel(option),
value: option - 1,
"data-test-id": "run-selection-option"
}, null, 8, ["label", "value"]);
}), 128))]),
_: 1
}, 8, ["model-value", "class"]), _ctx.canLinkRuns ? (openBlock(), createBlock(unref(N8nTooltip_default), {
key: 1,
placement: "right"
}, {
content: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText(_ctx.linkedRuns ? "runData.unlinking.hint" : "runData.linking.hint")), 1)]),
default: withCtx(() => [createVNode(unref(N8nIconButton_default), {
icon: _ctx.linkedRuns ? "unlink" : "link",
class: normalizeClass(["linkRun", _ctx.linkedRuns ? "linked" : ""]),
text: "",
type: "tertiary",
size: "small",
"data-test-id": "link-run",
onClick: toggleLinkRuns
}, null, 8, ["icon", "class"])]),
_: 1
})) : createCommentVNode("", true), renderSlot(_ctx.$slots, "run-info", {}, void 0, true)], 2), activeTaskMetadata.value && !(_ctx.paneType === "input" && hasInputOverwrite.value) ? (openBlock(), createBlock(ViewSubExecution_default, {
key: 0,
"task-metadata": activeTaskMetadata.value,
"display-mode": _ctx.displayMode
}, null, 8, ["task-metadata", "display-mode"])) : createCommentVNode("", true)], 2)), [[vShow, !editMode$1.value.enabled]]) : createCommentVNode("", true), !displaysMultipleNodes.value ? renderSlot(_ctx.$slots, "before-data", {
key: 2
}, void 0, true) : createCommentVNode("", true), props.calloutMessage || _ctx.$slots["callout-message"] ? (openBlock(), createElementBlock("div", {
key: 3,
class: normalizeClass(_ctx.$style.hintCallout)
}, [createVNode(unref(N8nCallout_default), {
theme: "info",
"data-test-id": "run-data-callout"
}, {
default: withCtx(() => [renderSlot(_ctx.$slots, "callout-message", {}, () => [withDirectives(createVNode(unref(N8nText_default), {
size: "small"
}, null, 512), [[_directive_n8n_html, props.calloutMessage]])], true)]),
_: 3
})], 2)) : createCommentVNode("", true), !props.disableSettingsHint && props.paneType === "output" ? (openBlock(), createBlock(NodeSettingsHint_default, {
key: 4,
node: node.value
}, null, 8, ["node"])) : createCommentVNode("", true), (openBlock(true), createElementBlock(Fragment, null, renderList(nodeHints.value, hint => {
return openBlock(), createBlock(unref(N8nCallout_default), {
key: hint.message,
class: normalizeClass(_ctx.$style.hintCallout),
theme: hint.type || "info",
"data-test-id": "node-hint"
}, {
default: withCtx(() => [withDirectives(createVNode(unref(N8nText_default), {
size: "small"
}, null, 512), [[_directive_n8n_html, hint.message]])]),
_: 2
}, 1032, ["class", "theme"]);
}), 128)), showBranchSwitch.value ? (openBlock(), createElementBlock("div", {
key: 5,
class: normalizeClass(_ctx.$style.outputs),
"data-test-id": "branches"
}, [inputSelectLocation.value === "outputs" ? renderSlot(_ctx.$slots, "input-select", {
key: 0
}, void 0, true) : createCommentVNode("", true), activeTaskMetadata.value && !(_ctx.paneType === "input" && hasInputOverwrite.value) ? (openBlock(), createBlock(ViewSubExecution_default, {
key: 1,
"task-metadata": activeTaskMetadata.value,
"display-mode": _ctx.displayMode
}, null, 8, ["task-metadata", "display-mode"])) : createCommentVNode("", true), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.tabs)
}, [createVNode(unref(N8nTabs_default), {
size: "small",
"model-value": currentOutputIndex.value,
options: branches.value,
"onUpdate:modelValue": onBranchChange
}, null, 8, ["model-value", "options"])], 2)], 2)) : !props.compact && hasNodeRun.value && !isSearchInSchemaView.value && (dataCount.value > 0 && maxRunIndex.value === 0 || search$1.value) && !isArtificialRecoveredEventItem.value && !displaysMultipleNodes.value ? withDirectives((openBlock(), createElementBlock("div", {
key: 6,
class: normalizeClass(_ctx.$style.itemsCount),
"data-test-id": "ndv-items-count"
}, [inputSelectLocation.value === "items" ? renderSlot(_ctx.$slots, "input-select", {
key: 0
}, void 0, true) : createCommentVNode("", true), createVNode(RunDataItemCount_default, normalizeProps(guardReactiveProps(itemsCountProps.value)), null, 16), activeTaskMetadata.value && !(_ctx.paneType === "input" && hasInputOverwrite.value) ? (openBlock(), createBlock(ViewSubExecution_default, {
key: 1,
"task-metadata": activeTaskMetadata.value,
"display-mode": _ctx.displayMode
}, null, 8, ["task-metadata", "display-mode"])) : createCommentVNode("", true)], 2)), [[vShow, !editMode$1.value.enabled]]) : createCommentVNode("", true)], 512), [[vShow, !binaryDataDisplayVisible.value]]), createBaseVNode("div", {
ref_key: "dataContainerRef",
ref: dataContainerRef,
class: normalizeClass(_ctx.$style.dataContainer),
"data-test-id": "ndv-data-container",
onWheelCapture: _cache[11] || (_cache[11] = $event => emit("captureWheelDataContainer", $event))
}, [binaryDataDisplayData.value ? (openBlock(), createBlock(BinaryDataDisplay_default, {
key: 0,
"window-visible": binaryDataDisplayVisible.value,
"display-data": binaryDataDisplayData.value,
onClose: closeBinaryDataDisplay
}, null, 8, ["window-visible", "display-data"])) : createCommentVNode("", true), _ctx.isExecuting && !isWaitNodeWaiting.value ? (openBlock(), createElementBlock("div", {
key: 1,
class: normalizeClass([_ctx.$style.center, _ctx.$style.executingMessage]),
"data-test-id": "ndv-executing"
}, [!props.compact ? (openBlock(), createElementBlock("div", {
key: 0,
class: normalizeClass(_ctx.$style.spinner)
}, [createVNode(unref(N8nSpinner_default), {
type: "ring"
})], 2)) : createCommentVNode("", true), createVNode(unref(N8nText_default), null, {
default: withCtx(() => [createTextVNode(toDisplayString(_ctx.executingMessage), 1)]),
_: 1
})], 2)) : isTrimmedManualExecutionDataItem.value ? (openBlock(), createElementBlock("div", {
key: 2,
class: normalizeClass([_ctx.$style.center, _ctx.$style.executingMessage])
}, [!props.compact ? (openBlock(), createElementBlock("div", {
key: 0,
class: normalizeClass(_ctx.$style.spinner)
}, [createVNode(unref(N8nSpinner_default), {
type: "ring"
})], 2)) : createCommentVNode("", true), createVNode(unref(N8nText_default), null, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.trimmedData.loading")), 1)]),
_: 1
})], 2)) : editMode$1.value.enabled ? (openBlock(), createElementBlock("div", {
key: 3,
class: normalizeClass(_ctx.$style.editMode)
}, [previousExecutionDataUsedInEditMode.value ? (openBlock(), createBlock(unref(N8nText_default), {
key: 0,
class: "mb-2xs",
size: "small"
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.pinData.insertedExecutionData")), 1)]),
_: 1
})) : createCommentVNode("", true), createBaseVNode("div", {
class: normalizeClass([_ctx.$style.editModeBody, "ignore-key-press-canvas"])
}, [createVNode(JsonEditor_default, {
"model-value": editMode$1.value.value,
"fill-parent": true,
"onUpdate:modelValue": _cache[7] || (_cache[7] = $event => unref(ndvStore).setOutputPanelEditModeValue($event))
}, null, 8, ["model-value"])], 2), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.editModeFooter)
}, [createVNode(unref(N8nInfoTip_default), {
bold: false,
class: normalizeClass(_ctx.$style.editModeFooterInfotip)
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.editor.copyDataInfo")) + " ", 1), createVNode(unref(N8nLink_default), {
to: unref(DATA_EDITING_DOCS_URL),
size: "small"
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("generic.learnMore")), 1)]),
_: 1
}, 8, ["to"])]),
_: 1
}, 8, ["class"])], 2)], 2)) : isPaneTypeOutput.value && hasSubworkflowExecutionError.value && subworkflowExecutionError.value ? (openBlock(), createElementBlock("div", {
key: 4,
class: normalizeClass(_ctx.$style.stretchVertically)
}, [createVNode(NodeErrorView_default, {
compact: _ctx.compact,
error: subworkflowExecutionError.value,
class: normalizeClass(_ctx.$style.errorDisplay),
"show-details": ""
}, null, 8, ["compact", "error", "class"])], 2)) : isWaitNodeWaiting.value ? (openBlock(), createElementBlock("div", {
key: 5,
class: normalizeClass(_ctx.$style.center)
}, [renderSlot(_ctx.$slots, "node-waiting", {}, () => [_cache[12] || (_cache[12] = createTextVNode("xxx"))], true)], 2)) : shouldShowNodeNotRunState.value ? (openBlock(), createElementBlock("div", {
key: 6,
class: normalizeClass(_ctx.$style.center)
}, [renderSlot(_ctx.$slots, "node-not-run", {}, void 0, true)], 2)) : shouldShowDisabledNodeHint.value && node.value ? (openBlock(), createElementBlock("div", {
key: 7,
class: normalizeClass(_ctx.$style.center)
}, [createVNode(unref(N8nText_default), null, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("ndv.input.disabled", {
interpolate: {
nodeName: node.value.name
}
})) + " ", 1), createVNode(unref(N8nLink_default), {
onClick: enableNode
}, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("ndv.input.disabled.cta")), 1)]),
_: 1
})]),
_: 1
})], 2)) : hasNodeRun.value && isArtificialRecoveredEventItem.value ? (openBlock(), createElementBlock("div", {
key: 8,
class: normalizeClass(_ctx.$style.center)
}, [renderSlot(_ctx.$slots, "recovered-artificial-output-data", {}, void 0, true)], 2)) : hasNodeRun.value && hasRunError.value ? (openBlock(), createElementBlock("div", {
key: 9,
class: normalizeClass(_ctx.$style.stretchVertically)
}, [isPaneTypeInput.value ? (openBlock(), createBlock(NDVEmptyState_default, {
key: 0,
class: normalizeClass(_ctx.$style.center),
title: unref(i18n$1).baseText("nodeErrorView.inputPanel.previousNodeError.title", {
interpolate: {
nodeName: node.value?.name ?? ""
}
})
}, null, 8, ["class", "title"])) : _ctx.$slots["content"] ? (openBlock(), createElementBlock("div", _hoisted_2, [workflowRunErrorAsNodeError.value ? (openBlock(), createBlock(NodeErrorView_default, {
key: 0,
error: workflowRunErrorAsNodeError.value,
class: normalizeClass(_ctx.$style.inlineError),
compact: _ctx.compact
}, null, 8, ["error", "class", "compact"])) : createCommentVNode("", true), renderSlot(_ctx.$slots, "content", {}, void 0, true)])) : workflowRunErrorAsNodeError.value ? (openBlock(), createBlock(NodeErrorView_default, {
key: 2,
error: workflowRunErrorAsNodeError.value,
class: normalizeClass(_ctx.$style.dataDisplay),
compact: _ctx.compact,
"show-details": ""
}, null, 8, ["error", "class", "compact"])) : createCommentVNode("", true)], 2)) : shouldShowNoDataInBranch.value ? (openBlock(), createElementBlock("div", {
key: 10,
class: normalizeClass(_ctx.$style.center)
}, [search$1.value ? (openBlock(), createBlock(NDVEmptyState_default, {
key: 0,
title: unref(i18n$1).baseText("ndv.search.noMatch.title")
}, {
default: withCtx(() => [createVNode(unref(I18nT), {
keypath: "ndv.search.noMatch.description",
tag: "span",
scope: "global"
}, {
link: withCtx(() => [createBaseVNode("a", {
href: "#",
onClick: withModifiers(onSearchClear, ["prevent"])
}, toDisplayString(unref(i18n$1).baseText("ndv.search.noMatch.description.link")), 1)]),
_: 1
})]),
_: 1
}, 8, ["title"])) : (openBlock(), createBlock(unref(N8nText_default), {
key: 1
}, {
default: withCtx(() => [createTextVNode(toDisplayString(_ctx.noDataInBranchMessage), 1)]),
_: 1
}))], 2)) : shouldShowNoOutputData.value ? (openBlock(), createElementBlock("div", {
key: 11,
class: normalizeClass(_ctx.$style.center)
}, [renderSlot(_ctx.$slots, "no-output-data", {}, void 0, true)], 2)) : hasNodeRun.value && !showData.value ? (openBlock(), createElementBlock("div", {
key: 12,
"data-test-id": "ndv-data-size-warning",
class: normalizeClass(_ctx.$style.center)
}, [createBaseVNode("div", {
class: normalizeClass(_ctx.$style.dataSizeWarning)
}, [createVNode(NDVEmptyState_default, {
title: unref(i18n$1).baseText("ndv.tooMuchData.title", {
interpolate: {
size: dataSizeInMB.value
}
})
}, {
default: withCtx(() => [withDirectives(createBaseVNode("span", null, null, 512), [[_directive_n8n_html, unref(i18n$1).baseText("ndv.tooMuchData.message")]])]),
_: 1
}, 8, ["title"]), createBaseVNode("div", {
class: normalizeClass(_ctx.$style.warningActions)
}, [createVNode(unref(N8nButton_default), {
outline: "",
size: "small",
label: unref(i18n$1).baseText("runData.downloadBinaryData"),
onClick: _cache[8] || (_cache[8] = $event => downloadJsonData())
}, null, 8, ["label"]), createVNode(unref(N8nButton_default), {
size: "small",
label: unref(i18n$1).baseText("ndv.tooMuchData.showDataAnyway"),
onClick: showTooMuchData
}, null, 8, ["label"])], 2)], 2)], 2)) : hasNodeRun.value && _ctx.$slots["content"] ? renderSlot(_ctx.$slots, "content", {
key: 13
}, void 0, true) : shouldShowBinaryOnlyHint.value ? (openBlock(), createElementBlock("div", {
key: 14,
class: normalizeClass(_ctx.$style.center)
}, [createVNode(unref(N8nText_default), null, {
default: withCtx(() => [createTextVNode(toDisplayString(unref(i18n$1).baseText("runData.switchToBinary.info")) + " ", 1), createBaseVNode("a", {
onClick: switchToBinary
}, toDisplayString(unref(i18n$1).baseText("runData.switchToBinary.binary")), 1)]),
_: 1
})], 2)) : showIoSearchNoMatchContent.value ? (openBlock(), createBlock(NDVEmptyState_default, {
key: 15,
class: normalizeClass(_ctx.$style.center),
title: unref(i18n$1).baseText("ndv.search.noMatch.title")
}, {
default: withCtx(() => [createVNode(unref(I18nT), {
keypath: "ndv.search.noMatch.description",
tag: "span",
scope: "global"
}, {
link: withCtx(() => [createBaseVNode("a", {
href: "#",
onClick: onSearchClear
}, toDisplayString(unref(i18n$1).baseText("ndv.search.noMatch.description.link")), 1)]),
_: 1
})]),
_: 1
}, 8, ["class", "title"])) : hasNodeRun.value && _ctx.displayMode === "table" && node.value ? (openBlock(), createBlock(Suspense, {
key: 16
}, {
default: withCtx(() => [createVNode(unref(LazyRunDataTable), {
node: node.value,
"input-data": inputDataPage.value,
"mapping-enabled": _ctx.mappingEnabled,
"distance-from-active": _ctx.distanceFromActive,
"run-index": _ctx.runIndex,
"page-offset": currentPageOffset.value,
"total-runs": maxRunIndex.value,
"has-default-hover-state": _ctx.paneType === "input" && !search$1.value,
search: search$1.value,
"header-bg-color": _ctx.tableHeaderBgColor,
compact: props.compact,
"disable-hover-highlight": props.disableHoverHighlight,
"collapsing-column-name": _ctx.collapsingTableColumnName,
onMounted: _cache[9] || (_cache[9] = $event => emit("tableMounted", $event)),
onActiveRowChanged: onItemHover,
onDisplayModeChange,
onCollapsingColumnChanged: _cache[10] || (_cache[10] = $event => emit("collapsingTableColumnChanged", $event))
}, null, 8, ["node", "input-data", "mapping-enabled", "distance-from-active", "run-index", "page-offset", "total-runs", "has-default-hover-state", "search", "header-bg-color", "compact", "disable-hover-highlight", "collapsing-column-name"])]),
_: 1
})) : hasNodeRun.value && _ctx.displayMode === "json" && node.value ? (openBlock(), createBlock(Suspense, {
key: 17
}, {
default: withCtx(() => [createVNode(unref(LazyRunDataJson), {
"pane-type": _ctx.paneType,
"edit-mode": editMode$1.value,
"push-ref": _ctx.pushRef,
node: node.value,
"input-data": inputDataPage.value,
"mapping-enabled": _ctx.mappingEnabled,
"distance-from-active": _ctx.distanceFromActive,
"run-index": _ctx.runIndex,
"output-index": currentOutputIndex.value,
"total-runs": maxRunIndex.value,
search: search$1.value,
compact: props.compact
}, null, 8, ["pane-type", "edit-mode", "push-ref", "node", "input-data", "mapping-enabled", "distance-from-active", "run-index", "output-index", "total-runs", "search", "compact"])]),
_: 1
})) : hasNodeRun.value && isPaneTypeOutput.value && _ctx.displayMode === "html" ? (openBlock(), createBlock(Suspense, {
key: 18
}, {
default: withCtx(() => [createVNode(unref(LazyRunDataHtml), {
"input-html": inputHtml.value
}, null, 8, ["input-html"])]),
_: 1
})) : hasNodeRun.value && _ctx.displayMode === "ai" ? (openBlock(), createBlock(Suspense, {
key: 19
}, {
default: withCtx(() => [createVNode(unref(LazyRunDataAi), {
"render-type": "rendered",
compact: _ctx.compact,
content: parsedAiContent.value,
search: search$1.value
}, null, 8, ["compact", "content", "search"])]),
_: 1
})) : shouldShowSchemaView.value ? (openBlock(), createBlock(Suspense, {
key: 20
}, {
default: withCtx(() => [createVNode(unref(LazyRunDataSchema), {
nodes: _ctx.nodes,
"mapping-enabled": _ctx.mappingEnabled,
node: node.value,
data: jsonData.value,
"pane-type": _ctx.paneType,
"connection-type": connectionType.value,
"output-index": currentOutputIndex.value,
search: search$1.value,
class: normalizeClass(_ctx.$style.schema),
compact: props.compact,
"truncate-limit": props.truncateLimit,
"preview-execution": unref(workflowsStore).lastSuccessfulExecution,
"onClear:search": onSearchClear,
onExecute: executeNode
}, null, 8, ["nodes", "mapping-enabled", "node", "data", "pane-type", "connection-type", "output-index", "search", "class", "compact", "truncate-limit", "preview-execution"])]),
_: 1
})) : _ctx.displayMode === "binary" ? (openBlock(), createBlock(RunDataBinary_default, {
key: 21,
"binary-data": binaryData.value,
onPreview: displayBinaryData
}, null, 8, ["binary-data"])) : !hasNodeRun.value ? (openBlock(), createElementBlock("div", {
key: 22,
class: normalizeClass(_ctx.$style.center)
}, [renderSlot(_ctx.$slots, "node-not-run", {}, void 0, true)], 2)) : createCommentVNode("", true)], 34), _ctx.hidePagination === false && hasNodeRun.value && !hasRunError.value && _ctx.displayMode !== "binary" && dataCount.value > pageSize.value && !isSchemaView.value && !isArtificialRecoveredEventItem.value ? withDirectives((openBlock(), createBlock(RunDataPaginationBar_default, {
key: 1,
"current-page": currentPage.value,
"page-size": pageSize.value,
total: dataCount.value,
"onUpdate:currentPage": onCurrentPageChange,
"onUpdate:pageSize": onPageSizeChange
}, null, 8, ["current-page", "page-size", "total"])), [[vShow, !editMode$1.value.enabled]]) : createCommentVNode("", true), createVNode(unref(N8nBlockUi_default), {
show: _ctx.blockUI,
class: normalizeClass({
[_ctx.$style.uiBlocker]: true,
[_ctx.$style.uiBlockerNdvV2]: isNDVV2.value
})
}, null, 8, ["show", "class"])], 34);
};
}
}); //#endregion
//#region src/features/ndv/runData/components/RunData.vue?vue&type=style&index=0&lang.module.scss
infoIcon = "_infoIcon_1ykz7_123";
center = "_center_1ykz7_127";
container = "_container_1ykz7_141";
pinnedDataCallout = "_pinnedDataCallout_1ykz7_150";
header = "_header_1ykz7_159";
compact = "_compact_1ykz7_171";
dataContainer = "_dataContainer_1ykz7_184";
dataDisplay = "_dataDisplay_1ykz7_190";
inlineError = "_inlineError_1ykz7_205";
outputs = "_outputs_1ykz7_212";
tabs = "_tabs_1ykz7_227";
itemsCount = "_itemsCount_1ykz7_235";
inputSelect = "_inputSelect_1ykz7_249";
runSelector = "_runSelector_1ykz7_255";
runSelectorInner = "_runSelectorInner_1ykz7_268";
runSelectorSelect = "_runSelectorSelect_1ykz7_274";
search = "_search_1ykz7_278";
displayModes = "_displayModes_1ykz7_282";
showActionsOnHover = "_showActionsOnHover_1ykz7_293";
tooltipContain = "_tooltipContain_1ykz7_304";
spinner = "_spinner_1ykz7_308";
editMode = "_editMode_1ykz7_319";
editModeBody = "_editModeBody_1ykz7_328";
editModeFooter = "_editModeFooter_1ykz7_335";
editModeFooterInfotip = "_editModeFooterInfotip_1ykz7_345";
editModeActions = "_editModeActions_1ykz7_351";
stretchVertically = "_stretchVertically_1ykz7_358";
uiBlocker = "_uiBlocker_1ykz7_362";
uiBlockerNdvV2 = "_uiBlockerNdvV2_1ykz7_367";
hintCallout = "_hintCallout_1ykz7_371";
schema = "_schema_1ykz7_380";
messageSection = "_messageSection_1ykz7_384";
singleIcon = "_singleIcon_1ykz7_390";
multipleIcons = "_multipleIcons_1ykz7_395";
iconStack = "_iconStack_1ykz7_401";
icon = "_icon_1ykz7_401";
executingMessage = "_executingMessage_1ykz7_420";
resetCollapseButton = "_resetCollapseButton_1ykz7_424";
title = "_title_1ykz7_430";
dataSizeWarning = "_dataSizeWarning_1ykz7_440";
warningActions = "_warningActions_1ykz7_449";
RunData_vue_vue_type_style_index_0_lang_module_default = {
infoIcon,
center,
container,
pinnedDataCallout,
header,
compact,
dataContainer,
dataDisplay,
inlineError,
outputs,
tabs,
itemsCount,
"ndv-v2": "_ndv-v2_1ykz7_245",
inputSelect,
runSelector,
runSelectorInner,
runSelectorSelect,
search,
displayModes,
showActionsOnHover,
tooltipContain,
spinner,
editMode,
editModeBody,
editModeFooter,
editModeFooterInfotip,
editModeActions,
stretchVertically,
uiBlocker,
uiBlockerNdvV2,
hintCallout,
schema,
messageSection,
singleIcon,
multipleIcons,
iconStack,
icon,
executingMessage,
resetCollapseButton,
title,
dataSizeWarning,
warningActions
}; //#endregion
//#region src/features/ndv/runData/components/RunData.vue
cssModules = {
"$style": RunData_vue_vue_type_style_index_0_lang_module_default
};
_export("n", RunData_default = /* @__PURE__ */__plugin_vue_export_helper_default(RunData_vue_vue_type_script_setup_true_lang_default, [["__cssModules", cssModules], ["__scopeId", "data-v-fdcfc7f7"]])); //#endregion
//#region ../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isEmpty.js
_export("t", require_isEmpty = /* @__PURE__ */__commonJS({
"../../../node_modules/.pnpm/lodash@4.17.21/node_modules/lodash/isEmpty.js": (exports, module) => {
var baseKeys = require__baseKeys(),
getTag = require__getTag(),
isArguments = require_isArguments(),
isArray = require_isArray(),
isArrayLike = require_isArrayLike(),
isBuffer = require_isBuffer(),
isPrototype = require__isPrototype(),
isTypedArray = require_isTypedArray();
/** `Object#toString` result references. */
var mapTag = "[object Map]",
setTag = "[object Set]";
/** Used to check objects for own properties. */
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Checks if `value` is an empty object, collection, map, or set.
*
* Objects are considered empty if they have no own enumerable string keyed
* properties.
*
* Array-like values such as `arguments` objects, arrays, buffers, strings, or
* jQuery-like collections are considered empty if they have a `length` of `0`.
* Similarly, maps and sets are considered empty if they have a `size` of `0`.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is empty, else `false`.
* @example
*
* _.isEmpty(null);
* // => true
*
* _.isEmpty(true);
* // => true
*
* _.isEmpty(1);
* // => true
*
* _.isEmpty([1, 2, 3]);
* // => false
*
* _.isEmpty({ 'a': 1 });
* // => false
*/
function isEmpty(value) {
if (value == null) return true;
if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) return !value.length;
var tag = getTag(value);
if (tag == mapTag || tag == setTag) return !value.size;
if (isPrototype(value)) return !baseKeys(value).length;
for (var key in value) if (hasOwnProperty.call(value, key)) return false;
return true;
}
module.exports = isEmpty;
}
})); //#endregion
}
};
});
})();