Skip to content

Commit

Permalink
fix: hide cursor when editor not focused
Browse files Browse the repository at this point in the history
  • Loading branch information
Palanikannan1437 committed Nov 28, 2024
1 parent e206224 commit a4aefe4
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 203 deletions.
103 changes: 0 additions & 103 deletions packages/editor/src/core/extensions/smooth-cursor/plugin-better.ts

This file was deleted.

97 changes: 0 additions & 97 deletions packages/editor/src/core/extensions/smooth-cursor/plugin-good.ts

This file was deleted.

28 changes: 25 additions & 3 deletions packages/editor/src/core/extensions/smooth-cursor/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ export const PROSEMIRROR_SMOOTH_CURSOR_CLASS = "prosemirror-smooth-cursor";
export function smoothCursorPlugin(): Plugin {
let smoothCursor: HTMLElement | null = typeof document === "undefined" ? null : document.createElement("div");
let rafId: number | undefined;
let isEditorFocused = false;

function updateCursor(view?: EditorView, cursor?: HTMLElement) {
if (!view || !view.dom || view.isDestroyed || !cursor) return;

// Hide cursor if editor is not focused
if (!isEditorFocused) {
cursor.style.display = "none";
return;
}
cursor.style.display = "block";

const { state, dom } = view;
const { selection } = state;
if (!isTextSelection(selection)) return;
Expand Down Expand Up @@ -49,18 +57,32 @@ export function smoothCursorPlugin(): Plugin {
updateCursor(view, cursor);
};

const handleFocus = () => {
isEditorFocused = true;
update();
};

const handleBlur = () => {
isEditorFocused = false;
update();
};

let observer: ResizeObserver | undefined;
if (window.ResizeObserver) {
observer = new window.ResizeObserver(update);
observer?.observe(view.dom);
}

doc.addEventListener("selectionchange", update);
view.dom.addEventListener("focus", handleFocus);
view.dom.addEventListener("blur", handleBlur);

return {
update,
destroy: () => {
doc.removeEventListener("selectionchange", update);
view.dom.removeEventListener("focus", handleFocus);
view.dom.removeEventListener("blur", handleBlur);
observer?.unobserve(view.dom);
// Clean up any pending animation frame
if (rafId !== undefined) {
Expand All @@ -81,9 +103,9 @@ export function smoothCursorPlugin(): Plugin {
]);
},

attributes: {
class: "smooth-cursor-enabled",
},
attributes: () => ({
class: isEditorFocused ? "smooth-cursor-enabled" : "",
}),
},
});
}
Expand Down

0 comments on commit a4aefe4

Please sign in to comment.