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
30 changes: 23 additions & 7 deletions assets/js/hooks/cell.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,13 @@ 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);
}
} else if (event.type === "jump_to_line_and_column") {
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
if (this.isFocused) {
this.currentEditor().moveCursorToLine(event.line, event.column);
}
}
},

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

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

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

Expand All @@ -198,6 +198,8 @@ const Cell = {
if (this.isFocused && this.insertMode) {
this.currentEditor().focus();
}

this.sendCursorHistory();
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
}, 0);
});

Expand All @@ -211,6 +213,8 @@ const Cell = {
// gives it focus
if (!this.isFocused || !this.insertMode) {
this.currentEditor().blur();
} else if (this.insertMode) {
this.sendCursorHistory();
}
}, 0);
});
Expand Down Expand Up @@ -370,6 +374,18 @@ const Cell = {
});
});
},

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

globalPubsub.broadcast("history", {
type: "navigation",
cellId: this.props.cellId,
line: cursor.line.toString(),
column: cursor.column.toString(),
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
});
},
};

export default Cell;
26 changes: 23 additions & 3 deletions assets/js/hooks/cell_editor/live_editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,25 @@ 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 lineLength = line.to - line.from;
const column = pos - line.from;

if (column < 1 || column > lineLength)
return { line: line.number, column: 1 };

return { line: line.number, column };
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
}

/**
* Focuses the editor.
*
Expand All @@ -183,11 +202,13 @@ export default class LiveEditor {
/**
* Updates editor selection such that cursor points to the given line.
*/
moveCursorToLine(lineNumber) {
moveCursorToLine(lineNumber, column = "1") {
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
const line = this.view.state.doc.line(lineNumber);
const columnNumber = parseInt(column);
const position = line.from + columnNumber;
aleDsz marked this conversation as resolved.
Show resolved Hide resolved

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

Expand Down Expand Up @@ -389,7 +410,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 Down
57 changes: 55 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.goBackNavigationHistory();
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
return;
} else if (key === "=" && ctrl && alt) {
cancelEvent(event);
this.goForwardNavigationHistory();
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(payload) {
if (payload.type === "navigation") {
this.saveNavigationHistory(payload);
}
},

repositionJSViews() {
globalPubsub.broadcast("js_views", { type: "reposition" });
},
Expand Down Expand Up @@ -1447,12 +1468,44 @@ 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 });
},

saveNavigationHistory({ cellId, line, column }) {
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
if (cellId === null || line === null || column === null) return;
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
this.cursorHistory.push(cellId, line, column);
},

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

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

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

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

export default Session;
119 changes: 119 additions & 0 deletions assets/js/hooks/session/cursor_history.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
/**
* Allows for recording a sequence of focused cells with the focused line
* and navigate inside this stack.
*/
export default class CursorHistory {
constructor() {
this.entries = [];
this.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, column) {
const entry = { cellId, line, column };

if (this.isTheSameCell(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--;
}
}

/**
* Immediately clears the stack and reset the current index.
*/
destroy() {
this.entries = [];
this.index = -1;
}

/**
* 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);
}

/** @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 = Math.max(0, this.index + direction);
return this.entries[index] !== undefined;
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
}

/** @private **/
isTheSameCell(cellId) {
aleDsz marked this conversation as resolved.
Show resolved Hide resolved
const lastEntry = this.entries[this.index];
return lastEntry !== undefined && cellId === lastEntry.cellId;
}
}
Loading
Loading