Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ editor.insertInlineContent([
getSelectedText(): string
```

Retrieves the currently selected text as a plain string.
Retrieves the currently selected text as a plain string. When the selection spans multiple blocks, the text of each block is separated by a newline.

```typescript
const selectedText = editor.getSelectedText();
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/editor/BlockNoteEditor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1252,7 +1252,8 @@ export class BlockNoteEditor<
}

/**
* Gets the currently selected text.
* Gets the currently selected text. Text from different blocks is separated
* by a newline.
*/
public getSelectedText() {
return this._styleManager.getSelectedText();
Expand Down
32 changes: 32 additions & 0 deletions packages/core/src/editor/managers/StyleManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,35 @@ describe("getSelectedLinkUrl", () => {
expect(editor.getLinkMarkAtPos(from - 2)).toBeUndefined();
});
});

describe("getSelectedText", () => {
it("separates text from different blocks with a newline", () => {
const editor = BlockNoteEditor.create({
initialContent: [
{ type: "paragraph", content: "First" },
{
type: "paragraph",
content: "Second",
children: [{ type: "paragraph", content: "Nested" }],
},
{ type: "heading", content: "Third" },
],
});
editor.transact((tr) =>
tr.setSelection(TextSelection.create(tr.doc, 1, tr.doc.content.size - 1)),
);
expect(editor.getSelectedText()).toBe("First\nSecond\nNested\nThird");
});

it("returns the text of a selection within one block unchanged", () => {
const editor = BlockNoteEditor.create({
initialContent: [{ type: "paragraph", content: "Hello world" }],
});
editor.setTextCursorPosition(editor.document[0], "start");
const start = editor.prosemirrorState.selection.from;
editor.transact((tr) =>
tr.setSelection(TextSelection.create(tr.doc, start, start + 5)),
);
expect(editor.getSelectedText()).toBe("Hello");
});
});
5 changes: 3 additions & 2 deletions packages/core/src/editor/managers/StyleManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,11 +141,12 @@ export class StyleManager<
}

/**
* Gets the currently selected text.
* Gets the currently selected text. Text from different blocks is separated
* by a newline.
*/
public getSelectedText() {
return this.editor.transact((tr) => {
return tr.doc.textBetween(tr.selection.from, tr.selection.to);
return tr.doc.textBetween(tr.selection.from, tr.selection.to, "\n");
});
}

Expand Down
Loading