From 53f47b01d1c5e36f5576b73adcf8232e0c4c1e1e Mon Sep 17 00:00:00 2001 From: Jan Paepke Date: Mon, 7 Mar 2022 05:43:58 +0100 Subject: [PATCH] EXAMPLES: fix focus bug for hovering toolbar example (#4866) * fix focus bug for hovering toolbar example * added test --- .../integration/examples/hovering-toolbar.ts | 17 +++++++++++++++++ site/examples/hovering-toolbar.tsx | 15 ++++++++------- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/cypress/integration/examples/hovering-toolbar.ts b/cypress/integration/examples/hovering-toolbar.ts index ae44ca77d..db8ea8409 100644 --- a/cypress/integration/examples/hovering-toolbar.ts +++ b/cypress/integration/examples/hovering-toolbar.ts @@ -18,4 +18,21 @@ describe('hovering toolbar example', () => { .find('span.material-icons') .should('have.length', 3) }) + it('hovering toolbar disappears', () => { + cy.get('span[data-slate-string="true"]') + .eq(0) + .type(`{selectall}`) + .get('div') + .eq(12) + .should('exist') + .get('span[data-slate-string="true"]') + .eq(0) + .type(`{selectall}`) + .get('div') + .eq(0) + .click({ force: true }) + .get('div') + .eq(12) + .should('have.css', 'opacity', '0') + }) }) diff --git a/site/examples/hovering-toolbar.tsx b/site/examples/hovering-toolbar.tsx index 5718eadf0..bb04b7b9a 100644 --- a/site/examples/hovering-toolbar.tsx +++ b/site/examples/hovering-toolbar.tsx @@ -1,11 +1,10 @@ import React, { useState, useMemo, useRef, useEffect } from 'react' -import { Slate, Editable, ReactEditor, withReact, useSlate } from 'slate-react' +import { Slate, Editable, withReact, useSlate, useFocused } from 'slate-react' import { Editor, Transforms, Text, createEditor, - Element, Descendant, Range, } from 'slate' @@ -76,6 +75,7 @@ const Leaf = ({ attributes, children, leaf }) => { const HoveringToolbar = () => { const ref = useRef() const editor = useSlate() + const inFocus = useFocused() useEffect(() => { const el = ref.current @@ -87,7 +87,7 @@ const HoveringToolbar = () => { if ( !selection || - !ReactEditor.isFocused(editor) || + !inFocus || Range.isCollapsed(selection) || Editor.string(editor, selection) === '' ) { @@ -122,6 +122,10 @@ const HoveringToolbar = () => { border-radius: 4px; transition: opacity 0.75s; `} + onMouseDown={e => { + // prevent toolbar from taking focus away from editor + e.preventDefault() + }} > @@ -137,10 +141,7 @@ const FormatButton = ({ format, icon }) => {