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

Fix whole editor paste with locked code #125

Merged
merged 31 commits into from
Dec 12, 2024
Merged
Changes from 6 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
f2e327c
fix: select first editable range when pasting for locked code with de…
KaiSaba Dec 5, 2024
f538ee0
fix: recompute editor operations for locking code using decorations
KaiSaba Dec 6, 2024
04bfcfb
cleanup: remove override of editor paste
KaiSaba Dec 6, 2024
c40f3c1
fix: increment uneditable range index correctly when computing new op…
KaiSaba Dec 6, 2024
7ee4792
refactor: use position in minUsRange instead of lines and columns
KaiSaba Dec 6, 2024
b598071
refactor: split compute of new operations in multiple functions
KaiSaba Dec 6, 2024
8faaeb6
refactor: move range and operations functions in separate files
KaiSaba Dec 9, 2024
c291e16
refactor: split editable ranges and operation text separately
KaiSaba Dec 9, 2024
8412173
fix: allow paste when selected locked code doesn't change
KaiSaba Dec 9, 2024
e47df09
fix: use string indexOf instead of split to split text at the first o…
KaiSaba Dec 9, 2024
f8cea32
refactor: refactor minusRanges function to return all ranges
KaiSaba Dec 11, 2024
f8c1ed4
fix: use minusRanges to get hidden areas and visible ranges in hideCo…
KaiSaba Dec 11, 2024
0c5ae90
fix: fix split operation text function when uneditable range text not…
KaiSaba Dec 11, 2024
cf76aee
fix: fix locked code ranges and text split
KaiSaba Dec 11, 2024
8c76d0f
fix: fix ranges computation
KaiSaba Dec 12, 2024
8ba06e8
fix: fix operation split and operation text split
KaiSaba Dec 12, 2024
acd5928
test: add jest config and tests on locked code
KaiSaba Dec 12, 2024
8ec2433
test: simplify createTestRange function
KaiSaba Dec 12, 2024
0759eb0
refactor: rename computeNewOperationsForLockedCode to tryIgnoreLocked…
KaiSaba Dec 12, 2024
bbf980c
fix: throw custom error when operation is invalid with locked code
KaiSaba Dec 12, 2024
4211c36
refactor: rename functions on locked code and their variables
KaiSaba Dec 12, 2024
59ba25d
cleanup: remove unecessary configs in tsconfig
KaiSaba Dec 12, 2024
896f2d2
refactor: rename minusRange function and return values
KaiSaba Dec 12, 2024
7c5a675
cleanup: remove unneeded console.info
KaiSaba Dec 12, 2024
b749674
fix: removed line bug when pasting code
KaiSaba Dec 12, 2024
b450e74
fix: remove pollution logs in tests
Dec 12, 2024
6308574
refactor: change code so it's easier to test
Dec 12, 2024
cb5a8a4
refactor: extract error handling to facilitate tests
Dec 12, 2024
36c4ef1
lib: install @jest/globals
Dec 12, 2024
28be49e
test: update test by mocking code lock and edit operations
KaiSaba Dec 12, 2024
5cfb9f1
cleanup: remove unecessary constructor for LockedCodeError
KaiSaba Dec 12, 2024
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
212 changes: 162 additions & 50 deletions src/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,6 @@ import * as monaco from 'monaco-editor'
import { DisposableStore } from 'vscode/monaco'
import { IIdentifiedSingleEditOperation, ValidAnnotatedEditOperation } from 'vscode/vscode/vs/editor/common/model'

interface PastePayload {
text: string
pasteOnNewLine: boolean
multicursorText: string[] | null
mode: string | null
}

function isPasteAction (handlerId: string, payload: unknown): payload is PastePayload {
return handlerId === 'paste'
}

function getRangesFromDecorations (
editor: monaco.editor.ICodeEditor,
decorationFilter: (decoration: monaco.editor.IModelDecoration) => boolean
Expand All @@ -28,6 +17,166 @@ function getRangesFromDecorations (
.map((decoration) => decoration.range)
}

function minusRanges (uniqueRange: monaco.Range, ranges: monaco.Range[]): monaco.Range[] {
const newRanges: monaco.Range[] = []
let lastEndPosition = uniqueRange.getStartPosition()

for (const range of ranges) {
const newRange = monaco.Range.fromPositions(lastEndPosition, range.getStartPosition())
lastEndPosition = range.getEndPosition()
newRanges.push(newRange)
}

if (lastEndPosition.isBefore(uniqueRange.getEndPosition())) {
newRanges.push(monaco.Range.fromPositions(lastEndPosition, uniqueRange.getEndPosition()))
}

return newRanges
}

function createNewOperation (
oldOperation: ValidAnnotatedEditOperation,
newRange: monaco.Range,
newText: string,
index: number
): ValidAnnotatedEditOperation {
const identifier = oldOperation.identifier != null
? { major: oldOperation.identifier.major, minor: oldOperation.identifier.minor + index }
: null
return new ValidAnnotatedEditOperation(
identifier,
newRange,
newText,
oldOperation.forceMoveMarkers,
oldOperation.isAutoWhitespaceEdit,
oldOperation._isTracked
)
}

function getLockedRanges (
editor: monaco.editor.ICodeEditor,
decorationFilter: (decoration: monaco.editor.IModelDecoration) => boolean,
withDecoration: boolean
): monaco.Range[] {
const model = editor.getModel()
if (model == null) {
return []
}

const fullModelRange = model.getFullModelRange()
const ranges = getRangesFromDecorations(editor, decorationFilter)
return withDecoration ? ranges : minusRanges(fullModelRange, ranges)
}

function getLockedRangeValueIndexesInText (
editor: monaco.editor.ICodeEditor,
range: monaco.Range,
text: string
): {
startIndex: number | null
endIndex: number | null
} {
const model = editor.getModel()
if (model == null) {
return { startIndex: null, endIndex: null }
}

const editorValue = editor.getValue()
const rangeValue = editorValue.slice(model.getOffsetAt(range.getStartPosition()), model.getOffsetAt(range.getEndPosition()))
const startIndex = text.indexOf(rangeValue)
return {
startIndex,
endIndex: startIndex + rangeValue.length
CGNonofr marked this conversation as resolved.
Show resolved Hide resolved
}
}

function computeNewOperationsWithIntersectingLockedCode (
editor: monaco.editor.ICodeEditor,
operation: ValidAnnotatedEditOperation,
uneditableRanges: monaco.Range[]
): ValidAnnotatedEditOperation[] {
const newOperations: ValidAnnotatedEditOperation[] = []
const editableRanges: monaco.Range[] = minusRanges(operation.range, uneditableRanges)

// Index of the current uneditable range in the text
let uneditableRangeIndex: number = 0
// Index of the current editable range in the text
let editableRangeIndex: number = 0
// The operation text is null or an empty string when it's a delete
let remainingText: string = operation.text ?? ''

do {
const editableRange = editableRanges[editableRangeIndex]
if (editableRange == null) {
// There are no editable ranges left
return newOperations
}

const uneditableRange = uneditableRanges[uneditableRangeIndex]
if (uneditableRange == null) {
// There are no more locked ranges
return [
...newOperations,
createNewOperation(operation, editableRange, remainingText, editableRangeIndex)
]
}

const { startIndex, endIndex } = getLockedRangeValueIndexesInText(editor, uneditableRange, remainingText)
if (startIndex == null || endIndex == null) {
return newOperations
} else if (startIndex === -1) {
// The uneditable text is not in the remaining operation text
return [
...newOperations,
createNewOperation(operation, editableRange, remainingText, editableRangeIndex)
]
// remainingText = null
} else if (startIndex === 0) {
// The uneditable text is at the beginning of the remaining operation text
uneditableRangeIndex++
remainingText = remainingText.slice(endIndex)
} else {
// The uneditable text is in the middle or at the end of the remaining operation text
newOperations.push(
createNewOperation(operation, editableRange, remainingText.slice(0, startIndex), editableRangeIndex)
)
uneditableRangeIndex++
editableRangeIndex++
remainingText = remainingText.slice(endIndex)
}
} while (remainingText.length > 0)

return newOperations
}

function computeNewOperationsForLockedCode (
editor: monaco.editor.ICodeEditor,
decorationFilter: (decoration: monaco.editor.IModelDecoration) => boolean,
editorOperations: ValidAnnotatedEditOperation[],
withDecoration: boolean
): ValidAnnotatedEditOperation[] {
const uneditableRanges = getLockedRanges(editor, decorationFilter, withDecoration)
if (uneditableRanges.length <= 0) {
return editorOperations
}

const newOperations: ValidAnnotatedEditOperation[] = []
for (const operation of editorOperations) {
const operationRange = operation.range
const uneditableRangesThatIntersects = uneditableRanges.filter(range => monaco.Range.areIntersecting(range, operationRange))

if (uneditableRangesThatIntersects.length <= 0) {
// The operation range doesn't intersect with an uneditable range
newOperations.push(operation)
} else {
// The operation range intersects with one or more uneditable range
newOperations.push(...computeNewOperationsWithIntersectingLockedCode(editor, operation, uneditableRangesThatIntersects))
}
}

return newOperations
}
CGNonofr marked this conversation as resolved.
Show resolved Hide resolved

/**
* Exctract ranges between startToken and endToken
*/
Expand Down Expand Up @@ -126,43 +275,6 @@ function lockCodeUsingDecoration (
: ranges.some((editableRange) => editableRange.containsRange(range))
}

const originalTrigger = editor.trigger
editor.trigger = function (source, handlerId, payload) {
// Try to transform whole file pasting into a paste in the editable area only
const ranges = getRangesFromDecorations(editor, decorationFilter)
const lastEditableRange =
ranges.length > 0 ? ranges[ranges.length - 1] : undefined
if (isPasteAction(handlerId, payload) && lastEditableRange != null) {
const selections = editor.getSelections()
const model = editor.getModel()!
if (selections != null && selections.length === 1) {
const selection = selections[0]!
const fullModelRange = model.getFullModelRange()
const wholeFileSelected = fullModelRange.equalsRange(selection)
if (wholeFileSelected) {
const currentEditorValue = editor.getValue()
const before = model.getOffsetAt(lastEditableRange.getStartPosition())
const after =
currentEditorValue.length - model.getOffsetAt(lastEditableRange.getEndPosition())
if (
currentEditorValue.slice(0, before) === payload.text.slice(0, before) &&
currentEditorValue.slice(currentEditorValue.length - after) ===
payload.text.slice(payload.text.length - after)
) {
editor.setSelection(lastEditableRange)
const newPayload: PastePayload = {
...payload,
text: payload.text.slice(before, payload.text.length - after)
}
payload = newPayload
}
}
}
}

return originalTrigger.call(editor, source, handlerId, payload)
}

let currentEditSource: string | null | undefined
const originalExecuteEdit = editor.executeEdits
editor.executeEdits = (source, edits, endCursorState) => {
Expand Down Expand Up @@ -191,7 +303,7 @@ function lockCodeUsingDecoration (

const original = model._validateEditOperations
model._validateEditOperations = function (this: AugmentedITextModel, rawOperations) {
const editorOperations: ValidAnnotatedEditOperation[] = original.call(this, rawOperations)
let editorOperations: ValidAnnotatedEditOperation[] = original.call(this, rawOperations)

if (currentEditSource != null && allowChangeFromSources.includes(currentEditSource)) {
return editorOperations
Expand All @@ -201,6 +313,7 @@ function lockCodeUsingDecoration (
return editorOperations
}

editorOperations = computeNewOperationsForLockedCode(editor, decorationFilter, editorOperations, withDecoration)
if (transactionMode) {
const firstForbiddenOperation = editorOperations.find(operation => !canEditRange(operation.range))
if (firstForbiddenOperation != null) {
Expand Down Expand Up @@ -253,7 +366,6 @@ function lockCodeUsingDecoration (
dispose () {
restoreModel?.()
editor.executeEdits = originalExecuteEdit
editor.trigger = originalTrigger
}
})

Expand Down
Loading