From 74bf684ec9515e8d3861e108cce000ea2acb25bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samy=20Pess=C3=A9?= Date: Tue, 11 Jul 2017 22:34:02 +0200 Subject: [PATCH] Add property "isEmpty" (#863) * Add property isEmpty to State * Update hovering menu example * Document isEmpty * Improve perf of isEmpty with @Soreine 's suggestion * Fix return of isEmpty --- docs/reference/models/state.md | 5 +++++ examples/hovering-menu/index.js | 2 +- src/models/state.js | 20 ++++++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/docs/reference/models/state.md b/docs/reference/models/state.md index 5e059f750..ff2aa8201 100644 --- a/docs/reference/models/state.md +++ b/docs/reference/models/state.md @@ -33,6 +33,7 @@ For convenience, in addition to transforms, many of the [`Selection`](./selectio - [`isExpanded`](#isExpanded) - [`isFocused`](#isfocused) - [`isForward`](#isForward) + - [`isEmpty`](#isEmpty) - [Static Methods](#static-methods) - [`State.create`](#statecreate) - [Methods](#methods) @@ -153,6 +154,10 @@ Whether the current selection is focused. Whether the current selection is forward. +### `isEmpty` +`Boolean` + +Whether the current selection is empty. ## Static Methods diff --git a/examples/hovering-menu/index.js b/examples/hovering-menu/index.js index 157f24fec..0d7f7fab3 100644 --- a/examples/hovering-menu/index.js +++ b/examples/hovering-menu/index.js @@ -179,7 +179,7 @@ class HoveringMenu extends React.Component { const { menu, state } = this.state if (!menu) return - if (state.isBlurred || state.isCollapsed) { + if (state.isBlurred || state.isEmpty) { menu.removeAttribute('style') return } diff --git a/src/models/state.js b/src/models/state.js index 384219590..10408dd8e 100644 --- a/src/models/state.js +++ b/src/models/state.js @@ -425,6 +425,26 @@ class State extends new Record(DEFAULTS) { : this.document.getTextsAtRange(this.selection) } + /** + * Check whether the selection is empty. + * + * @return {Boolean} + */ + + get isEmpty() { + const { startOffset, endOffset } = this + + if (this.isCollapsed) { + return true + } + + if (endOffset != 0 && startOffset != 0) { + return false + } + + return this.fragment.text.length == 0 + } + /** * Return a new `Transform` with the current state as a starting point. *