📝

Lexicalで現在の画像の数を取得するには

に公開

やりたいこと

Lexicalエディター内の画像ノードの数をカウントする関数 を作る

画像カウント関数

  const countImagesInEditor = (editor: LexicalEditor): number => {
    // エディターの現在の状態を取得
    const editorState = editor.getEditorState();

    let imageCount = 0;

    editorState.read(() => {
      // すべての子ノードを再帰的に処理する
      const traverseNodes = (node: LexicalNode): void => {
        if (node.getType() === 'image') {
          imageCount++;
        }

        // ElementNodeの場合のみ子ノードを処理
        if ($isElementNode(node)) {
          const children = node.getChildren();
          for (const child of children) {
            traverseNodes(child);
          }
        }
      };

      const root = $getRoot();
      // ルートノードから開始
      traverseNodes(root);
    });

    return imageCount;
  };

使用例

    <OnChangePlugin
      onChange={(editorState, editor) => {
        editorState.read(async () => {
          const imageCount = countImagesInEditor(editor);
        });
      }}
    />

Discussion