Skip to content
Open
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
44 changes: 17 additions & 27 deletions lib/components/BlockWorkPackage/BlockWorkPackage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ import { SearchContainer, SearchLabel } from "../Search/SearchContainer";
import { SearchDropdown } from "../Search/SearchDropdown";
import { defaultWpVariables } from "../WorkPackage/atoms";
import { formatWorkPackageId } from "../../utils/id";
import { pendingBlockRegistry } from "./pendingBlockRegistry";

const Block = styled.div.attrs({ className: "op-bn-extensions" })`
const Block = styled.div.attrs({ className: "op-bn-extensions" })<{ $pending?: boolean }>`
${defaultWpVariables}
background-color: var(--op-chip-bg);
background-color: ${({ $pending }) => ($pending ? "transparent" : "var(--op-chip-bg)")};
`;

const BlockCardWrapper = styled.div`
Expand All @@ -29,6 +30,8 @@ interface BlockProps {
id: string;
props: {
wpid?: number;
// Not used for render logic - only written on select so the spec serialises
// data-initialized="true" in toExternalHTML.
initialized?: boolean;
size?: BlockWpSize;
};
Expand All @@ -47,40 +50,31 @@ export const BlockWorkPackageComponent = ({
// The hook handles triggering re-renders when data arrives.
useColors();

const [isActive, setIsActive] = useState(false);
const [isOptionsOpen, setIsOptionsOpen] = useState(false);

const workPackageResult = useWorkPackage(block.props.wpid);
const selectedWorkPackage = workPackageResult.workPackage;

const cardSize: BlockWpSize = block.props.size ?? "m";

useEffect(() => {
return () => { pendingBlockRegistry.delete(block.id); };
}, [block.id]);

const handleSelectWorkPackage = (wp: WorkPackage) => {
pendingBlockRegistry.delete(block.id);
editor.updateBlock(block, {
props: { ...block.props, wpid: wp.id, initialized: true },
});
requestAnimationFrame(() => moveCursorToNextBlock(editor, block.id));
};

useEffect(() => {
// accessing private tiptap instance until public API is available
const tiptap = (editor as any)._tiptapEditor;
if (!tiptap) return;

const updateActiveState = () => {
setIsActive(editor.getTextCursorPosition()?.block?.id === block.id);
};

tiptap.on("selectionUpdate", updateActiveState);
updateActiveState();
return () => { tiptap.off("selectionUpdate", updateActiveState); };
}, [editor, block.id]);

// Close options popover on outside click
useEffect(() => {
if (!isOptionsOpen) return;
const handleClickOutside = (e: MouseEvent) => {
if (cardRef.current && !cardRef.current.contains(e.target as Node)) {
const path = e.composedPath();
if (cardRef.current && !path.includes(cardRef.current as EventTarget)) {
setIsOptionsOpen(false);
}
};
Expand Down Expand Up @@ -132,15 +126,12 @@ export const BlockWorkPackageComponent = ({
editor.removeBlocks([block]);
};

const disableFocus = block.props.initialized && !block.props.wpid;
const isPending = pendingBlockRegistry.has(block.id);

return (
<Block
tabIndex={disableFocus ? -1 : 0}
style={disableFocus ? { pointerEvents: "none" } : undefined}
>
<Block $pending={isPending}>
<div contentEditable={false} style={{ userSelect: "none" }}>
{!block.props.wpid && !block.props.initialized && isActive && (
{isPending && (
<SearchContainer>
Comment on lines +129 to 135
<SearchLabel>
{t("search.label")}
Expand All @@ -149,9 +140,8 @@ export const BlockWorkPackageComponent = ({
autoFocus
onSelect={handleSelectWorkPackage}
onCancel={() => {
editor.updateBlock(block, {
props: { ...block.props, initialized: true },
});
pendingBlockRegistry.delete(block.id);
editor.removeBlocks([block]);
editor.focus();
}}
renderItem={(wp) => <BlockCard workPackage={wp} inDropdown />}
Expand Down
7 changes: 7 additions & 0 deletions lib/components/BlockWorkPackage/pendingBlockRegistry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const pending = new Set<string>();

export const pendingBlockRegistry = {
add: (blockId: string) => pending.add(blockId),
has: (blockId: string) => pending.has(blockId),
delete: (blockId: string) => pending.delete(blockId),
};
32 changes: 31 additions & 1 deletion lib/components/SlashMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import i18n from "../services/i18n.ts";
import { getAliases } from "../services/slashMenuAliases";
import { registerInlineWpCallbacks, clearInlineWpCallbacks, makePendingWpid } from "./InlineWorkPackage/callbacks";
import { makeInstanceId } from "../utils/id.ts";
import { pendingBlockRegistry } from "./BlockWorkPackage/pendingBlockRegistry";

type AnyEditor = BlockNoteEditor<any, any, any>;
type AnyInlineNode = InlineContentFromConfig<any, any>;
Expand Down Expand Up @@ -75,6 +76,29 @@ function buildOnCancel(
};
}

function isCurrentBlockEmpty(editor: AnyEditor): boolean {
const block = editor.getTextCursorPosition()?.block;
if (!block) return false;
const content = (block as any).content;
return Array.isArray(content) && content.length === 0;
}

function handleBlockWorkPackageClick(editor: AnyEditor): void {
const blockId = editor.getTextCursorPosition()?.block?.id as string | undefined;
if (!blockId) return;

const block = {
type: "openProjectWorkPackageBlock" as const,
props: { initialized: false },
} as Parameters<typeof editor.insertBlocks>[0][number];

const [insertedBlock] = editor.insertBlocks([block], blockId, "after");
if (!insertedBlock?.id) return;

pendingBlockRegistry.add(insertedBlock.id);
editor.removeBlocks([blockId]);
}

function handleInlineWorkPackageClick(editor: AnyEditor): void {
const instanceId = makeInstanceId();
const pendingWpid = makePendingWpid(instanceId);
Expand All @@ -100,7 +124,13 @@ function handleInlineWorkPackageClick(editor: AnyEditor): void {

export const workPackageSlashMenu = (editor: BlockNoteEditor<any>) => ({
title: i18n.t("slashMenu.title"),
onItemClick: () => handleInlineWorkPackageClick(editor),
onItemClick: () => {
if (isCurrentBlockEmpty(editor)) {
handleBlockWorkPackageClick(editor);
} else {
handleInlineWorkPackageClick(editor);
}
},
aliases: [...getAliases()],
group: "OpenProject",
icon: <LinkIcon size={18} />,
Expand Down
2 changes: 1 addition & 1 deletion test/helpers/editorHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export async function openEditorAndType(text: string) {
}

export async function insertInlineChipViaSlashMenu(searchTerm:string='Fix', resultTerm:string='Fix login bug') {
await openEditorAndType('/');
await openEditorAndType(' /');
await expect.element(page.getByText('Link existing work package').first()).toBeVisible();
await userEvent.click(page.getByText('Link existing work package').first());

Expand Down
42 changes: 42 additions & 0 deletions test/lib/components/integration/editor.slashMenu.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, it, expect } from 'vitest';
import { page, userEvent } from 'vitest/browser';
import { renderEditor } from '../../../helpers/renderEditor';

async function openSlashMenuAndSelectWp() {
await expect.element(page.getByText('Link existing work package').first()).toBeVisible();
await userEvent.click(page.getByText('Link existing work package').first());

const searchInput = page.getByPlaceholder('Search by work package ID or subject');
await expect.element(searchInput).toBeVisible();
await userEvent.type(searchInput, 'Fix');
await expect.element(page.getByText('Fix login bug')).toBeVisible();
await userEvent.click(page.getByText('Fix login bug'));
await expect.element(searchInput).not.toBeInTheDocument();
}

describe('Slash menu - block vs inline routing', () => {
it('inserts a block card when triggered on an empty line', async () => {
renderEditor();
const editorEl = page.getByRole('textbox');
await userEvent.click(editorEl);
await userEvent.type(editorEl, '/');

await openSlashMenuAndSelectWp();

await expect.element(page.getByTestId('block-card')).toBeVisible();
await expect.element(page.getByTestId('op-bn-work-package--type')).toBeVisible();
});

it('inserts an inline chip when triggered on a non-empty line', async () => {
renderEditor();
const editorEl = page.getByRole('textbox');
await userEvent.click(editorEl);
await userEvent.type(editorEl, 'Some text ');
await userEvent.type(editorEl, '/');

await openSlashMenuAndSelectWp();

await expect.element(page.getByText('#123')).toBeVisible();
await expect.element(page.getByTestId('block-card')).not.toBeInTheDocument();
});
});
Loading