Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

25.9 KB
Raw Blame
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import {
  DOCUMENT_WITH_THREE_CARDS_AND_COLUMNS,
  DOCUMENT_WITH_TWO_CARDS,
} from "e2e/support/document-initial-data";

const { H } = cy;

describe("documents card embed node custom logic", () => {
  beforeEach(() => {
    H.restore();
    cy.signInAsAdmin();
  });

  describe("cardEmbed drag and drop", () => {
    beforeEach(() => {
      H.createDocument({
        name: "DnD Test Document",
        document: DOCUMENT_WITH_TWO_CARDS,
        collection_id: null,
        idAlias: "documentId",
      });

      H.visitDocument("@documentId");
    });

    it("should not group a card dropped onto itself, group a card dropped onto another, and add supporting text to the group", () => {
      // Wait for cards to load
      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      // Verify no flexContainer exists initially
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("not.exist");

      cy.log("dropping a card onto itself does nothing");
      H.dragAndDropCardOnAnotherCard("Orders", "Orders");

      // Verify no flexContainer was created
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("not.exist");

      // Verify the card is still standalone
      H.getDocumentCard("Orders").should("exist");

      cy.log("dropping a card onto another card creates a flexContainer");
      H.dragAndDropCardOnAnotherCard("Orders", "Orders, Count");

      // Verify flexContainer was created
      H.documentContent().find('[data-type="flexContainer"]').should("exist");

      // Verify both cards are now inside the flexContainer
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .within(() => {
          assertFlexContainerCardsOrder(["Orders", "Orders, Count"]);
        });

      // Verify the flexContainer is wrapped in a resizeNode
      H.documentContent()
        .find('[data-type="resizeNode"]')
        .should("exist")
        .within(() => {
          cy.get('[data-type="flexContainer"]').should("exist");
        });

      cy.log("add supporting text to a card in the flexContainer");
      H.documentContent()
        .findByTestId("document-card-supporting-text")
        .should("not.exist");

      H.openDocumentCardMenu("Orders");
      H.popover()
        .findByText("Add supporting text")
        .closest("button")
        .should("be.enabled")
        .click();

      H.documentContent()
        .findByTestId("document-card-supporting-text")
        .should("exist");

      // Verify the supporting text has the placeholder text
      H.documentContent()
        .findByTestId("document-card-supporting-text")
        .should("contain.text", "Write whatever you'd like to");

      // Verify the flexContainer now contains supporting text and both cards
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .within(() => {
          cy.findByTestId("document-card-supporting-text").should("exist");
          cy.findAllByTestId("document-card-embed").should("have.length", 2);
        });

      // Verify supporting text was added at the beginning of the flexContainer
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .find(
          '[data-testid="document-card-supporting-text"], [data-testid="document-card-embed"]',
        )
        .first()
        .should("have.attr", "data-testid", "document-card-supporting-text");
    });

    it("should handle drag and drop with proper drop side positioning", () => {
      // Wait for cards to load
      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      H.dragAndDropCardOnAnotherCard("Orders", "Orders, Count", {
        side: "right",
      });

      // Verify flexContainer was created with correct order
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          // Orders, Count should be first (left), Orders should be second (right)
          assertFlexContainerCardsOrder(["Orders, Count", "Orders"]);
        });
    });
  });

  describe("advanced flexContainer scenarios", () => {
    beforeEach(() => {
      H.createDocument({
        name: "Advanced DnD Test Document",
        document: DOCUMENT_WITH_THREE_CARDS_AND_COLUMNS,
        collection_id: null,
        idAlias: "documentId",
      });

      H.visitDocument("@documentId");
    });

    it("should add a third card to an existing flexContainer with 2 cards", () => {
      // Wait for all cards to load
      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count, Grouped by Created At (year)")
        .should("be.visible")
        .findByTestId("chart-container")
        .should("exist");

      // Verify initial state - flexContainer exists with 2 cards
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          cy.findAllByTestId("document-card-embed").should("have.length", 2);
        });

      // Drag the standalone card (Orders by Year) onto one of the cards in the flexContainer
      H.dragAndDropCardOnAnotherCard(
        "Orders, Count, Grouped by Created At (year)",
        "Orders",
        { side: "left" },
      );

      // Verify the flexContainer now has 3 cards

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          assertFlexContainerCardsOrder([
            "Orders, Count, Grouped by Created At (year)",
            "Orders",
            "Orders, Count",
          ]);
        });

      H.documentUndo();

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("have.length", 1)
        .within(() => {
          assertFlexContainerCardsOrder(["Orders", "Orders, Count"]);
        });
      H.getDocumentCard("Orders, Count, Grouped by Created At (year)")
        .should("be.visible")
        .closest('[data-type="flexContainer"]')
        .should("not.exist");

      // Drag the standalone card (Orders by Year) onto one of the cards in the flexContainer
      H.dragAndDropCardOnAnotherCard(
        "Orders, Count, Grouped by Created At (year)",
        "Orders",
        { side: "right" },
      );

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          assertFlexContainerCardsOrder([
            "Orders",
            "Orders, Count, Grouped by Created At (year)",
            "Orders, Count",
          ]);
        });

      H.documentUndo();

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("have.length", 1)
        .within(() => {
          assertFlexContainerCardsOrder(["Orders", "Orders, Count"]);
        });
      H.getDocumentCard("Orders, Count, Grouped by Created At (year)")
        .should("be.visible")
        .closest('[data-type="flexContainer"]')
        .should("not.exist");

      // Drag the standalone card (Orders by Year) onto one of the cards in the flexContainer
      H.dragAndDropCardOnAnotherCard(
        "Orders, Count, Grouped by Created At (year)",
        "Orders, Count",
        { side: "right" },
      );

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          assertFlexContainerCardsOrder([
            "Orders",
            "Orders, Count",
            "Orders, Count, Grouped by Created At (year)",
          ]);
        });

      cy.log("changing the widths of 2 cards should leave the 3rd alone");

      const cardNames = [
        "Orders",
        "Orders, Count",
        "Orders, Count, Grouped by Created At (year)",
      ];

      getCardWidths(cardNames, (first, second, third) => {
        cy.wrap(first).as("_first");
        cy.wrap(second).as("_second");
        cy.wrap(third).as("_third");
        expect(first).to.be.closeTo(second, 10);
        // Unjustified type cast. FIXME
        expect(first).to.be.closeTo(third as unknown as number, 10);
      });

      const flexContainer = H.getFlexContainerForCard("Orders");

      const handles = H.getResizeHandlesForFlexContianer(flexContainer);

      H.documentDoDrag(handles.eq(1), { x: 50 });

      getCardWidths(cardNames, (first, second, third) => {
        cy.get("@_first").then((_first) => {
          cy.get("@_second").then((_second) => {
            cy.get("@_third").then((_third) => {
              // Unjustified type cast. FIXME
              expect(first).to.be.closeTo(_first as unknown as number, 3);
              // Unjustified type cast. FIXME
              expect(second).to.be.greaterThan(_second as unknown as number);
              // Unjustified type cast. FIXME
              expect(third).to.be.lessThan(_third as unknown as number);
            });
          });
        });
      });
    });

    it("should disable 'Add supporting text', prevent adding a fourth card, and delete cards with Backspace when a flexContainer has 3 cards", () => {
      // Wait for all cards to load
      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      cy.log("'Add supporting text' is enabled with 2 cards");
      H.openDocumentCardMenu("Orders");
      H.popover()
        .findByText("Add supporting text")
        .closest("button")
        .should("be.enabled");
      cy.realPress("Escape");
      cy.get(H.POPOVER_ELEMENT).should("not.exist");

      cy.log("a standalone card dropped onto a 2-card flexContainer joins it");
      H.getDocumentCard("Orders, Count, Grouped by Created At (year)")
        .should("be.visible")
        .closest('[data-type="flexContainer"]')
        .should("not.exist");
      H.dragAndDropCardOnAnotherCard(
        "Orders, Count, Grouped by Created At (year)",
        "Orders",
        { side: "right" },
      );

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("have.length", 1)
        .within(() => {
          assertFlexContainerCardsOrder([
            "Orders",
            "Orders, Count, Grouped by Created At (year)",
            "Orders, Count",
          ]);
        });

      cy.log("a fourth card is rejected");
      addNewStandaloneCard("Orders Model");
      H.getDocumentCard("Orders Model")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders Model")
        .closest('[data-type="flexContainer"]')
        .should("not.exist");

      H.dragAndDropCardOnAnotherCard("Orders Model", "Orders", {
        side: "left",
      });

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("have.length", 1)
        .within(() => {
          assertFlexContainerCardsOrder([
            "Orders",
            "Orders, Count, Grouped by Created At (year)",
            "Orders, Count",
          ]);
        });
      H.getDocumentCard("Orders Model")
        .should("be.visible")
        .closest('[data-type="flexContainer"]')
        .should("not.exist");
      H.documentContent()
        .findAllByTestId("document-card-embed")
        .should("have.length", 4);

      cy.log("'Add supporting text' is disabled with 3 cards");
      H.openDocumentCardMenu("Orders");
      H.popover()
        .findByText("Add supporting text")
        .closest("button")
        .should("have.attr", "data-disabled");
      cy.realPress("Escape");
      cy.get(H.POPOVER_ELEMENT).should("not.exist");

      cy.log("Backspace deletes a selected card from the flexContainer");
      H.getDocumentCard("Orders").realClick({ position: "top" });
      cy.realPress("Backspace");

      H.documentContent()
        .findAllByTestId("card-embed-title")
        .filter((_index, element) => element.innerText === "Orders")
        .should("not.exist");
      H.documentContent()
        .findAllByTestId("document-card-embed")
        .should("have.length", 3);
      H.documentContent().find('[data-type="flexContainer"]').should("exist");

      cy.log("deleting down to 1 card unwraps the flexContainer");
      H.getDocumentCard("Orders, Count").realClick({ position: "top" });
      cy.realPress("Backspace");

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("not.exist");
      H.documentContent()
        .findAllByTestId("document-card-embed")
        .should("have.length", 2);
      H.getDocumentCard("Orders, Count, Grouped by Created At (year)").should(
        "exist",
      );
      H.getDocumentCard("Orders Model").should("exist");
    });

    it("should reorder cards within the same flexContainer and preserve resized widths when swapping", () => {
      // Wait for all cards to load
      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      // Verify initial order: Orders | Orders, Count
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          assertFlexContainerCardsOrder(["Orders", "Orders, Count"]);
        });

      // Drag Orders to the right side of Orders, Count to reorder them
      H.dragAndDropCardOnAnotherCard("Orders", "Orders, Count", {
        side: "right",
      });

      // Verify new order: Orders, Count | Orders
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          assertFlexContainerCardsOrder(["Orders, Count", "Orders"]);
        });

      H.dragAndDropCardOnAnotherCard("Orders", "Orders, Count", {
        side: "left",
      });

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          assertFlexContainerCardsOrder(["Orders", "Orders, Count"]);
        });

      cy.log("resized widths are preserved when swapping cards");
      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      // Verify both cards start with equal widths
      getCardWidths(["Orders", "Orders, Count"], (first, second) => {
        cy.wrap(first).as("ogWidth1");
        cy.wrap(second).as("ogWidth2");
        expect(first).to.be.closeTo(second, 3);
      });

      // Resize the columns to have different widths
      const flexContainer = H.getFlexContainerForCard("Orders");
      const handles = H.getResizeHandlesForFlexContianer(flexContainer);
      H.documentDoDrag(handles.eq(0), { x: 150 });

      // Store the widths after resizing
      getCardWidths(
        ["Orders", "Orders, Count"],
        (ordersWidth, ordersCountWidth) => {
          cy.wrap(ordersWidth).as("ordersWidth");
          cy.wrap(ordersCountWidth).as("ordersCountWidth");
          // Verify the widths are now different
          expect(ordersWidth).to.be.greaterThan(ordersCountWidth);
          expect(ordersWidth).to.be.closeTo(ordersCountWidth + 300, 3);

          cy.get<number>("@ogWidth1").then((ogWidth1) => {
            cy.get<number>("@ogWidth2").then((ogWidth2) => {
              cy.log("compare that changes are close to the drag distance");
              expect(ordersWidth).to.be.closeTo(ogWidth1 + 150, 3);
              expect(ordersCountWidth).to.be.closeTo(ogWidth2 - 150, 3);
            });
          });
        },
      );

      // Swap the cards by dragging Orders to the right side of Orders, Count
      H.dragAndDropCardOnAnotherCard("Orders", "Orders, Count", {
        side: "right",
      });

      // Verify new order: Orders, Count | Orders
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("exist")
        .within(() => {
          assertFlexContainerCardsOrder(["Orders, Count", "Orders"]);
        });

      // Verify that each card preserved its width after swapping
      getCardWidths(
        ["Orders, Count", "Orders"],
        (ordersCountNewWidth, ordersNewWidth) => {
          cy.get<number>("@ordersWidth").then((originalOrdersWidth) => {
            cy.get<number>("@ordersCountWidth").then(
              (originalOrdersCountWidth) => {
                // Orders should still have its original width (now on the right)
                expect(ordersNewWidth).to.be.closeTo(originalOrdersWidth, 3);
                // Orders, Count should still have its original width (now on the left)
                expect(ordersCountNewWidth).to.be.closeTo(
                  originalOrdersCountWidth,
                  3,
                );
              },
            );
          });
        },
      );
    });

    it("should handle moving cards between different flexContainers", () => {
      // First create another flexContainer by dragging the standalone card onto a new location
      // Add another standalone card first
      addNewStandaloneCard("Orders Model");

      // Wait for the new card
      H.documentContent()
        .findAllByTestId("document-card-embed")
        .should("have.length", 4);

      // Create a second flexContainer by dropping Orders by Year onto the new Orders card
      H.dragAndDropCardOnAnotherCard(
        "Orders, Count, Grouped by Created At (year)",
        "Orders Model",
      );

      // Verify we now have 2 flexContainers
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("have.length", 2);

      // Move a card from the first flexContainer to the second one
      H.dragAndDropCardOnAnotherCard(
        "Orders, Count",
        "Orders, Count, Grouped by Created At (year)",
        { side: "right" },
      );

      // Verify the first flexContainer now has only 1 card (should be unwrapped)
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("have.length", 1);

      // Verify the remaining flexContainer has 3 cards
      H.documentContent()
        .find('[data-type="flexContainer"]')
        .within(() => {
          cy.findAllByTestId("document-card-embed").should("have.length", 3);
        });

      H.dragAndDropCardOnAnotherCard(
        "Orders, Count, Grouped by Created At (year)",
        "Orders",
        { side: "right" },
      );

      H.documentContent()
        .find('[data-type="flexContainer"]')
        .should("have.length", 2);
    });
  });

  describe("cardEmbed on a new document", () => {
    it("should remove a card that is the first item in a document (UXW-2169) and support text wrapping with proper row heights", () => {
      H.createQuestion({
        name: "reviews",
        type: "model",
        query: {
          "source-table": SAMPLE_DATABASE.REVIEWS_ID,
        },
        visualization_settings: {
          "table.column_widths": [246, 195, 69, 116, 134, 83],
          column_settings: {
            '["name","BODY"]': {
              text_wrapping: true,
            },
          },
        },
      });

      cy.visit("/document/new");

      cy.log("a card that is the first item in a document can be removed");
      H.documentContent().click();
      H.addToDocument("/ord", false);
      H.commandSuggestionItem(/Orders, Count$/).click();

      H.openDocumentCardMenu("Orders, Count");
      H.popover().findByText("Remove Chart").click();

      cy.findAllByTestId("document-card-embed").should("have.length", 0);
      cy.get(H.POPOVER_ELEMENT).should("not.exist");

      cy.log("text wrapping in table cards");
      H.documentContent().click();
      H.addToDocument("/reviews", false);
      H.commandSuggestionItem(/reviews/).click();

      H.getDocumentCard("reviews")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      H.getDocumentCard("reviews").within(() => {
        H.tableInteractive()
          .find("[data-index=0]")
          .should("exist")
          .invoke("height")
          .should("be.greaterThan", 60);
      });
    });
  });

  describe("navigating from and deleting a cardEmbed", () => {
    it("should open a question and a drill-through action in a new tab when clicking with ctrl/meta key, and delete a selected card with Backspace", () => {
      H.createDocument({
        name: "Test Document",
        document: DOCUMENT_WITH_TWO_CARDS,
        collection_id: null,
        idAlias: "documentId",
      });

      H.visitDocument("@documentId");

      // Wait for cards to load
      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      // Verify window.open was called
      cy.on("uncaught:exception", (error) => {
        expect(error.message.includes("expected '<a>' to have attribute")).to.be
          .false;
      });

      H.onNextAnchorClick(
        cy
          .spy((anchor: HTMLAnchorElement) => {
            expect(anchor)
              .to.have.attr("href")
              .match(/\/question\//);
            expect(anchor).to.have.attr("rel", "noopener");
            expect(anchor).to.have.attr("target", "_blank");
          })
          .as("titleAnchorClick"),
      );

      // Click on the card title with ctrl/meta key
      H.getDocumentCard("Orders")
        .findByTestId("card-embed-title")
        .click(H.holdMetaKey);

      cy.get("@titleAnchorClick").should("have.been.calledOnce");
      cy.location("pathname").should("match", /^\/document\//);

      cy.log("drill-through action");
      // Wait for cards to load
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      // Click on a table cell to trigger click actions menu
      H.getDocumentCard("Orders, Count")
        .findByTestId("table-body")
        .findAllByTestId("cell-data")
        .first()
        .click();

      H.onNextAnchorClick(
        cy
          .spy((anchor: HTMLAnchorElement) => {
            expect(anchor)
              .to.have.attr("href")
              .match(/\/question/);
            expect(anchor).to.have.attr("rel", "noopener");
            expect(anchor).to.have.attr("target", "_blank");
          })
          .as("drillAnchorClick"),
      );

      // Wait for the popover to appear and click the first action with ctrl/meta key
      H.popover()
        .findByText("See these Orders")
        .should("be.visible")
        .click(H.holdMetaKey);

      cy.get("@drillAnchorClick").should("have.been.calledOnce");
      cy.location("pathname").should("match", /^\/document\//);

      cy.log("Backspace deletes a selected cardEmbed");
      cy.realPress("Escape");
      cy.get(H.POPOVER_ELEMENT).should("not.exist");

      H.getDocumentCard("Orders")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");
      H.getDocumentCard("Orders, Count")
        .should("be.visible")
        .findByTestId("table-root")
        .should("exist");

      // The ctrl/meta-clicks leave the document with its 2 standalone cards
      H.documentContent()
        .findAllByTestId("document-card-embed")
        .should("have.length", 2);

      // Click on the Orders card to select it
      H.getDocumentCard("Orders").realClick({ position: "top" });

      // Press Backspace to delete the selected card
      cy.realPress("Backspace");

      // Verify the Orders card has been deleted
      H.documentContent()
        .findAllByTestId("card-embed-title")
        .filter((_index, element) => element.innerText === "Orders")
        .should("not.exist");

      // Verify only one card remains
      H.documentContent()
        .findAllByTestId("document-card-embed")
        .should("have.length", 1);

      // Verify the remaining card is Orders, Count
      H.getDocumentCard("Orders, Count").should("exist").and("be.visible");
    });
  });
});

function assertFlexContainerCardsOrder(expectedCardTitles: string[]) {
  for (let i = 0; i < expectedCardTitles.length; i++) {
    cy.findAllByTestId("document-card-embed")
      .should("have.length", expectedCardTitles.length)
      .eq(i)
      .findByTestId("card-embed-title")
      .should("contain.text", expectedCardTitles[i]);
  }
}

function addNewStandaloneCard(cardName: string) {
  // Move the cursor to the document's trailing empty paragraph
  H.documentContent().findByText("Advanced drag and drop scenarios").click();
  cy.realPress([
    H.metaKey,
    Cypress.platform === "darwin" ? "ArrowDown" : "End",
  ]);
  H.addToDocument("/", false);
  H.commandSuggestionItem("Chart").click();
  H.commandSuggestionItem(/Browse all/).click();
  H.pickEntity({ path: ["Our analytics", cardName], select: true });
}

function getCardWidths(
  cardNames: string[],
  cb: (val1: number, val2: number, val3?: number) => void,
) {
  const [firstCardName, secondCardName, thirdCardName] = cardNames;
  H.getDocumentCard(firstCardName).then((firstCard) => {
    H.getDocumentCard(secondCardName).then((secondCard) => {
      if (thirdCardName) {
        H.getDocumentCard(thirdCardName).then((thirdCard) => {
          cb(
            // Unjustified type cast. FIXME
            firstCard.width() as number,
            // Unjustified type cast. FIXME
            secondCard.width() as number,
            thirdCard.width(),
          );
        });
      } else {
        // Unjustified type cast. FIXME
        cb(firstCard.width() as number, secondCard.width() as number);
      }
    });
  });
}