Skip to content

WIP: dnd plugin #2839

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@
"jwt-decode": "^4.0.0",
"lodash": "^4.17.21",
"monaco-editor": "0.47.0",
"nanoid": "^5.0.9",
"prettier": "^3.1.1",
"prismjs": "^1.29.0",
"punycode": "2.3.1",
Expand Down
98 changes: 73 additions & 25 deletions src/components/SlateEditor/RichTextEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,21 @@ import { useFormikContext } from "formik";
import { isKeyHotkey } from "is-hotkey";
import isEqual from "lodash/isEqual";
import { FocusEvent, KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createEditor, Descendant, Editor, NodeEntry, Range, Transforms } from "slate";
import { createEditor, Descendant, Editor, NodeEntry, Range, Transforms, Element, Path } from "slate";
import { withHistory } from "slate-history";
import { Slate, Editable, withReact, RenderElementProps, RenderLeafProps, ReactEditor } from "slate-react";
import { Slate, Editable, withReact, RenderLeafProps, ReactEditor, RenderElementProps } from "slate-react";
import { EditableProps } from "slate-react/dist/components/editable";
import { useFieldContext } from "@ark-ui/react";
import {
closestCenter,
DndContext,
DragEndEvent,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { sortableKeyboardCoordinates } from "@dnd-kit/sortable";
import { Spinner } from "@ndla/primitives";
import { styled } from "@ndla/styled-system/jsx";
import "../DisplayEmbed/helpers/h5pResizer";
Expand All @@ -24,7 +34,6 @@ import { Action, commonActions } from "./plugins/blockPicker/actions";
import { BlockPickerOptions, createBlockpickerOptions } from "./plugins/blockPicker/options";
import SlateBlockPicker from "./plugins/blockPicker/SlateBlockPicker";
import { TYPE_DEFINITION_LIST } from "./plugins/definitionList/types";
import { onDragOver, onDragStart, onDrop } from "./plugins/DND";
import { TYPE_HEADING } from "./plugins/heading/types";
import { TYPE_LIST } from "./plugins/list/types";
import { TYPE_PARAGRAPH } from "./plugins/paragraph/types";
Expand Down Expand Up @@ -229,13 +238,6 @@ const RichTextEditor = ({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

// eslint-disable-next-line react-hooks/exhaustive-deps
const onDragStartCallback = useCallback(onDragStart(editor), []);
// eslint-disable-next-line react-hooks/exhaustive-deps
const onDragOverCallback = useCallback(onDragOver(), []);
// eslint-disable-next-line react-hooks/exhaustive-deps
const onDropCallback = useCallback(onDrop(editor), []);

// Deselect selection if focus is moved to any other element than the toolbar
const onBlur = useCallback(
(e: FocusEvent<HTMLDivElement>) => {
Expand Down Expand Up @@ -319,6 +321,53 @@ const RichTextEditor = ({
[additionalOnKeyDown, editor],
);

const onDragEnd = (dragEvent: DragEndEvent) => {
const overId = dragEvent.over?.data.current?.nodeId;
const activeId = dragEvent.active.id;
const dropAreaPosition = dragEvent.over?.data.current?.position;
if (!(dropAreaPosition === "top" || dropAreaPosition === "bottom")) return;

const [entry1, entry2] = editor.nodes({
match: (n) => {
return Element.isElement(n) && (n.id === activeId || n.id === overId);
},
at: [],
});

if (!entry1 || !("id" in entry1[0]) || !entry2) {
return;
}

const [, overPath] = entry1[0].id === overId ? entry1 : entry2;
const [, activePath] = entry1[0].id === activeId ? entry1 : entry2;

let targetPath = overPath;
// TODO: this logic needs to be adjusted for nested elements
// Move node to top or bottom based on drop area
if (dropAreaPosition === "top") {
if (Path.isBefore(overPath, activePath)) {
targetPath = overPath;
} else {
targetPath = Path.previous(overPath);
}
} else if (dropAreaPosition === "bottom") {
if (Path.isBefore(overPath, activePath)) {
targetPath = Path.next(overPath);
} else {
targetPath = overPath;
}
}
if (Path.equals(activePath, targetPath) || Path.isAncestor(activePath, targetPath)) return;
Transforms.moveNodes(editor, { mode: "lowest", at: activePath, to: targetPath });
};

const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);

return (
<article className={noArticleStyling ? undefined : "ndla-article"}>
<ArticleLanguageProvider language={language}>
Expand All @@ -338,21 +387,20 @@ const RichTextEditor = ({
{...createBlockpickerOptions(blockpickerOptions)}
/>
)}
<StyledEditable
{...fieldProps}
aria-labelledby={labelledBy}
{...rest}
onBlur={onBlur}
decorate={decorations}
onKeyDown={handleKeyDown}
placeholder={placeholder}
renderElement={renderElement}
renderLeaf={renderLeaf}
readOnly={submitted}
onDragStart={onDragStartCallback}
onDragOver={onDragOverCallback}
onDrop={onDropCallback}
/>
<DndContext sensors={sensors} onDragEnd={onDragEnd} collisionDetection={closestCenter}>
<StyledEditable
{...fieldProps}
aria-labelledby={labelledBy}
{...rest}
onBlur={onBlur}
decorate={decorations}
onKeyDown={handleKeyDown}
placeholder={placeholder}
renderElement={renderElement}
renderLeaf={renderLeaf}
readOnly={submitted}
/>
</DndContext>
</>
)}
</Slate>
Expand Down
103 changes: 52 additions & 51 deletions src/components/SlateEditor/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,60 +76,61 @@ export type CustomEditor = {
mathjaxInitialized?: boolean;
};

type CustomElement =
| ParagraphElement
| SectionElement
| BreakElement
| LinkElement
| ContentLinkElement
| BlockQuoteElement
| HeadingElement
| ListElement
| ListItemElement
| FootnoteElement
| MathmlElement
| ConceptInlineElement
| ConceptBlockElement
| AsideElement
| FileElement
| DetailsElement
| SummaryElement
| CodeblockElement
| TableElement
| TableCaptionElement
| TableRowElement
| TableCellElement
| TableHeadElement
| TableBodyElement
| RelatedElement
| BrightcoveEmbedElement
| AudioElement
| ImageElement
| ErrorEmbedElement
| H5pElement
| FramedContentElement
| DivElement
| SpanElement
| DefinitionListElement
| DefinitionDescriptionElement
| DefinitionTermElement
| PitchElement
| GridElement
| GridCellElement
| KeyFigureElement
| ContactBlockElement
| CampaignBlockElement
| LinkBlockListElement
| DisclaimerElement
| NoopElement
| ExternalElement
| IframeElement
| CopyrightElement
| CommentInlineElement
| CommentBlockElement;
declare module "slate" {
interface CustomTypes {
Editor: BaseEditor & ReactEditor & HistoryEditor & CustomEditor;
Element:
| ParagraphElement
| SectionElement
| BreakElement
| LinkElement
| ContentLinkElement
| BlockQuoteElement
| HeadingElement
| ListElement
| ListItemElement
| FootnoteElement
| MathmlElement
| ConceptInlineElement
| ConceptBlockElement
| AsideElement
| FileElement
| DetailsElement
| SummaryElement
| CodeblockElement
| TableElement
| TableCaptionElement
| TableRowElement
| TableCellElement
| TableHeadElement
| TableBodyElement
| RelatedElement
| BrightcoveEmbedElement
| AudioElement
| ImageElement
| ErrorEmbedElement
| H5pElement
| FramedContentElement
| DivElement
| SpanElement
| DefinitionListElement
| DefinitionDescriptionElement
| DefinitionTermElement
| PitchElement
| GridElement
| GridCellElement
| KeyFigureElement
| ContactBlockElement
| CampaignBlockElement
| LinkBlockListElement
| DisclaimerElement
| NoopElement
| ExternalElement
| IframeElement
| CopyrightElement
| CommentInlineElement
| CommentBlockElement;
Element: CustomElement & { id?: string };
Text: CustomTextWithMarks;
}
}
Expand Down
83 changes: 83 additions & 0 deletions src/components/SlateEditor/plugins/DND/DraggableContainer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* Copyright (c) 2025-present, NDLA.
*
* This source code is licensed under the GPLv3 license found in the
* LICENSE file in the root directory of this source tree.
*
*/

import { ReactNode } from "react";
import { RenderElementProps } from "slate-react";
import { useDraggable } from "@dnd-kit/core";
import { CSS } from "@dnd-kit/utilities";
import { Draggable } from "@ndla/icons";
import { IconButton } from "@ndla/primitives";
import { styled } from "@ndla/styled-system/jsx";
import DropArea from "./DropArea";

const StyledDragHandle = styled(IconButton, {
base: {
touchAction: "none",
position: "absolute",
left: "-large",
top: "50%",
transform: "translateY(-50%)",
opacity: "0",
},
});

const StyledDndContainer = styled("div", {
base: {
position: "relative",
_hover: {
"& > [data-handle-wrapper] > [data-handle]": {
opacity: "1",
},
},
},
});

const StyledContent = styled("div", {
base: {
position: "relative",
},
variants: {
isDragging: {
true: {
position: "relative",
zIndex: "tooltip",
},
false: {},
},
},
});

interface Props {
attributes: RenderElementProps["attributes"];
children: ReactNode;
elementId: string;
}

const DraggableContainer = ({ attributes: slateAttributes, children, elementId }: Props) => {
const { attributes, listeners, setNodeRef, transform, isDragging } = useDraggable({ id: elementId });
return (
<StyledDndContainer {...slateAttributes}>
{!isDragging && <DropArea elementId={`${elementId}`} position="top" />}
<StyledContent
ref={setNodeRef}
data-handle-wrapper=""
style={{
transform: CSS.Translate.toString(transform),
}}
isDragging={isDragging}
>
<StyledDragHandle size="small" variant="clear" data-handle="" {...attributes} {...listeners}>
<Draggable />
</StyledDragHandle>
{children}
</StyledContent>
{!isDragging && <DropArea elementId={`${elementId}`} position="bottom" />}
</StyledDndContainer>
);
};
export default DraggableContainer;
41 changes: 41 additions & 0 deletions src/components/SlateEditor/plugins/DND/DropArea.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Copyright (c) 2025-present, NDLA.
*
* This source code is licensed under the GPLv3 license found in the
* LICENSE file in the root directory of this source tree.
*
*/

import { useDroppable } from "@dnd-kit/core";
import { styled } from "@ndla/styled-system/jsx";

const StyledDropArea = styled("div", {
base: {
width: "100%",
height: "4xsmall",
position: "absolute",
},
variants: {
variant: { top: { top: "-xxsmall" }, bottom: {} },
visible: {
true: {
background: "surface.action.brand.2",
},
},
},
});

interface Props {
elementId: string;
position: "top" | "bottom";
}

const DropArea = ({ elementId, position }: Props) => {
const { setNodeRef, isOver } = useDroppable({
id: `${elementId}-${position}`,
data: { nodeId: elementId, position: position },
});

return <StyledDropArea contentEditable={false} ref={setNodeRef} visible={isOver} variant={position} />;
};
export default DropArea;
Loading
Loading