Skip to content

Commit

Permalink
fix: scratch api integration
Browse files Browse the repository at this point in the history
  • Loading branch information
rajasekhar524 committed Feb 24, 2025
1 parent d4f1f73 commit cd79c87
Show file tree
Hide file tree
Showing 11 changed files with 555 additions and 438 deletions.
3 changes: 3 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export const config = {

This comment has been minimized.

Copy link
@romeshqubits

romeshqubits Feb 25, 2025

make this URL dynamic

API_URL: "https://api.stage-uae.myqubit.co",
};
357 changes: 105 additions & 252 deletions package-lock.json

Large diffs are not rendered by default.

12 changes: 1 addition & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,18 +36,8 @@
"path": "cz-conventional-changelog"
}
},
"overrides": {
"@tensorflow/tfjs": "^4.22.0",
"@tensorflow/tfjs-backend-webgl": "^4.22.0",
"@tensorflow/tfjs-converter": "^4.22.0",
"@tensorflow/tfjs-data": "^4.22.0",
"@tensorflow/tfjs-layers": "^4.22.0",
"@tensorflow/tfjs-core": "^4.22.0",
"@tensorflow/tfjs-core@3": "^3.0.0"
},
"dependencies": {
"@heroicons/react": "^2.1.3",
"@tensorflow-models/handpose": "^0.1.0",
"@microbit/microbit-universal-hex": "^0.2.2",
"@tensorflow-models/speech-commands": "^0.5.4",
"arraybuffer-loader": "^1.0.6",
Expand Down Expand Up @@ -179,4 +169,4 @@
"editor-msgs(\\.js)?$": "<rootDir>/test/__mocks__/editor-msgs-mock.js"
}
}
}
}
2 changes: 1 addition & 1 deletion src/components/gui/gui.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ const GUIComponent = (props) => {
if (isRendererSupported === null) {

This comment has been minimized.

Copy link
@romeshqubits

romeshqubits Feb 25, 2025

use query parameter for current layout value

isRendererSupported = Renderer.isSupported()
}
const [currentLayout, setCurrentLayout] = React.useState('student')
const [currentLayout, setCurrentLayout] = React.useState('normal')

useEffect(() => {
localforage.getItem('currentLayout').then(value => {
Expand Down
3 changes: 3 additions & 0 deletions src/components/menu-bar/content.json

Large diffs are not rendered by default.

166 changes: 139 additions & 27 deletions src/components/menu-bar/menu-bar-gui-sub.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
remixProject,
saveProjectAsCopy,
} from "../../reducers/project-state";
import {setIsLoadingState, setIsFirstState } from '../../reducers/vm-status.js';
import {
openAboutMenu,
closeAboutMenu,
Expand Down Expand Up @@ -99,6 +100,9 @@ import oldtimeyLogo from "./oldtimey-logo.svg";
import sharedMessages from "../../lib/shared-messages";
import { ChevronDoubleDownIcon, FolderIcon } from "@heroicons/react/24/outline";
import localforage from 'localforage';
import data from './content.json';
import { config } from "../../../config.js";


class MenuBarGuiSub extends React.Component {
constructor(props) {
Expand Down Expand Up @@ -140,9 +144,7 @@ class MenuBarGuiSub extends React.Component {
}
};

componentDidMount() {
document.addEventListener("keydown", this.handleKeyPress);
}

componentWillUnmount() {
document.removeEventListener("keydown", this.handleKeyPress);
}
Expand Down Expand Up @@ -250,28 +252,119 @@ class MenuBarGuiSub extends React.Component {
};
}

async componentDidMount() {
const currentLayout = await localforage.getItem('currentLayout');
this.setState({ currentLayout });
if(currentLayout === 'teacher') {
this.onLocalStorageFileUploadTeacher()
} else if(currentLayout === 'student'){
this.onLocalStorageFileUploadStudent()
}
else if(currentLayout === 'ico'){
this.onLocalStorageFileUploadStudent()
getProjectIdFromURL() {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get("id") || null;
}

async fetchProjectData(projectId) {
if (!projectId) return;

try {
const apiUrl = `${config.API_URL}/projects/${projectId}`;
const response = await fetch(apiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
});
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching project:", error);
}
else {
localforage.getItem('Current_Project_Name')
.then(projectName => {
this.setState({ projectName });
})
.then(() => this.onLocalStorageFileUpload())
.catch((error) =>
console.log('')
);
}

async fetchProjectDataTeacher(scratchElementSettingsId, scratchSubmissionType, scratchUserId, scratchSubstatus, scratchisActivein) {
if (!scratchElementSettingsId) return;

try {
const apiUrl = `${config.API_URL}/challenges/user-submission/${scratchElementSettingsId}?user=${scratchUserId}&type=${scratchSubmissionType}&filter=all`;
const response = await fetch(apiUrl, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
credentials: 'include',
});

const dataReceived = await response.json();

if (!Array.isArray(dataReceived) || dataReceived.length === 0) {
console.error("No valid submissions found in API response.");
return null;
}


if (scratchSubstatus === 'submitted' || scratchSubstatus === 'graded') {
console.log('✅ dataReceived for dataReceived', dataReceived);

This comment has been minimized.

Copy link
@romeshqubits

romeshqubits Feb 25, 2025

remove this console

const activeSubmission = dataReceived.find(
(submission) => String(submission.submissionStatus) == 'submitted' && String(submission.isActive) == String(scratchisActivein),
);
if(activeSubmission) {
return activeSubmission.submission
}
}

if (scratchSubstatus === 'resubmitted' || scratchSubstatus === 'graded') {
if (dataReceived && Array.isArray(dataReceived)) {
const activeResubmission = dataReceived.find(
(resub) => String(resub.submissionStatus) === 'resubmitted' && String(resub.isActive) === String(scratchisActivein),
);
if (activeResubmission) {
return activeResubmission.submission;
}
} else {
console.error("Data received is not an array or is undefined");
}
}

} catch (error) {
console.error("Error fetching project:", error);
return null;
}

}



async componentDidMount() {
document.addEventListener("keydown", this.handleKeyPress);
const url = new URLSearchParams(window.location.search);

const projectId = url.get('projectid');
const currentprojectName = url.get('projectname');
const currentLayout = url.get('inputLayout');
let result;

const scratchElementSettingsId = url.get('scratchElementSettingsId');
const scratchSubmissionType = url.get('scratchSubmissionType');
const scratchUserId = url.get('scratchUserId');
const scratchSubstatus = url.get('scratchSubstatus');
const scratchisActivein = url.get('scratchisActivein');

this.setState({ currentLayout });

try {
if (currentLayout === 'teacher') {
result = await this.fetchProjectDataTeacher(scratchElementSettingsId, scratchSubmissionType, scratchUserId, scratchSubstatus, scratchisActivein);
this.onLocalStorageFileUploadTeacher(result);
} else if (currentLayout === 'myprojects') {
this.props.onClickLoadingTrue();
result = await this.fetchProjectData(projectId);
this.onLocalStorageFileUploadStudentICO(result.content);
} else if (currentLayout === 'student') {
this.onLocalStorageFileUploadStudent();
} else {
const projectName = await localforage.getItem('Current_Project_Name');
this.setState({ projectName });
this.onLocalStorageFileUpload();
}
} catch (error) {
this.props.onClickLoadingFalse();
} finally {
this.props.onClickLoadingFalse();
}
}

componentDidUpdate(prevProps) {
Expand All @@ -284,7 +377,6 @@ class MenuBarGuiSub extends React.Component {

async onLocalStorageFileUploadStudent() {
let base64blocks = await localforage.getItem('ScratchStudentSubmission');
console.log('loaded from scratch', base64blocks)
let binaryString = atob(base64blocks);
let bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
Expand All @@ -294,6 +386,17 @@ class MenuBarGuiSub extends React.Component {
await this.props.vm.loadProject(bytes.buffer);
}

async onLocalStorageFileUploadStudentICO(base64blocks) {
let binaryString = atob(base64blocks);
let bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
await new Promise(resolve => setTimeout(resolve, 500));
await this.props.vm.loadProject(bytes.buffer);
this.props.onClickFirstFalse();
}

async onLocalStorageFileUpload() {
const projectData = await localforage.getItem(this.state.projectName);
if (projectData) {
Expand All @@ -305,12 +408,10 @@ class MenuBarGuiSub extends React.Component {
await this.props.vm.loadProject(buffer);
}
} else {
// console.error('No project found in local storage');
}
}

async onLocalStorageFileUploadTeacher() {
let base64blocks = await localforage.getItem('loadteacher');
async onLocalStorageFileUploadTeacher(base64blocks) {
let binaryString = atob(base64blocks);
let bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
Expand Down Expand Up @@ -461,6 +562,10 @@ class MenuBarGuiSub extends React.Component {
</SB3Downloader>
</div>
<FolderIcon className={styles.fileDropDown} />

{this.props.isSaving && <span className={styles.loadingState}>Saving data <div className={styles.loader}></div></span>}
{this.props.isLoading&&<span className={styles.loadingState}>Fetching data, please wait <div className={styles.loader}></div></span>}

<MenuBarMenu
className={classNames(styles.menuBarMenu)}
open={this.props.fileMenuOpen}
Expand Down Expand Up @@ -570,6 +675,9 @@ const mapStateToProps = (state, ownProps) => {
mode2020: isTimeTravel2020(state),
modeNow: isTimeTravelNow(state),
flagClicked: state.scratchGui.vmStatus.flagClicked,
isSaving: state.scratchGui.vmStatus.isSaving,
isFirst: state.scratchGui.vmStatus.isFirst,
isLoading: state.scratchGui.vmStatus.isLoading,
autoSave: state.scratchGui.vmStatus.autoSave,
};
};
Expand Down Expand Up @@ -597,6 +705,10 @@ const mapDispatchToProps = (dispatch) => ({
onClickSaveAsCopy: () => dispatch(saveProjectAsCopy()),
onSeeCommunity: () => dispatch(setPlayer(true)),
onSetTimeTravelMode: (mode) => dispatch(setTimeTravel(mode)),
onClickFirst: () => dispatch(setFirst()),
onClickFirstFalse: () => dispatch(setIsFirstState(false)),
onClickLoadingFalse: () => dispatch(setIsLoadingState(false)),
onClickLoadingTrue: () => dispatch(setIsLoadingState(true)),
});

export default compose(
Expand Down
44 changes: 43 additions & 1 deletion src/components/menu-bar/menu-bar.css
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,51 @@
/* border: 1px solid #e0e0e0; */
/* border-radius: 5px; */
color: $ui-white;
/* padding: 1rem 0.3rem 1rem 0.3rem; */
/* padding: 1rem 0.3rem 1
rem 0.3rem; */
}

.loading-state{
width: 15rem;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
padding: 0.5rem 0.5rem 0.5rem 0.5rem;
margin-left: 1rem;
font-size: 0.8rem;
color: #855CD6;
}

.loader {
width: 6px;
height: 6px;
border-radius: 50%;
display: block;
margin:10px auto;
position: relative;
color: #855CD6;
box-sizing: border-box;
animation: animloader 1s linear infinite alternate;
}

@keyframes animloader {
0% {
box-shadow: -20px -6px, -7px 0, 7px 0, 20px 0;
}
33% {
box-shadow: -20px 0px, -7px -6px, 7px 0, 20px 0;
}
66% {
box-shadow: -20px 0px, -7px 0, 7px -6px, 20px 0;
}
100% {
box-shadow: -20px 0, -7px 0, 7px 0, 20px -6px;
}
}



.main-menu {
display: flex;
flex-direction: row;
Expand Down
2 changes: 1 addition & 1 deletion src/components/stage-header/stage-header.css
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
justify-content: flex-end;
flex-shrink: 0;
align-items: center;
background-color: white;
background-color: #FAFAFA;
height: $stage-menu-height;
padding-left: 1rem;
/* padding-top: $space; */
Expand Down
2 changes: 1 addition & 1 deletion src/components/stage/stage.css
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
display: block;

border-radius: $space;
border: $stage-standard-border-width solid $ui-black-transparent;
border: $stage-standard-border-width solid $ui-black-transparent !important;
overflow: hidden;

/* @todo: This is for overriding the value being set somewhere. Where is it being set? */
Expand Down
Loading

0 comments on commit cd79c87

Please sign in to comment.