{"version":3,"file":"variableCompletion.cjs","sources":["../../../../src/components/CodeMirror/variableCompletion.ts"],"sourcesContent":["import { insertCompletionText } from '@codemirror/autocomplete';\nimport { type EditorState } from '@codemirror/state';\n\nimport { type VariableSuggestion } from '@grafana/data';\n\nimport { type CodeMirrorCompletion, type CodeMirrorCompletionContext, type CodeMirrorCompletionResult } from './types';\n\n// The rest of a braced reference the cursor sits inside: the remainder of the\n// name, an optional `:format` suffix, then the closing brace.\nconst BRACED_TAIL_PATTERN = /^[\\w.:]*\\}/;\n\n/** How a suggestion is presented in the completion list. */\nexport interface VariableCompletionDisplay {\n  label: string;\n  detail?: string;\n}\n\nexport interface VariableCompletionOptions {\n  /**\n   * Characters besides `$` that open the popup. They are separators rather than\n   * part of the reference, so they are preserved: the replaced range starts\n   * after them. `['=']` for a URL query string.\n   */\n  separators?: string[];\n  /**\n   * Text inserted when an option is accepted. Defaults to `${value}`. Override\n   * to add a format suffix, for example `${value:queryparam}` inside a URL.\n   */\n  getInsertText?: (suggestion: VariableSuggestion) => string;\n  /**\n   * Label and detail shown in the list. Defaults to the suggestion's own label\n   * with its origin as the detail.\n   */\n  toDisplay?: (suggestion: VariableSuggestion) => VariableCompletionDisplay;\n}\n\ntype CompletionApply = NonNullable<Exclude<CodeMirrorCompletion['apply'], string>>;\n\nfunction escapeForCharClass(char: string): string {\n  return char.replace(/[\\\\\\]^-]/g, '\\\\$&');\n}\n\n/** `$`, or one of the separators, then an optional brace and the name so far. */\nfunction buildTriggerPattern(separators: string[]): RegExp {\n  return new RegExp(`[$${separators.map(escapeForCharClass).join('')}]\\\\{?[\\\\w.]*$`);\n}\n\nfunction referenceEnd(state: EditorState, from: number, to: number): number {\n  // Only a range that already opened a brace may close one. An unbraced `$name`\n  // supplies both braces itself, so a `}` further along the line is not ours.\n  if (!state.sliceDoc(from, to).startsWith('${')) {\n    return to;\n  }\n\n  const line = state.doc.lineAt(to);\n  const tail = state.sliceDoc(to, line.to).match(BRACED_TAIL_PATTERN);\n  return tail ? to + tail[0].length : to;\n}\n\n/**\n * `Completion.apply` for an option that inserts a whole `${...}` reference.\n *\n * The option carries its own closing brace, so a `}` already to the right of the\n * cursor has to be part of the replaced range. Two ways one gets there:\n * - `closeBrackets`, on in CodeMirror's default basic setup, inserts `}` the\n *   moment `{` is typed, leaving the document as `${|}`.\n * - The cursor sits inside a reference that is already complete: `${my|Var}`.\n *\n * Prefer {@link createVariableCompletionSource}. Reach for this directly only\n * when a source has to emit variable options alongside other kinds, where a\n * range on the result would apply to every option.\n */\nexport function applyVariableReference(text: string): CompletionApply {\n  return (view, _completion, from, to) => {\n    view.dispatch(insertCompletionText(view.state, text, from, referenceEnd(view.state, from, to)));\n  };\n}\n\n/**\n * Autocompletion source for Grafana variables, triggered by `$`.\n *\n * Options insert a full `${...}` reference, so the replaced range starts at the\n * `$`. That `${` prefix would defeat CodeMirror's own label matching, so\n * suggestions are filtered here instead and the result sets `filter: false`.\n */\nexport function createVariableCompletionSource(\n  suggestions: VariableSuggestion[],\n  options: VariableCompletionOptions = {}\n): (context: CodeMirrorCompletionContext) => CodeMirrorCompletionResult | null {\n  const {\n    separators = [],\n    getInsertText = (suggestion: VariableSuggestion) => `\\${${suggestion.value}}`,\n    toDisplay = (suggestion: VariableSuggestion) => ({ label: suggestion.label, detail: suggestion.origin }),\n  } = options;\n  const triggerPattern = buildTriggerPattern(separators);\n\n  const toCompletion = (suggestion: VariableSuggestion): CodeMirrorCompletion => ({\n    ...toDisplay(suggestion),\n    info: suggestion.documentation,\n    apply: applyVariableReference(getInsertText(suggestion)),\n    type: 'variable',\n  });\n\n  return (context: CodeMirrorCompletionContext): CodeMirrorCompletionResult | null => {\n    if (suggestions.length === 0) {\n      return null;\n    }\n\n    const word = context.matchBefore(triggerPattern);\n\n    // Outside a reference, only an explicit request (Ctrl+Space) responds, by\n    // inserting a fresh reference at the cursor.\n    if (!word) {\n      return context.explicit ? { from: context.pos, options: suggestions.map(toCompletion), filter: false } : null;\n    }\n\n    // A separator is preserved, so the range starts after it. A `$` is part of\n    // the reference and is replaced, which is what stops an explicit request\n    // after a typed `$` from producing `$${...}`.\n    const from = separators.includes(word.text.charAt(0)) ? word.from + 1 : word.from;\n    const typed = word.text.slice(1).replace(/^\\{/, '').toLowerCase();\n\n    // An explicit request shows every variable; implicit triggering filters by\n    // the name typed so far.\n    const matches =\n      context.explicit || !typed\n        ? suggestions\n        : suggestions.filter((s) => s.value.toLowerCase().includes(typed) || s.label.toLowerCase().includes(typed));\n\n    return { from, options: matches.map(toCompletion), filter: false };\n  };\n}\n"],"names":["insertCompletionText"],"mappings":";;;;;;;AASA,MAAM,mBAAA,GAAsB,YAAA;AA6B5B,SAAS,mBAAmB,IAAA,EAAsB;AAChD,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,WAAA,EAAa,MAAM,CAAA;AACzC;AAGA,SAAS,oBAAoB,UAAA,EAA8B;AACzD,EAAA,OAAO,IAAI,MAAA,CAAO,CAAA,EAAA,EAAK,UAAA,CAAW,GAAA,CAAI,kBAAkB,CAAA,CAAE,IAAA,CAAK,EAAE,CAAC,CAAA,aAAA,CAAe,CAAA;AACnF;AAEA,SAAS,YAAA,CAAa,KAAA,EAAoB,IAAA,EAAc,EAAA,EAAoB;AAG1E,EAAA,IAAI,CAAC,MAAM,QAAA,CAAS,IAAA,EAAM,EAAE,CAAA,CAAE,UAAA,CAAW,IAAI,CAAA,EAAG;AAC9C,IAAA,OAAO,EAAA;AAAA,EACT;AAEA,EAAA,MAAM,IAAA,GAAO,KAAA,CAAM,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA;AAChC,EAAA,MAAM,IAAA,GAAO,MAAM,QAAA,CAAS,EAAA,EAAI,KAAK,EAAE,CAAA,CAAE,MAAM,mBAAmB,CAAA;AAClE,EAAA,OAAO,IAAA,GAAO,EAAA,GAAK,IAAA,CAAK,CAAC,EAAE,MAAA,GAAS,EAAA;AACtC;AAeO,SAAS,uBAAuB,IAAA,EAA+B;AACpE,EAAA,OAAO,CAA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