linkedTokenBuilder.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import type { monacoTypes } from '@grafana/ui';
  2. import { LinkedToken } from './LinkedToken';
  3. import { LanguageDefinition } from './register';
  4. import { Monaco, TokenTypes } from './types';
  5. export function linkedTokenBuilder(
  6. monaco: Monaco,
  7. language: LanguageDefinition,
  8. model: monacoTypes.editor.ITextModel,
  9. position: monacoTypes.IPosition,
  10. tokenTypes: TokenTypes
  11. ) {
  12. let current: LinkedToken | null = null;
  13. let previous: LinkedToken | null = null;
  14. const tokensPerLine = monaco.editor.tokenize(model.getValue() ?? '', language.id);
  15. for (let lineIndex = 0; lineIndex < tokensPerLine.length; lineIndex++) {
  16. const tokens = tokensPerLine[lineIndex];
  17. // In case position is first column in new line, add empty whitespace token so that links are not broken
  18. if (!tokens.length && previous) {
  19. const token: monacoTypes.Token = {
  20. offset: 0,
  21. type: tokenTypes.Whitespace,
  22. language: language.id,
  23. _tokenBrand: undefined,
  24. };
  25. tokens.push(token);
  26. }
  27. for (let columnIndex = 0; columnIndex < tokens.length; columnIndex++) {
  28. const token = tokens[columnIndex];
  29. let endColumn =
  30. tokens.length > columnIndex + 1 ? tokens[columnIndex + 1].offset + 1 : model.getLineLength(lineIndex + 1) + 1;
  31. const range: monacoTypes.IRange = {
  32. startLineNumber: lineIndex + 1,
  33. startColumn: token.offset === 0 ? 0 : token.offset + 1,
  34. endLineNumber: lineIndex + 1,
  35. endColumn,
  36. };
  37. const value = model.getValueInRange(range);
  38. const newToken: LinkedToken = new LinkedToken(token.type, value, range, previous, null, tokenTypes);
  39. if (monaco.Range.containsPosition(range, position)) {
  40. current = newToken;
  41. }
  42. if (previous) {
  43. previous.next = newToken;
  44. }
  45. previous = newToken;
  46. }
  47. }
  48. return current;
  49. }