Skip to content
Merged
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
78 changes: 78 additions & 0 deletions cypress/e2e/spec-scratch.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ import {
} from "../helpers/scratch.js";

const origin = "http://localhost:3011/web-component.html";
const authKey = "oidc.user:https://auth-v1.raspberrypi.org:editor-api";
const user = {
access_token: "dummy-access-token",
profile: {
user: "student-id",
},
};

beforeEach(() => {
cy.intercept("*", (req) => {
Expand Down Expand Up @@ -75,3 +82,74 @@ describe("Scratch", () => {
});
});
});

describe("Scratch save integration", () => {
beforeEach(() => {
cy.on("window:before:load", (win) => {
win.localStorage.setItem(authKey, JSON.stringify(user));
});

const params = new URLSearchParams();
params.set("auth_key", authKey);
params.set("load_remix_disabled", "true");

cy.visit(`${origin}?${params.toString()}`);
cy.findByText("cool-scratch").click();
});

it("remixes on the first save, keeps the iframe project loaded, and saves after the identifier update", () => {
getEditorShadow()
.find("iframe[title='Scratch']")
.its("0.contentDocument.body")
.should("not.be.empty");

getEditorShadow()
.find("iframe[title='Scratch']")
.should(($iframe) => {
const url = new URL($iframe.attr("src"));
expect(url.searchParams.get("project_id")).to.eq("cool-scratch.json");
})
.then(($iframe) => {
cy.stub($iframe[0].contentWindow, "postMessage").as(
"scratchPostMessage",
);
});

getEditorShadow().findByRole("button", { name: "Save" }).click();

cy.get("@scratchPostMessage")
.its("firstCall.args.0")
.should("deep.include", { type: "scratch-gui-remix" });

cy.window().then((win) => {
win.dispatchEvent(
new win.MessageEvent("message", {
origin: win.location.origin,
data: {
type: "scratch-gui-project-id-updated",
projectId: "student-remix",
},
}),
);
});

cy.get("#project-identifier").should("have.text", "student-remix");

getEditorShadow()
.find("iframe[title='Scratch']")
.should(($iframe) => {
const url = new URL($iframe.attr("src"));
expect(url.searchParams.get("project_id")).to.eq("cool-scratch.json");
});

cy.get("@scratchPostMessage").then((postMessage) => {
postMessage.resetHistory();
});

getEditorShadow().findByRole("button", { name: "Save" }).click();

cy.get("@scratchPostMessage")
.its("firstCall.args.0")
.should("deep.include", { type: "scratch-gui-save" });
});
});
26 changes: 23 additions & 3 deletions src/components/Editor/Project/ScratchContainer.jsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,36 @@
import React from "react";
import { useSelector } from "react-redux";
import React, { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { applyScratchProjectIdentifierUpdate } from "../../../redux/EditorSlice";
import { subscribeToScratchProjectIdentifierUpdates } from "../../../utils/scratchIframe";

export default function ScratchContainer() {
const dispatch = useDispatch();
const projectIdentifier = useSelector(
(state) => state.editor.project.identifier,
);
const scratchIframeProjectIdentifier = useSelector(
(state) => state.editor.scratchIframeProjectIdentifier,
);
const scratchApiEndpoint = useSelector(
(state) => state.editor.scratchApiEndpoint,
);
const iframeProjectIdentifier =
scratchIframeProjectIdentifier || projectIdentifier;

useEffect(() => {
return subscribeToScratchProjectIdentifierUpdates(
(nextProjectIdentifier) => {
dispatch(
applyScratchProjectIdentifierUpdate({
projectIdentifier: nextProjectIdentifier,
}),
);
},
);
}, [dispatch]);

const queryParams = new URLSearchParams();
queryParams.set("project_id", projectIdentifier);
queryParams.set("project_id", iframeProjectIdentifier);
queryParams.set("api_url", scratchApiEndpoint);

const iframeSrcUrl = `${
Expand Down
67 changes: 59 additions & 8 deletions src/components/Editor/Project/ScratchContainer.test.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import configureStore from "redux-mock-store";
import { render, screen } from "@testing-library/react";
import { act, render, screen } from "@testing-library/react";
import React from "react";
import { Provider } from "react-redux";
import { configureStore } from "@reduxjs/toolkit";
import ScratchContainer from "./ScratchContainer";
import EditorReducer from "../../../redux/EditorSlice";

describe("ScratchContainer", () => {
let originalAssetsUrl;
Expand All @@ -17,13 +18,19 @@ describe("ScratchContainer", () => {
});

test("renders iframe with src built from project_id and api_url", () => {
const mockStore = configureStore([]);
const store = mockStore({
editor: {
project: {
identifier: "project-123",
const store = configureStore({
reducer: {
editor: EditorReducer,
},
preloadedState: {
editor: {
project: {
identifier: "project-123",
project_type: "code_editor_scratch",
},
scratchIframeProjectIdentifier: "project-123",
scratchApiEndpoint: "https://api.example.com/v1",
},
scratchApiEndpoint: "https://api.example.com/v1",
},
});

Expand All @@ -41,4 +48,48 @@ describe("ScratchContainer", () => {
expect(url.searchParams.get("project_id")).toBe("project-123");
expect(url.searchParams.get("api_url")).toBe("https://api.example.com/v1");
});

test("updates the parent project identifier without reloading the iframe project_id", () => {
const store = configureStore({
reducer: {
editor: EditorReducer,
},
preloadedState: {
editor: {
project: {
identifier: "project-123",
project_type: "code_editor_scratch",
},
scratchIframeProjectIdentifier: "project-123",
scratchApiEndpoint: "https://api.example.com/v1",
},
},
});

render(
<Provider store={store}>
<ScratchContainer />
</Provider>,
);

act(() => {
window.dispatchEvent(
new MessageEvent("message", {
origin: "https://example.com",
data: {
type: "scratch-gui-project-id-updated",
projectId: "project-456",
},
}),
);
});

expect(store.getState().editor.project.identifier).toBe("project-456");
expect(store.getState().editor.scratchIframeProjectIdentifier).toBe(
"project-123",
);

const url = new URL(screen.getByTitle("Scratch").getAttribute("src"));
expect(url.searchParams.get("project_id")).toBe("project-123");
});
});
19 changes: 10 additions & 9 deletions src/components/ProjectBar/ScratchProjectBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import UploadButton from "../UploadButton/UploadButton";
import DesignSystemButton from "../DesignSystemButton/DesignSystemButton";

import "../../assets/stylesheets/ProjectBar.scss";
import { useScratchSaveState } from "../../hooks/useScratchSaveState";
import { useScratchSave } from "../../hooks/useScratchSave";

const ScratchProjectBar = ({ nameEditable = true }) => {
const { t } = useTranslation();
Expand All @@ -19,13 +19,14 @@ const ScratchProjectBar = ({ nameEditable = true }) => {
const loading = useSelector((state) => state.editor.loading);
const readOnly = useSelector((state) => state.editor.readOnly);
const showScratchSaveButton = Boolean(user && !readOnly);
const enableScratchSaveState = Boolean(
loading === "success" && showScratchSaveButton,
);
const { isScratchSaving, saveScratchProject, scratchSaveLabelKey } =
useScratchSaveState({
enabled: enableScratchSaveState,
});
const {
isScratchSaving,
saveScratchProject,
scratchSaveLabelKey,
shouldRemixOnSave,
} = useScratchSave({
enabled: showScratchSaveButton,
});
const scratchSaveLabel = t(scratchSaveLabelKey);

if (loading !== "success") {
Expand Down Expand Up @@ -58,7 +59,7 @@ const ScratchProjectBar = ({ nameEditable = true }) => {
<div className="project-bar__btn-wrapper">
<DesignSystemButton
className="project-bar__btn btn--save btn--primary"
onClick={saveScratchProject}
onClick={() => saveScratchProject({ shouldRemixOnSave })}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: minor point but I think we pass out shouldRemixOnSave from the useScratchSave only to pass it back in. I don't think that shouldRemixOnSave is used anywhere else?

Maybe it could be just used in useScratchSave something like..

const {
  saveScratchProject: triggerScratchSaveOrRemixCommand,
  scratchSaveLabelKey,
  isScratchSaving,
} = useScratchSaveState({ enabled: enableScratchSaveState });

const saveScratchProject = () =>
  triggerScratchSaveOrRemixCommand({ shouldRemixOnSave });

and usage here 'onClick={() => saveScratchProject()} '

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you @DNR500, I do prefer the explicitness in the callback.
I think it obscure a little bit less the function.

When you are looking at the code it makes you think (or at least it does to me) that the button has more than one behaviour if passed there.

text={scratchSaveLabel}
textAlways
icon={<SaveIcon />}
Expand Down
61 changes: 35 additions & 26 deletions src/components/ProjectBar/ScratchProjectBar.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import { postMessageToScratchIframe } from "../../utils/scratchIframe";
jest.mock("axios");
jest.mock("../../utils/scratchIframe", () => ({
postMessageToScratchIframe: jest.fn(),
shouldRemixScratchProjectOnSave: jest.requireActual(
"../../utils/scratchIframe",
).shouldRemixScratchProjectOnSave,
}));

jest.mock("react-router-dom", () => ({
Expand All @@ -35,10 +38,12 @@ const user = {
const renderScratchProjectBar = (state) => {
const middlewares = [];
const mockStore = configureStore(middlewares);
const project = state.editor?.project || {};
const store = mockStore({
editor: {
loading: "success",
project: {},
project,
scratchIframeProjectIdentifier: project.identifier || null,
...state.editor,
},
auth: {
Expand Down Expand Up @@ -102,6 +107,26 @@ describe("When project is Scratch", () => {
type: "scratch-gui-save",
});
});

test("clicking Save remixes a non-owner Scratch project on the first save", () => {
renderScratchProjectBar({
editor: {
project: {
...scratchProject,
user_id: "teacher-id",
},
},
auth: {
user,
},
});

fireEvent.click(screen.getAllByRole("button", { name: "header.save" })[1]);

expect(postMessageToScratchIframe).toHaveBeenCalledWith({
type: "scratch-gui-remix",
});
});
});

describe("Additional Scratch manual save states", () => {
Expand Down Expand Up @@ -139,18 +164,7 @@ describe("Additional Scratch manual save states", () => {
).toBeInTheDocument();
});

test("does not show save for logged-out Scratch users", () => {
renderScratchProjectBar({
editor: {
project: scratchProject,
},
});

expect(screen.queryByText("header.save")).not.toBeInTheDocument();
expect(screen.queryByText("header.loginToSave")).not.toBeInTheDocument();
});

test("shows save for logged-in non-owners", () => {
test("shows the saving state during a Scratch remix", () => {
renderScratchProjectBar({
editor: {
project: {
Expand All @@ -163,26 +177,21 @@ describe("Additional Scratch manual save states", () => {
},
});

dispatchScratchMessage("scratch-gui-remixing-started");

expect(
screen.getByRole("button", { name: "header.save" }),
).toBeInTheDocument();
screen.getByRole("button", { name: "saveStatus.saving" }),
).toBeDisabled();
});

test("shows save for logged-in users without a Scratch project identifier", () => {
test("does not show save for logged-out Scratch users", () => {
renderScratchProjectBar({
editor: {
project: {
...scratchProject,
identifier: null,
},
},
auth: {
user,
project: scratchProject,
},
});

expect(
screen.getByRole("button", { name: "header.save" }),
).toBeInTheDocument();
expect(screen.queryByText("header.save")).not.toBeInTheDocument();
expect(screen.queryByText("header.loginToSave")).not.toBeInTheDocument();
});
});
Loading
Loading