1
0
mirror of https://github.com/ianstormtaylor/slate.git synced 2025-08-30 18:39:51 +02:00

refactor wrapText transform

This commit is contained in:
Ian Storm Taylor
2016-11-22 15:46:53 -08:00
parent a6844a4e58
commit 6893884174
3 changed files with 42 additions and 18 deletions

View File

@@ -499,22 +499,14 @@ export function wrapInline(transform, properties) {
export function wrapText(transform, prefix, suffix = prefix) {
const { state } = transform
const { selection } = state
const { anchorOffset, anchorKey, focusOffset, focusKey, isBackward } = selection
let after
transform.wrapTextAtRange(selection, prefix, suffix)
if (anchorKey == focusKey) {
after = selection.moveForward(prefix.length)
// Adding the suffix will have pushed the end of the selection further on, so
// we need to move it back to account for this.
transform.moveEndOffset(0 - suffix.length)
// If the selection was collapsed, it will have moved the start offset too.
if (selection.isCollapsed) {
transform.moveStartOffset(0 - prefix.length)
}
else {
after = selection.merge({
anchorOffset: isBackward ? anchorOffset : anchorOffset + prefix.length,
focusOffset: isBackward ? focusOffset + prefix.length : focusOffset
})
}
transform
.unsetSelection()
.wrapTextAtRange(selection, prefix, suffix)
.moveTo(after)
}

View File

@@ -126,6 +126,8 @@ import {
focus,
moveBackward,
moveForward,
moveEndOffset,
moveStartOffset,
moveTo,
moveToOffsets,
moveToRangeOf,
@@ -279,6 +281,8 @@ export default {
focus,
moveBackward,
moveForward,
moveEndOffset,
moveStartOffset,
moveTo,
moveToOffsets,
moveToRangeOf,

View File

@@ -352,10 +352,10 @@ export function moveTo(transform, properties) {
* @param {Number} focus (optional)
*/
export function moveToOffsets(transform, anchor, fokus) {
export function moveToOffsets(transform, anchor, _focus) {
const { state } = transform
const { selection } = state
const sel = selection.moveToOffsets(anchor, fokus)
const sel = selection.moveToOffsets(anchor, _focus)
transform.setSelectionOperation(sel)
}
@@ -374,6 +374,34 @@ export function moveToRangeOf(transform, start, end) {
transform.setSelectionOperation(sel)
}
/**
* Move the start offset by `n`.
*
* @param {Transform} transform
* @param {Number} n
*/
export function moveStartOffset(transform, n) {
const { state } = transform
const { document, selection } = state
const sel = selection.moveStartOffset(n).normalize(document)
transform.setSelectionOperation(sel)
}
/**
* Move the end offset by `n`.
*
* @param {Transform} transform
* @param {Number} n
*/
export function moveEndOffset(transform, n) {
const { state } = transform
const { document, selection } = state
const sel = selection.moveEndOffset(n).normalize(document)
transform.setSelectionOperation(sel)
}
/**
* Unset the selection's marks.
*