Skip to content
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

experimental: Enter support #4627

Merged
merged 11 commits into from
Dec 20, 2024
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 @@ -18,7 +18,6 @@ import { useEffectEvent } from "~/shared/hook-utils/effect-event";
import type { InstanceSelector } from "~/shared/tree-utils";
import type { Instance } from "@webstudio-is/sdk";
import { shallowEqual } from "shallow-equal";
import { emitCommand } from "~/builder/shared/commands";

const TriggerButton = styled("button", {
position: "absolute",
Expand Down Expand Up @@ -84,7 +83,6 @@ const Menu = ({
(templateSelector: InstanceSelector) => {
const insertBefore = modifierKeys.altKey;
insertTemplateAt(templateSelector, anchor, insertBefore);
emitCommand("newInstanceText");
},
[anchor, modifierKeys.altKey]
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { shallowEqual } from "shallow-equal";
import { selectInstance } from "~/shared/awareness";
import {
extractWebstudioFragment,
findAllEditableInstanceSelector,
findAvailableDataSources,
getWebstudioData,
insertInstanceChildrenMutable,
Expand All @@ -12,6 +13,8 @@ import {
} from "~/shared/instance-utils";
import {
$instances,
$registeredComponentMetas,
$textEditingInstanceSelector,
findBlockChildSelector,
findBlockSelector,
} from "~/shared/nano-states";
Expand Down Expand Up @@ -111,8 +114,34 @@ export const insertTemplateAt = (
const children: Instance["children"] = [
{ type: "id", value: newRootInstanceId },
];

insertInstanceChildrenMutable(data, children, target);

const selectedInstanceSelector = [
newRootInstanceId,
...target.parentSelector,
];

const selectors: InstanceSelector[] = [];

findAllEditableInstanceSelector(
selectedInstanceSelector,
data.instances,
$registeredComponentMetas.get(),
selectors
);

const editableInstanceSelector = selectors[0];

if (editableInstanceSelector) {
$textEditingInstanceSelector.set({
selector: editableInstanceSelector,
reason: "new",
});
} else {
$textEditingInstanceSelector.set(undefined);
}

selectInstance([newRootInstanceId, ...target.parentSelector]);
});
};
1 change: 0 additions & 1 deletion apps/builder/app/builder/shared/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,6 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
source: "builder",
externalCommands: [
"editInstanceText",
"newInstanceText",
"formatBold",
"formatItalic",
"formatSuperscript",
Expand Down
176 changes: 143 additions & 33 deletions apps/builder/app/canvas/features/text-editor/text-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
type NodeKey,
$getNodeByKey,
SELECTION_CHANGE_COMMAND,
$selectAll,
} from "lexical";
import { LinkNode } from "@lexical/link";
import { LexicalComposer } from "@lexical/react/LexicalComposer";
Expand All @@ -61,7 +62,11 @@ import { ToolbarConnectorPlugin } from "./toolbar-connector";
import { type Refs, $convertToLexical, $convertToUpdates } from "./interop";
import { colord } from "colord";
import { useEffectEvent } from "~/shared/hook-utils/effect-event";
import { findAllEditableInstanceSelector } from "~/shared/instance-utils";
import {
deleteInstanceMutable,
findAllEditableInstanceSelector,
updateWebstudioData,
} from "~/shared/instance-utils";
import {
$blockChildOutline,
$hoveredInstanceOutline,
Expand All @@ -72,6 +77,7 @@ import {
$textEditingInstanceSelector,
$textEditorContextMenu,
execTextEditorContextMenuCommand,
findBlockChildSelector,
findTemplates,
} from "~/shared/nano-states";
import {
Expand All @@ -86,6 +92,7 @@ import {
selectInstance,
} from "~/shared/awareness";
import { shallowEqual } from "shallow-equal";
import { insertTemplateAt } from "~/builder/features/workspace/canvas-tools/outline/block-utils";

const BindInstanceToNodePlugin = ({
refs,
Expand Down Expand Up @@ -709,6 +716,10 @@ const InitCursorPlugin = () => {

return;
}
if (reason === "new") {
$selectAll();
return;
}

reason satisfies never;
});
Expand Down Expand Up @@ -929,38 +940,39 @@ type ContextMenuParams = {
cursorRect: DOMRect;
};

type ContextMenuPluginProps = {
type RichTextContentPluginProps = {
rootInstanceSelector: InstanceSelector;
onOpen: (
editorState: EditorState,
params: undefined | ContextMenuParams
) => void;
onNext: (editorState: EditorState, params: HandleNextParams) => void;
};

const ContextMenuPlugin = (props: ContextMenuPluginProps) => {
const [hasTemplates] = useState(() => {
const templates = findTemplates(
props.rootInstanceSelector,
$instances.get()
);
if (templates === undefined) {
return false;
}
const RichTextContentPlugin = (props: RichTextContentPluginProps) => {
const [templates] = useState(() =>
findTemplates(props.rootInstanceSelector, $instances.get())
);

return templates.length > 0;
});
if (templates === undefined) {
return;
}

if (!hasTemplates) {
return null;
if (templates.length === 0) {
return;
}

return <ContextMenuPluginInternal {...props} />;
return <RichTextContentPluginInternal {...props} templates={templates} />;
};

const ContextMenuPluginInternal = ({
const RichTextContentPluginInternal = ({
rootInstanceSelector,
onOpen,
}: ContextMenuPluginProps) => {
templates,
onNext,
}: RichTextContentPluginProps & {
templates: [instance: Instance, instanceSelector: InstanceSelector][];
}) => {
const [editor] = useLexicalComposerContext();
const [preservedSelection] = useState(rootInstanceSelector);

Expand Down Expand Up @@ -1002,6 +1014,19 @@ const ContextMenuPluginInternal = ({

if (!isSelectionInSameComponent) {
node?.remove();

const rootNodeContent = $getRoot().getTextContent().trim();
// Delete current
if (rootNodeContent.length === 0) {
const blockChildSelector =
findBlockChildSelector(rootInstanceSelector);

if (blockChildSelector) {
updateWebstudioData((data) => {
deleteInstanceMutable(data, rootInstanceSelector);
});
}
}
}

// if selection changed, remove the slash node
Expand All @@ -1022,11 +1047,6 @@ const ContextMenuPluginInternal = ({
return false;
}

if (!isSingleCursorSelection()) {
closeMenu();
return false;
}

const selection = $getSelection();

if (!$isRangeSelection(selection)) {
Expand All @@ -1047,16 +1067,89 @@ const ContextMenuPluginInternal = ({
const unsubscibeKeyDown = editor.registerCommand(
KEY_DOWN_COMMAND,
(event) => {
if (!isSingleCursorSelection()) {
return false;
}

const selection = $getSelection();

if (!$isRangeSelection(selection)) {
return false;
}

if (event.key === "Backspace" || event.key === "Delete") {
const rootNodeContent = $getRoot().getTextContent().trim();
// Delete current
if (rootNodeContent.length === 0) {
const blockChildSelector =
findBlockChildSelector(rootInstanceSelector);

if (blockChildSelector) {
onNext(editor.getEditorState(), { reason: "left" });

updateWebstudioData((data) => {
deleteInstanceMutable(data, rootInstanceSelector);
});

event.preventDefault();
return true;
}
}
}

if (menuState === "closed") {
if (event.key === "Enter" && !event.shiftKey) {
// Check if it pressed on the last line, last symbol

const allowedComponents = ["Paragraph", "Text", "Heading"];

for (const component of allowedComponents) {
const templateSelector = templates.find(
([instance]) => instance.component === component
)?.[1];

if (templateSelector === undefined) {
continue;
}

/*
@todo Split logic idea
// clone root node then

// getPreviousSibling
const removeNextSiblings = (node: LexicalNode) => {
let current: LexicalNode | null = node;
while (current) {
const next = current.getNextSibling();
if (next) {
next.remove();
continue;
}
// Move up to parent and continue removing siblings

current = current.getParent();

if ($isRootNode(current)) {
break;
}
}
};

const anchorNode = selection.anchor.getNode();
const anchorOffset = selection.anchor.offset;

if (!$isTextNode(anchorNode)) {
continue;
}
anchorNode.splitText(anchorOffset);
removeNextSiblings(anchorNode);

*/

insertTemplateAt(templateSelector, rootInstanceSelector, false);

event.preventDefault();
return true;
}
}
}

if (menuState === "opened") {
if (event.key === "Escape") {
closeMenu();
Expand Down Expand Up @@ -1192,7 +1285,14 @@ const ContextMenuPluginInternal = ({
unsubscibeSelectionChange();
unsubscribeBlurListener();
};
}, [editor, handleOpen, preservedSelection]);
}, [
editor,
handleOpen,
onNext,
preservedSelection,
rootInstanceSelector,
templates,
]);

return null;
};
Expand Down Expand Up @@ -1282,13 +1382,14 @@ const AnyKeyDownPlugin = ({
};

export const TextEditor = ({
rootInstanceSelector,
rootInstanceSelector: rootInstanceSelectorUnstable,
instances,
contentEditable,
editable,
onChange,
onSelectInstance,
}: TextEditorProps) => {
const [rootInstanceSelector] = useState(() => rootInstanceSelectorUnstable);
// class names must be started with letter so we add a prefix
const [paragraphClassName] = useState(() => `a${nanoid()}`);
const [italicClassName] = useState(() => `a${nanoid()}`);
Expand All @@ -1314,6 +1415,15 @@ export const TextEditor = ({

setDataCollapsed(rootInstanceSelector[0], false);
});

const textEditingSelector = $textEditingInstanceSelector.get()?.selector;
if (textEditingSelector === undefined) {
return;
}

if (shallowEqual(textEditingSelector, rootInstanceSelector)) {
$textEditingInstanceSelector.set(undefined);
}
});

useLayoutEffect(() => {
Expand Down Expand Up @@ -1363,7 +1473,7 @@ export const TextEditor = ({
onError,
};

const handleNext = useCallback(
const handleNext = useEffectEvent(
(state: EditorState, args: HandleNextParams) => {
const rootInstanceId = $selectedPage.get()?.rootInstanceId;

Expand Down Expand Up @@ -1444,8 +1554,7 @@ export const TextEditor = ({

break;
}
},
[handleChange, instances, rootInstanceSelector]
}
);

const handleAnyKeydown = useCallback((event: KeyboardEvent) => {
Expand Down Expand Up @@ -1506,9 +1615,10 @@ export const TextEditor = ({
<HistoryPlugin />

<SwitchBlockPlugin onNext={handleNext} />
<ContextMenuPlugin
<RichTextContentPlugin
onOpen={handleContextMenuOpen}
rootInstanceSelector={rootInstanceSelector}
onNext={handleNext}
/>
<OnChangeOnBlurPlugin onChange={handleChange} />
<InitCursorPlugin />
Expand Down
Loading
Loading