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

Implements the go back and forward keyboard shortcuts #2789

Merged
merged 17 commits into from
Sep 25, 2024
Merged
31 changes: 24 additions & 7 deletions assets/js/hooks/cell.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ const Cell = {
if (event.type === "dispatch_queue_evaluation") {
this.handleDispatchQueueEvaluation(event.dispatch);
} else if (event.type === "jump_to_line") {
this.handleJumpToLine(event.line);
if (this.isFocused) {
this.currentEditor().moveCursorToLine(event.line, event.offset || 0);
}
}
},

Expand All @@ -173,12 +175,6 @@ const Cell = {
}
},

handleJumpToLine(line) {
if (this.isFocused) {
this.currentEditor().moveCursorToLine(line);
}
},

handleCellEditorCreated(tag, liveEditor) {
this.liveEditors[tag] = liveEditor;

Expand Down Expand Up @@ -215,6 +211,16 @@ const Cell = {
}, 0);
});

liveEditor.onViewUpdate((viewUpdate) => {
// We defer the check to happen after all focus/click events have
// been processed, in case the state changes as a result
setTimeout(() => {
if (this.isFocused && viewUpdate.selectionSet) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can check if the selection changed:

!update.state.selection.eq(update.startState.selection)

I would make the event more specific liveEditor.onSelectionChange and have that check there.

The only difference is that when the user goes into insert mode in existing cell, the selection doesn't change, so we can call sendCursorHistory on focus separately.

Once we do that, I don't think we need the setTimeout here (since it's only specific to the focus case?). wdyt?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if I understood about the focus change, because it makes the pubsub event to be dispatched twice

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My idea is that in onFocus we do this:

if (!this.isFocused || !this.insertMode) {
  this.currentEditor().blur();
} else {
  this.sendCursorHistory();
}

This way we send the cursor history when the editor is focused and when the cursor changes location within the editor (focusing alone does not change the cursor location).

this.sendCursorHistory();
}
}, 0);
});

if (tag === "primary") {
const source = liveEditor.getSource();

Expand Down Expand Up @@ -370,6 +376,17 @@ const Cell = {
});
});
},

sendCursorHistory() {
const cursor = this.currentEditor().getCurrentCursorPosition();
if (cursor === null) return;

globalPubsub.broadcast("history", {
...cursor,
type: "navigation",
cellId: this.props.cellId,
});
},
};

export default Cell;
39 changes: 36 additions & 3 deletions assets/js/hooks/cell_editor/live_editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ export default class LiveEditor {
*/
onFocus = this._onFocus.event;

/** @private */
_onViewUpdate = new Emitter();

/**
* Registers a callback called whenever the editor updates the view.
*/
onViewUpdate = this._onViewUpdate.event;

constructor(
container,
connection,
Expand Down Expand Up @@ -166,6 +174,21 @@ export default class LiveEditor {
return node.parentElement;
}

/**
* Returns the current main cursor position.
*/
getCurrentCursorPosition() {
if (!this.isMounted()) {
return null;
}

const pos = this.view.state.selection.main.head;
const line = this.view.state.doc.lineAt(pos);
const offset = pos - line.from;

return { line: line.number, offset };
}

/**
* Focuses the editor.
*
Expand All @@ -183,11 +206,12 @@ export default class LiveEditor {
/**
* Updates editor selection such that cursor points to the given line.
*/
moveCursorToLine(lineNumber) {
moveCursorToLine(lineNumber, offset) {
const line = this.view.state.doc.line(lineNumber);
const position = line.from + offset;

this.view.dispatch({
selection: EditorSelection.single(line.from),
selection: EditorSelection.single(position),
});
}

Expand Down Expand Up @@ -308,6 +332,10 @@ export default class LiveEditor {
{ key: "Alt-Enter", run: insertBlankLineAndCloseHints },
];

const selectionChangeListener = EditorView.updateListener.of((viewUpdate) =>
this.handleViewUpdate(viewUpdate),
);

this.view = new EditorView({
parent: this.container,
doc: this.source,
Expand Down Expand Up @@ -369,6 +397,7 @@ export default class LiveEditor {
focus: this.handleEditorFocus.bind(this),
}),
EditorView.clickAddsSelectionRange.of((event) => event.altKey),
selectionChangeListener,
],
});
}
Expand All @@ -389,7 +418,6 @@ export default class LiveEditor {
// We dispatch escape event, but only if it is not consumed by any
// registered handler in the editor, such as closing autocompletion
// or escaping Vim insert mode

if (event.key === "Escape") {
this.container.dispatchEvent(
new CustomEvent("lb:editor_escape", { bubbles: true }),
Expand All @@ -415,6 +443,11 @@ export default class LiveEditor {
return false;
}

/** @private */
handleViewUpdate(viewUpdate) {
this._onViewUpdate.dispatch(viewUpdate);
}

/** @private */
completionSource(context) {
const settings = settingsStore.get();
Expand Down
52 changes: 50 additions & 2 deletions assets/js/hooks/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { leaveChannel } from "./js_view/channel";
import { isDirectlyEditable, isEvaluable } from "../lib/notebook";
import { settingsStore } from "../lib/settings";
import { LiveStore } from "../lib/live_store";
import CursorHistory from "./session/cursor_history";

/**
* A hook managing the whole session.
Expand Down Expand Up @@ -81,6 +82,7 @@ const Session = {
this.viewOptions = null;
this.keyBuffer = new KeyBuffer();
this.lastLocationReportByClientId = {};
this.cursorHistory = new CursorHistory();
this.followedClientId = null;
this.store = LiveStore.create("session");

Expand Down Expand Up @@ -161,6 +163,7 @@ const Session = {
globalPubsub.subscribe("jump_to_editor", ({ line, file }) =>
this.jumpToLine(file, line),
),
globalPubsub.subscribe("history", this.handleHistoryEvent.bind(this)),
];

this.initializeDragAndDrop();
Expand Down Expand Up @@ -304,6 +307,7 @@ const Session = {
}

const cmd = isMacOS() ? event.metaKey : event.ctrlKey;
const ctrl = event.ctrlKey;
const alt = event.altKey;
const shift = event.shiftKey;
const key = event.key;
Expand All @@ -316,7 +320,16 @@ const Session = {
event.target.closest(`[data-el-outputs-container]`)
)
) {
if (cmd && shift && !alt && key === "Enter") {
// On macOS, ctrl+alt+- becomes an em-dash, so we check for the code
if (event.code === "Minus" && ctrl && alt) {
cancelEvent(event);
this.cursorHistoryGoBack();
return;
} else if (key === "=" && ctrl && alt) {
cancelEvent(event);
this.cursorHistoryGoForward();
return;
} else if (cmd && shift && !alt && key === "Enter") {
cancelEvent(event);
this.queueFullCellsEvaluation(true);
return;
Expand Down Expand Up @@ -1227,6 +1240,8 @@ const Session = {
},

handleCellDeleted(cellId, siblingCellId) {
this.cursorHistory.removeAllFromCell(cellId);

if (this.focusedId === cellId) {
if (this.view) {
const visibleSiblingId = this.ensureVisibleFocusableEl(siblingCellId);
Expand Down Expand Up @@ -1324,6 +1339,12 @@ const Session = {
}
},

handleHistoryEvent(event) {
if (event.type === "navigation") {
this.cursorHistory.push(event.cellId, event.line, event.offset);
}
},

repositionJSViews() {
globalPubsub.broadcast("js_views", { type: "reposition" });
},
Expand Down Expand Up @@ -1447,12 +1468,39 @@ const Session = {

jumpToLine(file, line) {
const [_filename, cellId] = file.split("#cell:");

this.setFocusedEl(cellId, { scroll: false });
this.setInsertMode(true);

globalPubsub.broadcast(`cells:${cellId}`, { type: "jump_to_line", line });
},

cursorHistoryGoBack() {
if (this.cursorHistory.canGoBack()) {
const { cellId, line, offset } = this.cursorHistory.goBack();
this.setFocusedEl(cellId, { scroll: false });
this.setInsertMode(true);

globalPubsub.broadcast(`cells:${cellId}`, {
type: "jump_to_line",
line,
offset,
});
}
},

cursorHistoryGoForward() {
if (this.cursorHistory.canGoForward()) {
const { cellId, line, offset } = this.cursorHistory.goForward();
this.setFocusedEl(cellId, { scroll: false });
this.setInsertMode(true);

globalPubsub.broadcast(`cells:${cellId}`, {
type: "jump_to_line",
line,
offset,
});
}
},
};

export default Session;
123 changes: 123 additions & 0 deletions assets/js/hooks/session/cursor_history.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/**
* Allows for recording a sequence of focused cells with the focused line
* and navigate inside this stack.
*/
export default class CursorHistory {
/** @private */
entries = [];

/** @private */
index = -1;

/**
* Adds a new cell to the stack.
*
* If the stack length is greater than the stack limit,
* it will remove the oldest entries.
*/
push(cellId, line, offset) {
const entry = { cellId, line, offset };

if (this.isSameCell(cellId)) {
this.entries[this.index] = entry;
} else {
if (this.entries[this.index + 1] !== undefined) {
this.entries = this.entries.slice(0, this.index + 1);
}

this.entries.push(entry);
this.index++;
}

if (this.entries.length > 20) {
this.entries.shift();
this.index--;
}
}

/**
* Removes all matching cells with given id from the stack.
*/
removeAllFromCell(cellId) {
// We need to make sure the last entry from history
// doesn't belong to the given cell id that we need
// to remove from the entries list.
let currentEntryIndex = this.index;
let currentEntry = this.entries[currentEntryIndex];

while (currentEntry.cellId === cellId) {
currentEntryIndex--;
currentEntry = this.entries[currentEntryIndex];
}

this.entries = this.entries.filter((entry) => entry.cellId !== cellId);
this.index = this.entries.lastIndexOf(currentEntry);
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Checks if the current stack is available to navigate back.
*/
canGoBack() {
return this.canGetFromHistory(-1);
}

/**
* Navigates back in the current stack.
*
* If the navigation succeeds, it will return the entry from current index.
* Otherwise, returns null;
*/
goBack() {
return this.getFromHistory(-1);
}

/**
* Checks if the current stack is available to navigate forward.
*/
canGoForward() {
return this.canGetFromHistory(1);
}

/**
* Navigates forward in the current stack.
*
* If the navigation succeeds, it will return the entry from current index.
* Otherwise, returns null;
*/
goForward() {
return this.getFromHistory(1);
}

/**
* Gets the entry in the current stack.
*
* If the stack have at least one entry, it will return the entry from current index.
* Otherwise, returns null;
*/
getCurrent() {
if (this.entries.length <= 0) return null;
return this.entries[this.index];
}

/** @private **/
getFromHistory(direction) {
if (!this.canGetFromHistory(direction)) return null;

this.index = Math.max(0, this.index + direction);
return this.entries[this.index];
}

/** @private **/
canGetFromHistory(direction) {
if (this.entries.length === 0) return false;

const index = this.index + direction;
return 0 <= index && index < this.entries.length;
}

/** @private **/
isSameCell(cellId) {
const lastEntry = this.entries[this.index];
return lastEntry !== undefined && cellId === lastEntry.cellId;
}
}
Loading
Loading