Skip to content

Commit

Permalink
Refactor alignment determination logic in useAlignDropdownMenuState t…
Browse files Browse the repository at this point in the history
…o handle multiple nodes and simplify return conditions
  • Loading branch information
kumarajay0412 committed May 20, 2024
1 parent c9efba4 commit 168ed8f
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 71 deletions.
44 changes: 29 additions & 15 deletions packages/alignment/src/client/useAlignDropdownMenu.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,45 @@
import type { Location } from 'slate';

import {
focusEditor,
getNodeEntries,
isBlock,
useEditorRef,
useEditorSelector,
} from '@udecode/plate-common';
import { findNode, isCollapsed, isDefined } from '@udecode/plate-common/server';
import { isDefined } from '@udecode/plate-common/server';

import { type Alignment, KEY_ALIGN, setAlign } from '../index';

export const useAlignDropdownMenuState = () => {
const value: Alignment = useEditorSelector((editor) => {
if (isCollapsed(editor.selection)) {
const entry = findNode(editor, {
match: (n) => isDefined(n[KEY_ALIGN]),
});

if (entry) {
const nodeValue = entry[0][KEY_ALIGN] as string;

if (nodeValue === 'left') return 'left';
if (nodeValue === 'center') return 'center';
if (nodeValue === 'right') return 'right';
if (nodeValue === 'end') return 'end';
if (nodeValue === 'justify') return 'justify';
let commonAlignment: string | undefined;
const codeBlockEntries = getNodeEntries(editor, {
at: editor.selection as Location,
match: (n) => isBlock(editor, n),
});
const nodes = Array.from(codeBlockEntries);
nodes.forEach(([node, path]) => {
const align: string = (node[KEY_ALIGN] as string) || 'left';

if (!isDefined(commonAlignment)) {
commonAlignment = align;
} else if (commonAlignment !== align) {
commonAlignment = undefined;
}
});

if (isDefined(commonAlignment)) {
const nodeValue = commonAlignment;

if (nodeValue === 'left') return 'left';
if (nodeValue === 'center') return 'center';
if (nodeValue === 'right') return 'right';
if (nodeValue === 'end') return 'end';
if (nodeValue === 'justify') return 'justify';
}

return 'start';
return 'left';
}, []);

return {
Expand Down
Loading

0 comments on commit 168ed8f

Please sign in to comment.