Skip to content

Commit

Permalink
Make TextArea on_cursor_change include old cursor
Browse files Browse the repository at this point in the history
Also add tests for TextArea `on_cursor_change` callback
  • Loading branch information
wiktor-obrebski committed Nov 17, 2024
1 parent 58c8d9b commit cdda92e
Show file tree
Hide file tree
Showing 4 changed files with 154 additions and 23 deletions.
5 changes: 3 additions & 2 deletions docs/dev/Lua API.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5525,6 +5525,7 @@ Attributes:
* ``init_text``: The initial text content for the text area.

* ``init_cursor``: The initial cursor position within the text content.
If not specified, defaults to end of the text (length of ``init_text``).

* ``text_pen``: Optional pen used to draw the text.

Expand All @@ -5536,8 +5537,8 @@ Attributes:
* ``on_text_change``: Callback function called whenever the text changes.
The function signature should be ``on_text_change(new_text)``.

* ``on_cursor_change``: Callback function called whenever the cursor
position changes. The function signature should be ``on_cursor_change(new_cursor_pos)``.
* ``on_cursor_change``: Callback function called whenever the cursor position changes.
Expected function signature is ``on_cursor_change(new_cursor, old_cursor)``.

* ``one_line_mode``: Boolean attribute that, when set to ``true``,
disables multi-line text features and restricts the text area to a single line.
Expand Down
4 changes: 2 additions & 2 deletions library/lua/gui/widgets/text_area.lua
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ function TextArea:clearHistory()
return self.text_area.history:clear()
end

function TextArea:onCursorChange(cursor)
function TextArea:onCursorChange(cursor, old_cursor)
local x, y = self.text_area.wrapped_text:indexToCoords(
self.text_area.cursor
)
Expand All @@ -95,7 +95,7 @@ function TextArea:onCursorChange(cursor)
end

if self.on_cursor_change then
self.on_cursor_change(cursor)
self.on_cursor_change(cursor, old_cursor)
end
end

Expand Down
6 changes: 4 additions & 2 deletions library/lua/gui/widgets/text_area/text_area_content.lua
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ function TextAreaContent:recomputeLines()
end

function TextAreaContent:setCursor(cursor_offset)
local old_cursor = self.cursor

self.cursor = math.max(
1,
math.min(#self.text + 1, cursor_offset)
Expand All @@ -92,8 +94,8 @@ function TextAreaContent:setCursor(cursor_offset)
self.sel_end = nil
self.last_cursor_x = nil

if self.on_cursor_change then
self.on_cursor_change(self.cursor)
if self.on_cursor_change and self.cursor ~= old_cursor then
self.on_cursor_change(self.cursor, old_cursor)
end
end

Expand Down
Loading

0 comments on commit cdda92e

Please sign in to comment.