Skip to content

Commit

Permalink
Merge pull request #3209 from kumarajay0412/bug-alignment-determinati…
Browse files Browse the repository at this point in the history
…on-logic-in-useAlignDropdownMenuState

Bug : Refactor alignment determination logic in useAlignDropdownMenuState
  • Loading branch information
zbeyens committed May 22, 2024
2 parents c9efba4 + f54d2e8 commit 9b339c1
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 71 deletions.
5 changes: 5 additions & 0 deletions .changeset/sour-candles-sneeze.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@udecode/plate-alignment": patch
---

Fix `useAlignDropdownMenuState`: align value for multiple selected blocks
41 changes: 26 additions & 15 deletions packages/alignment/src/client/useAlignDropdownMenu.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,42 @@
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, {
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 9b339c1

Please sign in to comment.