Skip to content

Autocomplete random variables #4695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ module.exports = defineConfig([
"no-undef": "error",
},
},
{
files: ["packages/bruno-app/**/__mocks__/*.{js,jsx,ts}"],
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
},
rules: {
"no-undef": "error",
},
},
{
files: ["packages/bruno-electron/**/*.{js}"],
ignores: ["**/*.config.js"],
Expand Down
955 changes: 833 additions & 122 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion packages/bruno-app/.babelrc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"presets": ["@babel/preset-env"],
"presets": ["@babel/preset-env", "@babel/preset-react"],
"plugins": [["styled-components", { "ssr": true }]]
}
17 changes: 14 additions & 3 deletions packages/bruno-app/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
module.exports = {
rootDir: '.',
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
},
transformIgnorePatterns: [
"/node_modules/(?!strip-json-comments|nanoid)/",
],
moduleNameMapper: {
'^assets/(.*)$': '<rootDir>/src/assets/$1',
'^components/(.*)$': '<rootDir>/src/components/$1',
Expand All @@ -8,9 +14,14 @@ module.exports = {
'^api/(.*)$': '<rootDir>/src/api/$1',
'^pageComponents/(.*)$': '<rootDir>/src/pageComponents/$1',
'^providers/(.*)$': '<rootDir>/src/providers/$1',
'^utils/(.*)$': '<rootDir>/src/utils/$1'
'^utils/(.*)$': '<rootDir>/src/utils/$1',
'^codemirror$': '<rootDir>/src/components/CodeEditor/__mocks__/codemirror.js',
},
clearMocks: true,
moduleDirectories: ['node_modules', 'src'],
testEnvironment: 'node'
};
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['@testing-library/jest-dom'],
setupFiles: [
'<rootDir>/jest.setup.js',
],
};
11 changes: 11 additions & 0 deletions packages/bruno-app/jest.setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
jest.mock('nanoid', () => {
return {
nanoid: () => {}
};
});

jest.mock('strip-json-comments', () => {
return {
stripJsonComments: (str) => str
};
});
8 changes: 8 additions & 0 deletions packages/bruno-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
},
"dependencies": {
"@babel/preset-env": "^7.26.0",
"@babel/preset-react": "^7.27.1",
"@fontsource/inter": "^5.0.15",
"@prantlf/jsonlint": "^16.0.0",
"@reduxjs/toolkit": "^1.8.0",
"@tabler/icons": "^1.46.0",
"@testing-library/dom": "^10.4.0",
"@tippyjs/react": "^4.2.6",
"@usebruno/common": "0.1.0",
"@usebruno/graphql-docs": "0.1.0",
Expand All @@ -39,6 +41,7 @@
"iconv-lite": "^0.6.3",
"idb": "^7.0.0",
"immer": "^9.0.15",
"jest-environment-jsdom": "^29.7.0",
"jsesc": "^3.0.2",
"jshint": "^2.13.6",
"json5": "^2.2.3",
Expand Down Expand Up @@ -88,13 +91,18 @@
"@rsbuild/plugin-react": "^1.0.7",
"@rsbuild/plugin-sass": "^1.1.0",
"@rsbuild/plugin-styled-components": "1.1.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"autoprefixer": "10.4.20",
"babel-jest": "^29.7.0",
"babel-plugin-react-compiler": "19.0.0-beta-a7bf2bd-20241110",
"cross-env": "^7.0.3",
"css-loader": "7.1.2",
"file-loader": "^6.2.0",
"html-loader": "^3.0.1",
"html-webpack-plugin": "^5.5.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.7.0",
"mini-css-extract-plugin": "^2.4.5",
"postcss": "8.4.47",
"style-loader": "^3.3.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const CodeMirror = jest.fn((node, options) => {
const editor = {
options,
_currentValue: '',
inputReadHandler: null,
getCursor: jest.fn(() => ({ line: 0, ch: editor._currentValue?.length || 0 })),
getRange: jest.fn((from, to) => editor._currentValue?.slice(0, to.ch) || ''),
getValue: jest.fn(() => editor._currentValue),
setValue: jest.fn(function (val) {
editor._currentValue = val;
}),
getLine: jest.fn(() => editor._currentValue || ''),
setOption: jest.fn(),
refresh: jest.fn(),
off: jest.fn(),
showHint: jest.fn(),
on: jest.fn(function (event, handler) {
if (event === 'inputRead') {
this.inputReadHandler = handler;
}
}),
};
return editor;
});

CodeMirror.commands = {
autocomplete: jest.fn()
};

CodeMirror.hint = {};

CodeMirror.registerHelper = jest.fn((type, name, value) => {
if (!CodeMirror[type]) {
CodeMirror[type] = {};
}

CodeMirror[type][name] = value;
});

CodeMirror.fromTextArea = jest.fn();
CodeMirror.defineMode = jest.fn();

module.exports = CodeMirror;
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import React from 'react';
import { render, act } from '@testing-library/react';
import CodeEditor from '../../CodeEditor';
import { ThemeProvider } from 'styled-components';

jest.mock('codemirror');

const MOCK_THEME = {
codemirror: {
bg: "#1e1e1e",
border: "#333",
},
textLink: "#007acc",
};

const setupEditorState = (editor, { value, cursorPosition }) => {
editor._currentValue = value;
editor.getCursor.mockReturnValue({ line: 0, ch: cursorPosition });
editor.getRange.mockImplementation((from, to) => {
if (from.line === 0 && from.ch === 0 && to.line === 0 && to.ch === cursorPosition) {
return value;
}
return editor._currentValue.slice(from.ch, to.ch);
});
};

const setupEditorWithRef = () => {
const ref = React.createRef();
const { rerender } = render(
<ThemeProvider theme={MOCK_THEME}>
<CodeEditor ref={ref} />
</ThemeProvider>
);
return { ref, rerender };
};

describe('CodeEditor Autocomplete', () => {
beforeEach(() => {
jest.clearAllMocks();
});

it('shows hint suggestions when typing {{$f', () => {
// Setup
const { ref } = setupEditorWithRef();

const editorInstance = ref.current;
expect(editorInstance).toBeTruthy();

const editor = editorInstance.editor;
expect(editor).toBeTruthy();

// Configure editor state
setupEditorState(editor, {
value: '{{$r',
cursorPosition: 4
});

// Trigger autocomplete
const inputReadHandler = editor.inputReadHandler;
expect(typeof inputReadHandler).toBe('function');

act(() => {
inputReadHandler(editor, { text: ['a'], origin: '+input' });
});

// Assertions
expect(editor.showHint).toHaveBeenCalled();
const call = editor.showHint.mock.calls[0][0];
expect(typeof call.hint).toBe('function');

const hints = call.hint();
expect(Array.isArray(hints.list)).toBe(true);
expect(hints.list.some((s) => s.startsWith('$'))).toBe(true);
});

it('does not show hints for regular text input', () => {
// Setup
const { ref } = setupEditorWithRef();
const editor = ref.current.editor;

// Configure editor state
setupEditorState(editor, {
value: 'regular text',
cursorPosition: 11
});

// Trigger input
const inputReadHandler = editor.inputReadHandler;

act(() => {
inputReadHandler(editor, { text: ['x'], origin: '+input' });
});

// Assert no hints shown for regular text
expect(editor.showHint).not.toHaveBeenCalled();
});
});
16 changes: 16 additions & 0 deletions packages/bruno-app/src/components/CodeEditor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import React from 'react';
import { isEqual, escapeRegExp } from 'lodash';
import { defineCodeMirrorBrunoVariablesMode } from 'utils/common/codemirror';
import { getMockDataHints } from 'utils/codemirror/mock-data-hints';
import StyledWrapper from './StyledWrapper';
import * as jsonlint from '@prantlf/jsonlint';
import { JSHINT } from 'jshint';
Expand Down Expand Up @@ -87,6 +88,7 @@ if (!SERVER_RENDERED) {
'bru.runner.skipRequest()',
'bru.runner.stopExecution()'
];

CodeMirror.registerHelper('hint', 'brunoJS', (editor, options) => {
const cursor = editor.getCursor();
const currentLine = editor.getLine(cursor.line);
Expand Down Expand Up @@ -114,6 +116,7 @@ if (!SERVER_RENDERED) {
}
return result;
});

CodeMirror.commands.autocomplete = (cm, hint, options) => {
cm.showHint({ hint, ...options });
};
Expand Down Expand Up @@ -280,6 +283,7 @@ export default class CodeEditor extends React.Component {
editor.on('change', this._onEdit);
this.addOverlay();
}

if (this.props.mode == 'javascript') {
editor.on('keyup', function (cm, event) {
const cursor = editor.getCursor();
Expand All @@ -300,6 +304,18 @@ export default class CodeEditor extends React.Component {
}
});
}

editor.on('inputRead', function (cm, event) {
const hints = getMockDataHints(cm);
if (!hints) {
return;
}

cm.showHint({
hint: () => hints,
completeSingle: false,
});
});
}

componentDidUpdate(prevProps) {
Expand Down
17 changes: 16 additions & 1 deletion packages/bruno-app/src/components/SingleLineEditor/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React, { Component } from 'react';
import isEqual from 'lodash/isEqual';
import { getAllVariables } from 'utils/collections';
import { defineCodeMirrorBrunoVariablesMode, MaskedEditor } from 'utils/common/codemirror';
import { getMockDataHints } from 'utils/codemirror/mock-data-hints';
import StyledWrapper from './StyledWrapper';
import { IconEye, IconEyeOff } from '@tabler/icons';

Expand All @@ -26,6 +27,7 @@ class SingleLineEditor extends Component {
maskInput: props.isSecret || false // Always mask the input by default (if it's a secret)
};
}

componentDidMount() {
// Initialize CodeMirror as a single line editor
/** @type {import("codemirror").Editor} */
Expand Down Expand Up @@ -75,6 +77,7 @@ class SingleLineEditor extends Component {
'Shift-Tab': false
}
});

if (this.props.autocomplete) {
this.editor.on('keyup', (cm, event) => {
if (!cm.state.completionActive /*Enables keyboard navigation in autocomplete list*/ && event.key !== 'Enter') {
Expand All @@ -83,6 +86,19 @@ class SingleLineEditor extends Component {
}
});
}

this.editor.on('inputRead', function (cm, event) {
const hints = getMockDataHints(cm);
if (!hints) {
return;
}

cm.showHint({
hint: () => hints,
completeSingle: false,
});
});

this.editor.setValue(String(this.props.value) || '');
this.editor.on('change', this._onEdit);
this.addOverlay(variables);
Expand All @@ -94,7 +110,6 @@ class SingleLineEditor extends Component {
_enableMaskedEditor = (enabled) => {
if (typeof enabled !== 'boolean') return;

console.log('Enabling masked editor: ' + enabled);
if (enabled == true) {
if (!this.maskedEditor) this.maskedEditor = new MaskedEditor(this.editor, '*');
this.maskedEditor.enable();
Expand Down
25 changes: 25 additions & 0 deletions packages/bruno-app/src/utils/codemirror/mock-data-hints.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { mockDataFunctions } from '@usebruno/common';

const MOCK_FUNCTION_SUGGESTIONS = Object.keys(mockDataFunctions).map(key => `$${key}`);

export const getMockDataHints = (cm) => {
const cursor = cm.getCursor();
const currentString = cm.getRange({ line: cursor.line, ch: 0 }, cursor);

const match = currentString.match(/\{\{\$(\w*)$/);
if (!match) return null;

const wordMatch = match[1];
if (!wordMatch) return null;

const suggestions = MOCK_FUNCTION_SUGGESTIONS.filter(name => name.startsWith(`$${wordMatch}`));
if (!suggestions.length) return null;

const startPos = { line: cursor.line, ch: currentString.lastIndexOf('{{$') + 2 }; // +2 accounts for `{{`

return {
list: suggestions,
from: startPos,
to: cm.getCursor(),
};
};
1 change: 1 addition & 0 deletions packages/bruno-common/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { mockDataFunctions } from './utils/faker-functions';
export { default as interpolate } from './interpolate';
1 change: 0 additions & 1 deletion packages/bruno-electron/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
},
"dependencies": {
"@aws-sdk/credential-providers": "3.750.0",
"@faker-js/faker": "^9.5.1",
"@usebruno/common": "0.1.0",
"@usebruno/converters": "^0.1.0",
"@usebruno/js": "0.12.0",
Expand Down
Loading