Skip to content
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

Desktop,Mobile: Plugins: Legacy editor API: Fix delayed crash caused by out-of-bounds inputs #11714

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -185,4 +185,29 @@ describe('CodeMirror5Emulation', () => {

expect(lastThis).toBe(codeMirror);
});

it('.markText should support specifying ranges outside the document', () => {
const codeMirror = makeCodeMirrorEmulation('Test...');

const testClassName = 'out-of-range-test-mark';
codeMirror.markText(
// In range
{ line: 0, ch: 4 },
// Out of range
{ line: 0, ch: 1002 },
{ className: testClassName },
);

const dom = codeMirror.editor.dom;
expect(dom.querySelectorAll(`.${testClassName}`)).toHaveLength(1);
});

it('.markText should throw when given non-integer boundaries', () => {
const codeMirror = makeCodeMirrorEmulation('Test...');

expect(() => codeMirror.markText(
{ line: 0, ch: 4.2 },
{ line: 0, ch: 5 },
)).toThrow(/is not an integer/i);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ interface DocumentPositionRange {
to: DocumentPosition;
}

const clampPositionToDoc = (doc: Text, pos: number) => {
return Math.min(Math.max(0, pos), doc.length);
};

const documentPositionFromPos = (doc: Text, pos: number): DocumentPosition => {
const line = doc.lineAt(pos);
return {
Expand All @@ -48,7 +52,12 @@ const documentPositionFromPos = (doc: Text, pos: number): DocumentPosition => {

const posFromDocumentPosition = (doc: Text, pos: DocumentPosition) => {
const line = doc.line(pos.line + 1);
return line.from + pos.ch;
const result = line.from + pos.ch;

if (!Number.isInteger(result)) {
throw new Error(`Document position ${result} (${pos.line}:${pos.ch}) is not an integer`);
}
return result;
};

export default class CodeMirror5Emulation extends BaseCodeMirror5Emulation {
Expand Down Expand Up @@ -420,8 +429,8 @@ export default class CodeMirror5Emulation extends BaseCodeMirror5Emulation {
const doc = this.editor.state.doc;

return this._decorator.markText(
posFromDocumentPosition(doc, from),
posFromDocumentPosition(doc, to),
clampPositionToDoc(doc, posFromDocumentPosition(doc, from)),
clampPositionToDoc(doc, posFromDocumentPosition(doc, to)),
options,
);
}
Expand Down
Loading