Compare commits

...
Author SHA1 Message Date
felixerdy d20d8b9e97 add xml code changes 2021-09-16 16:51:10 +02:00
felixerdy 53b4f5dfeb keep workspace code and prepare dialog 2021-09-16 16:00:27 +02:00
Mario PeschandGitHub 9ed49f2972 Merge pull request #99 from sensebox/update-blockly-core
update blockly core and plugins
2021-08-20 10:47:17 +02:00
Mario Pesch 2a9eecd76b prevent edgeScroll 2021-08-20 10:42:37 +02:00
Mario Pesch c23b74ce8d update blockly core and plugins
closes #97
2021-08-18 15:18:47 +02:00
Mario PeschandGitHub f2d50a33c1 Merge pull request #98 from sensebox/remove-mybadges-integration
remove mybadges integration
2021-08-18 14:56:07 +02:00
Mario Pesch 5b2add4098 remove mybadges integration 2021-07-27 11:57:46 +02:00
Mario PeschandGitHub ed36a27ac2 Merge pull request #79 from sensebox/ui-updates
ui-updates
2021-07-01 15:58:35 +02:00
Mario Pesch 4e2b57d46a revert commit 2021-07-01 15:25:33 +02:00
Mario Pesch 9c02fa1ec6 Merge branch 'master' into ui-updates 2021-07-01 11:02:03 +02:00
Mario PeschandGitHub e7cfc5c5d3 Merge pull request #95 from sensebox/dependabot/npm_and_yarn/prismjs-1.24.0
Bump prismjs from 1.23.0 to 1.24.0
2021-06-29 15:21:27 +02:00
dependabot[bot]andGitHub 4f24ba607f Bump prismjs from 1.23.0 to 1.24.0
Bumps [prismjs](https://github.com/PrismJS/prism) from 1.23.0 to 1.24.0.
- [Release notes](https://github.com/PrismJS/prism/releases)
- [Changelog](https://github.com/PrismJS/prism/blob/master/CHANGELOG.md)
- [Commits](https://github.com/PrismJS/prism/compare/v1.23.0...v1.24.0)

---
updated-dependencies:
- dependency-name: prismjs
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-28 20:28:48 +00:00
Mario PeschandGitHub c3bd3a5bef Merge pull request #94 from sensebox/add-curly-brackets
add curly brackets
2021-06-22 13:22:44 +02:00
Mario Pesch 1e979f948c add curly brackets
closes #93
2021-06-22 12:15:39 +02:00
Mario PeschandGitHub f6947f8c6b Merge pull request #92 from sensebox/add-matamo-image-tracker
Add matamo image tracker
2021-06-16 15:08:13 +02:00
Mario Pesch bb19a77896 fix mail in impressum 2021-06-16 12:59:50 +02:00
Mario Pesch f4344f842c add matamo image tracker 2021-06-16 11:17:08 +02:00
Mario PeschandGitHub ee19598728 Merge pull request #91 from sensebox/add-rtc
Add rtc
2021-06-16 10:59:53 +02:00
Mario Pesch d65948fca7 cleanup code and add translations 2021-06-14 14:36:22 +02:00
Mario Pesch c1eff07b7e fix timestamp 2021-06-11 11:19:39 +02:00
Mario Pesch aef8a164ce Merge branch 'master' into add-rtc 2021-06-11 10:10:51 +02:00
Mario Pesch 8c3a86b667 Merge branch 'master' into ui-updates 2021-06-02 14:49:58 +02:00
Mario PeschandGitHub 5ecc776db2 Merge pull request #89 from sensebox/add-phyphox
Add phyphox
2021-05-21 12:21:26 +02:00
Mario Pesch b6c90772ed add rtc blocks 2021-05-21 11:28:35 +02:00
Mario Pesch 283da13455 update tooltip 2021-05-18 13:46:35 +02:00
Mario Pesch 59142b4c25 update randomInt function 2021-05-17 17:03:53 +02:00
Mario Pesch da65e23d3f remove experiment field a 2021-05-17 17:03:42 +02:00
Mario Pesch 531db63b85 add tooltips and en translations 2021-05-17 15:51:57 +02:00
Mario Pesch 44d48997d4 update phyphox blocks 2021-05-16 20:03:21 +02:00
Mario Pesch 47984fa66c add first phyphox blocks 2021-05-06 15:21:54 +02:00
Mario Pesch 4522760e9c update blockly version and add zoom to fit plugin 2021-05-04 11:53:15 +02:00
Mario Pesch 21d282ee1b add multiplexer
closes #81
2021-03-30 15:03:34 +02:00
Mario Pesch 6b12c501a0 fix variable naming 2021-03-30 12:26:26 +02:00
Mario Pesch 255b1619b8 update variable names 2021-03-29 15:07:39 +02:00
Mario Pesch 687ac32166 add ide output fixes #71 2021-03-25 10:38:32 +01:00
Mario Pesch 6a6b2e2f58 get rid of console.log 2021-03-24 17:07:23 +01:00
Mario Pesch d835ffc449 fix load projects 2021-03-24 17:05:21 +01:00
Mario Pesch 190d676e5b fix #58 2021-03-24 15:33:08 +01:00
Mario Pesch 65fa627aeb add dialog before reset workspace
fixes #78
2021-03-24 11:46:05 +01:00
69 changed files with 15928 additions and 14624 deletions
-3
View File
@@ -2,8 +2,5 @@ REACT_APP_COMPILER_URL=https://compiler.sensebox.de
REACT_APP_BOARD=sensebox-mcu REACT_APP_BOARD=sensebox-mcu
REACT_APP_BLOCKLY_API=https://api.blockly.sensebox.de REACT_APP_BLOCKLY_API=https://api.blockly.sensebox.de
REACT_APP_MYBADGES=https://mybadges.org
REACT_APP_MYBADGES_API=https://mybadges.org/api/v1
# in days # in days
REACT_APP_SHARE_LINK_EXPIRES=30 REACT_APP_SHARE_LINK_EXPIRES=30
+171 -146
View File
@@ -10,7 +10,9 @@
"dependencies": { "dependencies": {
"@blockly/block-plus-minus": "^2.0.10", "@blockly/block-plus-minus": "^2.0.10",
"@blockly/field-slider": "^2.1.1", "@blockly/field-slider": "^2.1.1",
"@blockly/plugin-typed-variable-modal": "^3.1.1", "@blockly/plugin-scroll-options": "^1.0.2",
"@blockly/plugin-typed-variable-modal": "^3.1.26",
"@blockly/zoom-to-fit": "^2.0.7",
"@fortawesome/fontawesome-svg-core": "^1.2.30", "@fortawesome/fontawesome-svg-core": "^1.2.30",
"@fortawesome/free-solid-svg-icons": "^5.14.0", "@fortawesome/free-solid-svg-icons": "^5.14.0",
"@fortawesome/react-fontawesome": "^0.1.11", "@fortawesome/react-fontawesome": "^0.1.11",
@@ -21,16 +23,17 @@
"@testing-library/react": "^9.5.0", "@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1", "@testing-library/user-event": "^7.2.1",
"axios": "^0.21.0", "axios": "^0.21.0",
"blockly": "^3.20200924.0", "blockly": "^6.20210701.0",
"file-saver": "^2.0.2", "file-saver": "^2.0.2",
"mnemonic-id": "^3.2.7", "mnemonic-id": "^3.2.7",
"moment": "^2.28.0", "moment": "^2.28.0",
"prismjs": "^1.23.0", "prismjs": "^1.24.0",
"react": "^16.13.1", "react": "^17.0.2",
"react-cookie-consent": "^5.2.0", "react-cookie-consent": "^5.2.0",
"react-dom": "^16.13.1", "react-dom": "^17.0.2",
"react-markdown": "^5.0.2", "react-markdown": "^5.0.2",
"react-redux": "^7.2.0", "react-mde": "^11.5.0",
"react-redux": "^7.2.4",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "^4.0.3", "react-scripts": "^4.0.3",
"reactour": "^1.18.0", "reactour": "^1.18.0",
@@ -1476,15 +1479,40 @@
"node": ">=8.17.0" "node": ">=8.17.0"
} }
}, },
"node_modules/@blockly/plugin-scroll-options": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@blockly/plugin-scroll-options/-/plugin-scroll-options-1.0.2.tgz",
"integrity": "sha512-j0ehQlHv/0EWPw8UQEplGs4jCxfo45yp6ZzxYxReMirM0/j4EXXFvgXTZoruPgRYgMl+pCwya32Z6Dkv19sURA==",
"engines": {
"node": ">=8.17.0"
},
"peerDependencies": {
"blockly": "^6.20210701.0"
}
},
"node_modules/@blockly/plugin-typed-variable-modal": { "node_modules/@blockly/plugin-typed-variable-modal": {
"version": "3.1.1", "version": "3.1.26",
"resolved": "https://registry.npmjs.org/@blockly/plugin-typed-variable-modal/-/plugin-typed-variable-modal-3.1.1.tgz", "resolved": "https://registry.npmjs.org/@blockly/plugin-typed-variable-modal/-/plugin-typed-variable-modal-3.1.26.tgz",
"integrity": "sha512-+g/lQ3HrCcivBNOtgvQEvfZCPq9VeP1Zgs7J02zxAfw4f+s4aOQb+hChv7qAb5AnzEnMk0BoB5vKgQmaP6Wkuw==", "integrity": "sha512-3aKdr/NkcyH93zt0etnmR+urZ3csHbhqyUBn9Q8r/w6GNm54S8s916B921YnGFUBtnWnUEzieMHRAt5KveSKug==",
"dependencies": { "dependencies": {
"@blockly/plugin-modal": "^1.20200427.4" "@blockly/plugin-modal": "^1.20200427.4"
}, },
"engines": { "engines": {
"node": ">=8.17.0" "node": ">=8.17.0"
},
"peerDependencies": {
"blockly": "3.20200625.0 - 6"
}
},
"node_modules/@blockly/zoom-to-fit": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@blockly/zoom-to-fit/-/zoom-to-fit-2.0.7.tgz",
"integrity": "sha512-ZMY6k1V97B3IwBWcbxFlpKwKtfWg2vmJuLfmdIymrJQZtswRyY303F1JOl1G1+zsCKeyW/FVo/ysrSDZTIaRCQ==",
"engines": {
"node": ">=8.17.0"
},
"peerDependencies": {
"blockly": "^6.20210701.0"
} }
}, },
"node_modules/@cnakazawa/watch": { "node_modules/@cnakazawa/watch": {
@@ -3951,6 +3979,15 @@
"@types/node": "*" "@types/node": "*"
} }
}, },
"node_modules/@types/hoist-non-react-statics": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
"integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
"dependencies": {
"@types/react": "*",
"hoist-non-react-statics": "^3.3.0"
}
},
"node_modules/@types/html-minifier-terser": { "node_modules/@types/html-minifier-terser": {
"version": "5.1.1", "version": "5.1.1",
"resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-5.1.1.tgz", "resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-5.1.1.tgz",
@@ -4048,6 +4085,17 @@
"@types/react": "*" "@types/react": "*"
} }
}, },
"node_modules/@types/react-redux": {
"version": "7.1.16",
"resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.16.tgz",
"integrity": "sha512-f/FKzIrZwZk7YEO9E1yoxIuDNRiDducxkFlkw/GNMGEnK9n4K8wJzlJBghpSuOVDgEUHoDkDF7Gi9lHNQR4siw==",
"dependencies": {
"@types/hoist-non-react-statics": "^3.3.0",
"@types/react": "*",
"hoist-non-react-statics": "^3.3.0",
"redux": "^4.0.0"
}
},
"node_modules/@types/react-transition-group": { "node_modules/@types/react-transition-group": {
"version": "4.4.0", "version": "4.4.0",
"resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.0.tgz", "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.0.tgz",
@@ -5845,11 +5893,11 @@
} }
}, },
"node_modules/blockly": { "node_modules/blockly": {
"version": "3.20200924.0", "version": "6.20210701.0",
"resolved": "https://registry.npmjs.org/blockly/-/blockly-3.20200924.0.tgz", "resolved": "https://registry.npmjs.org/blockly/-/blockly-6.20210701.0.tgz",
"integrity": "sha512-mOZiXi908oNFAcVb8Q5LKJNRZ5jtBJtgNilddqTYMAXEdqSY/BhcnU2rgytWARDnu2iSQlI374kEafCNuUEWKQ==", "integrity": "sha512-cNrwFOAxXE5Pbs1FJAyLTlSRzpNW/C+0gPT2rGQDOJVVKcyF3vhFC1StgnxvQNsv//ueuksKWIXxDuSWh1VI4w==",
"dependencies": { "dependencies": {
"jsdom": "^15.2.1" "jsdom": "15.2.1"
} }
}, },
"node_modules/blockly/node_modules/jsdom": { "node_modules/blockly/node_modules/jsdom": {
@@ -6578,17 +6626,6 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/clipboard": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.6.tgz",
"integrity": "sha512-g5zbiixBRk/wyKakSwCKd7vQXDjFnAMGHoEyBogG/bw9kTD9GvdAvaoRR1ALcEzt3pVKxZR0pViekPMIS0QyGg==",
"optional": true,
"dependencies": {
"good-listener": "^1.2.2",
"select": "^1.1.2",
"tiny-emitter": "^2.0.0"
}
},
"node_modules/cliui": { "node_modules/cliui": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
@@ -7821,12 +7858,6 @@
"node": ">=0.4.0" "node": ">=0.4.0"
} }
}, },
"node_modules/delegate": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/delegate/-/delegate-3.2.0.tgz",
"integrity": "sha512-IofjkYBZaZivn0V8nnsMJGBr4jVLxHDheKSW88PyxS5QC4Vo9ZbZVvhzlSxY87fVq3STR6r+4cGepyHkcWOQSw==",
"optional": true
},
"node_modules/depd": { "node_modules/depd": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
@@ -10530,15 +10561,6 @@
"node": ">= 4" "node": ">= 4"
} }
}, },
"node_modules/good-listener": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/good-listener/-/good-listener-1.2.2.tgz",
"integrity": "sha1-1TswzfkxPf+33JoNR3CWqm0UXFA=",
"optional": true,
"dependencies": {
"delegate": "^3.1.2"
}
},
"node_modules/graceful-fs": { "node_modules/graceful-fs": {
"version": "4.2.4", "version": "4.2.4",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz",
@@ -18871,12 +18893,9 @@
} }
}, },
"node_modules/prismjs": { "node_modules/prismjs": {
"version": "1.23.0", "version": "1.24.0",
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.23.0.tgz", "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.24.0.tgz",
"integrity": "sha512-c29LVsqOaLbBHuIbsTxaKENh1N2EQBOHaWv7gkHN4dgRbxSREqDnDbtFJYdpPauS4YCplMSNCABQ6Eeor69bAA==", "integrity": "sha512-SqV5GRsNqnzCL8k5dfAjCNhUrF3pR0A9lTDSCUZeh/LIshheXJEaP0hwLz2t4XHivd2J/v2HR+gRnigzeKe3cQ=="
"optionalDependencies": {
"clipboard": "^2.0.0"
}
}, },
"node_modules/process": { "node_modules/process": {
"version": "0.11.10", "version": "0.11.10",
@@ -19140,13 +19159,12 @@
} }
}, },
"node_modules/react": { "node_modules/react": {
"version": "16.13.1", "version": "17.0.2",
"resolved": "https://registry.npmjs.org/react/-/react-16.13.1.tgz", "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz",
"integrity": "sha512-YMZQQq32xHLX0bz5Mnibv1/LHb3Sqzngu7xstSM+vrkE5Kzr9xE0yMByK5kMoTK30YVJE61WfbxIFFvfeDKT1w==", "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==",
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"object-assign": "^4.1.1", "object-assign": "^4.1.1"
"prop-types": "^15.6.2"
}, },
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
@@ -19309,14 +19327,16 @@
} }
}, },
"node_modules/react-dom": { "node_modules/react-dom": {
"version": "16.13.1", "version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.13.1.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz",
"integrity": "sha512-81PIMmVLnCNLO/fFOQxdQkvEq/+Hfpv24XNJfpyZhTRfO0QcmQIF/PgCa1zCOj2w1hrn12MFLyaJ/G0+Mxtfag==", "integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==",
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"object-assign": "^4.1.1", "object-assign": "^4.1.1",
"prop-types": "^15.6.2", "scheduler": "^0.20.2"
"scheduler": "^0.19.1" },
"peerDependencies": {
"react": "17.0.2"
} }
}, },
"node_modules/react-error-overlay": { "node_modules/react-error-overlay": {
@@ -19359,16 +19379,37 @@
"xtend": "^4.0.1" "xtend": "^4.0.1"
} }
}, },
"node_modules/react-mde": {
"version": "11.5.0",
"resolved": "https://registry.npmjs.org/react-mde/-/react-mde-11.5.0.tgz",
"integrity": "sha512-CH/VK6d+tpVjJ8rTXfh1dDt6GWedTgCU0668p8toqhAc3vy0Lu872O2RKYDSpkUrlbHI08fjUPTl++nExp6gag==",
"peerDependencies": {
"react": "^17.0.0",
"react-dom": "^17.0.0"
}
},
"node_modules/react-redux": { "node_modules/react-redux": {
"version": "7.2.0", "version": "7.2.4",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.0.tgz", "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.4.tgz",
"integrity": "sha512-EvCAZYGfOLqwV7gh849xy9/pt55rJXPwmYvI4lilPM5rUT/1NxuuN59ipdBksRVSvz0KInbPnp4IfoXJXCqiDA==", "integrity": "sha512-hOQ5eOSkEJEXdpIKbnRyl04LhaWabkDPV+Ix97wqQX3T3d2NQ8DUblNXXtNMavc7DpswyQM6xfaN4HQDKNY2JA==",
"dependencies": { "dependencies": {
"@babel/runtime": "^7.5.5", "@babel/runtime": "^7.12.1",
"hoist-non-react-statics": "^3.3.0", "@types/react-redux": "^7.1.16",
"hoist-non-react-statics": "^3.3.2",
"loose-envify": "^1.4.0", "loose-envify": "^1.4.0",
"prop-types": "^15.7.2", "prop-types": "^15.7.2",
"react-is": "^16.9.0" "react-is": "^16.13.1"
},
"peerDependencies": {
"react": "^16.8.3 || ^17"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
}
} }
}, },
"node_modules/react-refresh": { "node_modules/react-refresh": {
@@ -20694,9 +20735,9 @@
} }
}, },
"node_modules/scheduler": { "node_modules/scheduler": {
"version": "0.19.1", "version": "0.20.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz",
"integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==", "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==",
"dependencies": { "dependencies": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"object-assign": "^4.1.1" "object-assign": "^4.1.1"
@@ -20725,12 +20766,6 @@
"resolved": "https://registry.npmjs.org/scrollparent/-/scrollparent-2.0.1.tgz", "resolved": "https://registry.npmjs.org/scrollparent/-/scrollparent-2.0.1.tgz",
"integrity": "sha1-cV1bnMV3YPsivczDvvtb/gaxoxc=" "integrity": "sha1-cV1bnMV3YPsivczDvvtb/gaxoxc="
}, },
"node_modules/select": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/select/-/select-1.1.2.tgz",
"integrity": "sha1-DnNQrN7ICxEIUoeG7B1EGNEbOW0=",
"optional": true
},
"node_modules/select-hose": { "node_modules/select-hose": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz",
@@ -22424,12 +22459,6 @@
"resolved": "https://registry.npmjs.org/timsort/-/timsort-0.3.0.tgz", "resolved": "https://registry.npmjs.org/timsort/-/timsort-0.3.0.tgz",
"integrity": "sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q=" "integrity": "sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q="
}, },
"node_modules/tiny-emitter": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/tiny-emitter/-/tiny-emitter-2.1.0.tgz",
"integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==",
"optional": true
},
"node_modules/tiny-invariant": { "node_modules/tiny-invariant": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.1.0.tgz", "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.1.0.tgz",
@@ -26215,14 +26244,26 @@
"resolved": "https://registry.npmjs.org/@blockly/plugin-modal/-/plugin-modal-1.20200427.4.tgz", "resolved": "https://registry.npmjs.org/@blockly/plugin-modal/-/plugin-modal-1.20200427.4.tgz",
"integrity": "sha512-eA9p+W3mtcWLJQZ23D0Le/Uw3JdxFxwJqTUYtAiRlVON4qnuDXrHQLlvxEiWctNXJZGUTh57zqbvO6ZxNRQPrA==" "integrity": "sha512-eA9p+W3mtcWLJQZ23D0Le/Uw3JdxFxwJqTUYtAiRlVON4qnuDXrHQLlvxEiWctNXJZGUTh57zqbvO6ZxNRQPrA=="
}, },
"@blockly/plugin-scroll-options": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@blockly/plugin-scroll-options/-/plugin-scroll-options-1.0.2.tgz",
"integrity": "sha512-j0ehQlHv/0EWPw8UQEplGs4jCxfo45yp6ZzxYxReMirM0/j4EXXFvgXTZoruPgRYgMl+pCwya32Z6Dkv19sURA==",
"requires": {}
},
"@blockly/plugin-typed-variable-modal": { "@blockly/plugin-typed-variable-modal": {
"version": "3.1.1", "version": "3.1.26",
"resolved": "https://registry.npmjs.org/@blockly/plugin-typed-variable-modal/-/plugin-typed-variable-modal-3.1.1.tgz", "resolved": "https://registry.npmjs.org/@blockly/plugin-typed-variable-modal/-/plugin-typed-variable-modal-3.1.26.tgz",
"integrity": "sha512-+g/lQ3HrCcivBNOtgvQEvfZCPq9VeP1Zgs7J02zxAfw4f+s4aOQb+hChv7qAb5AnzEnMk0BoB5vKgQmaP6Wkuw==", "integrity": "sha512-3aKdr/NkcyH93zt0etnmR+urZ3csHbhqyUBn9Q8r/w6GNm54S8s916B921YnGFUBtnWnUEzieMHRAt5KveSKug==",
"requires": { "requires": {
"@blockly/plugin-modal": "^1.20200427.4" "@blockly/plugin-modal": "^1.20200427.4"
} }
}, },
"@blockly/zoom-to-fit": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/@blockly/zoom-to-fit/-/zoom-to-fit-2.0.7.tgz",
"integrity": "sha512-ZMY6k1V97B3IwBWcbxFlpKwKtfWg2vmJuLfmdIymrJQZtswRyY303F1JOl1G1+zsCKeyW/FVo/ysrSDZTIaRCQ==",
"requires": {}
},
"@cnakazawa/watch": { "@cnakazawa/watch": {
"version": "1.0.4", "version": "1.0.4",
"resolved": "https://registry.npmjs.org/@cnakazawa/watch/-/watch-1.0.4.tgz", "resolved": "https://registry.npmjs.org/@cnakazawa/watch/-/watch-1.0.4.tgz",
@@ -28075,6 +28116,15 @@
"@types/node": "*" "@types/node": "*"
} }
}, },
"@types/hoist-non-react-statics": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz",
"integrity": "sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA==",
"requires": {
"@types/react": "*",
"hoist-non-react-statics": "^3.3.0"
}
},
"@types/html-minifier-terser": { "@types/html-minifier-terser": {
"version": "5.1.1", "version": "5.1.1",
"resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-5.1.1.tgz", "resolved": "https://registry.npmjs.org/@types/html-minifier-terser/-/html-minifier-terser-5.1.1.tgz",
@@ -28172,6 +28222,17 @@
"@types/react": "*" "@types/react": "*"
} }
}, },
"@types/react-redux": {
"version": "7.1.16",
"resolved": "https://registry.npmjs.org/@types/react-redux/-/react-redux-7.1.16.tgz",
"integrity": "sha512-f/FKzIrZwZk7YEO9E1yoxIuDNRiDducxkFlkw/GNMGEnK9n4K8wJzlJBghpSuOVDgEUHoDkDF7Gi9lHNQR4siw==",
"requires": {
"@types/hoist-non-react-statics": "^3.3.0",
"@types/react": "*",
"hoist-non-react-statics": "^3.3.0",
"redux": "^4.0.0"
}
},
"@types/react-transition-group": { "@types/react-transition-group": {
"version": "4.4.0", "version": "4.4.0",
"resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.0.tgz", "resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.0.tgz",
@@ -29613,11 +29674,11 @@
} }
}, },
"blockly": { "blockly": {
"version": "3.20200924.0", "version": "6.20210701.0",
"resolved": "https://registry.npmjs.org/blockly/-/blockly-3.20200924.0.tgz", "resolved": "https://registry.npmjs.org/blockly/-/blockly-6.20210701.0.tgz",
"integrity": "sha512-mOZiXi908oNFAcVb8Q5LKJNRZ5jtBJtgNilddqTYMAXEdqSY/BhcnU2rgytWARDnu2iSQlI374kEafCNuUEWKQ==", "integrity": "sha512-cNrwFOAxXE5Pbs1FJAyLTlSRzpNW/C+0gPT2rGQDOJVVKcyF3vhFC1StgnxvQNsv//ueuksKWIXxDuSWh1VI4w==",
"requires": { "requires": {
"jsdom": "^15.2.1" "jsdom": "15.2.1"
}, },
"dependencies": { "dependencies": {
"jsdom": { "jsdom": {
@@ -30227,17 +30288,6 @@
"resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz",
"integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==" "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A=="
}, },
"clipboard": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/clipboard/-/clipboard-2.0.6.tgz",
"integrity": "sha512-g5zbiixBRk/wyKakSwCKd7vQXDjFnAMGHoEyBogG/bw9kTD9GvdAvaoRR1ALcEzt3pVKxZR0pViekPMIS0QyGg==",
"optional": true,
"requires": {
"good-listener": "^1.2.2",
"select": "^1.1.2",
"tiny-emitter": "^2.0.0"
}
},
"cliui": { "cliui": {
"version": "6.0.0", "version": "6.0.0",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz",
@@ -31233,12 +31283,6 @@
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk=" "integrity": "sha1-3zrhmayt+31ECqrgsp4icrJOxhk="
}, },
"delegate": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/delegate/-/delegate-3.2.0.tgz",
"integrity": "sha512-IofjkYBZaZivn0V8nnsMJGBr4jVLxHDheKSW88PyxS5QC4Vo9ZbZVvhzlSxY87fVq3STR6r+4cGepyHkcWOQSw==",
"optional": true
},
"depd": { "depd": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz",
@@ -33372,15 +33416,6 @@
} }
} }
}, },
"good-listener": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/good-listener/-/good-listener-1.2.2.tgz",
"integrity": "sha1-1TswzfkxPf+33JoNR3CWqm0UXFA=",
"optional": true,
"requires": {
"delegate": "^3.1.2"
}
},
"graceful-fs": { "graceful-fs": {
"version": "4.2.4", "version": "4.2.4",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz",
@@ -39929,12 +39964,9 @@
} }
}, },
"prismjs": { "prismjs": {
"version": "1.23.0", "version": "1.24.0",
"resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.23.0.tgz", "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.24.0.tgz",
"integrity": "sha512-c29LVsqOaLbBHuIbsTxaKENh1N2EQBOHaWv7gkHN4dgRbxSREqDnDbtFJYdpPauS4YCplMSNCABQ6Eeor69bAA==", "integrity": "sha512-SqV5GRsNqnzCL8k5dfAjCNhUrF3pR0A9lTDSCUZeh/LIshheXJEaP0hwLz2t4XHivd2J/v2HR+gRnigzeKe3cQ=="
"requires": {
"clipboard": "^2.0.0"
}
}, },
"process": { "process": {
"version": "0.11.10", "version": "0.11.10",
@@ -40150,13 +40182,12 @@
} }
}, },
"react": { "react": {
"version": "16.13.1", "version": "17.0.2",
"resolved": "https://registry.npmjs.org/react/-/react-16.13.1.tgz", "resolved": "https://registry.npmjs.org/react/-/react-17.0.2.tgz",
"integrity": "sha512-YMZQQq32xHLX0bz5Mnibv1/LHb3Sqzngu7xstSM+vrkE5Kzr9xE0yMByK5kMoTK30YVJE61WfbxIFFvfeDKT1w==", "integrity": "sha512-gnhPt75i/dq/z3/6q/0asP78D0u592D5L1pd7M8P+dck6Fu/jJeL6iVVK23fptSUZj8Vjf++7wXA8UNclGQcbA==",
"requires": { "requires": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"object-assign": "^4.1.1", "object-assign": "^4.1.1"
"prop-types": "^15.6.2"
} }
}, },
"react-app-polyfill": { "react-app-polyfill": {
@@ -40285,14 +40316,13 @@
} }
}, },
"react-dom": { "react-dom": {
"version": "16.13.1", "version": "17.0.2",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.13.1.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-17.0.2.tgz",
"integrity": "sha512-81PIMmVLnCNLO/fFOQxdQkvEq/+Hfpv24XNJfpyZhTRfO0QcmQIF/PgCa1zCOj2w1hrn12MFLyaJ/G0+Mxtfag==", "integrity": "sha512-s4h96KtLDUQlsENhMn1ar8t2bEa+q/YAtj8pPPdIjPDGBDIVNsrD9aXNWqspUe6AzKCIG0C1HZZLqLV7qpOBGA==",
"requires": { "requires": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"object-assign": "^4.1.1", "object-assign": "^4.1.1",
"prop-types": "^15.6.2", "scheduler": "^0.20.2"
"scheduler": "^0.19.1"
} }
}, },
"react-error-overlay": { "react-error-overlay": {
@@ -40335,16 +40365,23 @@
"xtend": "^4.0.1" "xtend": "^4.0.1"
} }
}, },
"react-mde": {
"version": "11.5.0",
"resolved": "https://registry.npmjs.org/react-mde/-/react-mde-11.5.0.tgz",
"integrity": "sha512-CH/VK6d+tpVjJ8rTXfh1dDt6GWedTgCU0668p8toqhAc3vy0Lu872O2RKYDSpkUrlbHI08fjUPTl++nExp6gag==",
"requires": {}
},
"react-redux": { "react-redux": {
"version": "7.2.0", "version": "7.2.4",
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.0.tgz", "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-7.2.4.tgz",
"integrity": "sha512-EvCAZYGfOLqwV7gh849xy9/pt55rJXPwmYvI4lilPM5rUT/1NxuuN59ipdBksRVSvz0KInbPnp4IfoXJXCqiDA==", "integrity": "sha512-hOQ5eOSkEJEXdpIKbnRyl04LhaWabkDPV+Ix97wqQX3T3d2NQ8DUblNXXtNMavc7DpswyQM6xfaN4HQDKNY2JA==",
"requires": { "requires": {
"@babel/runtime": "^7.5.5", "@babel/runtime": "^7.12.1",
"hoist-non-react-statics": "^3.3.0", "@types/react-redux": "^7.1.16",
"hoist-non-react-statics": "^3.3.2",
"loose-envify": "^1.4.0", "loose-envify": "^1.4.0",
"prop-types": "^15.7.2", "prop-types": "^15.7.2",
"react-is": "^16.9.0" "react-is": "^16.13.1"
} }
}, },
"react-refresh": { "react-refresh": {
@@ -41384,9 +41421,9 @@
} }
}, },
"scheduler": { "scheduler": {
"version": "0.19.1", "version": "0.20.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.19.1.tgz", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.2.tgz",
"integrity": "sha512-n/zwRWRYSUj0/3g/otKDRPMh6qv2SYMWNq85IEa8iZyAv8od9zDYpGSnpBEjNgcMNq6Scbu5KfIPxNF72R/2EA==", "integrity": "sha512-2eWfGgAqqWFGqtdMmcL5zCMK1U8KlXv8SQFGglL3CEtd0aDVDWgeF/YoCmvln55m5zSk3J/20hTaSBeSObsQDQ==",
"requires": { "requires": {
"loose-envify": "^1.1.0", "loose-envify": "^1.1.0",
"object-assign": "^4.1.1" "object-assign": "^4.1.1"
@@ -41412,12 +41449,6 @@
"resolved": "https://registry.npmjs.org/scrollparent/-/scrollparent-2.0.1.tgz", "resolved": "https://registry.npmjs.org/scrollparent/-/scrollparent-2.0.1.tgz",
"integrity": "sha1-cV1bnMV3YPsivczDvvtb/gaxoxc=" "integrity": "sha1-cV1bnMV3YPsivczDvvtb/gaxoxc="
}, },
"select": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/select/-/select-1.1.2.tgz",
"integrity": "sha1-DnNQrN7ICxEIUoeG7B1EGNEbOW0=",
"optional": true
},
"select-hose": { "select-hose": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz",
@@ -42798,12 +42829,6 @@
"resolved": "https://registry.npmjs.org/timsort/-/timsort-0.3.0.tgz", "resolved": "https://registry.npmjs.org/timsort/-/timsort-0.3.0.tgz",
"integrity": "sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q=" "integrity": "sha1-QFQRqOfmM5/mTbmiNN4R3DHgK9Q="
}, },
"tiny-emitter": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/tiny-emitter/-/tiny-emitter-2.1.0.tgz",
"integrity": "sha512-NB6Dk1A9xgQPMoGqC5CVXn123gWyte215ONT5Pp5a0yt4nlEoO1ZWeCwpncaekPHXO60i47ihFnZPiRPjRMq4Q==",
"optional": true
},
"tiny-invariant": { "tiny-invariant": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.1.0.tgz", "resolved": "https://registry.npmjs.org/tiny-invariant/-/tiny-invariant-1.1.0.tgz",
+11 -7
View File
@@ -5,7 +5,9 @@
"dependencies": { "dependencies": {
"@blockly/block-plus-minus": "^2.0.10", "@blockly/block-plus-minus": "^2.0.10",
"@blockly/field-slider": "^2.1.1", "@blockly/field-slider": "^2.1.1",
"@blockly/plugin-typed-variable-modal": "^3.1.1", "@blockly/plugin-scroll-options": "^1.0.2",
"@blockly/plugin-typed-variable-modal": "^3.1.26",
"@blockly/zoom-to-fit": "^2.0.7",
"@fortawesome/fontawesome-svg-core": "^1.2.30", "@fortawesome/fontawesome-svg-core": "^1.2.30",
"@fortawesome/free-solid-svg-icons": "^5.14.0", "@fortawesome/free-solid-svg-icons": "^5.14.0",
"@fortawesome/react-fontawesome": "^0.1.11", "@fortawesome/react-fontawesome": "^0.1.11",
@@ -16,16 +18,18 @@
"@testing-library/react": "^9.5.0", "@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1", "@testing-library/user-event": "^7.2.1",
"axios": "^0.21.0", "axios": "^0.21.0",
"blockly": "^3.20200924.0", "blockly": "^6.20210701.0",
"diff-js-xml": "^1.0.6",
"file-saver": "^2.0.2", "file-saver": "^2.0.2",
"mnemonic-id": "^3.2.7", "mnemonic-id": "^3.2.7",
"moment": "^2.28.0", "moment": "^2.28.0",
"prismjs": "^1.23.0", "prismjs": "^1.24.0",
"react": "^16.13.1", "react": "^17.0.2",
"react-cookie-consent": "^5.2.0", "react-cookie-consent": "^5.2.0",
"react-dom": "^16.13.1", "react-dom": "^17.0.2",
"react-markdown": "^5.0.2", "react-markdown": "^5.0.2",
"react-redux": "^7.2.0", "react-mde": "^11.5.0",
"react-redux": "^7.2.4",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "^4.0.3", "react-scripts": "^4.0.3",
"reactour": "^1.18.0", "reactour": "^1.18.0",
@@ -36,7 +40,7 @@
}, },
"scripts": { "scripts": {
"start": "react-scripts start", "start": "react-scripts start",
"dev": "set \"REACT_APP_BLOCKLY_API=http://localhost:8080\" && set \"REACT_APP_MYBADGES_API=http://localhost:3001/api/v1\"&& npm start", "dev": "set \"REACT_APP_BLOCKLY_API=http://localhost:8080\" && npm start",
"build": "react-scripts build", "build": "react-scripts build",
"test": "react-scripts test", "test": "react-scripts test",
"eject": "react-scripts eject" "eject": "react-scripts eject"
+7
View File
@@ -24,6 +24,13 @@
</head> </head>
<body> <body>
<noscript>You need to enable JavaScript to run this app.</noscript> <noscript>You need to enable JavaScript to run this app.</noscript>
<!-- Matomo Image Tracker-->
<img
src="https://piwik.sensebox.kaufen/matomo.php?idsite=9&amp;rec=1"
style="border: 0; display: none"
alt=""
/>
<!-- End Matomo -->
<div id="root"></div> <div id="root"></div>
<!-- <!--
This HTML file is a template. This HTML file is a template.
+114 -144
View File
@@ -1,245 +1,211 @@
import { MYBADGES_CONNECT, MYBADGES_DISCONNECT, GET_STATUS, USER_LOADED, USER_LOADING, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT_SUCCESS, LOGOUT_FAIL, REFRESH_TOKEN_SUCCESS } from '../actions/types'; import {
GET_STATUS,
USER_LOADED,
USER_LOADING,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT_SUCCESS,
LOGOUT_FAIL,
REFRESH_TOKEN_SUCCESS,
} from "../actions/types";
import axios from 'axios'; import axios from "axios";
import { returnErrors, returnSuccess } from './messageActions'; import { returnErrors, returnSuccess } from "./messageActions";
import { setLanguage } from './generalActions'; import { setLanguage } from "./generalActions";
// Check token & load user // Check token & load user
export const loadUser = () => (dispatch) => { export const loadUser = () => (dispatch) => {
// user loading // user loading
dispatch({ dispatch({
type: USER_LOADING type: USER_LOADING,
}); });
const config = { const config = {
success: res => { success: (res) => {
dispatch({ dispatch({
type: GET_STATUS, type: GET_STATUS,
payload: res.data.user.status payload: res.data.user.status,
}); });
dispatch(setLanguage(res.data.user.language)); dispatch(setLanguage(res.data.user.language));
dispatch({ dispatch({
type: USER_LOADED, type: USER_LOADED,
payload: res.data.user payload: res.data.user,
}); });
}, },
error: err => { error: (err) => {
if(err.response){ if (err.response) {
dispatch(returnErrors(err.response.data.message, err.response.status)); dispatch(returnErrors(err.response.data.message, err.response.status));
} }
var status = []; var status = [];
if (window.localStorage.getItem('status')) { if (window.localStorage.getItem("status")) {
status = JSON.parse(window.localStorage.getItem('status')); status = JSON.parse(window.localStorage.getItem("status"));
} }
dispatch({ dispatch({
type: GET_STATUS, type: GET_STATUS,
payload: status payload: status,
}); });
dispatch({ dispatch({
type: AUTH_ERROR type: AUTH_ERROR,
}); });
} },
}; };
axios.get(`${process.env.REACT_APP_BLOCKLY_API}/user`, config, dispatch(authInterceptor())) axios
.then(res => { .get(
`${process.env.REACT_APP_BLOCKLY_API}/user`,
config,
dispatch(authInterceptor())
)
.then((res) => {
res.config.success(res); res.config.success(res);
}) })
.catch(err => { .catch((err) => {
err.config.error(err); err.config.error(err);
}); });
}; };
var logoutTimerId; var logoutTimerId;
const timeToLogout = 14.9*60*1000; // nearly 15 minutes corresponding to the API const timeToLogout = 14.9 * 60 * 1000; // nearly 15 minutes corresponding to the API
// Login user // Login user
export const login = ({ email, password }) => (dispatch) => { export const login =
({ email, password }) =>
(dispatch) => {
dispatch({ dispatch({
type: USER_LOADING type: USER_LOADING,
}); });
// Headers // Headers
const config = { const config = {
headers: { headers: {
'Content-Type': 'application/json' "Content-Type": "application/json",
} },
}; };
// Request Body // Request Body
const body = JSON.stringify({ email, password }); const body = JSON.stringify({ email, password });
axios.post(`${process.env.REACT_APP_BLOCKLY_API}/user`, body, config) axios
.then(res => { .post(`${process.env.REACT_APP_BLOCKLY_API}/user`, body, config)
.then((res) => {
// Logout automatically if refreshToken "expired" // Logout automatically if refreshToken "expired"
const logoutTimer = () => setTimeout( const logoutTimer = () =>
() => dispatch(logout()), setTimeout(() => dispatch(logout()), timeToLogout);
timeToLogout
);
logoutTimerId = logoutTimer(); logoutTimerId = logoutTimer();
dispatch(setLanguage(res.data.user.language)); dispatch(setLanguage(res.data.user.language));
dispatch({ dispatch({
type: LOGIN_SUCCESS, type: LOGIN_SUCCESS,
payload: res.data payload: res.data,
}); });
dispatch({ dispatch({
type: GET_STATUS, type: GET_STATUS,
payload: res.data.user.status payload: res.data.user.status,
}); });
dispatch(returnSuccess(res.data.message, res.status, 'LOGIN_SUCCESS')); dispatch(returnSuccess(res.data.message, res.status, "LOGIN_SUCCESS"));
}) })
.catch(err => { .catch((err) => {
dispatch(returnErrors(err.response.data.message, err.response.status, 'LOGIN_FAIL')); dispatch(
returnErrors(
err.response.data.message,
err.response.status,
"LOGIN_FAIL"
)
);
dispatch({ dispatch({
type: LOGIN_FAIL type: LOGIN_FAIL,
}); });
var status = []; var status = [];
if (window.localStorage.getItem('status')) { if (window.localStorage.getItem("status")) {
status = JSON.parse(window.localStorage.getItem('status')); status = JSON.parse(window.localStorage.getItem("status"));
} }
dispatch({ dispatch({
type: GET_STATUS, type: GET_STATUS,
payload: status payload: status,
}); });
}); });
};
// Connect to MyBadges-Account
export const connectMyBadges = ({ username, password }) => (dispatch, getState) => {
const config = {
success: res => {
var user = getState().auth.user;
user.badge = res.data.account;
user.badges = res.data.badges;
dispatch({
type: MYBADGES_CONNECT,
payload: user
});
dispatch(returnSuccess(res.data.message, res.status, 'MYBADGES_CONNECT_SUCCESS'));
},
error: err => {
dispatch(returnErrors(err.response.data.message, err.response.status, 'MYBADGES_CONNECT_FAIL'));
}
}; };
// Request Body
const body = JSON.stringify({ username, password });
axios.post(`${process.env.REACT_APP_BLOCKLY_API}/user/badge`, body, config)
.then(res => {
res.config.success(res);
})
.catch(err => {
if(err.response && err.response.status !== 401){
err.config.error(err);
}
});
};
// Disconnect MyBadges-Account
export const disconnectMyBadges = () => (dispatch, getState) => {
const config = {
success: res => {
var user = getState().auth.user;
user.badge = null;
user.badges = null;
dispatch({
type: MYBADGES_DISCONNECT,
payload: user
});
dispatch(returnSuccess(res.data.message, res.status, 'MYBADGES_DISCONNECT_SUCCESS'));
},
error: err => {
dispatch(returnErrors(err.response.data.message, err.response.status, 'MYBADGES_DISCONNECT_FAIL'));
}
};
axios.put(`${process.env.REACT_APP_BLOCKLY_API}/user/badge`, {}, config)
.then(res => {
res.config.success(res);
})
.catch(err => {
if(err.response && err.response.status !== 401){
err.config.error(err);
}
});
};
// Logout User // Logout User
export const logout = () => (dispatch) => { export const logout = () => (dispatch) => {
const config = { const config = {
success: res => { success: (res) => {
dispatch({ dispatch({
type: LOGOUT_SUCCESS type: LOGOUT_SUCCESS,
}); });
var status = []; var status = [];
if (window.localStorage.getItem('status')) { if (window.localStorage.getItem("status")) {
status = JSON.parse(window.localStorage.getItem('status')); status = JSON.parse(window.localStorage.getItem("status"));
} }
dispatch({ dispatch({
type: GET_STATUS, type: GET_STATUS,
payload: status payload: status,
}); });
var locale = 'en_US'; var locale = "en_US";
if (window.localStorage.getItem('locale')) { if (window.localStorage.getItem("locale")) {
locale = window.localStorage.getItem('locale'); locale = window.localStorage.getItem("locale");
} } else if (navigator.language === "de-DE") {
else if (navigator.language === 'de-DE'){ locale = "de_DE";
locale = 'de_DE';
} }
dispatch(setLanguage(locale)); dispatch(setLanguage(locale));
dispatch(returnSuccess(res.data.message, res.status, 'LOGOUT_SUCCESS')); dispatch(returnSuccess(res.data.message, res.status, "LOGOUT_SUCCESS"));
clearTimeout(logoutTimerId); clearTimeout(logoutTimerId);
}, },
error: err => { error: (err) => {
dispatch(returnErrors(err.response.data.message, err.response.status, 'LOGOUT_FAIL')); dispatch(
returnErrors(
err.response.data.message,
err.response.status,
"LOGOUT_FAIL"
)
);
dispatch({ dispatch({
type: LOGOUT_FAIL type: LOGOUT_FAIL,
}); });
var status = []; var status = [];
if (window.localStorage.getItem('status')) { if (window.localStorage.getItem("status")) {
status = JSON.parse(window.localStorage.getItem('status')); status = JSON.parse(window.localStorage.getItem("status"));
} }
dispatch({ dispatch({
type: GET_STATUS, type: GET_STATUS,
payload: status payload: status,
}); });
clearTimeout(logoutTimerId); clearTimeout(logoutTimerId);
} },
}; };
axios.post('https://api.opensensemap.org/users/sign-out', {}, config) axios
.then(res => { .post("https://api.opensensemap.org/users/sign-out", {}, config)
.then((res) => {
res.config.success(res); res.config.success(res);
}) })
.catch(err => { .catch((err) => {
if(err.response && err.response.status !== 401){ if (err.response && err.response.status !== 401) {
err.config.error(err); err.config.error(err);
} }
}); });
}; };
export const authInterceptor = () => (dispatch, getState) => { export const authInterceptor = () => (dispatch, getState) => {
// Add a request interceptor // Add a request interceptor
axios.interceptors.request.use( axios.interceptors.request.use(
config => { (config) => {
config.headers['Content-Type'] = 'application/json'; config.headers["Content-Type"] = "application/json";
const token = getState().auth.token; const token = getState().auth.token;
if (token) { if (token) {
config.headers['Authorization'] = `Bearer ${token}`; config.headers["Authorization"] = `Bearer ${token}`;
} }
return config; return config;
}, },
error => { (error) => {
Promise.reject(error); Promise.reject(error);
} }
); );
// Add a response interceptor // Add a response interceptor
axios.interceptors.response.use( axios.interceptors.response.use(
response => { (response) => {
// request was successfull // request was successfull
return response; return response;
}, },
error => { (error) => {
const originalRequest = error.config; const originalRequest = error.config;
const refreshToken = getState().auth.refreshToken; const refreshToken = getState().auth.refreshToken;
if(refreshToken){ if (refreshToken) {
// try to refresh the token failed // try to refresh the token failed
if (error.response.status === 401 && originalRequest._retry) { if (error.response.status === 401 && originalRequest._retry) {
// router.push('/login'); // router.push('/login');
@@ -250,38 +216,42 @@ export const authInterceptor = () => (dispatch, getState) => {
originalRequest._retry = true; originalRequest._retry = true;
const refreshToken = getState().auth.refreshToken; const refreshToken = getState().auth.refreshToken;
// request to refresh the token, in request-body is the refreshToken // request to refresh the token, in request-body is the refreshToken
axios.post('https://api.opensensemap.org/users/refresh-auth', {"token": refreshToken}) axios
.then(res => { .post("https://api.opensensemap.org/users/refresh-auth", {
token: refreshToken,
})
.then((res) => {
if (res.status === 200) { if (res.status === 200) {
clearTimeout(logoutTimerId); clearTimeout(logoutTimerId);
const logoutTimer = () => setTimeout( const logoutTimer = () =>
() => dispatch(logout()), setTimeout(() => dispatch(logout()), timeToLogout);
timeToLogout
);
logoutTimerId = logoutTimer(); logoutTimerId = logoutTimer();
dispatch({ dispatch({
type: REFRESH_TOKEN_SUCCESS, type: REFRESH_TOKEN_SUCCESS,
payload: res.data payload: res.data,
}); });
axios.defaults.headers.common['Authorization'] = 'Bearer ' + getState().auth.token; axios.defaults.headers.common["Authorization"] =
"Bearer " + getState().auth.token;
// request was successfull, new request with the old parameters and the refreshed token // request was successfull, new request with the old parameters and the refreshed token
return axios(originalRequest) return axios(originalRequest)
.then(res => { .then((res) => {
originalRequest.success(res); originalRequest.success(res);
}) })
.catch(err => { .catch((err) => {
originalRequest.error(err); originalRequest.error(err);
}); });
} }
return Promise.reject(error); return Promise.reject(error);
}) })
.catch(err => { .catch((err) => {
// request failed, token could not be refreshed // request failed, token could not be refreshed
if(err.response){ if (err.response) {
dispatch(returnErrors(err.response.data.message, err.response.status)); dispatch(
returnErrors(err.response.data.message, err.response.status)
);
} }
dispatch({ dispatch({
type: AUTH_ERROR type: AUTH_ERROR,
}); });
return Promise.reject(error); return Promise.reject(error);
}); });
+128 -102
View File
@@ -1,109 +1,105 @@
import { MYBADGES_DISCONNECT, TUTORIAL_PROGRESS, GET_TUTORIAL, GET_TUTORIALS, TUTORIAL_SUCCESS, TUTORIAL_ERROR, TUTORIAL_CHANGE, TUTORIAL_XML, TUTORIAL_STEP } from './types'; import {
TUTORIAL_PROGRESS,
GET_TUTORIAL,
GET_TUTORIALS,
TUTORIAL_SUCCESS,
TUTORIAL_ERROR,
TUTORIAL_CHANGE,
TUTORIAL_XML,
TUTORIAL_STEP,
} from "./types";
import axios from 'axios'; import axios from "axios";
import { returnErrors, returnSuccess } from './messageActions'; import { returnErrors, returnSuccess } from "./messageActions";
export const tutorialProgress = () => (dispatch) => { export const tutorialProgress = () => (dispatch) => {
dispatch({type: TUTORIAL_PROGRESS}); dispatch({ type: TUTORIAL_PROGRESS });
}; };
export const getTutorial = (id) => (dispatch, getState) => { export const getTutorial = (id) => (dispatch, getState) => {
axios.get(`${process.env.REACT_APP_BLOCKLY_API}/tutorial/${id}`) axios
.then(res => { .get(`${process.env.REACT_APP_BLOCKLY_API}/tutorial/${id}`)
.then((res) => {
var tutorial = res.data.tutorial; var tutorial = res.data.tutorial;
existingTutorial(tutorial, getState().tutorial.status).then(status => { existingTutorial(tutorial, getState().tutorial.status).then((status) => {
dispatch({ dispatch({
type: TUTORIAL_SUCCESS, type: TUTORIAL_SUCCESS,
payload: status payload: status,
}); });
dispatch(updateStatus(status)); dispatch(updateStatus(status));
dispatch({ dispatch({
type: GET_TUTORIAL, type: GET_TUTORIAL,
payload: tutorial payload: tutorial,
}); });
dispatch({type: TUTORIAL_PROGRESS}); dispatch({ type: TUTORIAL_PROGRESS });
dispatch(returnSuccess(res.data.message, res.status)); dispatch(returnSuccess(res.data.message, res.status));
}); });
}) })
.catch(err => { .catch((err) => {
if (err.response) { if (err.response) {
dispatch(returnErrors(err.response.data.message, err.response.status, 'GET_TUTORIAL_FAIL')); dispatch(
returnErrors(
err.response.data.message,
err.response.status,
"GET_TUTORIAL_FAIL"
)
);
} }
dispatch({ type: TUTORIAL_PROGRESS }); dispatch({ type: TUTORIAL_PROGRESS });
}); });
}; };
export const getTutorials = () => (dispatch, getState) => { export const getTutorials = () => (dispatch, getState) => {
axios.get(`${process.env.REACT_APP_BLOCKLY_API}/tutorial`) axios
.then(res => { .get(`${process.env.REACT_APP_BLOCKLY_API}/tutorial`)
.then((res) => {
var tutorials = res.data.tutorials; var tutorials = res.data.tutorials;
console.log(tutorials); existingTutorials(tutorials, getState().tutorial.status).then(
existingTutorials(tutorials, getState().tutorial.status).then(status => { (status) => {
dispatch({ dispatch({
type: TUTORIAL_SUCCESS, type: TUTORIAL_SUCCESS,
payload: status payload: status,
}); });
console.log('zwei');
dispatch(updateStatus(status)); dispatch(updateStatus(status));
dispatch({ dispatch({
type: GET_TUTORIALS, type: GET_TUTORIALS,
payload: tutorials payload: tutorials,
}); });
dispatch({ type: TUTORIAL_PROGRESS }); dispatch({ type: TUTORIAL_PROGRESS });
dispatch(returnSuccess(res.data.message, res.status)); dispatch(returnSuccess(res.data.message, res.status));
}); }
);
}) })
.catch(err => { .catch((err) => {
if (err.response) { if (err.response) {
dispatch(returnErrors(err.response.data.message, err.response.status, 'GET_TUTORIALS_FAIL')); dispatch(
returnErrors(
err.response.data.message,
err.response.status,
"GET_TUTORIALS_FAIL"
)
);
} }
dispatch({ type: TUTORIAL_PROGRESS }); dispatch({ type: TUTORIAL_PROGRESS });
}); });
}; };
export const assigneBadge = (id) => (dispatch, getState) => {
const config = {
success: res => {
var badge = res.data.badge;
var user = getState().auth.user;
user.badges.push(badge._id);
dispatch({
type: MYBADGES_DISCONNECT,
payload: user
});
dispatch(returnSuccess(badge, res.status, 'ASSIGNE_BADGE_SUCCESS'));
},
error: err => {
dispatch(returnErrors(err.response.data.message, err.response.status, 'ASSIGNE_BADGE_FAIL'));
}
};
axios.put(`${process.env.REACT_APP_BLOCKLY_API}/user/badge/${id}`, {}, config)
.then(res => {
res.config.success(res);
})
.catch(err => {
if(err.response && err.response.status !== 401){
err.config.error(err);
}
});
};
export const updateStatus = (status) => (dispatch, getState) => { export const updateStatus = (status) => (dispatch, getState) => {
if(getState().auth.isAuthenticated){ if (getState().auth.isAuthenticated) {
// update user account in database - sync with redux store // update user account in database - sync with redux store
axios.put(`${process.env.REACT_APP_BLOCKLY_API}/user/status`, {status: status}) axios
.then(res => { .put(`${process.env.REACT_APP_BLOCKLY_API}/user/status`, {
// dispatch(returnSuccess(badge, res.status, 'UPDATE_STATUS_SUCCESS')); status: status,
}) })
.catch(err => { .then((res) => {})
if(err.response){ .catch((err) => {
if (err.response) {
// dispatch(returnErrors(err.response.data.message, err.response.status, 'UPDATE_STATUS_FAIL')); // dispatch(returnErrors(err.response.data.message, err.response.status, 'UPDATE_STATUS_FAIL'));
} }
}); });
} else { } else {
// update locale storage - sync with redux store // update locale storage - sync with redux store
window.localStorage.setItem('status', JSON.stringify(status)); window.localStorage.setItem("status", JSON.stringify(status));
} }
}; };
@@ -111,66 +107,77 @@ export const deleteTutorial = (id) => (dispatch, getState) => {
var tutorial = getState().tutorial; var tutorial = getState().tutorial;
var id = getState().builder.id; var id = getState().builder.id;
const config = { const config = {
success: res => { success: (res) => {
var tutorials = tutorial.tutorials; var tutorials = tutorial.tutorials;
var index = tutorials.findIndex(res => res._id === id); var index = tutorials.findIndex((res) => res._id === id);
tutorials.splice(index, 1) tutorials.splice(index, 1);
dispatch({ dispatch({
type: GET_TUTORIALS, type: GET_TUTORIALS,
payload: tutorials payload: tutorials,
}); });
dispatch(returnSuccess(res.data.message, res.status, 'TUTORIAL_DELETE_SUCCESS')); dispatch(
returnSuccess(res.data.message, res.status, "TUTORIAL_DELETE_SUCCESS")
);
},
error: (err) => {
dispatch(
returnErrors(
err.response.data.message,
err.response.status,
"TUTORIAL_DELETE_FAIL"
)
);
}, },
error: err => {
dispatch(returnErrors(err.response.data.message, err.response.status, 'TUTORIAL_DELETE_FAIL'));
}
}; };
axios.delete(`${process.env.REACT_APP_BLOCKLY_API}/tutorial/${id}`, config) axios
.then(res => { .delete(`${process.env.REACT_APP_BLOCKLY_API}/tutorial/${id}`, config)
.then((res) => {
res.config.success(res); res.config.success(res);
}) })
.catch(err => { .catch((err) => {
if(err.response && err.response.status !== 401){ if (err.response && err.response.status !== 401) {
err.config.error(err); err.config.error(err);
} }
}); });
}; };
export const resetTutorial = () => (dispatch) => { export const resetTutorial = () => (dispatch) => {
dispatch({ dispatch({
type: GET_TUTORIALS, type: GET_TUTORIALS,
payload: [] payload: [],
}); });
dispatch({ dispatch({
type: TUTORIAL_STEP, type: TUTORIAL_STEP,
payload: 0 payload: 0,
}); });
}; };
export const tutorialChange = () => (dispatch) => { export const tutorialChange = () => (dispatch) => {
dispatch({ dispatch({
type: TUTORIAL_CHANGE type: TUTORIAL_CHANGE,
}); });
}; };
export const tutorialCheck = (status, step) => (dispatch, getState) => { export const tutorialCheck = (status, step) => (dispatch, getState) => {
var tutorialsStatus = getState().tutorial.status; var tutorialsStatus = getState().tutorial.status;
var id = getState().tutorial.tutorials[0]._id; var id = getState().tutorial.tutorials[0]._id;
var tutorialsStatusIndex = tutorialsStatus.findIndex(tutorialStatus => tutorialStatus._id === id); var tutorialsStatusIndex = tutorialsStatus.findIndex(
var tasksIndex = tutorialsStatus[tutorialsStatusIndex].tasks.findIndex(task => task._id === step._id); (tutorialStatus) => tutorialStatus._id === id
);
var tasksIndex = tutorialsStatus[tutorialsStatusIndex].tasks.findIndex(
(task) => task._id === step._id
);
tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex] = { tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex] = {
...tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex], ...tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex],
type: status type: status,
}; };
dispatch({ dispatch({
type: status === 'success' ? TUTORIAL_SUCCESS : TUTORIAL_ERROR, type: status === "success" ? TUTORIAL_SUCCESS : TUTORIAL_ERROR,
payload: tutorialsStatus payload: tutorialsStatus,
}); });
console.log('drei');
dispatch(updateStatus(tutorialsStatus)); dispatch(updateStatus(tutorialsStatus));
dispatch(tutorialChange()); dispatch(tutorialChange());
dispatch(returnSuccess('', '', 'TUTORIAL_CHECK_SUCCESS')); dispatch(returnSuccess("", "", "TUTORIAL_CHECK_SUCCESS"));
}; };
export const storeTutorialXml = (code) => (dispatch, getState) => { export const storeTutorialXml = (code) => (dispatch, getState) => {
@@ -179,17 +186,21 @@ export const storeTutorialXml = (code) => (dispatch, getState) => {
var id = tutorial._id; var id = tutorial._id;
var activeStep = getState().tutorial.activeStep; var activeStep = getState().tutorial.activeStep;
var steps = tutorial.steps; var steps = tutorial.steps;
if (steps && steps[activeStep].type === 'task') { if (steps && steps[activeStep].type === "task") {
var tutorialsStatus = getState().tutorial.status; var tutorialsStatus = getState().tutorial.status;
var tutorialsStatusIndex = tutorialsStatus.findIndex(tutorialStatus => tutorialStatus._id === id); var tutorialsStatusIndex = tutorialsStatus.findIndex(
var tasksIndex = tutorialsStatus[tutorialsStatusIndex].tasks.findIndex(task => task._id === steps[activeStep]._id); (tutorialStatus) => tutorialStatus._id === id
);
var tasksIndex = tutorialsStatus[tutorialsStatusIndex].tasks.findIndex(
(task) => task._id === steps[activeStep]._id
);
tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex] = { tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex] = {
...tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex], ...tutorialsStatus[tutorialsStatusIndex].tasks[tasksIndex],
xml: code xml: code,
}; };
dispatch({ dispatch({
type: TUTORIAL_XML, type: TUTORIAL_XML,
payload: tutorialsStatus payload: tutorialsStatus,
}); });
dispatch(updateStatus(tutorialsStatus)); dispatch(updateStatus(tutorialsStatus));
} }
@@ -199,38 +210,45 @@ export const storeTutorialXml = (code) => (dispatch, getState) => {
export const tutorialStep = (step) => (dispatch) => { export const tutorialStep = (step) => (dispatch) => {
dispatch({ dispatch({
type: TUTORIAL_STEP, type: TUTORIAL_STEP,
payload: step payload: step,
}); });
}; };
const existingTutorials = (tutorials, status) =>
const existingTutorials = (tutorials, status) => new Promise(function (resolve, reject) { new Promise(function (resolve, reject) {
var newstatus; var newstatus;
new Promise(function (resolve, reject) { new Promise(function (resolve, reject) {
var existingTutorialIds = tutorials.map((tutorial, i) => { var existingTutorialIds = tutorials.map((tutorial, i) => {
existingTutorial(tutorial, status).then(status => { existingTutorial(tutorial, status).then((status) => {
newstatus = status; newstatus = status;
}); });
return tutorial._id; return tutorial._id;
}); });
resolve(existingTutorialIds) resolve(existingTutorialIds);
}).then(existingTutorialIds => { }).then((existingTutorialIds) => {
// deleting old tutorials which do not longer exist // deleting old tutorials which do not longer exist
if (existingTutorialIds.length > 0) { if (existingTutorialIds.length > 0) {
status = newstatus.filter(status => existingTutorialIds.indexOf(status._id) > -1); status = newstatus.filter(
(status) => existingTutorialIds.indexOf(status._id) > -1
);
} }
resolve(status); resolve(status);
}); });
}); });
const existingTutorial = (tutorial, status) => new Promise(function(resolve, reject){ const existingTutorial = (tutorial, status) =>
new Promise(function (resolve, reject) {
var tutorialsId = tutorial._id; var tutorialsId = tutorial._id;
var statusIndex = status.findIndex(status => status._id === tutorialsId); var statusIndex = status.findIndex((status) => status._id === tutorialsId);
if (statusIndex > -1) { if (statusIndex > -1) {
var tasks = tutorial.steps.filter(step => step.type === 'task'); var tasks = tutorial.steps.filter((step) => step.type === "task");
var existingTaskIds = tasks.map((task, j) => { var existingTaskIds = tasks.map((task, j) => {
var tasksId = task._id; var tasksId = task._id;
if (status[statusIndex].tasks.findIndex(task => task._id === tasksId) === -1) { if (
status[statusIndex].tasks.findIndex(
(task) => task._id === tasksId
) === -1
) {
// task does not exist // task does not exist
status[statusIndex].tasks.push({ _id: tasksId }); status[statusIndex].tasks.push({ _id: tasksId });
} }
@@ -238,11 +256,19 @@ const existingTutorial = (tutorial, status) => new Promise(function(resolve, rej
}); });
// deleting old tasks which do not longer exist // deleting old tasks which do not longer exist
if (existingTaskIds.length > 0) { if (existingTaskIds.length > 0) {
status[statusIndex].tasks = status[statusIndex].tasks.filter(task => existingTaskIds.indexOf(task._id) > -1); status[statusIndex].tasks = status[statusIndex].tasks.filter(
(task) => existingTaskIds.indexOf(task._id) > -1
);
} }
} } else {
else { status.push({
status.push({ _id: tutorialsId, tasks: tutorial.steps.filter(step => step.type === 'task').map(task => { return { _id: task._id }; }) }); _id: tutorialsId,
tasks: tutorial.steps
.filter((step) => step.type === "task")
.map((task) => {
return { _id: task._id };
}),
});
} }
resolve(status); resolve(status);
}); });
+89 -78
View File
@@ -1,24 +1,36 @@
import { PROGRESS, JSON_STRING, BUILDER_CHANGE, BUILDER_ERROR, BUILDER_TITLE, BUILDER_ID, BUILDER_BADGE, BUILDER_ADD_STEP, BUILDER_DELETE_STEP, BUILDER_CHANGE_STEP, BUILDER_CHANGE_ORDER, BUILDER_DELETE_PROPERTY } from './types'; import {
PROGRESS,
JSON_STRING,
BUILDER_CHANGE,
BUILDER_ERROR,
BUILDER_TITLE,
BUILDER_ID,
BUILDER_ADD_STEP,
BUILDER_DELETE_STEP,
BUILDER_CHANGE_STEP,
BUILDER_CHANGE_ORDER,
BUILDER_DELETE_PROPERTY,
} from "./types";
import data from '../data/hardware.json'; import data from "../data/hardware.json";
export const changeTutorialBuilder = () => (dispatch) => { export const changeTutorialBuilder = () => (dispatch) => {
dispatch({ dispatch({
type: BUILDER_CHANGE type: BUILDER_CHANGE,
}); });
}; };
export const jsonString = (json) => (dispatch) => { export const jsonString = (json) => (dispatch) => {
dispatch({ dispatch({
type: JSON_STRING, type: JSON_STRING,
payload: json payload: json,
}); });
}; };
export const tutorialTitle = (title) => (dispatch) => { export const tutorialTitle = (title) => (dispatch) => {
dispatch({ dispatch({
type: BUILDER_TITLE, type: BUILDER_TITLE,
payload: title payload: title,
}); });
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
@@ -26,7 +38,7 @@ export const tutorialTitle = (title) => (dispatch) => {
export const tutorialSteps = (steps) => (dispatch) => { export const tutorialSteps = (steps) => (dispatch) => {
dispatch({ dispatch({
type: BUILDER_ADD_STEP, type: BUILDER_ADD_STEP,
payload: steps payload: steps,
}); });
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
@@ -34,15 +46,7 @@ export const tutorialSteps = (steps) => (dispatch) => {
export const tutorialId = (id) => (dispatch) => { export const tutorialId = (id) => (dispatch) => {
dispatch({ dispatch({
type: BUILDER_ID, type: BUILDER_ID,
payload: id payload: id,
});
dispatch(changeTutorialBuilder());
};
export const tutorialBadge = (badge) => (dispatch) => {
dispatch({
type: BUILDER_BADGE,
payload: badge
}); });
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
@@ -51,14 +55,14 @@ export const addStep = (index) => (dispatch, getState) => {
var steps = getState().builder.steps; var steps = getState().builder.steps;
var step = { var step = {
id: index + 1, id: index + 1,
type: 'instruction', type: "instruction",
headline: '', headline: "",
text: '' text: "",
}; };
steps.splice(index, 0, step); steps.splice(index, 0, step);
dispatch({ dispatch({
type: BUILDER_ADD_STEP, type: BUILDER_ADD_STEP,
payload: steps payload: steps,
}); });
dispatch(addErrorStep(index)); dispatch(addErrorStep(index));
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
@@ -69,7 +73,7 @@ export const addErrorStep = (index) => (dispatch, getState) => {
error.steps.splice(index, 0, {}); error.steps.splice(index, 0, {});
dispatch({ dispatch({
type: BUILDER_ERROR, type: BUILDER_ERROR,
payload: error payload: error,
}); });
}; };
@@ -78,7 +82,7 @@ export const removeStep = (index) => (dispatch, getState) => {
steps.splice(index, 1); steps.splice(index, 1);
dispatch({ dispatch({
type: BUILDER_DELETE_STEP, type: BUILDER_DELETE_STEP,
payload: steps payload: steps,
}); });
dispatch(removeErrorStep(index)); dispatch(removeErrorStep(index));
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
@@ -89,11 +93,12 @@ export const removeErrorStep = (index) => (dispatch, getState) => {
error.steps.splice(index, 1); error.steps.splice(index, 1);
dispatch({ dispatch({
type: BUILDER_ERROR, type: BUILDER_ERROR,
payload: error payload: error,
}); });
}; };
export const changeContent = (content, index, property1, property2) => (dispatch, getState) => { export const changeContent =
(content, index, property1, property2) => (dispatch, getState) => {
var steps = getState().builder.steps; var steps = getState().builder.steps;
var step = steps[index]; var step = steps[index];
if (property2) { if (property2) {
@@ -107,12 +112,13 @@ export const changeContent = (content, index, property1, property2) => (dispatch
} }
dispatch({ dispatch({
type: BUILDER_CHANGE_STEP, type: BUILDER_CHANGE_STEP,
payload: steps payload: steps,
}); });
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
export const deleteProperty = (index, property1, property2) => (dispatch, getState) => { export const deleteProperty =
(index, property1, property2) => (dispatch, getState) => {
var steps = getState().builder.steps; var steps = getState().builder.steps;
var step = steps[index]; var step = steps[index];
if (property2) { if (property2) {
@@ -124,10 +130,10 @@ export const deleteProperty = (index, property1, property2) => (dispatch, getSta
} }
dispatch({ dispatch({
type: BUILDER_DELETE_PROPERTY, type: BUILDER_DELETE_PROPERTY,
payload: steps payload: steps,
}); });
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
export const changeStepIndex = (fromIndex, toIndex) => (dispatch, getState) => { export const changeStepIndex = (fromIndex, toIndex) => (dispatch, getState) => {
var steps = getState().builder.steps; var steps = getState().builder.steps;
@@ -136,34 +142,34 @@ export const changeStepIndex = (fromIndex, toIndex) => (dispatch, getState) => {
steps.splice(toIndex, 0, step); steps.splice(toIndex, 0, step);
dispatch({ dispatch({
type: BUILDER_CHANGE_ORDER, type: BUILDER_CHANGE_ORDER,
payload: steps payload: steps,
}); });
dispatch(changeErrorStepIndex(fromIndex, toIndex)); dispatch(changeErrorStepIndex(fromIndex, toIndex));
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
export const changeErrorStepIndex = (fromIndex, toIndex) => (dispatch, getState) => { export const changeErrorStepIndex =
(fromIndex, toIndex) => (dispatch, getState) => {
var error = getState().builder.error; var error = getState().builder.error;
var errorStep = error.steps[fromIndex]; var errorStep = error.steps[fromIndex];
error.steps.splice(fromIndex, 1); error.steps.splice(fromIndex, 1);
error.steps.splice(toIndex, 0, errorStep); error.steps.splice(toIndex, 0, errorStep);
dispatch({ dispatch({
type: BUILDER_ERROR, type: BUILDER_ERROR,
payload: error payload: error,
}); });
}; };
export const setError = (index, property) => (dispatch, getState) => { export const setError = (index, property) => (dispatch, getState) => {
var error = getState().builder.error; var error = getState().builder.error;
if (index !== undefined) { if (index !== undefined) {
error.steps[index][property] = true; error.steps[index][property] = true;
} } else {
else {
error[property] = true; error[property] = true;
} }
dispatch({ dispatch({
type: BUILDER_ERROR, type: BUILDER_ERROR,
payload: error payload: error,
}); });
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
@@ -172,13 +178,12 @@ export const deleteError = (index, property) => (dispatch, getState) => {
var error = getState().builder.error; var error = getState().builder.error;
if (index !== undefined) { if (index !== undefined) {
delete error.steps[index][property]; delete error.steps[index][property];
} } else {
else {
delete error[property]; delete error[property];
} }
dispatch({ dispatch({
type: BUILDER_ERROR, type: BUILDER_ERROR,
payload: error payload: error,
}); });
dispatch(changeTutorialBuilder()); dispatch(changeTutorialBuilder());
}; };
@@ -188,11 +193,11 @@ export const setSubmitError = () => (dispatch, getState) => {
// if(builder.id === undefined || builder.id === ''){ // if(builder.id === undefined || builder.id === ''){
// dispatch(setError(undefined, 'id')); // dispatch(setError(undefined, 'id'));
// } // }
if (builder.title === '') { if (builder.title === "") {
dispatch(setError(undefined, 'title')); dispatch(setError(undefined, "title"));
} }
if (builder.title === null) { if (builder.title === null) {
dispatch(setError(undefined, 'badge')); dispatch(setError(undefined, "title"));
} }
var type = builder.steps.map((step, i) => { var type = builder.steps.map((step, i) => {
// media and xml are directly checked for errors in their components and // media and xml are directly checked for errors in their components and
@@ -200,76 +205,82 @@ export const setSubmitError = () => (dispatch, getState) => {
step.id = i + 1; step.id = i + 1;
if (i === 0) { if (i === 0) {
if (step.requirements && step.requirements.length > 0) { if (step.requirements && step.requirements.length > 0) {
var requirements = step.requirements.filter(requirement => /^[0-9a-fA-F]{24}$/.test(requirement)); var requirements = step.requirements.filter((requirement) =>
/^[0-9a-fA-F]{24}$/.test(requirement)
);
if (requirements.length < step.requirements.length) { if (requirements.length < step.requirements.length) {
dispatch(changeContent(requirements, i, 'requirements')); dispatch(changeContent(requirements, i, "requirements"));
} }
} }
if (step.hardware === undefined || step.hardware.length < 1) { if (step.hardware === undefined || step.hardware.length < 1) {
dispatch(setError(i, 'hardware')); dispatch(setError(i, "hardware"));
} } else {
else { var hardwareIds = data.map((hardware) => hardware.id);
var hardwareIds = data.map(hardware => hardware.id); var hardware = step.hardware.filter((hardware) =>
var hardware = step.hardware.filter(hardware => hardwareIds.includes(hardware)); hardwareIds.includes(hardware)
);
if (hardware.length < step.hardware.length) { if (hardware.length < step.hardware.length) {
dispatch(changeContent(hardware, i, 'hardware')); dispatch(changeContent(hardware, i, "hardware"));
} }
} }
} }
if (step.headline === undefined || step.headline === '') { if (step.headline === undefined || step.headline === "") {
dispatch(setError(i, 'headline')); dispatch(setError(i, "headline"));
} }
if (step.text === undefined || step.text === '') { if (step.text === undefined || step.text === "") {
dispatch(setError(i, 'text')); dispatch(setError(i, "text"));
} }
return step.type; return step.type;
}); });
if (!(type.filter(item => item === 'task').length > 0 && type.filter(item => item === 'instruction').length > 0)) { if (
dispatch(setError(undefined, 'type')); !(
type.filter((item) => item === "task").length > 0 &&
type.filter((item) => item === "instruction").length > 0
)
) {
dispatch(setError(undefined, "type"));
} }
}; };
export const checkError = () => (dispatch, getState) => { export const checkError = () => (dispatch, getState) => {
dispatch(setSubmitError()); dispatch(setSubmitError());
var error = getState().builder.error; var error = getState().builder.error;
if (error.id || error.title || error.badge ||error.type) { if (error.id || error.title || error.type) {
return true; return true;
} }
for (var i = 0; i < error.steps.length; i++) { for (var i = 0; i < error.steps.length; i++) {
if (Object.keys(error.steps[i]).length > 0) { if (Object.keys(error.steps[i]).length > 0) {
return true return true;
} }
} }
return false; return false;
} };
export const progress = (inProgress) => (dispatch) => { export const progress = (inProgress) => (dispatch) => {
dispatch({ dispatch({
type: PROGRESS, type: PROGRESS,
payload: inProgress payload: inProgress,
}) });
}; };
export const resetTutorial = () => (dispatch, getState) => { export const resetTutorial = () => (dispatch, getState) => {
dispatch(jsonString('')); dispatch(jsonString(""));
dispatch(tutorialTitle('')); dispatch(tutorialTitle(""));
dispatch(tutorialBadge(undefined));
var steps = [ var steps = [
{ {
type: 'instruction', type: "instruction",
headline: '', headline: "",
text: '', text: "",
hardware: [], hardware: [],
requirements: [] requirements: [],
} },
]; ];
dispatch(tutorialSteps(steps)); dispatch(tutorialSteps(steps));
dispatch({ dispatch({
type: BUILDER_ERROR, type: BUILDER_ERROR,
payload: { payload: {
steps: [{}] steps: [{}],
} },
}); });
}; };
@@ -278,8 +289,10 @@ export const readJSON = (json) => (dispatch, getState) => {
dispatch({ dispatch({
type: BUILDER_ERROR, type: BUILDER_ERROR,
payload: { payload: {
steps: json.steps.map(() => { return {}; }) steps: json.steps.map(() => {
} return {};
}),
},
}); });
// accept only valid attributes // accept only valid attributes
var steps = json.steps.map((step, i) => { var steps = json.steps.map((step, i) => {
@@ -287,7 +300,7 @@ export const readJSON = (json) => (dispatch, getState) => {
_id: step._id, _id: step._id,
type: step.type, type: step.type,
headline: step.headline, headline: step.headline,
text: step.text text: step.text,
}; };
if (i === 0) { if (i === 0) {
object.hardware = step.hardware; object.hardware = step.hardware;
@@ -296,19 +309,17 @@ export const readJSON = (json) => (dispatch, getState) => {
if (step.xml) { if (step.xml) {
object.xml = step.xml; object.xml = step.xml;
} }
if (step.media && step.type === 'instruction') { if (step.media && step.type === "instruction") {
object.media = {}; object.media = {};
if (step.media.picture) { if (step.media.picture) {
object.media.picture = step.media.picture; object.media.picture = step.media.picture;
} } else if (step.media.youtube) {
else if (step.media.youtube) {
object.media.youtube = step.media.youtube; object.media.youtube = step.media.youtube;
} }
} }
return object; return object;
}); });
dispatch(tutorialTitle(json.title)); dispatch(tutorialTitle(json.title));
dispatch(tutorialBadge(json.badge));
dispatch(tutorialSteps(steps)); dispatch(tutorialSteps(steps));
dispatch(setSubmitError()); dispatch(setSubmitError());
dispatch(progress(false)); dispatch(progress(false));
+50 -56
View File
@@ -1,65 +1,59 @@
// authentication // authentication
export const USER_LOADING = 'USER_LOADING'; export const USER_LOADING = "USER_LOADING";
export const USER_LOADED = 'USER_LOADED'; export const USER_LOADED = "USER_LOADED";
export const AUTH_ERROR = 'AUTH_ERROR'; export const AUTH_ERROR = "AUTH_ERROR";
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = 'LOGIN_FAIL'; export const LOGIN_FAIL = "LOGIN_FAIL";
export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS'; export const LOGOUT_SUCCESS = "LOGOUT_SUCCESS";
export const LOGOUT_FAIL = 'LOGOUT_FAIL'; export const LOGOUT_FAIL = "LOGOUT_FAIL";
export const REFRESH_TOKEN_FAIL = 'REFRESH_TOKEN_FAIL'; export const REFRESH_TOKEN_FAIL = "REFRESH_TOKEN_FAIL";
export const REFRESH_TOKEN_SUCCESS = 'REFRESH_TOKEN_SUCCESS'; export const REFRESH_TOKEN_SUCCESS = "REFRESH_TOKEN_SUCCESS";
export const MYBADGES_CONNECT = 'MYBADGES_CONNECT';
export const MYBADGES_DISCONNECT = 'MYBADGES_DISCONNECT';
export const NEW_CODE = 'NEW_CODE'; export const NEW_CODE = "NEW_CODE";
export const CHANGE_WORKSPACE = 'CHANGE_WORKSPACE'; export const CHANGE_WORKSPACE = "CHANGE_WORKSPACE";
export const CREATE_BLOCK = 'CREATE_BLOCK'; export const CREATE_BLOCK = "CREATE_BLOCK";
export const MOVE_BLOCK = 'MOVE_BLOCK'; export const MOVE_BLOCK = "MOVE_BLOCK";
export const CHANGE_BLOCK = 'CHANGE_BLOCK'; export const CHANGE_BLOCK = "CHANGE_BLOCK";
export const DELETE_BLOCK = 'DELETE_BLOCK'; export const DELETE_BLOCK = "DELETE_BLOCK";
export const CLEAR_STATS = 'CLEAR_STATS'; export const CLEAR_STATS = "CLEAR_STATS";
export const NAME = 'NAME'; export const NAME = "NAME";
export const TUTORIAL_PROGRESS = 'TUTORIAL_PROGRESS'; export const TUTORIAL_PROGRESS = "TUTORIAL_PROGRESS";
export const GET_TUTORIAL = 'GET_TUTORIAL'; export const GET_TUTORIAL = "GET_TUTORIAL";
export const GET_TUTORIALS = 'GET_TUTORIALS'; export const GET_TUTORIALS = "GET_TUTORIALS";
export const GET_STATUS = 'GET_STATUS'; export const GET_STATUS = "GET_STATUS";
export const TUTORIAL_SUCCESS = 'TUTORIAL_SUCCESS'; export const TUTORIAL_SUCCESS = "TUTORIAL_SUCCESS";
export const TUTORIAL_ERROR = 'TUTORIAL_ERROR'; export const TUTORIAL_ERROR = "TUTORIAL_ERROR";
export const TUTORIAL_CHANGE = 'TUTORIAL_CHANGE'; export const TUTORIAL_CHANGE = "TUTORIAL_CHANGE";
export const TUTORIAL_XML = 'TUTORIAL_XML'; export const TUTORIAL_XML = "TUTORIAL_XML";
export const TUTORIAL_ID = 'TUTORIAL_ID'; export const TUTORIAL_ID = "TUTORIAL_ID";
export const TUTORIAL_STEP = 'TUTORIAL_STEP'; export const TUTORIAL_STEP = "TUTORIAL_STEP";
export const JSON_STRING = 'JSON_STRING'; export const JSON_STRING = "JSON_STRING";
export const BUILDER_CHANGE = "BUILDER_CHANGE";
export const BUILDER_TITLE = "BUILDER_TITLE";
export const BUILDER_ID = "BUILDER_ID";
export const BUILDER_ADD_STEP = "BUILDER_ADD_STEP";
export const BUILDER_DELETE_STEP = "BUILDER_DELETE_STEP";
export const BUILDER_CHANGE_STEP = "BUILDER_CHANGE_STEP";
export const BUILDER_CHANGE_ORDER = "BUILDER_CHANGE_ORDER";
export const BUILDER_DELETE_PROPERTY = "BUILDER_DELETE_PROPERTY";
export const BUILDER_ERROR = "BUILDER_ERROR";
export const PROGRESS = "PROGRESS";
export const BUILDER_CHANGE = 'BUILDER_CHANGE'; export const VISIT = "VISIT";
export const BUILDER_TITLE = 'BUILDER_TITLE'; export const LANGUAGE = "LANGUAGE";
export const BUILDER_BADGE = 'BUILDER_BADGE'; export const RENDERER = "RENDERER";
export const BUILDER_ID = 'BUILDER_ID'; export const STATISTICS = "STATISTICS";
export const BUILDER_ADD_STEP = 'BUILDER_ADD_STEP';
export const BUILDER_DELETE_STEP = 'BUILDER_DELETE_STEP';
export const BUILDER_CHANGE_STEP = 'BUILDER_CHANGE_STEP';
export const BUILDER_CHANGE_ORDER = 'BUILDER_CHANGE_ORDER';
export const BUILDER_DELETE_PROPERTY = 'BUILDER_DELETE_PROPERTY';
export const BUILDER_ERROR = 'BUILDER_ERROR';
export const PROGRESS = 'PROGRESS';
export const VISIT = 'VISIT';
export const LANGUAGE = 'LANGUAGE';
export const RENDERER = 'RENDERER';
export const STATISTICS = 'STATISTICS';
// messages // messages
export const GET_ERRORS = 'GET_ERRORS'; export const GET_ERRORS = "GET_ERRORS";
export const GET_SUCCESS = 'GET_SUCCESS'; export const GET_SUCCESS = "GET_SUCCESS";
export const CLEAR_MESSAGES = 'CLEAR_MESSAGES'; export const CLEAR_MESSAGES = "CLEAR_MESSAGES";
// projects: share, gallery, project // projects: share, gallery, project
export const PROJECT_PROGRESS = 'PROJECT_PROGRESS'; export const PROJECT_PROGRESS = "PROJECT_PROGRESS";
export const GET_PROJECT = 'GET_PROJECT'; export const GET_PROJECT = "GET_PROJECT";
export const GET_PROJECTS = 'GET_PROJECTS'; export const GET_PROJECTS = "GET_PROJECTS";
export const PROJECT_TYPE = 'PROJECT_TYPE'; export const PROJECT_TYPE = "PROJECT_TYPE";
export const PROJECT_DESCRIPTION = 'PROJECT_DESCRIPTION'; export const PROJECT_DESCRIPTION = "PROJECT_DESCRIPTION";
-1
View File
@@ -17,7 +17,6 @@ export const onChangeCode = () => (dispatch, getState) => {
var xmlDom = Blockly.Xml.workspaceToDom(workspace); var xmlDom = Blockly.Xml.workspaceToDom(workspace);
code.xml = Blockly.Xml.domToPrettyText(xmlDom); code.xml = Blockly.Xml.domToPrettyText(xmlDom);
var selectedBlock = Blockly.selected var selectedBlock = Blockly.selected
console.log(selectedBlock)
if (selectedBlock !== null) { if (selectedBlock !== null) {
code.helpurl = selectedBlock.helpUrl code.helpurl = selectedBlock.helpUrl
code.tooltip = selectedBlock.tooltip code.tooltip = selectedBlock.tooltip
+38 -19
View File
@@ -21,18 +21,20 @@
* @author samelh@google.com (Sam El-Husseini) * @author samelh@google.com (Sam El-Husseini)
*/ */
import React from 'react'; import React from "react";
import Blockly from 'blockly/core';
import 'blockly/blocks';
import Toolbox from './toolbox/Toolbox';
import { Card } from '@material-ui/core';
import Blockly from "blockly/core";
import "blockly/blocks";
import Toolbox from "./toolbox/Toolbox";
import { Card } from "@material-ui/core";
import {
ScrollOptions,
ScrollBlockDragger,
ScrollMetricsManager,
} from "@blockly/plugin-scroll-options";
class BlocklyComponent extends React.Component { class BlocklyComponent extends React.Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.blocklyDiv = React.createRef(); this.blocklyDiv = React.createRef();
@@ -42,17 +44,25 @@ class BlocklyComponent extends React.Component {
componentDidMount() { componentDidMount() {
const { initialXml, children, ...rest } = this.props; const { initialXml, children, ...rest } = this.props;
this.primaryWorkspace = Blockly.inject( this.primaryWorkspace = Blockly.inject(this.blocklyDiv.current, {
this.blocklyDiv.current,
{
toolbox: this.toolbox.current, toolbox: this.toolbox.current,
...rest plugins: {
// These are both required.
blockDragger: ScrollBlockDragger,
metricsManager: ScrollMetricsManager,
}, },
); ...rest,
this.setState({ workspace: this.primaryWorkspace }) });
// Initialize plugin.
this.setState({ workspace: this.primaryWorkspace });
const plugin = new ScrollOptions(this.workspace);
plugin.init({ enableWheelScroll: true, enableEdgeScroll: false });
if (initialXml) { if (initialXml) {
Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(initialXml), this.primaryWorkspace); Blockly.Xml.domToWorkspace(
Blockly.Xml.textToDom(initialXml),
this.primaryWorkspace
);
} }
} }
@@ -61,14 +71,23 @@ class BlocklyComponent extends React.Component {
} }
setXml(xml) { setXml(xml) {
Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(xml), this.primaryWorkspace); Blockly.Xml.domToWorkspace(
Blockly.Xml.textToDom(xml),
this.primaryWorkspace
);
} }
render() { render() {
return <React.Fragment> return (
<Card ref={this.blocklyDiv} id="blocklyDiv" style={this.props.style ? this.props.style : {}} /> <React.Fragment>
<Card
ref={this.blocklyDiv}
id="blocklyDiv"
style={this.props.style ? this.props.style : {}}
/>
<Toolbox toolbox={this.toolbox} workspace={this.state.workspace} /> <Toolbox toolbox={this.toolbox} workspace={this.state.workspace} />
</React.Fragment>; </React.Fragment>
);
} }
} }
+64 -40
View File
@@ -1,20 +1,18 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { onChangeWorkspace, clearStats } from '../../actions/workspaceActions'; import { onChangeWorkspace, clearStats } from "../../actions/workspaceActions";
import BlocklyComponent from './BlocklyComponent'; import BlocklyComponent from "./BlocklyComponent";
import BlocklySvg from './BlocklySvg'; import BlocklySvg from "./BlocklySvg";
import * as Blockly from 'blockly/core';
import './blocks/index';
import './generator/index';
import { initialXml } from './initialXml.js';
import * as Blockly from "blockly/core";
import "./blocks/index";
import "./generator/index";
import { ZoomToFitControl } from "@blockly/zoom-to-fit";
import { initialXml } from "./initialXml.js";
class BlocklyWindow extends Component { class BlocklyWindow extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.simpleWorkspace = React.createRef(); this.simpleWorkspace = React.createRef();
@@ -22,6 +20,7 @@ class BlocklyWindow extends Component {
componentDidMount() { componentDidMount() {
const workspace = Blockly.getMainWorkspace(); const workspace = Blockly.getMainWorkspace();
if (!this.props.readOnly) {
this.props.onChangeWorkspace({}); this.props.onChangeWorkspace({});
this.props.clearStats(); this.props.clearStats();
workspace.addChangeListener((event) => { workspace.addChangeListener((event) => {
@@ -32,11 +31,15 @@ class BlocklyWindow extends Component {
Blockly.Events.disableOrphans(event); Blockly.Events.disableOrphans(event);
} }
}); });
}
Blockly.svgResize(workspace); Blockly.svgResize(workspace);
const zoomToFit = new ZoomToFitControl(workspace);
zoomToFit.init();
} }
componentDidUpdate(props) { componentDidUpdate(props) {
const workspace = Blockly.getMainWorkspace(); const workspace = Blockly.getMainWorkspace();
if (!this.props.readOnly) {
var xml = this.props.initialXml; var xml = this.props.initialXml;
// if svg is true, then the update process is done in the BlocklySvg component // if svg is true, then the update process is done in the BlocklySvg component
if (props.initialXml !== xml && !this.props.svg) { if (props.initialXml !== xml && !this.props.svg) {
@@ -51,62 +54,83 @@ class BlocklyWindow extends Component {
var xmlDom = Blockly.Xml.textToDom(xml); var xmlDom = Blockly.Xml.textToDom(xml);
Blockly.Xml.clearWorkspaceAndLoadFromXml(xmlDom, workspace); Blockly.Xml.clearWorkspaceAndLoadFromXml(xmlDom, workspace);
// var toolbox = workspace.getToolbox(); // var toolbox = workspace.getToolbox();
// console.log(toolbox);
// workspace.updateToolbox(toolbox.toolboxDef_); // workspace.updateToolbox(toolbox.toolboxDef_);
} }
}
Blockly.svgResize(workspace); Blockly.svgResize(workspace);
} }
render() { render() {
return ( return (
<div> <div>
<BlocklyComponent ref={this.simpleWorkspace} <BlocklyComponent
ref={this.simpleWorkspace}
style={this.props.svg ? { height: 0 } : this.props.blocklyCSS} style={this.props.svg ? { height: 0 } : this.props.blocklyCSS}
readOnly={this.props.readOnly !== undefined ? this.props.readOnly : false} readOnly={
trashcan={this.props.trashcan !== undefined ? this.props.trashcan : true} this.props.readOnly !== undefined ? this.props.readOnly : false
}
trashcan={
this.props.trashcan !== undefined ? this.props.trashcan : true
}
renderer={this.props.renderer} renderer={this.props.renderer}
zoom={{ // https://developers.google.com/blockly/guides/configure/web/zoom zoom={{
controls: this.props.zoomControls !== undefined ? this.props.zoomControls : true, // https://developers.google.com/blockly/guides/configure/web/zoom
controls:
this.props.zoomControls !== undefined
? this.props.zoomControls
: true,
wheel: false, wheel: false,
startScale: 1, startScale: 1,
maxScale: 3, maxScale: 3,
minScale: 0.3, minScale: 0.3,
scaleSpeed: 1.2 scaleSpeed: 1.2,
}} }}
grid={this.props.grid !== undefined && !this.props.grid ? {} : grid={
{ // https://developers.google.com/blockly/guides/configure/web/grid this.props.grid !== undefined && !this.props.grid
? {}
: {
// https://developers.google.com/blockly/guides/configure/web/grid
spacing: 20, spacing: 20,
length: 1, length: 1,
colour: '#4EAF47', // senseBox-green colour: "#4EAF47", // senseBox-green
snap: false snap: false,
}} }
media={'/media/blockly/'} }
move={this.props.move !== undefined && !this.props.move ? {} : media={"/media/blockly/"}
{ // https://developers.google.com/blockly/guides/configure/web/move move={
this.props.move !== undefined && !this.props.move
? {}
: {
// https://developers.google.com/blockly/guides/configure/web/move
scrollbars: true, scrollbars: true,
drag: true, drag: true,
wheel: false wheel: true,
}} }
initialXml={this.props.initialXml ? this.props.initialXml : initialXml} }
> initialXml={
</BlocklyComponent > this.props.initialXml ? this.props.initialXml : initialXml
{this.props.svg && this.props.initialXml ? <BlocklySvg initialXml={this.props.initialXml} /> : null} }
></BlocklyComponent>
{this.props.svg && this.props.initialXml ? (
<BlocklySvg initialXml={this.props.initialXml} />
) : null}
</div> </div>
); );
}; }
} }
BlocklyWindow.propTypes = { BlocklyWindow.propTypes = {
onChangeWorkspace: PropTypes.func.isRequired, onChangeWorkspace: PropTypes.func.isRequired,
clearStats: PropTypes.func.isRequired, clearStats: PropTypes.func.isRequired,
renderer: PropTypes.string.isRequired, renderer: PropTypes.string.isRequired,
language: PropTypes.string.isRequired language: PropTypes.string.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
renderer: state.general.renderer, renderer: state.general.renderer,
language: state.general.language language: state.general.language,
}); });
export default connect(mapStateToProps, { onChangeWorkspace, clearStats })(BlocklyWindow); export default connect(mapStateToProps, { onChangeWorkspace, clearStats })(
BlocklyWindow
);
+25 -23
View File
@@ -1,24 +1,26 @@
import './loops'; import "./loops";
import './sensebox'; import "./sensebox";
import './logic'; import "./logic";
import './sensebox-sensors'; import "./sensebox-sensors";
import './sensebox-telegram'; import "./sensebox-telegram";
import './sensebox-osem'; import "./sensebox-osem";
import './sensebox-web'; import "./sensebox-web";
import './sensebox-display'; import "./sensebox-display";
import './sensebox-lora'; import "./sensebox-lora";
import './sensebox-led'; import "./sensebox-led";
import './sensebox-sd'; import "./sensebox-rtc";
import './mqtt'; import "./sensebox-ble";
import './text'; import "./sensebox-sd";
import './io'; import "./mqtt";
import './audio'; import "./text";
import './math'; import "./io";
import './map'; import "./audio";
import './procedures'; import "./math";
import './time'; import "./map";
import './variables'; import "./procedures";
import './lists'; import "./time";
import './webserver'; import "./variables";
import "./lists";
import "./webserver";
import '../helpers/types' import "../helpers/types";
+6 -6
View File
@@ -16,7 +16,7 @@ Blockly.Blocks['controls_whileUntil'] = {
this.setHelpUrl(Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL); this.setHelpUrl(Blockly.Msg.CONTROLS_WHILEUNTIL_HELPURL);
this.setColour(getColour().loops); this.setColour(getColour().loops);
this.appendValueInput('BOOL') this.appendValueInput('BOOL')
.setCheck(getCompatibleTypes(Boolean)) .setCheck(getCompatibleTypes('boolean'))
.appendField(new Blockly.FieldDropdown(OPERATORS), 'MODE'); .appendField(new Blockly.FieldDropdown(OPERATORS), 'MODE');
this.appendStatementInput('DO') this.appendStatementInput('DO')
.appendField(Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO); .appendField(Blockly.Msg.CONTROLS_WHILEUNTIL_INPUT_DO);
@@ -53,19 +53,19 @@ Blockly.Blocks['controls_for'] = {
{ {
"type": "input_value", "type": "input_value",
"name": "FROM", "name": "FROM",
"check": getCompatibleTypes(Number), "check": getCompatibleTypes('int'),
"align": "RIGHT" "align": "RIGHT"
}, },
{ {
"type": "input_value", "type": "input_value",
"name": "TO", "name": "TO",
"check": getCompatibleTypes(Number), "check": getCompatibleTypes('int'),
"align": "RIGHT" "align": "RIGHT"
}, },
{ {
"type": "input_value", "type": "input_value",
"name": "BY", "name": "BY",
"check": getCompatibleTypes(Number), "check": getCompatibleTypes('int'),
"align": "RIGHT" "align": "RIGHT"
} }
], ],
@@ -104,7 +104,7 @@ Blockly.Blocks['controls_forEach'] = {
{ {
"type": "input_value", "type": "input_value",
"name": "LIST", "name": "LIST",
"check": getCompatibleTypes(Array) "check": getCompatibleTypes('Array')
} }
], ],
"previousStatement": null, "previousStatement": null,
@@ -197,7 +197,7 @@ Blockly.Blocks['controls_repeat_ext'] = {
{ {
"type": "input_value", "type": "input_value",
"name": "TIMES", "name": "TIMES",
"check": getCompatibleTypes(Number), "check": getCompatibleTypes('int'),
} }
], ],
"previousStatement": null, "previousStatement": null,
+1 -3
View File
@@ -1148,9 +1148,7 @@ Blockly.Blocks['procedures_callnoreturn'] = {
// This should only be possible programatically and may indicate a problem // This should only be possible programatically and may indicate a problem
// with event grouping. If you see this message please investigate. If the // with event grouping. If you see this message please investigate. If the
// use ends up being valid we may need to reorder events in the undo stack. // use ends up being valid we may need to reorder events in the undo stack.
console.log(
'Saw an existing group while responding to a definition change'
);
} }
Blockly.Events.setGroup(event.group); Blockly.Events.setGroup(event.group);
if (event.newValue) { if (event.newValue) {
@@ -0,0 +1,145 @@
import * as Blockly from "blockly";
import { getColour } from "../helpers/colour";
Blockly.Blocks["sensebox_phyphox_init"] = {
init: function () {
this.setColour(getColour().phyphox);
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_init)
.appendField(new Blockly.FieldTextInput("Geräte Name"), "devicename");
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip(Blockly.Msg.sensebox_phyphox_init_tooltip);
},
};
Blockly.Blocks["sensebox_phyphox_experiment"] = {
init: function () {
this.setColour(getColour().phyphox);
this.appendDummyInput().appendField(
Blockly.Msg.sensebox_phyphox_createExperiment
);
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_experimentTitle)
.appendField(new Blockly.FieldTextInput("Experiment Title"), "title");
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_experimentDescription)
.appendField(
new Blockly.FieldTextInput(
Blockly.Msg.sensebox_phyphox_experiment_description
),
"description"
);
this.appendStatementInput("view").appendField(
Blockly.Msg.sensebox_phyphox_createView
);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip(Blockly.Msg.sensebox_phyphox_experiment_tooltip);
},
};
Blockly.Blocks["sensebox_phyphox_graph"] = {
init: function () {
this.setColour(getColour().phyphox);
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_createGraph)
.appendField(Blockly.Msg.sensebox_phyphox_graphLabel)
.appendField(new Blockly.FieldTextInput("Label"), "label");
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_unitx)
.appendField(new Blockly.FieldTextInput("Unit X"), "unitx");
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_unity)
.appendField(new Blockly.FieldTextInput("Unit Y"), "unity");
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_labelx)
.appendField(new Blockly.FieldTextInput("Label X"), "labelx");
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_labely)
.appendField(new Blockly.FieldTextInput("Label Y"), "labely");
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_graphStyle)
.appendField(
new Blockly.FieldDropdown([
[Blockly.Msg.sensebox_phyphox_style_dots, "dots"],
[Blockly.Msg.sensebox_phyphox_style_line, "line"],
]),
"style"
);
this.appendValueInput("channel0").appendField(
Blockly.Msg.sensebox_phyphox_channel0
);
this.appendValueInput("channel1").appendField(
Blockly.Msg.sensebox_phyphox_channel1
);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip(Blockly.Msg.sensebox_phyphox_graph_tooltip);
},
};
Blockly.Blocks["sensebox_phyphox_timestamp"] = {
init: function () {
this.setColour(getColour().phyphox);
this.appendDummyInput().appendField(Blockly.Msg.sensebox_phyphox_timestamp);
this.setOutput(true);
this.setTooltip(Blockly.Msg.sensebox_phyphox_timestamp_tooltip);
},
};
Blockly.Blocks["sensebox_phyphox_channel"] = {
init: function () {
this.setColour(getColour().phyphox);
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_phyphox_channel)
.appendField(
new Blockly.FieldDropdown([
["1", "1"],
["2", "2"],
["3", "3"],
["4", "4"],
["5", "5"],
]),
"channel"
);
this.setOutput(true);
this.setTooltip(Blockly.Msg.sensebox_phyphox_channel_tooltip);
},
};
Blockly.Blocks["sensebox_phyphox_sendchannel"] = {
init: function () {
this.setColour(getColour().phyphox);
this.appendValueInput("value")
.appendField(Blockly.Msg.sensebox_phyphox_sendchannel)
.appendField(
new Blockly.FieldDropdown([
["1", "1"],
["2", "2"],
["3", "3"],
["4", "4"],
["5", "5"],
]),
"channel"
);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip(Blockly.Msg.sensebox_phyphox_sendchannel_tooltip);
},
};
Blockly.Blocks["sensebox_phyphox_experiment_send"] = {
init: function () {
this.setColour(getColour().phyphox);
this.appendStatementInput("sendValues").appendField(
Blockly.Msg.sensebox_phyphox_writeValues
);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setTooltip(Blockly.Msg.sensebox_phyphox_experiment_send_tooltip);
},
};
+102 -85
View File
@@ -1,30 +1,34 @@
import * as Blockly from 'blockly/core'; import * as Blockly from "blockly/core";
import { getColour } from '../helpers/colour'; import { getColour } from "../helpers/colour";
/* /*
----------------------------------LoRa-------------------------------------------------- ----------------------------------LoRa--------------------------------------------------
*/ */
Blockly.Blocks['sensebox_lora_initialize_otaa'] = { Blockly.Blocks["sensebox_lora_initialize_otaa"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_init_otaa_tooltip); this.setTooltip(Blockly.Msg.senseBox_LoRa_init_otaa_tooltip);
this.setHelpUrl(Blockly.Msg.senseBox_LoRa_init_helpurl); this.setHelpUrl(Blockly.Msg.senseBox_LoRa_init_helpurl);
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendDummyInput() this.appendDummyInput().appendField("Initialize LoRa (OTAA)");
.appendField("Initialize LoRa (OTAA)");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_device_id) .appendField(Blockly.Msg.senseBox_LoRa_device_id)
.appendField(new Blockly.FieldTextInput("DEVICE ID"), "DEVICEID"); .appendField("{")
.appendField(new Blockly.FieldTextInput("DEVICE ID"), "DEVICEID")
.appendField("}");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_app_id) .appendField(Blockly.Msg.senseBox_LoRa_app_id)
.appendField(new Blockly.FieldTextInput("APP ID"), "APPID"); .appendField("{")
.appendField(new Blockly.FieldTextInput("APP ID"), "APPID")
.appendField("}");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_app_key) .appendField(Blockly.Msg.senseBox_LoRa_app_key)
.appendField(new Blockly.FieldTextInput("APP KEY"), "APPKEY"); .appendField("{")
.appendField(new Blockly.FieldTextInput("APP KEY"), "APPKEY")
.appendField("}");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_interval) .appendField(Blockly.Msg.senseBox_LoRa_interval)
@@ -34,21 +38,24 @@ Blockly.Blocks['sensebox_lora_initialize_otaa'] = {
}, },
}; };
Blockly.Blocks['sensebox_lora_initialize_abp'] = { Blockly.Blocks["sensebox_lora_initialize_abp"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_init_abp_tooltip); this.setTooltip(Blockly.Msg.senseBox_LoRa_init_abp_tooltip);
this.setHelpUrl(Blockly.Msg.senseBox_LoRa_init_helpurl); this.setHelpUrl(Blockly.Msg.senseBox_LoRa_init_helpurl);
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendDummyInput() this.appendDummyInput().appendField("Initialize LoRa (ABP)");
.appendField("Initialize LoRa (ABP)");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_nwskey_id) .appendField(Blockly.Msg.senseBox_LoRa_nwskey_id)
.appendField(new Blockly.FieldTextInput("NWSKEY"), "NWSKEY"); .appendField("{")
.appendField(new Blockly.FieldTextInput("NWSKEY"), "NWSKEY")
.appendField("}");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_appskey_id) .appendField(Blockly.Msg.senseBox_LoRa_appskey_id)
.appendField(new Blockly.FieldTextInput("APPSKEY"), "APPSKEY"); .appendField("{")
.appendField(new Blockly.FieldTextInput("APPSKEY"), "APPSKEY")
.appendField("}");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_devaddr_id) .appendField(Blockly.Msg.senseBox_LoRa_devaddr_id)
@@ -65,26 +72,27 @@ Blockly.Blocks['sensebox_lora_initialize_abp'] = {
}, },
}; };
Blockly.Blocks['sensebox_lora_message_send'] = { Blockly.Blocks["sensebox_lora_message_send"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_message_tooltip); this.setTooltip(Blockly.Msg.senseBox_LoRa_message_tooltip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendStatementInput('DO') this.appendStatementInput("DO")
.appendField(Blockly.Msg.senseBox_LoRa_send_message) .appendField(Blockly.Msg.senseBox_LoRa_send_message)
.setCheck(null); .setCheck(null);
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
} },
}; };
Blockly.Blocks['sensebox_send_lora_sensor_value'] = { Blockly.Blocks["sensebox_send_lora_sensor_value"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_sensor_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_sensor_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('Value') this.appendValueInput("Value").appendField(
.appendField(Blockly.Msg.senseBox_measurement) Blockly.Msg.senseBox_measurement
);
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField("Bytes") .appendField("Bytes")
@@ -115,60 +123,65 @@ Blockly.Blocks['sensebox_send_lora_sensor_value'] = {
this.setWarningText(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING); this.setWarningText(Blockly.Msg.CONTROLS_FLOW_STATEMENTS_WARNING);
} }
}, },
LOOP_TYPES: ['sensebox_lora_message_send'], LOOP_TYPES: ["sensebox_lora_message_send"],
}; };
Blockly.Blocks['sensebox_lora_ttn_mapper'] = { Blockly.Blocks["sensebox_lora_ttn_mapper"] = {
init: function (block) { init: function (block) {
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendDummyInput() this.appendDummyInput().appendField("TTN Mapper");
.appendField("TTN Mapper");
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_RIGHT) .setAlign(Blockly.ALIGN_RIGHT)
.appendField("Fix Type Limit") .appendField("Fix Type Limit")
.appendField(new Blockly.FieldDropdown([["0", "0"], ["1", "1"], ["2", "2"], ["3", "3"]].reverse()), "dropdown"); .appendField(
new Blockly.FieldDropdown(
[
["0", "0"],
["1", "1"],
["2", "2"],
["3", "3"],
].reverse()
),
"dropdown"
);
// reverse() because i want 3 be be at first and i'm to lazy to write the array again // reverse() because i want 3 be be at first and i'm to lazy to write the array again
this.appendValueInput('Latitude') this.appendValueInput("Latitude")
.appendField(Blockly.Msg.senseBox_gps_lat) .appendField(Blockly.Msg.senseBox_gps_lat)
.setCheck(null); .setCheck(null);
this.appendValueInput('Longitude') this.appendValueInput("Longitude")
.appendField(Blockly.Msg.senseBox_gps_lng) .appendField(Blockly.Msg.senseBox_gps_lng)
.setCheck(null); .setCheck(null);
this.appendValueInput('Altitude') this.appendValueInput("Altitude")
.appendField(Blockly.Msg.senseBox_gps_alt) .appendField(Blockly.Msg.senseBox_gps_alt)
.setCheck(null); .setCheck(null);
this.appendValueInput('pDOP') this.appendValueInput("pDOP").appendField("pDOP").setCheck(null);
.appendField('pDOP') this.appendValueInput("Fix Type").appendField("Fix Type").setCheck(null);
.setCheck(null);
this.appendValueInput('Fix Type')
.appendField('Fix Type')
.setCheck(null);
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
this.setTooltip(Blockly.Msg.senseBox_display_printDisplay_tip); this.setTooltip(Blockly.Msg.senseBox_display_printDisplay_tip);
},
}
}; };
Blockly.Blocks['sensebox_lora_cayenne_send'] = { Blockly.Blocks["sensebox_lora_cayenne_send"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendStatementInput('DO') this.appendStatementInput("DO")
.appendField(Blockly.Msg.senseBox_LoRa_send_cayenne) .appendField(Blockly.Msg.senseBox_LoRa_send_cayenne)
.setCheck(null); .setCheck(null);
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
} },
}; };
Blockly.Blocks['sensebox_lora_cayenne_temperature'] = { Blockly.Blocks["sensebox_lora_cayenne_temperature"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_temperature_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_temperature_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('Value') this.appendValueInput("Value").appendField(
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_temperature) Blockly.Msg.senseBox_LoRa_cayenne_temperature
);
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel) .appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel)
@@ -176,15 +189,16 @@ Blockly.Blocks['sensebox_lora_cayenne_temperature'] = {
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
}, },
LOOP_TYPES: ['sensebox_lora_cayenne_send'], LOOP_TYPES: ["sensebox_lora_cayenne_send"],
}; };
Blockly.Blocks['sensebox_lora_cayenne_humidity'] = { Blockly.Blocks["sensebox_lora_cayenne_humidity"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_humidity_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_humidity_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('Value') this.appendValueInput("Value").appendField(
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_humidity) Blockly.Msg.senseBox_LoRa_cayenne_humidity
);
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel) .appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel)
@@ -192,15 +206,16 @@ Blockly.Blocks['sensebox_lora_cayenne_humidity'] = {
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
}, },
LOOP_TYPES: ['sensebox_lora_cayenne_send'], LOOP_TYPES: ["sensebox_lora_cayenne_send"],
}; };
Blockly.Blocks['sensebox_lora_cayenne_pressure'] = { Blockly.Blocks["sensebox_lora_cayenne_pressure"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_pressure_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_pressure_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('Value') this.appendValueInput("Value").appendField(
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_pressure) Blockly.Msg.senseBox_LoRa_cayenne_pressure
);
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel) .appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel)
@@ -208,15 +223,16 @@ Blockly.Blocks['sensebox_lora_cayenne_pressure'] = {
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
}, },
LOOP_TYPES: ['sensebox_lora_cayenne_send'], LOOP_TYPES: ["sensebox_lora_cayenne_send"],
}; };
Blockly.Blocks['sensebox_lora_cayenne_luminosity'] = { Blockly.Blocks["sensebox_lora_cayenne_luminosity"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_luminosity_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_luminosity_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('Value') this.appendValueInput("Value").appendField(
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_luminosity) Blockly.Msg.senseBox_LoRa_cayenne_luminosity
);
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel) .appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel)
@@ -224,15 +240,16 @@ Blockly.Blocks['sensebox_lora_cayenne_luminosity'] = {
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
}, },
LOOP_TYPES: ['sensebox_lora_cayenne_send'], LOOP_TYPES: ["sensebox_lora_cayenne_send"],
}; };
Blockly.Blocks['sensebox_lora_cayenne_sensor'] = { Blockly.Blocks["sensebox_lora_cayenne_sensor"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_analog_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_analog_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('Value') this.appendValueInput("Value").appendField(
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_analog) Blockly.Msg.senseBox_LoRa_cayenne_analog
);
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel) .appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel)
@@ -240,19 +257,16 @@ Blockly.Blocks['sensebox_lora_cayenne_sensor'] = {
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
}, },
LOOP_TYPES: ['sensebox_lora_cayenne_send'], LOOP_TYPES: ["sensebox_lora_cayenne_send"],
}; };
Blockly.Blocks['sensebox_lora_cayenne_accelerometer'] = { Blockly.Blocks["sensebox_lora_cayenne_accelerometer"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_gyros_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_gyros_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('X') this.appendValueInput("X").appendField(Blockly.Msg.senseBox_LoRa_cayenne_x);
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_x) this.appendValueInput("Y").appendField(Blockly.Msg.senseBox_LoRa_cayenne_y);
this.appendValueInput('Y') this.appendValueInput("Z").appendField(Blockly.Msg.senseBox_LoRa_cayenne_z);
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_y)
this.appendValueInput('Z')
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_z)
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel) .appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel)
@@ -260,19 +274,22 @@ Blockly.Blocks['sensebox_lora_cayenne_accelerometer'] = {
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
}, },
LOOP_TYPES: ['sensebox_lora_cayenne_send'], LOOP_TYPES: ["sensebox_lora_cayenne_send"],
}; };
Blockly.Blocks['sensebox_lora_cayenne_gps'] = { Blockly.Blocks["sensebox_lora_cayenne_gps"] = {
init: function () { init: function () {
this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_gps_tip); this.setTooltip(Blockly.Msg.senseBox_LoRa_cayenne_gps_tip);
this.setHelpUrl(''); this.setHelpUrl("");
this.setColour(getColour().sensebox); this.setColour(getColour().sensebox);
this.appendValueInput('LAT') this.appendValueInput("LAT").appendField(
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_lat) Blockly.Msg.senseBox_LoRa_cayenne_lat
this.appendValueInput('LNG') );
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_lng) this.appendValueInput("LNG").appendField(
this.appendValueInput('ALT') Blockly.Msg.senseBox_LoRa_cayenne_lng
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_alt) );
this.appendValueInput("ALT").appendField(
Blockly.Msg.senseBox_LoRa_cayenne_alt
);
this.appendDummyInput() this.appendDummyInput()
.setAlign(Blockly.ALIGN_LEFT) .setAlign(Blockly.ALIGN_LEFT)
.appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel) .appendField(Blockly.Msg.senseBox_LoRa_cayenne_channel)
@@ -280,5 +297,5 @@ Blockly.Blocks['sensebox_lora_cayenne_gps'] = {
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
}, },
LOOP_TYPES: ['sensebox_lora_cayenne_send'], LOOP_TYPES: ["sensebox_lora_cayenne_send"],
}; };
@@ -73,7 +73,6 @@ Blockly.Blocks['sensebox_osem_connection'] = {
* Blockly.Blocks['controls_flow_statements'].LOOP_TYPES.push('custom_loop'); * Blockly.Blocks['controls_flow_statements'].LOOP_TYPES.push('custom_loop');
*/ */
selectedBox = this.getFieldValue('BoxID'); selectedBox = this.getFieldValue('BoxID');
console.log(selectedBox)
if (selectedBox !== '' && boxes) { if (selectedBox !== '' && boxes) {
var accessToken = boxes.find(element => element._id === selectedBox).access_token var accessToken = boxes.find(element => element._id === selectedBox).access_token
if (accessToken !== undefined) { if (accessToken !== undefined) {
@@ -160,7 +159,6 @@ Blockly.Blocks['sensebox_send_to_osem'] = {
for (var i = 0; i < box.sensors.length; i++) { for (var i = 0; i < box.sensors.length; i++) {
dropdown.push([box.sensors[i].title, box.sensors[i]._id]) dropdown.push([box.sensors[i].title, box.sensors[i]._id])
} }
console.log(dropdown)
} }
if (dropdown.length > 1) { if (dropdown.length > 1) {
var options = dropdown.slice(1) var options = dropdown.slice(1)
@@ -0,0 +1,78 @@
import * as Blockly from "blockly";
import { getColour } from "../helpers/colour";
import * as Types from "../helpers/types";
Blockly.Blocks["sensebox_rtc_init"] = {
init: function () {
this.setHelpUrl(Blockly.Msg.sensebox_rtc_helpurl);
this.setColour(getColour().time);
this.appendDummyInput().appendField(Blockly.Msg.sensebox_rtc_init);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip(Blockly.Msg.sensebox_rtc_init_tooltip);
},
};
Blockly.Blocks["sensebox_rtc_set"] = {
init: function () {
this.setHelpUrl(Blockly.Msg.sensebox_rtc_helpurl);
this.setColour(getColour().time);
this.appendDummyInput().appendField(Blockly.Msg.sensebox_rtc_set);
this.appendValueInput("second").appendField(
Blockly.Msg.sensebox_rtc_second
);
this.appendValueInput("minutes").appendField(
Blockly.Msg.sensebox_rtc_minutes
);
this.appendValueInput("hour").appendField(Blockly.Msg.sensebox_rtc_hour);
this.appendValueInput("day").appendField(Blockly.Msg.sensebox_rtc_day);
this.appendValueInput("month").appendField(Blockly.Msg.sensebox_rtc_month);
this.appendValueInput("year").appendField(Blockly.Msg.sensebox_rtc_year);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip(Blockly.Msg.sensebox_rtc_set_tooltip);
},
};
Blockly.Blocks["sensebox_rtc_set_ntp"] = {
init: function () {
this.setHelpUrl(Blockly.Msg.sensebox_rtc_helpurl);
this.setColour(getColour().time);
this.appendValueInput("time").appendField(Blockly.Msg.sensebox_rtc_set_ntp);
this.setPreviousStatement(true);
this.setNextStatement(true);
this.setTooltip(Blockly.Msg.sensebox_rtc_set_ntp_tooltip);
},
};
Blockly.Blocks["sensebox_rtc_get"] = {
init: function () {
this.setHelpUrl(Blockly.Msg.sensebox_rtc_helpurl);
this.setColour(getColour().time);
this.appendDummyInput()
.appendField(Blockly.Msg.sensebox_rtc_get)
.appendField(
new Blockly.FieldDropdown([
[Blockly.Msg.sensebox_rtc_hour, "hour"],
[Blockly.Msg.sensebox_rtc_minutes, "minutes"],
[Blockly.Msg.sensebox_rtc_second, "seconds"],
[Blockly.Msg.sensebox_rtc_day, "day"],
[Blockly.Msg.sensebox_rtc_month, "month"],
[Blockly.Msg.sensebox_rtc_year, "year"],
]),
"dropdown"
);
this.setOutput(true, Types.LARGE_NUMBER.typeId);
this.setTooltip(Blockly.Msg.sensebox_rtc_get_tooltip);
},
};
Blockly.Blocks["sensebox_rtc_get_timestamp"] = {
init: function () {
this.setHelpUrl(Blockly.Msg.sensebox_rtc_helpurl);
this.setColour(getColour().time);
this.appendDummyInput().appendField(Blockly.Msg.sensebox_rtc_get_timestamp);
this.setOutput(true);
this.setTooltip(Blockly.Msg.sensebox_rtc_get_timestamp_tooltip);
},
};
+34 -2
View File
@@ -1,4 +1,36 @@
import * as Blockly from "blockly/core";
import { getColour } from "../helpers/colour";
import * as Types from "../helpers/types";
Blockly.Blocks["sensebox_multiplexer_init"] = {
init: function () {
this.appendDummyInput().appendField(Blockly.Msg.senseBox_multiplexer_init);
this.appendValueInput("nrChannels").setCheck(
Types.getCompatibleTypes("int")
);
this.appendDummyInput().appendField(
Blockly.Msg.senseBox_multplexer_nchannels
);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setInputsInline("true");
this.setColour(getColour().sensebox);
this.setTooltip(Blockly.Msg.senseBox_multiplexer_init_tooltip);
this.setHelpUrl(Blockly.Msg.senseBox_multiplexer_init_helpurl);
},
};
Blockly.Blocks["sensebox_multiplexer_changeChannel"] = {
init: function () {
this.appendDummyInput().appendField(
Blockly.Msg.senseBox_multiplexer_changeChannel
);
this.appendValueInput("Channel").setCheck(Types.getCompatibleTypes("int"));
this.setInputsInline("true");
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(getColour().sensebox);
this.setTooltip(Blockly.Msg.sensebox_multiplexer_changeChannel_tooltip);
this.setHelpUrl(Blockly.Msg.sensebox_multiplexer_changeChannel_helpurl);
},
};
+29 -26
View File
@@ -1,43 +1,46 @@
import Blockly from 'blockly/core'; import Blockly from "blockly/core";
import { getColour } from '../helpers/colour'; import { getColour } from "../helpers/colour";
import { getCompatibleTypes } from '../helpers/types' import { getCompatibleTypes } from "../helpers/types";
Blockly.Blocks["variables_set_dynamic"] = {
Blockly.Blocks['variables_set_dynamic'] = {
init: function () { init: function () {
// const type = myVar.type; // const type = myVar.type;
this.setColour(getColour().variables); this.setColour(getColour().variables);
this.setPreviousStatement(true, null); this.setPreviousStatement(true, null);
this.setNextStatement(true, null); this.setNextStatement(true, null);
this.appendValueInput('VALUE') this.appendValueInput("VALUE")
.appendField('set', 'set') .appendField("set", "set")
.appendField('', 'type') .appendField("", "type")
.appendField(new Blockly.FieldVariable('VAR'), 'VAR') .appendField(new Blockly.FieldVariable("VAR"), "VAR")
.appendField('to'); .appendField("to");
}, },
onchange: function (e) { onchange: function (e) {
let variableID = this.getFieldValue('VAR'); let variableID = this.getFieldValue("VAR");
let variable = Blockly.getMainWorkspace().getVariableMap().getVariableById(variableID) let variable = Blockly.getMainWorkspace()
this.getField('type').setValue(variable.type); .getVariableMap()
this.getInput('VALUE').setCheck(getCompatibleTypes(variable.type)); .getVariableById(variableID);
if (variable !== null) {
this.getField("type").setValue(variable.type);
this.getInput("VALUE").setCheck(getCompatibleTypes(variable.type));
} }
} },
};
Blockly.Blocks['variables_get_dynamic'] = { Blockly.Blocks["variables_get_dynamic"] = {
init: function () { init: function () {
this.setColour(getColour().variables); this.setColour(getColour().variables);
this.appendDummyInput() this.appendDummyInput()
.appendField('', 'type') .appendField("", "type")
.appendField(new Blockly.FieldVariable('VAR'), 'VAR'); .appendField(new Blockly.FieldVariable("VAR"), "VAR");
this.setOutput(true); this.setOutput(true);
}, },
onchange: function (e) { onchange: function (e) {
let variableID = this.getFieldValue('VAR'); let variableID = this.getFieldValue("VAR");
let variable = Blockly.getMainWorkspace().getVariableMap().getVariableById(variableID) let variable = Blockly.getMainWorkspace()
this.getField('type').setValue(variable.type); .getVariableMap()
.getVariableById(variableID);
if (variable !== null) {
this.getField("type").setValue(variable.type);
} }
} },
};
+145 -140
View File
@@ -24,13 +24,13 @@
// More on generating code: // More on generating code:
// https://developers.google.com/blockly/guides/create-custom-blocks/generating-code // https://developers.google.com/blockly/guides/create-custom-blocks/generating-code
import * as Blockly from 'blockly/core'; import * as Blockly from "blockly/core";
/** /**
* Arduino code generator. * Arduino code generator.
* @type !Blockly.Generator * @type !Blockly.Generator
*/ */
Blockly['Arduino'] = new Blockly.Generator('Arduino'); Blockly["Arduino"] = new Blockly.Generator("Arduino");
/** /**
* List of illegal variable names. * List of illegal variable names.
@@ -39,49 +39,46 @@ Blockly['Arduino'] = new Blockly.Generator('Arduino');
* accidentally clobbering a built-in object or function. * accidentally clobbering a built-in object or function.
* @private * @private
*/ */
Blockly['Arduino'].addReservedWords( Blockly["Arduino"].addReservedWords(
// http://arduino.cc/en/Reference/HomePage // http://arduino.cc/en/Reference/HomePage
'setup,loop,if,else,for,switch,case,while,' + "setup,loop,if,else,for,switch,case,while," +
'do,break,continue,return,goto,define,include,' + "do,break,continue,return,goto,define,include," +
'HIGH,LOW,INPUT,OUTPUT,INPUT_PULLUP,true,false,' + "HIGH,LOW,INPUT,OUTPUT,INPUT_PULLUP,true,false," +
'interger, constants,floating,point,void,boolean,char,' + "interger, constants,floating,point,void,boolean,char," +
'unsigned,byte,int,word,long,float,double,string,String,array,' + "unsigned,byte,int,word,long,float,double,string,String,array," +
'static, volatile,const,sizeof,pinMode,digitalWrite,digitalRead,' + "static, volatile,const,sizeof,pinMode,digitalWrite,digitalRead," +
'analogReference,analogRead,analogWrite,tone,noTone,shiftOut,shitIn,' + "analogReference,analogRead,analogWrite,tone,noTone,shiftOut,shitIn," +
'pulseIn,millis,micros,delay,delayMicroseconds,min,max,abs,constrain,' + "pulseIn,millis,micros,delay,delayMicroseconds,min,max,abs,constrain," +
'map,pow,sqrt,sin,cos,tan,randomSeed,random,lowByte,highByte,bitRead,' + "map,pow,sqrt,sin,cos,tan,randomSeed,random,lowByte,highByte,bitRead," +
'bitWrite,bitSet,bitClear,ultraSonicDistance,parseDouble,setNeoPixelColor,' + "bitWrite,bitSet,bitClear,ultraSonicDistance,parseDouble,setNeoPixelColor," +
'bit,attachInterrupt,detachInterrupt,interrupts,noInterrupts', "bit,attachInterrupt,detachInterrupt,interrupts,noInterrupts",
'short', "short",
'isBtnPressed' "isBtnPressed"
); );
/** /**
* Order of operation ENUMs. * Order of operation ENUMs.
* *
*/ */
Blockly['Arduino'].ORDER_ATOMIC = 0; // 0 "" ... Blockly["Arduino"].ORDER_ATOMIC = 0; // 0 "" ...
Blockly['Arduino'].ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] . Blockly["Arduino"].ORDER_UNARY_POSTFIX = 1; // expr++ expr-- () [] .
Blockly['Arduino'].ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr Blockly["Arduino"].ORDER_UNARY_PREFIX = 2; // -expr !expr ~expr ++expr --expr
Blockly['Arduino'].ORDER_MULTIPLICATIVE = 3; // * / % ~/ Blockly["Arduino"].ORDER_MULTIPLICATIVE = 3; // * / % ~/
Blockly['Arduino'].ORDER_ADDITIVE = 4; // + - Blockly["Arduino"].ORDER_ADDITIVE = 4; // + -
Blockly['Arduino'].ORDER_LOGICAL_NOT = 4.4; // ! Blockly["Arduino"].ORDER_LOGICAL_NOT = 4.4; // !
Blockly['Arduino'].ORDER_SHIFT = 5; // << >> Blockly["Arduino"].ORDER_SHIFT = 5; // << >>
Blockly['Arduino'].ORDER_MODULUS = 5.3; // % Blockly["Arduino"].ORDER_MODULUS = 5.3; // %
Blockly['Arduino'].ORDER_RELATIONAL = 6; // is is! >= > <= < Blockly["Arduino"].ORDER_RELATIONAL = 6; // is is! >= > <= <
Blockly['Arduino'].ORDER_EQUALITY = 7; // === !== === !== Blockly["Arduino"].ORDER_EQUALITY = 7; // === !== === !==
Blockly['Arduino'].ORDER_BITWISE_AND = 8; // & Blockly["Arduino"].ORDER_BITWISE_AND = 8; // &
Blockly['Arduino'].ORDER_BITWISE_XOR = 9; // ^ Blockly["Arduino"].ORDER_BITWISE_XOR = 9; // ^
Blockly['Arduino'].ORDER_BITWISE_OR = 10; // | Blockly["Arduino"].ORDER_BITWISE_OR = 10; // |
Blockly['Arduino'].ORDER_LOGICAL_AND = 11; // && Blockly["Arduino"].ORDER_LOGICAL_AND = 11; // &&
Blockly['Arduino'].ORDER_LOGICAL_OR = 12; // || Blockly["Arduino"].ORDER_LOGICAL_OR = 12; // ||
Blockly['Arduino'].ORDER_CONDITIONAL = 13; // expr ? expr : expr Blockly["Arduino"].ORDER_CONDITIONAL = 13; // expr ? expr : expr
Blockly['Arduino'].ORDER_ASSIGNMENT = 14; // = *= /= ~/= %= += -= <<= >>= &= ^= |= Blockly["Arduino"].ORDER_ASSIGNMENT = 14; // = *= /= ~/= %= += -= <<= >>= &= ^= |=
Blockly['Arduino'].ORDER_COMMA = 18; // , Blockly["Arduino"].ORDER_COMMA = 18; // ,
Blockly['Arduino'].ORDER_NONE = 99; // (...) Blockly["Arduino"].ORDER_NONE = 99; // (...)
/** /**
* *
@@ -90,49 +87,49 @@ Blockly['Arduino'].ORDER_NONE = 99; // (...)
* Blockly Types * Blockly Types
*/ */
/** /**
* Initialise the database of variable names. * Initialise the database of variable names.
* @param {!Blockly.Workspace} workspace Workspace to generate code from. * @param {!Blockly.Workspace} workspace Workspace to generate code from.
*/ */
Blockly['Arduino'].init = function (workspace) { Blockly["Arduino"].init = function (workspace) {
// Create a dictionary of definitions to be printed before the code. // Create a dictionary of definitions to be printed before the code.
Blockly['Arduino'].libraries_ = Object.create(null); Blockly["Arduino"].libraries_ = Object.create(null);
Blockly['Arduino'].definitions_ = Object.create(null); Blockly["Arduino"].definitions_ = Object.create(null);
// creates a list of code to be setup before the setup block // creates a list of code to be setup before the setup block
Blockly['Arduino'].setupCode_ = Object.create(null); Blockly["Arduino"].setupCode_ = Object.create(null);
// creates a list of code to be setup before the setup block // creates a list of code to be setup before the setup block
Blockly['Arduino'].loraSetupCode_ = Object.create(null); Blockly["Arduino"].phyphoxSetupCode_ = Object.create(null);
// creates a list of code to be setup before the setup block
Blockly["Arduino"].loraSetupCode_ = Object.create(null);
// creates a list of code for the loop to be runned once // creates a list of code for the loop to be runned once
Blockly['Arduino'].loopCodeOnce_ = Object.create(null) Blockly["Arduino"].loopCodeOnce_ = Object.create(null);
// creates a list of code for the loop to be runned once // creates a list of code for the loop to be runned once
Blockly['Arduino'].codeFunctions_ = Object.create(null) Blockly["Arduino"].codeFunctions_ = Object.create(null);
// creates a list of code variables // creates a list of code variables
Blockly['Arduino'].variables_ = Object.create(null) Blockly["Arduino"].variables_ = Object.create(null);
// Create a dictionary mapping desired function names in definitions_ // Create a dictionary mapping desired function names in definitions_
// to actual function names (to avoid collisions with user functions). // to actual function names (to avoid collisions with user functions).
Blockly['Arduino'].functionNames_ = Object.create(null); Blockly["Arduino"].functionNames_ = Object.create(null);
Blockly['Arduino'].variablesInitCode_ = ''; Blockly["Arduino"].variablesInitCode_ = "";
if (!Blockly['Arduino'].variableDB_) { if (!Blockly["Arduino"].variableDB_) {
Blockly['Arduino'].variableDB_ = new Blockly.Names( Blockly["Arduino"].variableDB_ = new Blockly.Names(
Blockly['Arduino'].RESERVED_WORDS_ Blockly["Arduino"].RESERVED_WORDS_
); );
} else { } else {
Blockly['Arduino'].variableDB_.reset(); Blockly["Arduino"].variableDB_.reset();
} }
Blockly['Arduino'].variableDB_.setVariableMap(workspace.getVariableMap()); Blockly["Arduino"].variableDB_.setVariableMap(workspace.getVariableMap());
// We don't have developer variables for now // We don't have developer variables for now
// // Add developer variables (not created or named by the user). // // Add developer variables (not created or named by the user).
@@ -142,53 +139,53 @@ Blockly['Arduino'].init = function (workspace) {
// Blockly.Names.DEVELOPER_VARIABLE_TYPE)); // Blockly.Names.DEVELOPER_VARIABLE_TYPE));
// } // }
const doubleVariables = workspace.getVariablesOfType('Number'); const doubleVariables = workspace.getVariablesOfType("Number");
let i = 0; let i = 0;
let variableCode = ''; let variableCode = "";
for (i = 0; i < doubleVariables.length; i += 1) { for (i = 0; i < doubleVariables.length; i += 1) {
variableCode += variableCode +=
'double ' + "double " +
Blockly['Arduino'].variableDB_.getName( Blockly["Arduino"].variableDB_.getName(
doubleVariables[i].getId(), doubleVariables[i].getId(),
Blockly.Variables.NAME_TYPE Blockly.Variables.NAME_TYPE
) + ) +
' = 0; \n\n'; " = 0; \n\n";
} }
const stringVariables = workspace.getVariablesOfType('String'); const stringVariables = workspace.getVariablesOfType("String");
for (i = 0; i < stringVariables.length; i += 1) { for (i = 0; i < stringVariables.length; i += 1) {
variableCode += variableCode +=
'String ' + "String " +
Blockly['Arduino'].variableDB_.getName( Blockly["Arduino"].variableDB_.getName(
stringVariables[i].getId(), stringVariables[i].getId(),
Blockly.Variables.NAME_TYPE Blockly.Variables.NAME_TYPE
) + ) +
' = ""; \n\n'; ' = ""; \n\n';
} }
const booleanVariables = workspace.getVariablesOfType('Boolean'); const booleanVariables = workspace.getVariablesOfType("Boolean");
for (i = 0; i < booleanVariables.length; i += 1) { for (i = 0; i < booleanVariables.length; i += 1) {
variableCode += variableCode +=
'boolean ' + "boolean " +
Blockly['Arduino'].variableDB_.getDistinctName( Blockly["Arduino"].variableDB_.getDistinctName(
booleanVariables[i].getId(), booleanVariables[i].getId(),
Blockly.Variables.NAME_TYPE Blockly.Variables.NAME_TYPE
) + ) +
' = false; \n\n'; " = false; \n\n";
} }
const colourVariables = workspace.getVariablesOfType('Colour'); const colourVariables = workspace.getVariablesOfType("Colour");
for (i = 0; i < colourVariables.length; i += 1) { for (i = 0; i < colourVariables.length; i += 1) {
variableCode += variableCode +=
'RGB ' + "RGB " +
Blockly['Arduino'].variableDB_.getName( Blockly["Arduino"].variableDB_.getName(
colourVariables[i].getId(), colourVariables[i].getId(),
Blockly.Variables.NAME_TYPE Blockly.Variables.NAME_TYPE
) + ) +
' = {0, 0, 0}; \n\n'; " = {0, 0, 0}; \n\n";
} }
Blockly['Arduino'].variablesInitCode_ = variableCode; Blockly["Arduino"].variablesInitCode_ = variableCode;
}; };
/** /**
@@ -196,86 +193,95 @@ Blockly['Arduino'].init = function (workspace) {
* @param {string} code Generated code. * @param {string} code Generated code.
* @return {string} Completed code. * @return {string} Completed code.
*/ */
Blockly['Arduino'].finish = function (code) { Blockly["Arduino"].finish = function (code) {
let libraryCode = ''; let libraryCode = "";
let variablesCode = ''; let variablesCode = "";
let codeFunctions = ''; let codeFunctions = "";
let functionsCode = ''; let functionsCode = "";
let definitionsCode = ''; let definitionsCode = "";
let loopCodeOnce = ''; let phyphoxSetupCode = "";
let setupCode = ''; let loopCodeOnce = "";
let preSetupCode = ''; let setupCode = "";
let loraSetupCode = ''; let preSetupCode = "";
let devVariables = '\n'; let loraSetupCode = "";
let devVariables = "\n";
for (const key in Blockly['Arduino'].libraries_) { for (const key in Blockly["Arduino"].libraries_) {
libraryCode += Blockly['Arduino'].libraries_[key] + '\n'; libraryCode += Blockly["Arduino"].libraries_[key] + "\n";
} }
for (const key in Blockly['Arduino'].variables_) { for (const key in Blockly["Arduino"].variables_) {
variablesCode += Blockly['Arduino'].variables_[key] + '\n'; variablesCode += Blockly["Arduino"].variables_[key] + "\n";
} }
for (const key in Blockly['Arduino'].definitions_) { for (const key in Blockly["Arduino"].definitions_) {
definitionsCode += Blockly['Arduino'].definitions_[key] + '\n'; definitionsCode += Blockly["Arduino"].definitions_[key] + "\n";
} }
for (const key in Blockly['Arduino'].loopCodeOnce_) { for (const key in Blockly["Arduino"].loopCodeOnce_) {
loopCodeOnce += Blockly['Arduino'].loopCodeOnce_[key] + '\n'; loopCodeOnce += Blockly["Arduino"].loopCodeOnce_[key] + "\n";
} }
for (const key in Blockly['Arduino'].codeFunctions_) { for (const key in Blockly["Arduino"].codeFunctions_) {
codeFunctions += Blockly['Arduino'].codeFunctions_[key] + '\n'; codeFunctions += Blockly["Arduino"].codeFunctions_[key] + "\n";
} }
for (const key in Blockly['Arduino'].functionNames_) { for (const key in Blockly["Arduino"].functionNames_) {
functionsCode += Blockly['Arduino'].functionNames_[key] + '\n'; functionsCode += Blockly["Arduino"].functionNames_[key] + "\n";
} }
for (const key in Blockly["Arduino"].setupCode_) {
preSetupCode += Blockly["Arduino"].setupCode_[key] + "\n" || "";
for (const key in Blockly['Arduino'].setupCode_) {
preSetupCode += Blockly['Arduino'].setupCode_[key] || '';
} }
for (const key in Blockly['Arduino'].loraSetupCode_) { for (const key in Blockly["Arduino"].loraSetupCode_) {
loraSetupCode += Blockly['Arduino'].loraSetupCode_[key] || ''; loraSetupCode += Blockly["Arduino"].loraSetupCode_[key] + "\n" || "";
} }
setupCode =
"\nvoid setup() { \n" + preSetupCode + "\n" + loraSetupCode + "\n}\n";
for (const key in Blockly["Arduino"].phyphoxSetupCode_) {
phyphoxSetupCode += Blockly["Arduino"].phyphoxSetupCode_[key] + "\n" || "";
}
setupCode = '\nvoid setup() { \n' + preSetupCode + '\n' + loraSetupCode + '\n}\n'; setupCode =
"\nvoid setup() { \n" +
let loopCode = '\nvoid loop() { \n' + loopCodeOnce + code + '\n}\n'; preSetupCode +
"\n" +
phyphoxSetupCode +
"\n" +
loraSetupCode +
"\n}\n";
let loopCode = "\nvoid loop() { \n" + loopCodeOnce + code + "\n}\n";
// Convert the definitions dictionary into a list. // Convert the definitions dictionary into a list.
code = code =
devVariables + devVariables +
'\n' + "\n" +
libraryCode + libraryCode +
'\n' + "\n" +
variablesCode + variablesCode +
'\n' + "\n" +
definitionsCode + definitionsCode +
'\n' + "\n" +
codeFunctions + codeFunctions +
'\n' + "\n" +
Blockly['Arduino'].variablesInitCode_ + Blockly["Arduino"].variablesInitCode_ +
'\n' + "\n" +
functionsCode + functionsCode +
'\n' + "\n" +
setupCode + setupCode +
'\n' + "\n" +
loopCode loopCode;
;
// Clean up temporary data. // Clean up temporary data.
delete Blockly['Arduino'].definitions_; delete Blockly["Arduino"].definitions_;
delete Blockly['Arduino'].functionNames_; delete Blockly["Arduino"].functionNames_;
delete Blockly['Arduino'].loopCodeOnce_; delete Blockly["Arduino"].loopCodeOnce_;
delete Blockly['Arduino'].variablesInitCode_; delete Blockly["Arduino"].variablesInitCode_;
delete Blockly['Arduino'].libraries_; delete Blockly["Arduino"].libraries_;
Blockly['Arduino'].variableDB_.reset(); Blockly["Arduino"].variableDB_.reset();
return code; return code;
}; };
@@ -286,8 +292,8 @@ Blockly['Arduino'].finish = function (code) {
* @param {string} line Line of generated code. * @param {string} line Line of generated code.
* @return {string} Legal line of code. * @return {string} Legal line of code.
*/ */
Blockly['Arduino'].scrubNakedValue = function (line) { Blockly["Arduino"].scrubNakedValue = function (line) {
return line + ';\n'; return line + ";\n";
}; };
/** /**
@@ -297,12 +303,12 @@ Blockly['Arduino'].scrubNakedValue = function (line) {
* @return {string} Arduino string. * @return {string} Arduino string.
* @private * @private
*/ */
Blockly['Arduino'].quote_ = function (string) { Blockly["Arduino"].quote_ = function (string) {
// Can't use goog.string.quote since Google's style guide recommends // Can't use goog.string.quote since Google's style guide recommends
// JS string literals use single quotes. // JS string literals use single quotes.
string = string string = string
.replace(/\\/g, '\\\\') .replace(/\\/g, "\\\\")
.replace(/\n/g, '\\\n') .replace(/\n/g, "\\\n")
.replace(/'/g, "\\'"); .replace(/'/g, "\\'");
return '"' + string + '"'; return '"' + string + '"';
}; };
@@ -317,26 +323,25 @@ Blockly['Arduino'].quote_ = function (string) {
* @return {string} Arduino code with comments and subsequent blocks added. * @return {string} Arduino code with comments and subsequent blocks added.
* @private * @private
*/ */
Blockly['Arduino'].scrub_ = function (block, code) { Blockly["Arduino"].scrub_ = function (block, code) {
let commentCode = ''; let commentCode = "";
// Only collect comments for blocks that aren't inline. // Only collect comments for blocks that aren't inline.
if (!block.outputConnection || !block.outputConnection.targetConnection) { if (!block.outputConnection || !block.outputConnection.targetConnection) {
// Collect comment for this block. // Collect comment for this block.
let comment = block.getCommentText(); let comment = block.getCommentText();
//@ts-ignore //@ts-ignore
comment = comment ? Blockly.utils.string.wrap( comment = comment
comment, ? Blockly.utils.string.wrap(comment, Blockly["Arduino"].COMMENT_WRAP - 3)
Blockly['Arduino'].COMMENT_WRAP - 3 : null;
) : null;
if (comment) { if (comment) {
if (block.getProcedureDef) { if (block.getProcedureDef) {
// Use a comment block for function comments. // Use a comment block for function comments.
commentCode += commentCode +=
'/**\n' + "/**\n" +
Blockly['Arduino'].prefixLines(comment + '\n', ' * ') + Blockly["Arduino"].prefixLines(comment + "\n", " * ") +
' */\n'; " */\n";
} else { } else {
commentCode += Blockly['Arduino'].prefixLines(comment + '\n', '// '); commentCode += Blockly["Arduino"].prefixLines(comment + "\n", "// ");
} }
} }
// Collect comments for all value arguments. // Collect comments for all value arguments.
@@ -345,15 +350,15 @@ Blockly['Arduino'].scrub_ = function (block, code) {
if (block.inputList[i].type === Blockly.INPUT_VALUE) { if (block.inputList[i].type === Blockly.INPUT_VALUE) {
const childBlock = block.inputList[i].connection.targetBlock(); const childBlock = block.inputList[i].connection.targetBlock();
if (childBlock) { if (childBlock) {
const comment = Blockly['Arduino'].allNestedComments(childBlock); const comment = Blockly["Arduino"].allNestedComments(childBlock);
if (comment) { if (comment) {
commentCode += Blockly['Arduino'].prefixLines(comment, '// '); commentCode += Blockly["Arduino"].prefixLines(comment, "// ");
} }
} }
} }
} }
} }
const nextBlock = block.nextConnection && block.nextConnection.targetBlock(); const nextBlock = block.nextConnection && block.nextConnection.targetBlock();
const nextCode = Blockly['Arduino'].blockToCode(nextBlock); const nextCode = Blockly["Arduino"].blockToCode(nextBlock);
return commentCode + code + nextCode; return commentCode + code + nextCode;
}; };
+25 -24
View File
@@ -1,24 +1,25 @@
import './generator'; import "./generator";
import './loops'; import "./loops";
import './sensebox-sensors'; import "./sensebox-sensors";
import './sensebox-telegram'; import "./sensebox-telegram";
import './sensebox-osem'; import "./sensebox-osem";
import './sensebox-web'; import "./sensebox-web";
import './sensebox-display'; import "./sensebox-display";
import './sensebox-lora'; import "./sensebox-lora";
import './sensebox-led'; import "./sensebox-led";
import './sensebox-sd'; import "./sensebox";
import './mqtt'; import "./sensebox-rtc";
import './logic'; import "./sensebox-ble";
import './text'; import "./sensebox-sd";
import './math'; import "./mqtt";
import './map'; import "./logic";
import './io'; import "./text";
import './audio'; import "./math";
import './procedures'; import "./map";
import './time'; import "./io";
import './variables'; import "./audio";
import './lists'; import "./procedures";
import './webserver'; import "./time";
import "./variables";
import "./lists";
import "./webserver";
+210 -161
View File
@@ -1,5 +1,4 @@
import * as Blockly from "blockly/core";
import * as Blockly from 'blockly/core';
/** /**
* @license Licensed under the Apache License, Version 2.0 (the "License"): * @license Licensed under the Apache License, Version 2.0 (the "License"):
@@ -19,13 +18,13 @@ import * as Blockly from 'blockly/core';
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_number'] = function (block) { Blockly.Arduino["math_number"] = function (block) {
// Numeric value. // Numeric value.
var code = parseFloat(block.getFieldValue('NUM')); var code = parseFloat(block.getFieldValue("NUM"));
if (code === Infinity) { if (code === Infinity) {
code = 'INFINITY'; code = "INFINITY";
} else if (code === -Infinity) { } else if (code === -Infinity) {
code = '-INFINITY'; code = "-INFINITY";
} }
return [code, Blockly.Arduino.ORDER_ATOMIC]; return [code, Blockly.Arduino.ORDER_ATOMIC];
}; };
@@ -37,23 +36,23 @@ Blockly.Arduino['math_number'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_arithmetic'] = function (block) { Blockly.Arduino["math_arithmetic"] = function (block) {
var OPERATORS = { var OPERATORS = {
ADD: [' + ', Blockly.Arduino.ORDER_ADDITIVE], ADD: [" + ", Blockly.Arduino.ORDER_ADDITIVE],
MINUS: [' - ', Blockly.Arduino.ORDER_ADDITIVE], MINUS: [" - ", Blockly.Arduino.ORDER_ADDITIVE],
MULTIPLY: [' * ', Blockly.Arduino.ORDER_MULTIPLICATIVE], MULTIPLY: [" * ", Blockly.Arduino.ORDER_MULTIPLICATIVE],
DIVIDE: [' / ', Blockly.Arduino.ORDER_MULTIPLICATIVE], DIVIDE: [" / ", Blockly.Arduino.ORDER_MULTIPLICATIVE],
POWER: [null, Blockly.Arduino.ORDER_NONE] // Handle power separately. POWER: [null, Blockly.Arduino.ORDER_NONE], // Handle power separately.
}; };
var tuple = OPERATORS[block.getFieldValue('OP')]; var tuple = OPERATORS[block.getFieldValue("OP")];
var operator = tuple[0]; var operator = tuple[0];
var order = tuple[1]; var order = tuple[1];
var argument0 = Blockly.Arduino.valueToCode(block, 'A', order) || '0'; var argument0 = Blockly.Arduino.valueToCode(block, "A", order) || "0";
var argument1 = Blockly.Arduino.valueToCode(block, 'B', order) || '0'; var argument1 = Blockly.Arduino.valueToCode(block, "B", order) || "0";
var code; var code;
// Power in C++ requires a special case since it has no operator. // Power in C++ requires a special case since it has no operator.
if (!operator) { if (!operator) {
code = 'Math.pow(' + argument0 + ', ' + argument1 + ')'; code = "Math.pow(" + argument0 + ", " + argument1 + ")";
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX]; return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
} }
code = argument0 + operator + argument1; code = argument0 + operator + argument1;
@@ -66,65 +65,78 @@ Blockly.Arduino['math_arithmetic'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_single'] = function (block) { Blockly.Arduino["math_single"] = function (block) {
var operator = block.getFieldValue('OP'); var operator = block.getFieldValue("OP");
var code; var code;
var arg; var arg;
if (operator === 'NEG') { if (operator === "NEG") {
// Negation is a special case given its different operator precedents. // Negation is a special case given its different operator precedents.
arg = Blockly.Arduino.valueToCode(block, 'NUM', arg =
Blockly.Arduino.ORDER_UNARY_PREFIX) || '0'; Blockly.Arduino.valueToCode(
if (arg[0] === '-') { block,
"NUM",
Blockly.Arduino.ORDER_UNARY_PREFIX
) || "0";
if (arg[0] === "-") {
// --3 is not legal in C++ in this context. // --3 is not legal in C++ in this context.
arg = ' ' + arg; arg = " " + arg;
} }
code = '-' + arg; code = "-" + arg;
return [code, Blockly.Arduino.ORDER_UNARY_PREFIX]; return [code, Blockly.Arduino.ORDER_UNARY_PREFIX];
} }
if (operator === 'ABS' || operator.substring(0, 5) === 'ROUND') { if (operator === "ABS" || operator.substring(0, 5) === "ROUND") {
arg = Blockly.Arduino.valueToCode(block, 'NUM', arg =
Blockly.Arduino.ORDER_UNARY_POSTFIX) || '0'; Blockly.Arduino.valueToCode(
} else if (operator === 'SIN' || operator === 'COS' || operator === 'TAN') { block,
arg = Blockly.Arduino.valueToCode(block, 'NUM', "NUM",
Blockly.Arduino.ORDER_MULTIPLICATIVE) || '0'; Blockly.Arduino.ORDER_UNARY_POSTFIX
) || "0";
} else if (operator === "SIN" || operator === "COS" || operator === "TAN") {
arg =
Blockly.Arduino.valueToCode(
block,
"NUM",
Blockly.Arduino.ORDER_MULTIPLICATIVE
) || "0";
} else { } else {
arg = Blockly.Arduino.valueToCode(block, 'NUM', arg =
Blockly.Arduino.ORDER_NONE) || '0'; Blockly.Arduino.valueToCode(block, "NUM", Blockly.Arduino.ORDER_NONE) ||
"0";
} }
// First, handle cases which generate values that don't need parentheses. // First, handle cases which generate values that don't need parentheses.
switch (operator) { switch (operator) {
case 'ABS': case "ABS":
code = 'abs(' + arg + ')'; code = "abs(" + arg + ")";
break; break;
case 'ROOT': case "ROOT":
code = 'sqrt(' + arg + ')'; code = "sqrt(" + arg + ")";
break; break;
case 'LN': case "LN":
code = 'log(' + arg + ')'; code = "log(" + arg + ")";
break; break;
case 'EXP': case "EXP":
code = 'exp(' + arg + ')'; code = "exp(" + arg + ")";
break; break;
case 'POW10': case "POW10":
code = 'pow(10,' + arg + ')'; code = "pow(10," + arg + ")";
break; break;
case 'ROUND': case "ROUND":
code = 'round(' + arg + ')'; code = "round(" + arg + ")";
break; break;
case 'ROUNDUP': case "ROUNDUP":
code = 'ceil(' + arg + ')'; code = "ceil(" + arg + ")";
break; break;
case 'ROUNDDOWN': case "ROUNDDOWN":
code = 'floor(' + arg + ')'; code = "floor(" + arg + ")";
break; break;
case 'SIN': case "SIN":
code = 'sin(' + arg + ' / 180 * Math.PI)'; code = "sin(" + arg + " / 180 * Math.PI)";
break; break;
case 'COS': case "COS":
code = 'cos(' + arg + ' / 180 * Math.PI)'; code = "cos(" + arg + " / 180 * Math.PI)";
break; break;
case 'TAN': case "TAN":
code = 'tan(' + arg + ' / 180 * Math.PI)'; code = "tan(" + arg + " / 180 * Math.PI)";
break; break;
default: default:
break; break;
@@ -134,20 +146,20 @@ Blockly.Arduino['math_single'] = function (block) {
} }
// Second, handle cases which generate values that may need parentheses. // Second, handle cases which generate values that may need parentheses.
switch (operator) { switch (operator) {
case 'LOG10': case "LOG10":
code = 'log(' + arg + ') / log(10)'; code = "log(" + arg + ") / log(10)";
break; break;
case 'ASIN': case "ASIN":
code = 'asin(' + arg + ') / M_PI * 180'; code = "asin(" + arg + ") / M_PI * 180";
break; break;
case 'ACOS': case "ACOS":
code = 'acos(' + arg + ') / M_PI * 180'; code = "acos(" + arg + ") / M_PI * 180";
break; break;
case 'ATAN': case "ATAN":
code = 'atan(' + arg + ') / M_PI * 180'; code = "atan(" + arg + ") / M_PI * 180";
break; break;
default: default:
throw new Error('Unknown math operator: ' + operator); throw new Error("Unknown math operator: " + operator);
} }
return [code, Blockly.Arduino.ORDER_MULTIPLICATIVE]; return [code, Blockly.Arduino.ORDER_MULTIPLICATIVE];
}; };
@@ -161,16 +173,16 @@ Blockly.Arduino['math_single'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {string} Completed code. * @return {string} Completed code.
*/ */
Blockly.Arduino['math_constant'] = function (block) { Blockly.Arduino["math_constant"] = function (block) {
var CONSTANTS = { var CONSTANTS = {
'PI': ['M_PI', Blockly.Arduino.ORDER_UNARY_POSTFIX], PI: ["M_PI", Blockly.Arduino.ORDER_UNARY_POSTFIX],
'E': ['M_E', Blockly.Arduino.ORDER_UNARY_POSTFIX], E: ["M_E", Blockly.Arduino.ORDER_UNARY_POSTFIX],
'GOLDEN_RATIO': ['(1 + sqrt(5)) / 2', Blockly.Arduino.ORDER_MULTIPLICATIVE], GOLDEN_RATIO: ["(1 + sqrt(5)) / 2", Blockly.Arduino.ORDER_MULTIPLICATIVE],
'SQRT2': ['M_SQRT2', Blockly.Arduino.ORDER_UNARY_POSTFIX], SQRT2: ["M_SQRT2", Blockly.Arduino.ORDER_UNARY_POSTFIX],
'SQRT1_2': ['M_SQRT1_2', Blockly.Arduino.ORDER_UNARY_POSTFIX], SQRT1_2: ["M_SQRT1_2", Blockly.Arduino.ORDER_UNARY_POSTFIX],
'INFINITY': ['INFINITY', Blockly.Arduino.ORDER_ATOMIC] INFINITY: ["INFINITY", Blockly.Arduino.ORDER_ATOMIC],
}; };
return CONSTANTS[block.getFieldValue('CONSTANT')]; return CONSTANTS[block.getFieldValue("CONSTANT")];
}; };
/** /**
@@ -180,58 +192,67 @@ Blockly.Arduino['math_constant'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_number_property'] = function (block) { Blockly.Arduino["math_number_property"] = function (block) {
var number_to_check = Blockly.Arduino.valueToCode(block, 'NUMBER_TO_CHECK', var number_to_check =
Blockly.Arduino.ORDER_MULTIPLICATIVE) || '0'; Blockly.Arduino.valueToCode(
var dropdown_property = block.getFieldValue('PROPERTY'); block,
"NUMBER_TO_CHECK",
Blockly.Arduino.ORDER_MULTIPLICATIVE
) || "0";
var dropdown_property = block.getFieldValue("PROPERTY");
var code; var code;
if (dropdown_property === 'PRIME') { if (dropdown_property === "PRIME") {
var func = [ var func = [
'boolean ' + Blockly.Arduino.DEF_FUNC_NAME + '(int n) {', "boolean " + Blockly.Arduino.DEF_FUNC_NAME + "(int n) {",
' // https://en.wikipedia.org/wiki/Primality_test#Naive_methods', " // https://en.wikipedia.org/wiki/Primality_test#Naive_methods",
' if (n == 2 || n == 3) {', " if (n == 2 || n == 3) {",
' return true;', " return true;",
' }', " }",
' // False if n is NaN, negative, is 1.', " // False if n is NaN, negative, is 1.",
' // And false if n is divisible by 2 or 3.', " // And false if n is divisible by 2 or 3.",
' if (isnan(n) || (n <= 1) || (n == 1) || (n % 2 == 0) || ' + " if (isnan(n) || (n <= 1) || (n == 1) || (n % 2 == 0) || " +
'(n % 3 == 0)) {', "(n % 3 == 0)) {",
' return false;', " return false;",
' }', " }",
' // Check all the numbers of form 6k +/- 1, up to sqrt(n).', " // Check all the numbers of form 6k +/- 1, up to sqrt(n).",
' for (int x = 6; x <= sqrt(n) + 1; x += 6) {', " for (int x = 6; x <= sqrt(n) + 1; x += 6) {",
' if (n % (x - 1) == 0 || n % (x + 1) == 0) {', " if (n % (x - 1) == 0 || n % (x + 1) == 0) {",
' return false;', " return false;",
' }', " }",
' }', " }",
' return true;', " return true;",
'}']; "}",
var funcName = Blockly.Arduino.addFunction('mathIsPrime', func.join('\n')); ];
Blockly.Arduino.addInclude('math', '#include <math.h>'); var funcName = Blockly.Arduino.addFunction("mathIsPrime", func.join("\n"));
code = funcName + '(' + number_to_check + ')'; Blockly.Arduino.addInclude("math", "#include <math.h>");
code = funcName + "(" + number_to_check + ")";
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX]; return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
} }
switch (dropdown_property) { switch (dropdown_property) {
case 'EVEN': case "EVEN":
code = number_to_check + ' % 2 == 0'; code = number_to_check + " % 2 == 0";
break; break;
case 'ODD': case "ODD":
code = number_to_check + ' % 2 == 1'; code = number_to_check + " % 2 == 1";
break; break;
case 'WHOLE': case "WHOLE":
Blockly.Arduino.addInclude('math', '#include <math.h>'); Blockly.Arduino.addInclude("math", "#include <math.h>");
code = '(floor(' + number_to_check + ') == ' + number_to_check + ')'; code = "(floor(" + number_to_check + ") == " + number_to_check + ")";
break; break;
case 'POSITIVE': case "POSITIVE":
code = number_to_check + ' > 0'; code = number_to_check + " > 0";
break; break;
case 'NEGATIVE': case "NEGATIVE":
code = number_to_check + ' < 0'; code = number_to_check + " < 0";
break; break;
case 'DIVISIBLE_BY': case "DIVISIBLE_BY":
var divisor = Blockly.Arduino.valueToCode(block, 'DIVISOR', var divisor =
Blockly.Arduino.ORDER_MULTIPLICATIVE) || '0'; Blockly.Arduino.valueToCode(
code = number_to_check + ' % ' + divisor + ' == 0'; block,
"DIVISOR",
Blockly.Arduino.ORDER_MULTIPLICATIVE
) || "0";
code = number_to_check + " % " + divisor + " == 0";
break; break;
default: default:
break; break;
@@ -247,19 +268,25 @@ Blockly.Arduino['math_number_property'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_change'] = function (block) { Blockly.Arduino["math_change"] = function (block) {
var argument0 = Blockly.Arduino.valueToCode(block, 'DELTA', var argument0 =
Blockly.Arduino.ORDER_ADDITIVE) || '0'; Blockly.Arduino.valueToCode(
block,
"DELTA",
Blockly.Arduino.ORDER_ADDITIVE
) || "0";
var varName = Blockly.Arduino.variableDB_.getName( var varName = Blockly.Arduino.variableDB_.getName(
block.getFieldValue('VAR'), Blockly.Variables.NAME_TYPE); block.getFieldValue("VAR"),
return varName + ' += ' + argument0 + ';\n'; Blockly.Variables.NAME_TYPE
);
return varName + " += " + argument0 + ";\n";
}; };
/** Rounding functions have a single operand. */ /** Rounding functions have a single operand. */
Blockly.Arduino['math_round'] = Blockly.Arduino['math_single']; Blockly.Arduino["math_round"] = Blockly.Arduino["math_single"];
/** Trigonometry functions have a single operand. */ /** Trigonometry functions have a single operand. */
Blockly.Arduino['math_trig'] = Blockly.Arduino['math_single']; Blockly.Arduino["math_trig"] = Blockly.Arduino["math_single"];
/** /**
* Generator for the math function to a list. * Generator for the math function to a list.
@@ -268,7 +295,7 @@ Blockly.Arduino['math_trig'] = Blockly.Arduino['math_single'];
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_on_list'] = Blockly.Arduino.noGeneratorCodeInline; Blockly.Arduino["math_on_list"] = Blockly.Arduino.noGeneratorCodeInline;
/** /**
* Generator for the math modulo function (calculates remainder of X/Y). * Generator for the math modulo function (calculates remainder of X/Y).
@@ -276,12 +303,20 @@ Blockly.Arduino['math_on_list'] = Blockly.Arduino.noGeneratorCodeInline;
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_modulo'] = function (block) { Blockly.Arduino["math_modulo"] = function (block) {
var argument0 = Blockly.Arduino.valueToCode(block, 'DIVIDEND', var argument0 =
Blockly.Arduino.ORDER_MULTIPLICATIVE) || '0'; Blockly.Arduino.valueToCode(
var argument1 = Blockly.Arduino.valueToCode(block, 'DIVISOR', block,
Blockly.Arduino.ORDER_MULTIPLICATIVE) || '0'; "DIVIDEND",
var code = argument0 + ' % ' + argument1; Blockly.Arduino.ORDER_MULTIPLICATIVE
) || "0";
var argument1 =
Blockly.Arduino.valueToCode(
block,
"DIVISOR",
Blockly.Arduino.ORDER_MULTIPLICATIVE
) || "0";
var code = argument0 + " % " + argument1;
return [code, Blockly.Arduino.ORDER_MULTIPLICATIVE]; return [code, Blockly.Arduino.ORDER_MULTIPLICATIVE];
}; };
@@ -291,17 +326,33 @@ Blockly.Arduino['math_modulo'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_constrain'] = function (block) { Blockly.Arduino["math_constrain"] = function (block) {
// Constrain a number between two limits. // Constrain a number between two limits.
var argument0 = Blockly.Arduino.valueToCode(block, 'VALUE', var argument0 =
Blockly.Arduino.ORDER_NONE) || '0'; Blockly.Arduino.valueToCode(block, "VALUE", Blockly.Arduino.ORDER_NONE) ||
var argument1 = Blockly.Arduino.valueToCode(block, 'LOW', "0";
Blockly.Arduino.ORDER_NONE) || '0'; var argument1 =
var argument2 = Blockly.Arduino.valueToCode(block, 'HIGH', Blockly.Arduino.valueToCode(block, "LOW", Blockly.Arduino.ORDER_NONE) ||
Blockly.Arduino.ORDER_NONE) || '0'; "0";
var code = '(' + argument0 + ' < ' + argument1 + ' ? ' + argument1 + var argument2 =
' : ( ' + argument0 + ' > ' + argument2 + ' ? ' + argument2 + ' : ' + Blockly.Arduino.valueToCode(block, "HIGH", Blockly.Arduino.ORDER_NONE) ||
argument0 + '))'; "0";
var code =
"(" +
argument0 +
" < " +
argument1 +
" ? " +
argument1 +
" : ( " +
argument0 +
" > " +
argument2 +
" ? " +
argument2 +
" : " +
argument0 +
"))";
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX]; return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
}; };
@@ -312,28 +363,26 @@ Blockly.Arduino['math_constrain'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {array} Completed code with order of operation. * @return {array} Completed code with order of operation.
*/ */
Blockly.Arduino['math_random_int'] = function (block) { Blockly.Arduino["math_random_int"] = function (block) {
var argument0 = Blockly.Arduino.valueToCode(block, 'FROM', var argument0 =
Blockly.Arduino.ORDER_NONE) || '0'; Blockly.Arduino.valueToCode(block, "FROM", Blockly.Arduino.ORDER_NONE) ||
var argument1 = Blockly.Arduino.valueToCode(block, 'TO', "0";
Blockly.Arduino.ORDER_NONE) || '0'; var argument1 =
var functionName = Blockly.Arduino.variableDB_.getDistinctName( Blockly.Arduino.valueToCode(block, "TO", Blockly.Arduino.ORDER_NONE) || "0";
'math_random_int', Blockly.Generator.NAME_TYPE); Blockly.Arduino.setupCode_["init_rand"] = "randomSeed(analogRead(0));";
Blockly.Arduino.setups_['init_rand'] = 'randomSeed(analogRead(0));'; Blockly.Arduino.functionNames_[
Blockly.Arduino.math_random_int.random_function = functionName; "math_random_int"
var func = [ ] = `int mathRandomInt (int min, int max) {\n
'int ' + Blockly.Arduino.DEF_FUNC_NAME + '(int min, int max) {', if (min > max) {
' if (min > max) {', int temp = min;
' // Swap min and max to ensure min is smaller.', min = max;
' int temp = min;', max = temp;
' min = max;', }
' max = temp;', return min + (rand() % (max - min + 1));
' }', }
' return min + (rand() % (max - min + 1));', `;
'}']; var code = `mathRandomInt(${argument0},${argument1});`;
var funcName = Blockly.Arduino.addFunction('mathRandomInt', func.join('\n')); return [code, Blockly.Arduino.ORDER_ATOMIC];
var code = funcName + '(' + argument0 + ', ' + argument1 + ')';
return [code, Blockly.Arduino.ORDER_UNARY_POSTFIX];
}; };
/** /**
@@ -342,6 +391,6 @@ Blockly.Arduino['math_random_int'] = function (block) {
* @param {!Blockly.Block} block Block to generate the code from. * @param {!Blockly.Block} block Block to generate the code from.
* @return {string} Completed code. * @return {string} Completed code.
*/ */
Blockly.Arduino['math_random_float'] = function (block) { Blockly.Arduino["math_random_float"] = function (block) {
return ['(rand() / RAND_MAX)', Blockly.Arduino.ORDER_UNARY_POSTFIX]; return ["(rand() / RAND_MAX)", Blockly.Arduino.ORDER_UNARY_POSTFIX];
}; };
@@ -68,7 +68,6 @@ Blockly.Arduino['procedures_defreturn'] = function (block) {
}; };
function translateType(type) { function translateType(type) {
console.log(type);
switch (type) { switch (type) {
case 'int': case 'int':
@@ -0,0 +1,127 @@
import * as Blockly from "blockly/core";
Blockly.Arduino.sensebox_phyphox_init = function () {
var name = this.getFieldValue("devicename");
Blockly.Arduino.libraries_["phyphox_library"] = `#include <phyphoxBle.h>`;
Blockly.Arduino.libraries_["library_senseBoxMCU"] =
'#include "SenseBoxMCU.h"';
Blockly.Arduino.phyphoxSetupCode_[
"phyphox_start"
] = `PhyphoxBLE::start("${name}");`;
var code = ``;
return code;
};
Blockly.Arduino.sensebox_phyphox_experiment = function () {
var experimentname = "experiment";
var title = this.getFieldValue("title").replace(/[^a-zA-Z0-9]/g, "");
var description = this.getFieldValue("description");
var branch = Blockly.Arduino.statementToCode(this, "view");
Blockly.Arduino.phyphoxSetupCode_[
`PhyphoxBleExperiment_${experimentname}`
] = `PhyphoxBleExperiment ${experimentname};`;
Blockly.Arduino.phyphoxSetupCode_[
`setTitle_${title}`
] = `${experimentname}.setTitle("${title}");`;
Blockly.Arduino.phyphoxSetupCode_[
`setCategory_senseBoxExperiments}`
] = `${experimentname}.setCategory("senseBox Experimente");`;
Blockly.Arduino.phyphoxSetupCode_[
`setDescription_${description}`
] = `${experimentname}.setDescription("${description}");`;
Blockly.Arduino.phyphoxSetupCode_[
`addView_${experimentname}`
] = `PhyphoxBleExperiment::View firstView;\nfirstView.setLabel("Messwerte"); //Create a "view"`;
Blockly.Arduino.phyphoxSetupCode_[`addGraph`] = `${branch}`;
Blockly.Arduino.phyphoxSetupCode_[
`addView_firstview`
] = `${experimentname}.addView(firstView);`; //Attach view to experiment
Blockly.Arduino.phyphoxSetupCode_[
`addExperiment_${experimentname}`
] = `PhyphoxBLE::addExperiment(${experimentname});`; //Attach experiment to server
var code = ``;
return code;
};
Blockly.Arduino["sensebox_phyphox_timestamp"] = function () {
var code = 0;
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Arduino["sensebox_phyphox_channel"] = function () {
var channel = parseFloat(this.getFieldValue("channel"));
var code = channel;
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Arduino.sensebox_phyphox_sendchannel = function (block) {
var channel = this.getFieldValue("channel");
var value =
Blockly.Arduino.valueToCode(this, "value", Blockly.Arduino.ORDER_ATOMIC) ||
"1";
var code = `float channel${channel} = ${value};\n`;
return code;
};
Blockly.Arduino.sensebox_phyphox_graph = function () {
var label = this.getFieldValue("label").replace(/[^a-zA-Z0-9]/g, "");
var unitx = this.getFieldValue("unitx");
var unity = this.getFieldValue("unity");
var labelx = this.getFieldValue("labelx");
var labely = this.getFieldValue("labely");
var style = this.getFieldValue("style");
var channelX =
Blockly.Arduino.valueToCode(
this,
"channel0",
Blockly.Arduino.ORDER_ATOMIC
) || 0;
var channelY =
Blockly.Arduino.valueToCode(
this,
"channel1",
Blockly.Arduino.ORDER_ATOMIC
) || 1;
var code = `PhyphoxBleExperiment::Graph ${label};\n`; //Create graph which will plot random numbers over time
code += `${label}.setLabel("${label}");\n`;
code += `${label}.setUnitX("${unitx}");\n`;
code += `${label}.setUnitY("${unity}");\n`;
code += `${label}.setLabelX("${labelx}");\n`;
code += `${label}.setLabelY("${labely}");\n`;
code += `${label}.setStyle("${style}");\n`;
code += `${label}.setChannel(${channelX}, ${channelY});\n`;
code += `firstView.addElement(${label});\n`;
return code;
};
Blockly.Arduino.sensebox_phyphox_experiment_send = function () {
var branch = Blockly.Arduino.statementToCode(this, "sendValues");
var blocks = this.getDescendants();
console.log(blocks);
var count = 0;
if (blocks !== undefined) {
for (var i = 0; i < blocks.length; i++) {
if (blocks[i].type === "sensebox_phyphox_sendchannel") {
count++;
}
}
}
if (count === 5) {
}
var string = "";
for (var j = 1; j <= count; j++) {
console.log("append");
if (string === "") {
string += `channel${j}`;
} else if (string !== "") {
string += `, channel${j}`;
}
}
Blockly.Arduino.loopCodeOnce_["phyphox_poll"] = `PhyphoxBLE::poll();`;
var code = `${branch}\nPhyphoxBLE::write(${string});`;
return code;
};
@@ -33,7 +33,6 @@ Blockly.Arduino.sensebox_ws2818_led = function () {
var dropdown_pin = this.getFieldValue('Port'); var dropdown_pin = this.getFieldValue('Port');
var position = Blockly.Arduino.valueToCode(this, 'POSITION', Blockly.Arduino.ORDER_ATOMIC) || '0'; var position = Blockly.Arduino.valueToCode(this, 'POSITION', Blockly.Arduino.ORDER_ATOMIC) || '0';
var color = Blockly.Arduino.valueToCode(this, 'COLOR', Blockly.Arduino.ORDER_ATOMIC) || '0' var color = Blockly.Arduino.valueToCode(this, 'COLOR', Blockly.Arduino.ORDER_ATOMIC) || '0'
console.log(color)
var code = `rgb_led_${dropdown_pin}.setPixelColor(${position},rgb_led_${dropdown_pin}.Color(${color}));\nrgb_led_${dropdown_pin}.show();\n`; var code = `rgb_led_${dropdown_pin}.setPixelColor(${position},rgb_led_${dropdown_pin}.Color(${color}));\nrgb_led_${dropdown_pin}.show();\n`;
return code; return code;
}; };
+136 -94
View File
@@ -1,27 +1,27 @@
import * as Blockly from 'blockly/core'; import * as Blockly from "blockly/core";
Blockly.Arduino.sensebox_lora_initialize_otaa = function (block) { Blockly.Arduino.sensebox_lora_initialize_otaa = function (block) {
var deivceID = this.getFieldValue('DEVICEID'); var deivceID = this.getFieldValue("DEVICEID");
var appID = this.getFieldValue('APPID'); var appID = this.getFieldValue("APPID");
var appKey = this.getFieldValue('APPKEY'); var appKey = this.getFieldValue("APPKEY");
var interval = this.getFieldValue('INTERVAL'); var interval = this.getFieldValue("INTERVAL");
Blockly.Arduino.libraries_['library_senseBoxMCU'] = '#include "SenseBoxMCU.h"'; Blockly.Arduino.libraries_["library_senseBoxMCU"] =
Blockly.Arduino.libraries_['library_spi'] = '#include <SPI.h>'; '#include "SenseBoxMCU.h"';
Blockly.Arduino.libraries_['library_lmic'] = '#include <lmic.h>'; Blockly.Arduino.libraries_["library_spi"] = "#include <SPI.h>";
Blockly.Arduino.libraries_['library_hal'] = '#include <hal/hal.h>'; Blockly.Arduino.libraries_["library_lmic"] = "#include <lmic.h>";
Blockly.Arduino.definitions_['define_LoRaVariablesOTAA'] = ` Blockly.Arduino.libraries_["library_hal"] = "#include <hal/hal.h>";
static const u1_t PROGMEM APPEUI[8]= `+ appID + ` ; Blockly.Arduino.definitions_["define_LoRaVariablesOTAA"] = `
static const u1_t PROGMEM APPEUI[8]= {${appID}};
void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI , 8);} void os_getArtEui (u1_t* buf) { memcpy_P(buf, APPEUI , 8);}
static const u1_t PROGMEM DEVEUI[8]= `+ deivceID + `; static const u1_t PROGMEM DEVEUI[8]= {${deivceID}};
void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI , 8);} void os_getDevEui (u1_t* buf) { memcpy_P(buf, DEVEUI , 8);}
// This key should be in big endian format (or, since it is not really a // This key should be in big endian format (or, since it is not really a
// number but a block of memory, endianness does not really apply). In // number but a block of memory, endianness does not really apply). In
// practice, a key taken from ttnctl can be copied as-is. // practice, a key taken from ttnctl can be copied as-is.
// The key shown here is the semtech default key. // The key shown here is the semtech default key.
static const u1_t PROGMEM APPKEY[16] = `+ appKey + `; static const u1_t PROGMEM APPKEY[16] = {${appKey}};
void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY , 16);} void os_getDevKey (u1_t* buf) { memcpy_P(buf, APPKEY , 16);}
static osjob_t sendjob; static osjob_t sendjob;
@@ -38,7 +38,7 @@ Blockly.Arduino.sensebox_lora_initialize_otaa = function (block) {
.dio = {PIN_XB1_INT, PIN_XB1_INT, LMIC_UNUSED_PIN}, .dio = {PIN_XB1_INT, PIN_XB1_INT, LMIC_UNUSED_PIN},
};`; };`;
Blockly.Arduino.codeFunctions_['functions_initLora'] = ` Blockly.Arduino.codeFunctions_["functions_initLora"] = `
void initLora() { void initLora() {
delay(2000); delay(2000);
// LMIC init // LMIC init
@@ -48,9 +48,9 @@ Blockly.Arduino.sensebox_lora_initialize_otaa = function (block) {
// Start job (sending automatically starts OTAA too) // Start job (sending automatically starts OTAA too)
do_send(&sendjob); do_send(&sendjob);
}` }`;
Blockly.Arduino.codeFunctions_['functions_onEvent'] = ` Blockly.Arduino.codeFunctions_["functions_onEvent"] = `
void onEvent (ev_t ev) { void onEvent (ev_t ev) {
Serial.print(os_getTime()); Serial.print(os_getTime());
Serial.print(": "); Serial.print(": ");
@@ -120,16 +120,18 @@ Blockly.Arduino.sensebox_lora_initialize_otaa = function (block) {
break; break;
} }
}`; }`;
Blockly.Arduino.loraSetupCode_['initLora'] = 'initLora();\n'; Blockly.Arduino.loraSetupCode_["initLora"] = "initLora();\n";
Blockly.Arduino.setupCode_['serial.begin'] = 'Serial.begin(9600);\ndelay(1000);\n'; Blockly.Arduino.setupCode_["serial.begin"] =
var code = ''; "Serial.begin(9600);\ndelay(1000);\n";
var code = "";
return code; return code;
}; };
Blockly.Arduino.sensebox_lora_message_send = function (block) { Blockly.Arduino.sensebox_lora_message_send = function (block) {
Blockly.Arduino.libraries_['library_lora_message'] = '#include <LoraMessage.h>'; Blockly.Arduino.libraries_["library_lora_message"] =
var lora_sensor_values = Blockly.Arduino.statementToCode(block, 'DO'); "#include <LoraMessage.h>";
Blockly.Arduino.functionNames_['functions_do_send'] = ` var lora_sensor_values = Blockly.Arduino.statementToCode(block, "DO");
Blockly.Arduino.functionNames_["functions_do_send"] = `
void do_send(osjob_t* j){ void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running // Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) { if (LMIC.opmode & OP_TXRXPEND) {
@@ -144,39 +146,41 @@ Blockly.Arduino.sensebox_lora_message_send = function (block) {
} }
// Next TX is scheduled after TX_COMPLETE event. // Next TX is scheduled after TX_COMPLETE event.
}`; }`;
Blockly.Arduino.loopCodeOnce_['os_runloop'] = 'os_runloop_once();' Blockly.Arduino.loopCodeOnce_["os_runloop"] = "os_runloop_once();";
return '' return "";
} };
/** /**
* Block send Data to TTN * Block send Data to TTN
*/ */
Blockly.Arduino.sensebox_send_lora_sensor_value = function (block) { Blockly.Arduino.sensebox_send_lora_sensor_value = function (block) {
const reading = Blockly.Arduino.valueToCode(this, 'Value', Blockly.Arduino.ORDER_ATOMIC) || '"Keine Eingabe"'; const reading =
var messageBytes = this.getFieldValue('MESSAGE_BYTES'); Blockly.Arduino.valueToCode(this, "Value", Blockly.Arduino.ORDER_ATOMIC) ||
var code = '' '"Keine Eingabe"';
var messageBytes = this.getFieldValue("MESSAGE_BYTES");
var code = "";
switch (Number(messageBytes)) { switch (Number(messageBytes)) {
case 1: case 1:
code = `message.addUint8(${reading});\n` code = `message.addUint8(${reading});\n`;
break; break;
case 2: case 2:
code = `message.addUint16(${reading});\n` code = `message.addUint16(${reading});\n`;
break; break;
case 3: case 3:
code = `message.addUint8(${reading}); code = `message.addUint8(${reading});
message.addUint16(${reading} >> 8);\n` message.addUint16(${reading} >> 8);\n`;
break; break;
default: default:
code = `message.addUint16(${reading});\n` code = `message.addUint16(${reading});\n`;
} }
return code; return code;
}; };
Blockly.Arduino.sensebox_lora_cayenne_send = function (block) { Blockly.Arduino.sensebox_lora_cayenne_send = function (block) {
Blockly.Arduino.libraries_['library_cayene'] = '#include <CayenneLPP.h>'; Blockly.Arduino.libraries_["library_cayene"] = "#include <CayenneLPP.h>";
Blockly.Arduino.variables_['variable_cayenne'] = 'CayenneLPP lpp(51);' Blockly.Arduino.variables_["variable_cayenne"] = "CayenneLPP lpp(51);";
var lora_sensor_values = Blockly.Arduino.statementToCode(block, 'DO'); var lora_sensor_values = Blockly.Arduino.statementToCode(block, "DO");
Blockly.Arduino.functionNames_['functions_do_send'] = ` Blockly.Arduino.functionNames_["functions_do_send"] = `
void do_send(osjob_t* j){ void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running // Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) { if (LMIC.opmode & OP_TXRXPEND) {
@@ -191,18 +195,38 @@ Blockly.Arduino.sensebox_lora_cayenne_send = function (block) {
} }
// Next TX is scheduled after TX_COMPLETE event. // Next TX is scheduled after TX_COMPLETE event.
}`; }`;
Blockly.Arduino.loopCodeOnce_['os_runloop'] = 'os_runloop_once();' Blockly.Arduino.loopCodeOnce_["os_runloop"] = "os_runloop_once();";
return ''; return "";
} };
Blockly.Arduino.sensebox_lora_ttn_mapper = function (block) { Blockly.Arduino.sensebox_lora_ttn_mapper = function (block) {
var latitude = Blockly.Arduino.valueToCode(this, 'Latitude', Blockly.Arduino.ORDER_ATOMIC) var latitude = Blockly.Arduino.valueToCode(
var longitude = Blockly.Arduino.valueToCode(this, 'Longitude', Blockly.Arduino.ORDER_ATOMIC) this,
var altitude = Blockly.Arduino.valueToCode(this, 'Altitude', Blockly.Arduino.ORDER_ATOMIC) "Latitude",
var pDOP = Blockly.Arduino.valueToCode(this, 'pDOP', Blockly.Arduino.ORDER_ATOMIC) Blockly.Arduino.ORDER_ATOMIC
var fixType = Blockly.Arduino.valueToCode(this, 'Fix Type', Blockly.Arduino.ORDER_ATOMIC) );
var fixTypeLimit = this.getFieldValue('dropdown'); var longitude = Blockly.Arduino.valueToCode(
Blockly.Arduino.functionNames_['functions_do_send'] = ` this,
"Longitude",
Blockly.Arduino.ORDER_ATOMIC
);
var altitude = Blockly.Arduino.valueToCode(
this,
"Altitude",
Blockly.Arduino.ORDER_ATOMIC
);
var pDOP = Blockly.Arduino.valueToCode(
this,
"pDOP",
Blockly.Arduino.ORDER_ATOMIC
);
var fixType = Blockly.Arduino.valueToCode(
this,
"Fix Type",
Blockly.Arduino.ORDER_ATOMIC
);
var fixTypeLimit = this.getFieldValue("dropdown");
Blockly.Arduino.functionNames_["functions_do_send"] = `
void do_send(osjob_t* j){ void do_send(osjob_t* j){
// Check if there is not a current TX/RX job running // Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) { if (LMIC.opmode & OP_TXRXPEND) {
@@ -245,29 +269,30 @@ Blockly.Arduino.sensebox_lora_ttn_mapper = function (block) {
} }
// Next TX is scheduled after TX_COMPLETE event. // Next TX is scheduled after TX_COMPLETE event.
}`; }`;
Blockly.Arduino.loopCodeOnce_['os_runloop'] = 'os_runloop_once();' Blockly.Arduino.loopCodeOnce_["os_runloop"] = "os_runloop_once();";
return ''; return "";
} };
Blockly.Arduino.sensebox_lora_initialize_abp = function (block) { Blockly.Arduino.sensebox_lora_initialize_abp = function (block) {
var nwskey = this.getFieldValue('NWSKEY'); var nwskey = this.getFieldValue("NWSKEY");
var appskey = this.getFieldValue('APPSKEY'); var appskey = this.getFieldValue("APPSKEY");
var devaddr = this.getFieldValue('DEVADDR'); var devaddr = this.getFieldValue("DEVADDR");
var interval = this.getFieldValue('INTERVAL'); var interval = this.getFieldValue("INTERVAL");
Blockly.Arduino.libraries_['library_senseBoxMCU'] = '#include "SenseBoxMCU.h"'; Blockly.Arduino.libraries_["library_senseBoxMCU"] =
Blockly.Arduino.libraries_['library_spi'] = '#include <SPI.h>'; '#include "SenseBoxMCU.h"';
Blockly.Arduino.libraries_['library_lmic'] = '#include <lmic.h>'; Blockly.Arduino.libraries_["library_spi"] = "#include <SPI.h>";
Blockly.Arduino.libraries_['library_hal'] = '#include <hal/hal.h>'; Blockly.Arduino.libraries_["library_lmic"] = "#include <lmic.h>";
Blockly.Arduino.definitions_['define_LoRaVariablesABP'] = ` Blockly.Arduino.libraries_["library_hal"] = "#include <hal/hal.h>";
Blockly.Arduino.definitions_["define_LoRaVariablesABP"] = `
// LoRaWAN NwkSKey, network session key // LoRaWAN NwkSKey, network session key
// This is the default Semtech key, which is used by the early prototype TTN // This is the default Semtech key, which is used by the early prototype TTN
// network. // network.
static const PROGMEM u1_t NWKSKEY[16] = ${nwskey}; static const PROGMEM u1_t NWKSKEY[16] = { ${nwskey} };
// LoRaWAN AppSKey, application session key // LoRaWAN AppSKey, application session key
// This is the default Semtech key, which is used by the early prototype TTN // This is the default Semtech key, which is used by the early prototype TTN
// network. // network.
static const u1_t PROGMEM APPSKEY[16] = ${appskey}; static const u1_t PROGMEM APPSKEY[16] = { ${appskey} };
// LoRaWAN end-device address (DevAddr) // LoRaWAN end-device address (DevAddr)
static const u4_t DEVADDR = 0x${devaddr}; static const u4_t DEVADDR = 0x${devaddr};
@@ -293,7 +318,7 @@ Blockly.Arduino.sensebox_lora_initialize_abp = function (block) {
.dio = {PIN_XB1_INT, PIN_XB1_INT, LMIC_UNUSED_PIN}, .dio = {PIN_XB1_INT, PIN_XB1_INT, LMIC_UNUSED_PIN},
};`; };`;
Blockly.Arduino.codeFunctions_['functions_initLora'] = ` Blockly.Arduino.codeFunctions_["functions_initLora"] = `
void initLora() { void initLora() {
delay(2000); delay(2000);
// LMIC init // LMIC init
@@ -359,9 +384,9 @@ Blockly.Arduino.sensebox_lora_initialize_abp = function (block) {
// Start job // Start job
do_send(&sendjob); do_send(&sendjob);
}` }`;
Blockly.Arduino.codeFunctions_['functions_onEvent'] = ` Blockly.Arduino.codeFunctions_["functions_onEvent"] = `
void onEvent (ev_t ev) { void onEvent (ev_t ev) {
Serial.print(os_getTime()); Serial.print(os_getTime());
Serial.print(": "); Serial.print(": ");
@@ -426,60 +451,77 @@ Blockly.Arduino.sensebox_lora_initialize_abp = function (block) {
break; break;
} }
}`; }`;
Blockly.Arduino.loraSetupCode_['initLora'] = 'initLora();\n'; Blockly.Arduino.loraSetupCode_["initLora"] = "initLora();\n";
Blockly.Arduino.setupCode_['serial.begin'] = 'Serial.begin(9600);\ndelay(1000);\n'; Blockly.Arduino.setupCode_["serial.begin"] =
return ''; "Serial.begin(9600);\ndelay(1000);\n";
} return "";
};
Blockly.Arduino.sensebox_lora_cayenne_temperature = function (block) { Blockly.Arduino.sensebox_lora_cayenne_temperature = function (block) {
var temperature = Blockly.Arduino.valueToCode(this, 'Value', Blockly.Arduino.ORDER_ATOMIC) || 0 var temperature =
var channel = this.getFieldValue('CHANNEL'); Blockly.Arduino.valueToCode(this, "Value", Blockly.Arduino.ORDER_ATOMIC) ||
0;
var channel = this.getFieldValue("CHANNEL");
var code = `lpp.addTemperature(${channel}, ${temperature});\n`; var code = `lpp.addTemperature(${channel}, ${temperature});\n`;
return code; return code;
} };
Blockly.Arduino.sensebox_lora_cayenne_humidity = function (block) { Blockly.Arduino.sensebox_lora_cayenne_humidity = function (block) {
var humidity = Blockly.Arduino.valueToCode(this, 'Value', Blockly.Arduino.ORDER_ATOMIC) || 0 var humidity =
var channel = this.getFieldValue('CHANNEL'); Blockly.Arduino.valueToCode(this, "Value", Blockly.Arduino.ORDER_ATOMIC) ||
0;
var channel = this.getFieldValue("CHANNEL");
var code = `lpp.addRelativeHumidity(${channel}, ${humidity});\n`; var code = `lpp.addRelativeHumidity(${channel}, ${humidity});\n`;
return code; return code;
} };
Blockly.Arduino.sensebox_lora_cayenne_pressure = function (block) { Blockly.Arduino.sensebox_lora_cayenne_pressure = function (block) {
var pressure = Blockly.Arduino.valueToCode(this, 'Value', Blockly.Arduino.ORDER_ATOMIC) || 0 var pressure =
var channel = this.getFieldValue('CHANNEL'); Blockly.Arduino.valueToCode(this, "Value", Blockly.Arduino.ORDER_ATOMIC) ||
0;
var channel = this.getFieldValue("CHANNEL");
var code = `lpp.addBarometricPressure(${channel}, ${pressure});\n`; var code = `lpp.addBarometricPressure(${channel}, ${pressure});\n`;
return code; return code;
} };
Blockly.Arduino.sensebox_lora_cayenne_luminosity = function (block) { Blockly.Arduino.sensebox_lora_cayenne_luminosity = function (block) {
var luminosity = Blockly.Arduino.valueToCode(this, 'Value', Blockly.Arduino.ORDER_ATOMIC) || 0 var luminosity =
var channel = this.getFieldValue('CHANNEL'); Blockly.Arduino.valueToCode(this, "Value", Blockly.Arduino.ORDER_ATOMIC) ||
0;
var channel = this.getFieldValue("CHANNEL");
var code = `lpp.addLuminosity(${channel}, ${luminosity});\n`; var code = `lpp.addLuminosity(${channel}, ${luminosity});\n`;
return code; return code;
} };
Blockly.Arduino.sensebox_lora_cayenne_sensor = function (block) { Blockly.Arduino.sensebox_lora_cayenne_sensor = function (block) {
var sensorValue = Blockly.Arduino.valueToCode(this, 'Value', Blockly.Arduino.ORDER_ATOMIC) || 0 var sensorValue =
var channel = this.getFieldValue('CHANNEL'); Blockly.Arduino.valueToCode(this, "Value", Blockly.Arduino.ORDER_ATOMIC) ||
0;
var channel = this.getFieldValue("CHANNEL");
var code = `lpp.addAnalogInput(${channel}, ${sensorValue});\n`; var code = `lpp.addAnalogInput(${channel}, ${sensorValue});\n`;
return code; return code;
} };
Blockly.Arduino.sensebox_lora_cayenne_accelerometer = function (block) { Blockly.Arduino.sensebox_lora_cayenne_accelerometer = function (block) {
var x = Blockly.Arduino.valueToCode(this, 'X', Blockly.Arduino.ORDER_ATOMIC) || 0 var x =
var y = Blockly.Arduino.valueToCode(this, 'Y', Blockly.Arduino.ORDER_ATOMIC) || 0 Blockly.Arduino.valueToCode(this, "X", Blockly.Arduino.ORDER_ATOMIC) || 0;
var z = Blockly.Arduino.valueToCode(this, 'Z', Blockly.Arduino.ORDER_ATOMIC) || 0 var y =
var channel = this.getFieldValue('CHANNEL'); Blockly.Arduino.valueToCode(this, "Y", Blockly.Arduino.ORDER_ATOMIC) || 0;
var z =
Blockly.Arduino.valueToCode(this, "Z", Blockly.Arduino.ORDER_ATOMIC) || 0;
var channel = this.getFieldValue("CHANNEL");
var code = `lpp.addAccelerometer(${channel}, ${x}, ${y}, ${z});\n`; var code = `lpp.addAccelerometer(${channel}, ${x}, ${y}, ${z});\n`;
return code; return code;
} };
Blockly.Arduino.sensebox_lora_cayenne_gps = function (block) { Blockly.Arduino.sensebox_lora_cayenne_gps = function (block) {
var lat = Blockly.Arduino.valueToCode(this, 'LAT', Blockly.Arduino.ORDER_ATOMIC) || 0 var lat =
var lng = Blockly.Arduino.valueToCode(this, 'LNG', Blockly.Arduino.ORDER_ATOMIC) || 0 Blockly.Arduino.valueToCode(this, "LAT", Blockly.Arduino.ORDER_ATOMIC) || 0;
var alt = Blockly.Arduino.valueToCode(this, 'ALT', Blockly.Arduino.ORDER_ATOMIC) || 0 var lng =
var channel = this.getFieldValue('CHANNEL'); Blockly.Arduino.valueToCode(this, "LNG", Blockly.Arduino.ORDER_ATOMIC) || 0;
var code = `lpp.addGPS(${channel}, ${lat}, ${lng}, ${alt});\n` var alt =
Blockly.Arduino.valueToCode(this, "ALT", Blockly.Arduino.ORDER_ATOMIC) || 0;
var channel = this.getFieldValue("CHANNEL");
var code = `lpp.addGPS(${channel}, ${lat}, ${lng}, ${alt});\n`;
return code; return code;
} };
@@ -0,0 +1,96 @@
import Blockly from "blockly";
Blockly.Arduino.sensebox_rtc_init = function () {
Blockly.Arduino.libraries_["RV8523"] = `#include <RV8523.h>`;
Blockly.Arduino.definitions_["RTC"] = `RV8523 rtc;`;
Blockly.Arduino.libraries_["library_senseBoxMCU"] =
'#include "SenseBoxMCU.h"';
Blockly.Arduino.setupCode_["rtc.begin"] = `rtc.begin();`;
var code = ``;
return code;
};
Blockly.Arduino.sensebox_rtc_set = function () {
var second =
Blockly.Arduino.valueToCode(this, "second", Blockly.Arduino.ORDER_ATOMIC) ||
"0";
var minutes =
Blockly.Arduino.valueToCode(this, "second", Blockly.Arduino.ORDER_ATOMIC) ||
"0";
var hour =
Blockly.Arduino.valueToCode(this, "second", Blockly.Arduino.ORDER_ATOMIC) ||
"0";
var day =
Blockly.Arduino.valueToCode(this, "second", Blockly.Arduino.ORDER_ATOMIC) ||
"0";
var month =
Blockly.Arduino.valueToCode(this, "second", Blockly.Arduino.ORDER_ATOMIC) ||
"0";
var year =
Blockly.Arduino.valueToCode(this, "second", Blockly.Arduino.ORDER_ATOMIC) ||
"0";
Blockly.Arduino.libraries_["RV8523"] = `#include <RV8523.h>`;
Blockly.Arduino.setupCode_["rtc.start"] = `rtc.start();`;
Blockly.Arduino.setupCode_[
"rtc.batterySwitchOver"
] = `rtc.batterySwitchOver(1);`;
Blockly.Arduino.setupCode_[
"rtc.set"
] = `rtc.set(${second}, ${minutes}, ${hour}, ${day}, ${month}, ${year});`;
var code = ``;
return code;
};
Blockly.Arduino.sensebox_rtc_ntp = function () {
Blockly.Arduino.libraries_["RV8523"] = `#include <RV8523.h>`;
Blockly.Arduino.setupCode_["rtc.start"] = `rtc.start();`;
Blockly.Arduino.setupCode_[
"rtc.batterySwitchOver"
] = `rtc.batterySwitchOver(1);`;
Blockly.Arduino.setupCode_[
"rtc.set"
] = `rtc.set(SECOND, MINUTE, HOUR, DAY, MONTH, YEAR);`;
var code = ``;
return code;
};
Blockly.Arduino.sensebox_rtc_get = function () {
var dropdown = this.getFieldValue("dropdown");
Blockly.Arduino.libraries_["RV8523"] = `#include <RV8523.h>`;
Blockly.Arduino.setupCode_["rtc.start"] = `rtc.start();`;
Blockly.Arduino.setupCode_[
"rtc.batterySwitchOver"
] = `rtc.batterySwitchOver(1);`;
Blockly.Arduino.loopCodeOnce_[
"rtc_variables"
] = `uint8_t sec, min, hour, day, month;\nuint16_t year;`;
Blockly.Arduino.loopCodeOnce_[
"rtc_get"
] = `rtc.get(&sec, &min, &hour, &day, &month, &year);`;
var code = `${dropdown}`;
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
Blockly.Arduino.sensebox_rtc_get_timestamp = function () {
Blockly.Arduino.libraries_["RV8523"] = `#include <RV8523.h>`;
Blockly.Arduino.setupCode_["rtc.start"] = `rtc.start();`;
Blockly.Arduino.setupCode_[
"rtc.batterySwitchOver"
] = `rtc.batterySwitchOver(1);`;
Blockly.Arduino.loopCodeOnce_[
"rtc_variables"
] = `uint8_t sec, min, hour, day, month;\nuint16_t year;`;
Blockly.Arduino.variables_["rtc_timestamp"] = `char timestamp[20];`;
Blockly.Arduino.loopCodeOnce_[
"rtc_get"
] = `rtc.get(&sec, &min, &hour, &day, &month, &year);`;
Blockly.Arduino.loopCodeOnce_[
""
] = `sprintf(timestamp, "%02d-%02d-%02dT%02d:%02d:%02dZ", year, month, day, hour, min, sec);`;
var code = `timestamp`;
return [code, Blockly.Arduino.ORDER_ATOMIC];
};
+37 -2
View File
@@ -1,3 +1,38 @@
import * as Blockly from 'blockly/core'; import * as Blockly from "blockly/core";
import { Block } from 'blockly';
/*
* Multiplexer
*/
Blockly.Arduino.sensebox_multiplexer_init = function () {
// Blockly.Arduino.libraries_['library_spi'] = '#include <SPI.h>';
var nrChannels =
Blockly.Arduino.valueToCode(
this,
"nrChannels",
Blockly.Arduino.ORDER_ATOMIC
) | 0;
var array = [];
for (var i = 0; i < nrChannels; i++) {
array.push(i);
}
Blockly.Arduino.libraries_["library_wire"] = "#include <Wire.h>";
Blockly.Arduino.definitions_[
"define_multiplexer"
] = `byte multiplexAddress = 0x77;
byte channels[] = {${array}};`;
// Blockly.Arduino.setupCode_['sensebox_display_begin'] = 'senseBoxIO.powerI2C(true);\ndelay(2000);\ndisplay.begin(SSD1306_SWITCHCAPVCC, 0x3D);\ndisplay.display();\ndelay(100);\ndisplay.clearDisplay();';
var code = "";
return code;
};
Blockly.Arduino.sensebox_multiplexer_changeChannel = function () {
var channel = Blockly.Arduino.valueToCode(
this,
"Channel",
Blockly.Arduino.ORDER_ATOMIC
);
var code = `Wire.beginTransmission(0x77);
Wire.write(1 << channels[${channel - 1}]);
Wire.endTransmission();`;
return code;
};
+30 -22
View File
@@ -1,36 +1,44 @@
import Blockly from 'blockly'; import Blockly from "blockly";
const setVariableFunction = function (defaultValue) { const setVariableFunction = function (defaultValue) {
return function (block) { return function (block) {
const variableName = Blockly['Arduino'].variableDB_.getName( const variableName = Blockly["Arduino"].variableDB_.getName(
block.getFieldValue('VAR'), block.getFieldValue("VAR"),
Blockly.Variables.NAME_TYPE Blockly.Variables.NAME_TYPE
); );
const variableValue = Blockly['Arduino'].valueToCode( const variableValue = Blockly["Arduino"].valueToCode(
block, block,
'VALUE', "VALUE",
Blockly['Arduino'].ORDER_ATOMIC Blockly["Arduino"].ORDER_ATOMIC
); );
const allVars = Blockly.getMainWorkspace().getVariableMap().getAllVariables(); const allVars = Blockly.getMainWorkspace()
const myVar = allVars.filter(v => v.name === variableName)[0] .getVariableMap()
var code = '' .getAllVariables();
const myVar = allVars.filter((v) => v.name === variableName)[0];
var code = "";
switch (myVar.type) { switch (myVar.type) {
default: default:
Blockly.Arduino.variables_[myVar + myVar.type] = myVar.type + " " + myVar.name + ';\n'; Blockly.Arduino.variables_[variableName + myVar.type] =
code = variableName + ' = ' + (variableValue || defaultValue) + ';\n'; myVar.type + " " + myVar.name + ";\n";
code = variableName + " = " + (variableValue || defaultValue) + ";\n";
break; break;
case 'Array': case "Array":
var arrayType; var arrayType;
var number; var number;
if (this.getChildren().length > 0) { if (this.getChildren().length > 0) {
if (this.getChildren()[0].type === 'lists_create_empty') { if (this.getChildren()[0].type === "lists_create_empty") {
arrayType = this.getChildren()[0].getFieldValue("type");
arrayType = this.getChildren()[0].getFieldValue('type'); number = Blockly.Arduino.valueToCode(
number = Blockly.Arduino.valueToCode(this.getChildren()[0], 'NUMBER', Blockly['Arduino'].ORDER_ATOMIC); this.getChildren()[0],
Blockly.Arduino.variables_[myVar + myVar.type] = `${arrayType} ${myVar.name} [${number}];\n`; "NUMBER",
Blockly["Arduino"].ORDER_ATOMIC
);
Blockly.Arduino.variables_[
myVar + myVar.type
] = `${arrayType} ${myVar.name} [${number}];\n`;
} }
} }
break; break;
@@ -40,13 +48,13 @@ const setVariableFunction = function (defaultValue) {
}; };
const getVariableFunction = function (block) { const getVariableFunction = function (block) {
const variableName = Blockly['Arduino'].variableDB_.getName( const variableName = Blockly["Arduino"].variableDB_.getName(
block.getFieldValue('VAR'), block.getFieldValue("VAR"),
Blockly.Variables.NAME_TYPE Blockly.Variables.NAME_TYPE
); );
var code = variableName; var code = variableName;
return [code, Blockly['Arduino'].ORDER_ATOMIC]; return [code, Blockly["Arduino"].ORDER_ATOMIC];
}; };
Blockly['Arduino']['variables_set_dynamic'] = setVariableFunction() Blockly["Arduino"]["variables_set_dynamic"] = setVariableFunction();
Blockly['Arduino']['variables_get_dynamic'] = getVariableFunction; Blockly["Arduino"]["variables_get_dynamic"] = getVariableFunction;
+3 -5
View File
@@ -1,4 +1,3 @@
const colours = { const colours = {
sensebox: 120, sensebox: 120,
logic: 210, logic: 210,
@@ -12,11 +11,10 @@ const colours = {
audio: 250, audio: 250,
arrays: 33, arrays: 33,
mqtt: 90, mqtt: 90,
webserver: 40 webserver: 40,
} phyphox: 25,
};
export const getColour = () => { export const getColour = () => {
return colours; return colours;
}; };
-132
View File
@@ -105,135 +105,3 @@ export const getCompatibleTypes = (type) => {
}; };
export const VARIABLE_TYPES = [['SHORT_NUMBER', 'char'], ['NUMBER', 'int'], ['DECIMAL', 'long'], ['TEXT', 'String'], ['CHARACTER', 'char'], ['BOOLEAN', 'boolean'], ['NULL', 'void'], ['UNDEF', 'undefined']]; export const VARIABLE_TYPES = [['SHORT_NUMBER', 'char'], ['NUMBER', 'int'], ['DECIMAL', 'long'], ['TEXT', 'String'], ['CHARACTER', 'char'], ['BOOLEAN', 'boolean'], ['NULL', 'void'], ['UNDEF', 'undefined']];
// /**
// * Some Types have circular dependencies on their compatibilities, so add them
// * after declaration.
// */
// Blockly.Types.NUMBER.addCompatibleTypes([
// Blockly.Types.BOOLEAN,
// Blockly.Types.SHORT_NUMBER,
// Blockly.Types.LARGE_NUMBER,
// Blockly.Types.DECIMAL]);
// Blockly.Types.SHORT_NUMBER.addCompatibleTypes([
// Blockly.Types.BOOLEAN,
// Blockly.Types.NUMBER,
// Blockly.Types.LARGE_NUMBER,
// Blockly.Types.DECIMAL]);
// Blockly.Types.LARGE_NUMBER.addCompatibleTypes([
// Blockly.Types.BOOLEAN,
// Blockly.Types.SHORT_NUMBER,
// Blockly.Types.NUMBER,
// Blockly.Types.DECIMAL]);
// /**
// * Adds another type to the Blockly.Types collection.
// * @param {string} typeId_ Identifiable name of the type.
// * @param {string} typeMsgName_ Name of the member variable from Blockly.Msg
// * object to identify the translateble string.for the Type name.
// * @param {Array<Blockly.Type>} compatibleTypes_ List of types this Type is
// * compatible with.
// */
// Blockly.Types.addType = function (typeId_, typeMsgName_, compatibleTypes_) {
// // The Id is used as the key from the value pair in the BlocklyTypes object
// var key = typeId_.toUpperCase().replace(/ /g, '_');
// if (Blockly.Types[key] !== undefined) {
// throw 'The Blockly type ' + key + ' already exists.';
// }
// Blockly.Types[key] = new Blockly.Type({
// typeId: typeId_,
// typeName: typeMsgName_,
// compatibleTypes: compatibleTypes_
// });
// };
// /**
// * Converts the static types dictionary in to a an array with 2-item arrays.
// * This array only contains the valid types, excluding any error or temp types.
// * @return {!Array<Array<string>>} Blockly types in the format described above.
// */
// Blockly.Types.getValidTypeArray = function () {
// var typesArray = [];
// for (var typeKey in Blockly.Types) {
// if ((typeKey !== 'UNDEF') && (typeKey !== 'CHILD_BLOCK_MISSING') &&
// (typeKey !== 'NULL') && (typeKey !== 'ARRAY') &&
// (typeof Blockly.Types[typeKey] !== 'function') &&
// !(Blockly.Types[typeKey] instanceof RegExp)) {
// typesArray.push([Blockly.Types[typeKey].typeName, typeKey]);
// }
// }
// return typesArray;
// };
// /**
// * Navigates through child blocks of the argument block to get this block type.
// * @param {!Blockly.Block} block Block to navigate through children.
// * @return {Blockly.Type} Type of the input block.
// */
// Blockly.Types.getChildBlockType = function (block) {
// var blockType = null;
// var nextBlock = block;
// // Only checks first input block, so it decides the type. Incoherences amongst
// // multiple inputs dealt at a per-block level with their own block warnings
// while (nextBlock && (nextBlock.getBlockType === undefined) &&
// (nextBlock.inputList.length > 0) &&
// (nextBlock.inputList[0].connection)) {
// nextBlock = nextBlock.inputList[0].connection.targetBlock();
// }
// if (nextBlock === block) {
// // Set variable block is empty, so no type yet
// blockType = Blockly.Types.CHILD_BLOCK_MISSING;
// } else if (nextBlock === null) {
// // Null return from targetBlock indicates no block connected
// blockType = Blockly.Types.CHILD_BLOCK_MISSING;
// } else {
// var func = nextBlock.getBlockType;
// if (func) {
// blockType = nextBlock.getBlockType();
// } else {
// // Most inner block, supposed to define a type, is missing getBlockType()
// blockType = Blockly.Types.NULL;
// }
// }
// return blockType;
// };
// /**
// * Regular expressions to identify an integer.
// * @private
// */
// Blockly.Types.regExpInt_ = new RegExp(/^-?\d+$/);
// /**
// * Regular expressions to identify a decimal.
// * @private
// */
// Blockly.Types.regExpFloat_ = new RegExp(/^-?[0-9]*[.][0-9]+$/);
// /**
// * Uses regular expressions to identify if the input number is an integer or a
// * floating point.
// * @param {string} numberString String of the number to identify.
// * @return {!Blockly.Type} Blockly type.
// */
// Blockly.Types.identifyNumber = function (numberString) {
// if (Blockly.Types.regExpInt_.test(numberString)) {
// var intValue = parseInt(numberString);
// if (isNaN(intValue)) {
// return Blockly.Types.NULL;
// }
// if (intValue > 32767 || intValue < -32768) {
// return Blockly.Types.LARGE_NUMBER;
// }
// return Blockly.Types.NUMBER;
// } else if (Blockly.Types.regExpFloat_.test(numberString)) {
// return Blockly.Types.DECIMAL;
// }
// return Blockly.Types.NULL;
// };
+30 -25
View File
@@ -1,29 +1,32 @@
import { AUDIO } from "./de/audio";
import { AUDIO } from './de/audio'; import { BLE } from "./de/sensebox-ble";
import { FAQ } from './de/faq'; import { FAQ } from "./de/faq";
import { IO } from './de/io'; import { IO } from "./de/io";
import { LOGIC } from './de/logic'; import { LOGIC } from "./de/logic";
import { LOOPS } from './de/loops'; import { LOOPS } from "./de/loops";
import { MATH } from './de/math'; import { MATH } from "./de/math";
import { MQTT } from './de/mqtt'; import { MQTT } from "./de/mqtt";
import { DISPLAY } from './de/sensebox-display'; import { DISPLAY } from "./de/sensebox-display";
import { LED } from './de/sensebox-led'; import { LED } from "./de/sensebox-led";
import { LORA } from './de/sensebox-lora'; import { LORA } from "./de/sensebox-lora";
import { OSEM } from './de/sensebox-osem'; import { OSEM } from "./de/sensebox-osem";
import { SD } from './de/sensebox-sd'; import { RTC } from "./de/sensebox-rtc";
import { SENSORS } from './de/sensebox-sensors'; import { SD } from "./de/sensebox-sd";
import { TELEGRAM } from './de/sensebox-telegram'; import { SENSORS } from "./de/sensebox-sensors";
import { WEB } from './de/sensebox-web'; import { SENSEBOX } from "./de/sensebox";
import { TEXT } from './de/text'; import { TELEGRAM } from "./de/sensebox-telegram";
import { TIME } from './de/time'; import { WEB } from "./de/sensebox-web";
import { TOURS } from './de/tours'; import { TEXT } from "./de/text";
import { TRANSLATIONS } from './de/translations'; import { TIME } from "./de/time";
import { UI } from './de/ui'; import { TOURS } from "./de/tours";
import { VARIABLES } from './de/variables'; import { TRANSLATIONS } from "./de/translations";
import { WEBSERVER } from './de/webserver'; import { UI } from "./de/ui";
import { VARIABLES } from "./de/variables";
import { WEBSERVER } from "./de/webserver";
export const De = { export const De = {
...AUDIO, ...AUDIO,
...BLE,
...FAQ, ...FAQ,
...IO, ...IO,
...LOGIC, ...LOGIC,
@@ -34,8 +37,10 @@ export const De = {
...LED, ...LED,
...LORA, ...LORA,
...OSEM, ...OSEM,
...RTC,
...SD, ...SD,
...SENSORS, ...SENSORS,
...SENSEBOX,
...TELEGRAM, ...TELEGRAM,
...WEB, ...WEB,
...TEXT, ...TEXT,
@@ -44,5 +49,5 @@ export const De = {
...TRANSLATIONS, ...TRANSLATIONS,
...UI, ...UI,
...VARIABLES, ...VARIABLES,
...WEBSERVER ...WEBSERVER,
} };
@@ -0,0 +1,41 @@
export const BLE = {
/**
* Phyphox Blöcke
*/
sensebox_phyphox_init: "Initialisiere Phyphox Gerät mit Namen:",
sensebox_phyphox_createExperiment: "Erstelle Experiment",
sensebox_phyphox_experimentName: "Name des Experiments",
sensebox_phyphox_experimentTitle: "Titel",
sensebox_phyphox_experimentCategory: "Kategorie",
sensebox_phyphox_experimentDescription: "Beschreibung",
sensebox_phyphox_experiment_description: "Kurze Beschreibung des Experiments",
sensebox_phyphox_writeValues: "Sende Werte",
sensebox_phyphox_createView: "Mit Graphen:",
sensebox_phyphox_createGraph: "Erstelle Graph",
sensebox_phyphox_graphLabel: "",
sensebox_phyphox_unitx: "Einheit x-Achse",
sensebox_phyphox_unity: "Einheit y-Achse",
sensebox_phyphox_labelx: "Beschriftung x-Achse",
sensebox_phyphox_labely: "Beschriftung y-Achse",
sensebox_phyphox_channel0: "Wert x-Achse",
sensebox_phyphox_channel1: "Wert y-Achse",
sensebox_phyphox_style_dots: "Punkte",
sensebox_phyphox_style_line: "Linie",
sensebox_phyphox_timestamp: "Zeitstempel",
sensebox_phyphox_channel: "Kanal",
sensebox_phyphox_sendchannel: "sende an Kanal:",
sensebox_phyphox_graphStyle: "Stil",
sensebox_phyphox_init_tooltip:
"Initialisere das Bluetooth Bee. Stecke diese auf dem Steckplatz **XBEE1**. Gib dem Phphox Messgerät einen eindeutigen Namen, damit du dieses in der App wiederfindest",
sensebox_phyphox_experiment_tooltip:
"Erstelle ein Experiment und vergib einen eindeutigen Namen und eine kurze Beschreibung. Füge bis zu 5 verschiedene Graphen in der Ansicht hinzu. ",
sensebox_phyphox_graph_tooltip:
"Erstellt einen neuen Graph für das Experiment. Gibt die Einheit und Beschriftung für die Achsen an und wähle den Stil der Visualisuerng der Messwerte. Füge an die Schnittstellen für die Werte der X- und Y-Achse den Kanal an auf dem die Messwerte später gesendet werden. Möchtest du einen Zeitstempel über die Phyphox App erstellen lassen verbinde den Block *Zeitstempel*",
sensebox_phyphox_timestamp_tooltip:
"Verwende diesen Block, um einen Zeitstempel über die Phyphox App erstellen zu lassen",
sensebox_phyphox_sendchannel_tooltip:
"Sendet einen Messwert an den ausgewählten Kanal",
sensebox_phyphox_experiment_send_tooltip:
"Sendet die Messwerte an die Phyphox App",
};
+11 -7
View File
@@ -6,8 +6,10 @@ export const LED = {
senseBox_ws2818_rgb_led_init: "RGB LED (WS2818) initialisieren", senseBox_ws2818_rgb_led_init: "RGB LED (WS2818) initialisieren",
senseBox_ws2818_rgb_led_position: "Position", senseBox_ws2818_rgb_led_position: "Position",
senseBox_ws2818_rgb_led_brightness: "Helligkeit", senseBox_ws2818_rgb_led_brightness: "Helligkeit",
senseBox_ws2818_rgb_led_tooltip: "Verändere mit diesem Block die Farbe deiner RGB-LED. Verbinde einen Block für die Farbe. Wenn mehrere RGB-LEDs miteinander verkettet werden kannst du über die Position bestimmen welche LED angesteuert wird. ", senseBox_ws2818_rgb_led_tooltip:
senseBox_ws2818_rgb_led_init_tooltip: "Schließe die RGB-LED an einen der drei **digital/analog Ports** an. Wenn mehrere RGB-LEDs miteinander verkettet werden kannst du über die Position bestimmen welche LED angesteuert wird. ", "Verändere mit diesem Block die Farbe deiner RGB-LED. Verbinde einen Block für die Farbe. Wenn mehrere RGB-LEDs miteinander verkettet werden kannst du über die Position bestimmen welche LED angesteuert wird. ",
senseBox_ws2818_rgb_led_init_tooltip:
"Schließe die RGB-LED an einen der drei **digital/analog Ports** an. Wenn mehrere RGB-LEDs miteinander verkettet werden kannst du über die Position bestimmen welche LED angesteuert wird. ",
senseBox_ws2818_rgb_led_color: "Farbe", senseBox_ws2818_rgb_led_color: "Farbe",
senseBox_ws2818_rgb_led_number: "Anzahl", senseBox_ws2818_rgb_led_number: "Anzahl",
@@ -20,9 +22,11 @@ export const LED = {
COLOUR_BLEND_HELPURL: "http://meyerweb.com/eric/tools/color-blend/", COLOUR_BLEND_HELPURL: "http://meyerweb.com/eric/tools/color-blend/",
COLOUR_BLEND_RATIO: "im Verhältnis", COLOUR_BLEND_RATIO: "im Verhältnis",
COLOUR_BLEND_TITLE: "mische", COLOUR_BLEND_TITLE: "mische",
COLOUR_BLEND_TOOLTIP: "Vermische 2 Farben mit konfigurierbaren Farbverhältnis (0.0 - 1.0).", COLOUR_BLEND_TOOLTIP:
"Vermische 2 Farben mit konfigurierbaren Farbverhältnis (0.0 - 1.0).",
COLOUR_PICKER_HELPURL: "https://de.wikipedia.org/wiki/Farbe", COLOUR_PICKER_HELPURL: "https://de.wikipedia.org/wiki/Farbe",
COLOUR_PICKER_TOOLTIP: "Wähle eine Farbe aus der Palette. Die Farbe wird automatisch in RGB-Werte konvertiert.", COLOUR_PICKER_TOOLTIP:
"Wähle eine Farbe aus der Palette. Die Farbe wird automatisch in RGB-Werte konvertiert.",
COLOUR_RANDOM_HELPURL: "http://randomcolour.com", // untranslated COLOUR_RANDOM_HELPURL: "http://randomcolour.com", // untranslated
COLOUR_RANDOM_TITLE: "zufällige Farbe", COLOUR_RANDOM_TITLE: "zufällige Farbe",
COLOUR_RANDOM_TOOLTIP: "Erstelle eine Farbe nach dem Zufallsprinzip.", COLOUR_RANDOM_TOOLTIP: "Erstelle eine Farbe nach dem Zufallsprinzip.",
@@ -31,6 +35,6 @@ export const LED = {
COLOUR_RGB_HELPURL: "https://de.wikipedia.org/wiki/RGB-Farbraum", COLOUR_RGB_HELPURL: "https://de.wikipedia.org/wiki/RGB-Farbraum",
COLOUR_RGB_RED: "rot", COLOUR_RGB_RED: "rot",
COLOUR_RGB_TITLE: "Farbe mit", COLOUR_RGB_TITLE: "Farbe mit",
COLOUR_RGB_TOOLTIP: "Erstelle eine Farbe mit selbst definierten Rot-, Grün- und Blauwerten. Alle Werte müssen zwischen 0 und 255 liegen. 0 ist hierbei die geringte Intensität der Farbe 255 die höchste.", COLOUR_RGB_TOOLTIP:
"Erstelle eine Farbe mit selbst definierten Rot-, Grün- und Blauwerten. Alle Werte müssen zwischen 0 und 255 liegen. 0 ist hierbei die geringte Intensität der Farbe 255 die höchste.",
} };
@@ -0,0 +1,19 @@
export const RTC = {
sensebox_rtc_init: "Initialisiere RTC",
sensebox_rtc_init_tooltip:
"Initialisiere die RTC. Schließe diese an einen der 5 I2C/Wire Anschlüsse an und lege die Batterie ein. Bevor du die Uhrzeit auslesen kannst muss diese zunächst einmal gesetzt werden. Dieser Schritt muss normalerweise nur einmalig durchgeführt werden.",
sensebox_rtc_set: "Setze Uhrzeit/Datum der RTC",
sensebox_rtc_set_tooltip:
"Stellt die Uhrzeit der RTC ein. Beachte, dass du diesen Block im Setup ausführst.",
sensebox_rtc_get_timestamp: "Zeitstempel",
sensebox_rtc_get_timestamp_tooltip:
"Gibt dir einen in ISO 8601 formatierten Zeitstempel zurück. Bsp: 2021-12-24T18:21Z",
sensebox_rtc_get: "Wert: ",
sensebox_rtc_get_tooltip: "Gibt dir den ausgewählten Wert zurück.",
sensebox_rtc_second: "Sekunden",
sensebox_rtc_minutes: "Minuten",
sensebox_rtc_hour: "Stunden",
sensebox_rtc_day: "Tag",
sensebox_rtc_month: "Monat",
sensebox_rtc_year: "Jahr",
};
+16
View File
@@ -0,0 +1,16 @@
export const SENSEBOX = {
/**
* Multiplexer
*/
senseBox_multiplexer_init: "Initialisiere Multiplexer mit ",
senseBox_multiplexer_init_tooltip:
"Schließe den Multiplexer mit einem JST-JST Kabel an einen der 5 I2C-Ports an. Nun kannst du bis zu 8 gleiche Sensoren verwenden über die entsprechenden Kanäle ansprechen. Gib im Block die Anzahl der verwendeten Kanäle an",
senseBox_multiplexer_init_helpurl:
"https://docs.sensebox.de/hardware/zubehoer-multiplexer/",
senseBox_multplexer_nchannels: "Kanälen",
senseBox_multiplexer_changeChannel: "Wechsel Kanal auf:",
sensebox_multiplexer_changeChannel_tooltip:
"Wähle den entsprechenden Kanal aus",
sensebox_multiplexer_changeChannel_helpurl:
"https://docs.sensebox.de/hardware/zubehoer-multiplexer/",
};
+77 -45
View File
@@ -1,4 +1,3 @@
export const UI = { export const UI = {
/** /**
* Toolbox * Toolbox
@@ -11,6 +10,16 @@ export const UI = {
toolbox_time: "Zeit", toolbox_time: "Zeit",
toolbox_functions: "Funktionen", toolbox_functions: "Funktionen",
toolbox_variables: "Variablen", toolbox_variables: "Variablen",
variable_NUMBER: "Zahl (int)",
variable_SHORT_NUMBER: "char",
variable_LONG: "große Zahl (long)",
variable_DECIMAL: "Kommazahl (float)",
variables_TEXT: "Text (string)",
variables_ARRAY: "Array (array)",
variables_CHARACTER: "char (char)",
variables_BOOLEAN: "Boolean (boolean)",
variables_NULL: "void (void)",
variables_UNDEF: "undefined",
/** /**
* Tooltips * Tooltips
@@ -35,8 +44,8 @@ export const UI = {
tooltip_share_project: "Projekt teilen", tooltip_share_project: "Projekt teilen",
tooltip_reset_workspace: "Workspace zurücksetzen", tooltip_reset_workspace: "Workspace zurücksetzen",
tooltip_copy_link: "Link kopieren", tooltip_copy_link: "Link kopieren",
tooltip_trashcan_hide: 'gelöschte Blöcke ausblenden', tooltip_trashcan_hide: "gelöschte Blöcke ausblenden",
tooltip_trashcan_delete: 'Blöcke endgültig löschen', tooltip_trashcan_delete: "Blöcke endgültig löschen",
tooltip_project_title: "Titel des Projektes", tooltip_project_title: "Titel des Projektes",
tooltip_check_solution: "Lösung kontrollieren", tooltip_check_solution: "Lösung kontrollieren",
tooltip_copy_code: "Code in die Zwischenablage kopieren", tooltip_copy_code: "Code in die Zwischenablage kopieren",
@@ -46,24 +55,42 @@ export const UI = {
* *
*/ */
messages_delete_project_failed: "Fehler beim Löschen des Projektes. Versuche es noch einmal.", messages_delete_project_failed:
messages_reset_workspace_success: "Das Projekt wurde erfolgreich zurückgesetzt", "Fehler beim Löschen des Projektes. Versuche es noch einmal.",
messages_PROJECT_UPDATE_SUCCESS: "Das Projekt wurde erfolgreich aktualisiert.", messages_reset_workspace_success:
messages_GALLERY_UPDATE_SUCCESS: "Das Galerie-Projekt wurde erfolgreich aktualisiert.", "Das Projekt wurde erfolgreich zurückgesetzt",
messages_PROJECT_UPDATE_FAIL: "Fehler beim Aktualisieren des Projektes. Versuche es noch einmal.", messages_PROJECT_UPDATE_SUCCESS:
messages_GALLERY_UPDATE_FAIL: "Fehler beim Aktualisieren des Galerie-Projektes. Versuche es noch einmal.", "Das Projekt wurde erfolgreich aktualisiert.",
messages_GALLERY_UPDATE_SUCCESS:
"Das Galerie-Projekt wurde erfolgreich aktualisiert.",
messages_PROJECT_UPDATE_FAIL:
"Fehler beim Aktualisieren des Projektes. Versuche es noch einmal.",
messages_GALLERY_UPDATE_FAIL:
"Fehler beim Aktualisieren des Galerie-Projektes. Versuche es noch einmal.",
messages_gallery_save_fail_1: "Fehler beim Speichern des ", messages_gallery_save_fail_1: "Fehler beim Speichern des ",
messages_gallery_save_fail_2: "Projektes. Versuche es noch einmal.", messages_gallery_save_fail_2: "Projektes. Versuche es noch einmal.",
messages_SHARE_SUCCESS: 'Programm teilen', messages_SHARE_SUCCESS: "Programm teilen",
messages_SHARE_FAIL: "Fehler beim Erstellen eines Links zum Teilen deines Programmes. Versuche es noch einmal.", messages_SHARE_FAIL:
messages_copylink_success: 'Link erfolgreich in Zwischenablage gespeichert.', "Fehler beim Erstellen eines Links zum Teilen deines Programmes. Versuche es noch einmal.",
messages_rename_success_01: 'Das Projekt wurde erfolgreich in ', messages_copylink_success: "Link erfolgreich in Zwischenablage gespeichert.",
messages_rename_success_02: 'umbenannt.', messages_rename_success_01: "Das Projekt wurde erfolgreich in ",
messages_newblockly_head: "Willkommen zur neuen Version Blockly für die senseBox", messages_rename_success_02: "umbenannt.",
messages_newblockly_text: "Die neue Blockly-Version befindet sich derzeit in der Testphase. Wenn Sie einen Fehler finden, melden Sie diesen bitte in unserem [Forum](https://forum.sensebox.de/t/neue-blockly-version-beta-test-und-feedback/1176). Eine Übersicht über alle neuen Funktionen finden Sie [hier](/news)", messages_newblockly_head:
messages_GET_TUTORIAL_FAIL: 'Zurück zur Tutorials-Übersicht', "Willkommen zur neuen Version Blockly für die senseBox",
messages_LOGIN_FAIL: 'Der Benutzername oder das Passwort ist nicht korrekt.', messages_newblockly_text:
"Die neue Blockly-Version befindet sich derzeit in der Testphase. Wenn Sie einen Fehler finden, melden Sie diesen bitte in unserem [Forum](https://forum.sensebox.de/t/neue-blockly-version-beta-test-und-feedback/1176). Eine Übersicht über alle neuen Funktionen finden Sie [hier](/news)",
messages_GET_TUTORIAL_FAIL: "Zurück zur Tutorials-Übersicht",
messages_LOGIN_FAIL: "Der Benutzername oder das Passwort ist nicht korrekt.",
messages_copy_code: "Code wurde in die Zwischenablage kopiert", messages_copy_code: "Code wurde in die Zwischenablage kopiert",
/**
* Reset Dialog
*/
resetDialog_headline: "Workspace zurücksetzen?",
resetDialog_text:
"Möchtest du wirklich die Workspace zurücksetzen? Hierbei werden alle Blöcke gelöscht!",
/** /**
* Share Dialog * Share Dialog
*/ */
@@ -76,7 +103,8 @@ export const UI = {
*/ */
renamedialog_headline: "Projekt benennen", renamedialog_headline: "Projekt benennen",
renamedialog_text: "Bitte gib einen Namen für das Projekt ein und bestätige diesen mit einem Klick auf 'Bestätigen'.", renamedialog_text:
"Bitte gib einen Namen für das Projekt ein und bestätige diesen mit einem Klick auf 'Bestätigen'.",
/** /**
* Compile Dialog * Compile Dialog
@@ -84,7 +112,8 @@ export const UI = {
*/ */
compiledialog_headline: "Fehler", compiledialog_headline: "Fehler",
compiledialog_text: "Beim kompilieren ist ein Fehler aufgetreten. Überprüfe deine Blöcke und versuche es erneut", compiledialog_text:
"Beim kompilieren ist ein Fehler aufgetreten. Überprüfe deine Blöcke und versuche es erneut",
/** /**
* Buttons * Buttons
@@ -113,13 +142,16 @@ export const UI = {
*/ */
settings_head: "Einstellungen", settings_head: "Einstellungen",
settings_language: "Sprache", settings_language: "Sprache",
settings_language_text: "Auswahl der Sprache gilt für die gesamte Anwendung. Es kann zwischen Deutsch und Englisch unterschieden werden.", settings_language_text:
"Auswahl der Sprache gilt für die gesamte Anwendung. Es kann zwischen Deutsch und Englisch unterschieden werden.",
settings_language_de: "Deutsch", settings_language_de: "Deutsch",
settings_language_en: "Englisch", settings_language_en: "Englisch",
settings_renderer: "Renderer", settings_renderer: "Renderer",
settings_renderer_text: "Der eingestellte Renderer bestimmt das Aussehen der Blöcke. Es kann zwischen 'Geras' und 'Zelos' unterschieden werden, wobei 'Zelos' insbesondere für eine Touch-Anwendung geeignet ist.", settings_renderer_text:
"Der eingestellte Renderer bestimmt das Aussehen der Blöcke. Es kann zwischen 'Geras' und 'Zelos' unterschieden werden, wobei 'Zelos' insbesondere für eine Touch-Anwendung geeignet ist.",
settings_statistics: "Statistiken", settings_statistics: "Statistiken",
settings_statistics_text: "Die Anzeige von Statistiken zur Nutzung der Blöcke oberhalb der Arbeitsfläche kann ein- oder ausgeblendet werden.", settings_statistics_text:
"Die Anzeige von Statistiken zur Nutzung der Blöcke oberhalb der Arbeitsfläche kann ein- oder ausgeblendet werden.",
settings_statistics_on: "An", settings_statistics_on: "An",
settings_statistics_off: "Aus", settings_statistics_off: "Aus",
@@ -128,35 +160,29 @@ export const UI = {
*/ */
notfound_head: "Die von Ihnen angeforderte Seite kann nicht gefunden werden.", notfound_head: "Die von Ihnen angeforderte Seite kann nicht gefunden werden.",
notfound_text: "Die gesuchte Seite wurde möglicherweise entfernt, ihr Name wurde geändert oder sie ist vorübergehend nicht verfügbar.", notfound_text:
"Die gesuchte Seite wurde möglicherweise entfernt, ihr Name wurde geändert oder sie ist vorübergehend nicht verfügbar.",
/** /**
* Labels * Labels
*/ */
labels_donotshowagain: 'Dialog nicht mehr anzeigen', labels_donotshowagain: "Dialog nicht mehr anzeigen",
labels_here: "hier", labels_here: "hier",
labels_username: 'E-Mail oder Nutzername', labels_username: "E-Mail oder Nutzername",
labels_password: "Passwort", labels_password: "Passwort",
/**
* Badges
*/
badges_explaination: "Eine Übersicht über alle erhaltenen Badges im Kontext Blockly for senseBox findest du ",
badges_ASSIGNE_BADGE_SUCCESS_01: "Herzlichen Glückwunsch! Du hast den Badge ",
badges_ASSIGNE_BADGE_SUCCESS_02: " erhalten.",
/** /**
* Tutorials * Tutorials
*/ */
tutorials_assessment_task: "Aufgabe", tutorials_assessment_task: "Aufgabe",
tutorials_hardware_head: "Für die Umsetzung benötigst du folgende Hardware:", tutorials_hardware_head: "Für die Umsetzung benötigst du folgende Hardware:",
tutorials_hardware_moreInformation: "Weitere Informationen zur Hardware-Komponente findest du", tutorials_hardware_moreInformation:
"Weitere Informationen zur Hardware-Komponente findest du",
tutorials_hardware_here: "hier", tutorials_hardware_here: "hier",
tutorials_requirements: "Bevor du mit diesem Tutorial fortfährst solltest du folgende Tutorials erfolgreich abgeschlossen haben:", tutorials_requirements:
"Bevor du mit diesem Tutorial fortfährst solltest du folgende Tutorials erfolgreich abgeschlossen haben:",
/** /**
* Tutorial Builder * Tutorial Builder
@@ -165,17 +191,19 @@ export const UI = {
builder_solution: "Lösung", builder_solution: "Lösung",
builder_solution_submit: "Lösung einreichen", builder_solution_submit: "Lösung einreichen",
builder_example_submit: "Beispiel einreichen", builder_example_submit: "Beispiel einreichen",
builder_comment: "Anmerkung: Man kann den initialen Setup()- bzw. Endlosschleifen()-Block löschen. Zusätzlich ist es möglich u.a. nur einen beliebigen Block auszuwählen, ohne dass dieser als deaktiviert dargestellt wird.", builder_comment:
builder_hardware_order: "Beachte, dass die Reihenfolge des Auswählens maßgebend ist.", "Anmerkung: Man kann den initialen Setup()- bzw. Endlosschleifen()-Block löschen. Zusätzlich ist es möglich u.a. nur einen beliebigen Block auszuwählen, ohne dass dieser als deaktiviert dargestellt wird.",
builder_hardware_order:
"Beachte, dass die Reihenfolge des Auswählens maßgebend ist.",
builder_hardware_helper: "Wähle mindestens eine Hardware-Komponente aus.", builder_hardware_helper: "Wähle mindestens eine Hardware-Komponente aus.",
builder_requirements_head: "Voraussetzungen", builder_requirements_head: "Voraussetzungen",
builder_requirements_order: "Beachte, dass die Reihenfolge des Anhakens maßgebend ist.", builder_requirements_order:
"Beachte, dass die Reihenfolge des Anhakens maßgebend ist.",
/** /**
* Login * Login
*/ */
login_head: "Anmelden", login_head: "Anmelden",
login_osem_account_01: "Du benötigst einen ", login_osem_account_01: "Du benötigst einen ",
login_osem_account_02: "Account um dich einzuloggen", login_osem_account_02: "Account um dich einzuloggen",
@@ -192,7 +220,6 @@ export const UI = {
navbar_menu: "Menü", navbar_menu: "Menü",
navbar_login: "Einloggen", navbar_login: "Einloggen",
navbar_mybadges: "myBadges",
navbar_account: "Konto", navbar_account: "Konto",
navbar_logout: "Abmelden", navbar_logout: "Abmelden",
navbar_settings: "Einstellungen", navbar_settings: "Einstellungen",
@@ -204,8 +231,6 @@ export const UI = {
codeviewer_arduino: "Arduino Quellcode", codeviewer_arduino: "Arduino Quellcode",
codeviewer_xml: "XML Blöcke", codeviewer_xml: "XML Blöcke",
/** /**
* Overlay * Overlay
*/ */
@@ -221,4 +246,11 @@ export const UI = {
tooltip_viewer: "Hilfe", tooltip_viewer: "Hilfe",
tooltip_moreInformation: "Mehr Informationen findest du ", tooltip_moreInformation: "Mehr Informationen findest du ",
tooltip_hint: "Wähle einen Block aus um dir die Hilfe anzeigen zu lassen", tooltip_hint: "Wähle einen Block aus um dir die Hilfe anzeigen zu lassen",
}
/**
* IDEDrawer
*/
drawer_ideerror_head: "Hoppla da ist was schief gegangen.",
drawer_ideerror_text:
"Beim kompilieren ist ein Fehler aufgetreten, überprüfe deine Blöcke.",
};
File diff suppressed because it is too large Load Diff
+30 -24
View File
@@ -1,28 +1,32 @@
import { AUDIO } from './en/audio'; import { AUDIO } from "./en/audio";
import { FAQ } from './en/faq'; import { BLE } from "./en/sensebox-ble";
import { IO } from './en/io'; import { FAQ } from "./en/faq";
import { LOGIC } from './en/logic'; import { IO } from "./en/io";
import { LOOPS } from './en/loops'; import { LOGIC } from "./en/logic";
import { MATH } from './en/math'; import { LOOPS } from "./en/loops";
import { MQTT } from './en/mqtt'; import { MATH } from "./en/math";
import { DISPLAY } from './en/sensebox-display'; import { MQTT } from "./en/mqtt";
import { LED } from './en/sensebox-led'; import { SENSEBOX } from "./en/sensebox";
import { LORA } from './en/sensebox-lora'; import { DISPLAY } from "./en/sensebox-display";
import { OSEM } from './en/sensebox-osem'; import { LED } from "./en/sensebox-led";
import { SD } from './en/sensebox-sd'; import { LORA } from "./en/sensebox-lora";
import { SENSORS } from './en/sensebox-sensors'; import { OSEM } from "./en/sensebox-osem";
import { TELEGRAM } from './en/sensebox-telegram'; import { RTC } from "./en/sensebox-rtc";
import { WEB } from './en/sensebox-web'; import { SD } from "./en/sensebox-sd";
import { TEXT } from './en/text'; import { SENSORS } from "./en/sensebox-sensors";
import { TIME } from './en/time'; import { TELEGRAM } from "./en/sensebox-telegram";
import { TOURS } from './en/tours'; import { WEB } from "./en/sensebox-web";
import { TRANSLATIONS } from './en/translations'; import { TEXT } from "./en/text";
import { UI } from './en/ui'; import { TIME } from "./en/time";
import { VARIABLES } from './en/variables'; import { TOURS } from "./en/tours";
import { WEBSERVER } from './en/webserver'; import { TRANSLATIONS } from "./en/translations";
import { UI } from "./en/ui";
import { VARIABLES } from "./en/variables";
import { WEBSERVER } from "./en/webserver";
export const En = { export const En = {
...AUDIO, ...AUDIO,
...BLE,
...FAQ, ...FAQ,
...IO, ...IO,
...LOGIC, ...LOGIC,
@@ -33,8 +37,10 @@ export const En = {
...LED, ...LED,
...LORA, ...LORA,
...OSEM, ...OSEM,
...RTC,
...SD, ...SD,
...SENSORS, ...SENSORS,
...SENSEBOX,
...TELEGRAM, ...TELEGRAM,
...WEB, ...WEB,
...TEXT, ...TEXT,
@@ -43,5 +49,5 @@ export const En = {
...TRANSLATIONS, ...TRANSLATIONS,
...UI, ...UI,
...VARIABLES, ...VARIABLES,
...WEBSERVER ...WEBSERVER,
} };
@@ -0,0 +1,42 @@
export const BLE = {
/**
* Phyphox Init
*/
sensebox_phyphox_init: "Initialise Phyphox device with name:",
sensebox_phyphox_createExperiment: "Create experiment",
sensebox_phyphox_experimentName: "Name of experiment",
sensebox_phyphox_experimentTitle: "Title",
sensebox_phyphox_experimentCategory: "Category",
sensebox_phyphox_experimentDescription: "Description",
sensebox_phyphox_experiment_description:
"Short description of the experiment",
sensebox_phyphox_writeValues: "Send values",
sensebox_phyphox_createView: "With graphs:",
sensebox_phyphox_createGraph: "Create Graph",
sensebox_phyphox_graphLabel: "",
sensebox_phyphox_unitx: "Unit x-axis",
sensebox_phyphox_unity: "Unit y-axis",
sensebox_phyphox_labelx: "Label x-axis",
sensebox_phyphox_labely: "Label y-axis",
sensebox_phyphox_channel0: "x-axis value",
sensebox_phyphox_channel1: "y-axis value",
sensebox_phyphox_style_dots: "Dots",
sensebox_phyphox_style_line: "Line",
sensebox_phyphox_timestamp: "Timestamp",
sensebox_phyphox_channel: "Channel",
sensebox_phyphox_sendchannel: "send to channel:",
sensebox_phyphox_graphStyle: "style",
sensebox_phyphox_init_tooltip:
"Initialise the Bluetooth Bee. Plug it into the **XBEE1** slot. Give the Phphox meter a unique name so you can find it in the app",
sensebox_phyphox_experiment_tooltip:
"Create an experiment and give it a unique name and a short description. Add up to 5 different graphs in the view. ",
sensebox_phyphox_graph_tooltip:
"Creates a new graph for the experiment. Specify the unit and label for the axes and choose the style of visualisation of the measured values. Add to the interfaces for the values of the X- and Y-axis the channel on which the measured values will be sent later. If you want to create a timestamp via the Phyphox app, connect the block *Timestamp*",
sensebox_phyphox_timestamp_tooltip:
"Use this block to have a timestamp created via the Phyphox app",
sensebox_phyphox_sendchannel_tooltip:
"Sends a reading to the selected channel",
sensebox_phyphox_experiment_send_tooltip:
"Sends the measured values to the Phyphox App",
};
@@ -0,0 +1,20 @@
export const RTC = {
sensebox_rtc_init: "Initialise RTC",
sensebox_rtc_init_tooltip:
"Initialise the RTC. Connect it to one of the 5 I2C/Wire connections and insert the battery. Before you can read out the time, it must first be set. This step usually only needs to be done once.",
sensebox_rtc_set: "Set RTC time/date:",
sensebox_rtc_set_tooltip:
"Sets the time of the RTC. Note that you execute this block in the setup.",
sensebox_rtc_get_timestamp: "Get timestamp",
sensebox_rtc_get_timestamp_tooltip:
"Returns a timestamp formatted in ISO 8601. Ex: 2021-12-24T18:21Z",
sensebox_rtc_get_tooltip: "Returns the selected value",
sensebox_rtc_set_ntp: "Set time via NTP-Server",
sensebox_rtc_get: "Get: ",
sensebox_rtc_second: "seconds",
sensebox_rtc_minutes: "minutes",
sensebox_rtc_hour: "hour",
sensebox_rtc_day: "day",
sensebox_rtc_month: "month",
sensebox_rtc_year: "year",
};
+16
View File
@@ -0,0 +1,16 @@
export const SENSEBOX = {
/**
* Multiplexer
*/
senseBox_multiplexer_init: "Initialise Multiplexer with ",
senseBox_multiplexer_init_tooltip:
"Connect the multiplexer with a JST-JST cable to one of the 5 I2C ports. Now you can use up to 8 sensors of the same type and address them via the corresponding channels. Enter the number of used channels in the block",
senseBox_multiplexer_init_helpurl:
"https://en.docs.sensebox.de/hardware/zubehoer-multiplexer/",
senseBox_multplexer_nchannels: "Channels",
senseBox_multiplexer_changeChannel: "Change active channel to:",
sensebox_multiplexer_changeChannel_tooltip:
"Changes the active channel to the selected number",
sensebox_multiplexer_changeChannel_helpurl:
"https://en.docs.sensebox.de/hardware/zubehoer-multiplexer/",
};
+68 -52
View File
@@ -1,7 +1,4 @@
export const UI = { export const UI = {
/** /**
* Toolbox * Toolbox
*/ */
@@ -13,6 +10,16 @@ export const UI = {
toolbox_time: "Time", toolbox_time: "Time",
toolbox_functions: "Functions", toolbox_functions: "Functions",
toolbox_variables: "Variables", toolbox_variables: "Variables",
variable_NUMBER: "Number (int)",
variable_SHORT_NUMBER: "char",
variable_LONG: " Zahl (long)",
variable_DECIMAL: "Decimal (float)",
variables_TEXT: "Text (string)",
variables_ARRAY: "Array (array)",
variables_CHARACTER: "char (char)",
variables_BOOLEAN: "Boolean (boolean)",
variables_NULL: "void (void)",
variables_UNDEF: "undefined",
/** /**
* Tooltips * Tooltips
@@ -51,22 +58,36 @@ export const UI = {
messages_delete_project_failed: "Error deleting the project. Try again.", messages_delete_project_failed: "Error deleting the project. Try again.",
messages_reset_workspace_success: "The project has been successfully reset.", messages_reset_workspace_success: "The project has been successfully reset.",
messages_PROJECT_UPDATE_SUCCESS: "The project was successfully updated.", messages_PROJECT_UPDATE_SUCCESS: "The project was successfully updated.",
messages_GALLERY_UPDATE_SUCCESS: "The gallery project was successfully updated.", messages_GALLERY_UPDATE_SUCCESS:
"The gallery project was successfully updated.",
messages_PROJECT_UPDATE_FAIL: "Error updating the project. Try again.", messages_PROJECT_UPDATE_FAIL: "Error updating the project. Try again.",
messages_GALLERY_UPDATE_FAIL: "Error updating the gallery project. Try again.", messages_GALLERY_UPDATE_FAIL:
"Error updating the gallery project. Try again.",
messages_gallery_save_fail_1: "Error saving the ", messages_gallery_save_fail_1: "Error saving the ",
messages_gallery_save_fail_2: "Project. Try again.", messages_gallery_save_fail_2: "Project. Try again.",
messages_SHARE_SUCCESS: 'Share program', messages_SHARE_SUCCESS: "Share program",
messages_SHARE_FAIL: "Error creating a link to share your program. Try again.", messages_SHARE_FAIL:
messages_copylink_success: 'Link successfully saved to clipboard.', "Error creating a link to share your program. Try again.",
messages_rename_success_01: 'The project was successfully saved to ', messages_copylink_success: "Link successfully saved to clipboard.",
messages_rename_success_02: 'renamed.', messages_rename_success_01: "The project was successfully saved to ",
messages_newblockly_head: 'Welcome to the new version Blockly for the senseBox', messages_rename_success_02: "renamed.",
messages_newblockly_text: "The new Blockly version is currently in testing. If you find any errors please report them in our [forum](https://forum.sensebox.de/t/neue-blockly-version-beta-test-und-feedback/1176). You can find an overview of all new features [here](/news)", messages_newblockly_head:
messages_GET_TUTORIAL_FAIL: 'Back to tutorials overview', "Welcome to the new version Blockly for the senseBox",
messages_LOGIN_FAIL: 'The username or password is incorrect.', messages_newblockly_text:
"The new Blockly version is currently in testing. If you find any errors please report them in our [forum](https://forum.sensebox.de/t/neue-blockly-version-beta-test-und-feedback/1176). You can find an overview of all new features [here](/news)",
messages_GET_TUTORIAL_FAIL: "Back to tutorials overview",
messages_LOGIN_FAIL: "The username or password is incorrect.",
messages_login_error: "Enter both a username and a password.", messages_login_error: "Enter both a username and a password.",
messages_copy_code: "Copy code to clipboard succesfull", messages_copy_code: "Copy code to clipboard succesfull",
/**
* Reset Dialog
*/
resetDialog_headline: "Reset workspace?",
resetDialog_text:
"Do you really want to reset the workspace? All blocks will be deleted!",
/** /**
* Share Dialog * Share Dialog
*/ */
@@ -79,16 +100,16 @@ export const UI = {
*/ */
renamedialog_headline: "Rename project", renamedialog_headline: "Rename project",
renamedialog_text: "Please enter a name for the project and confirm it by clicking 'Confirm'.", renamedialog_text:
"Please enter a name for the project and confirm it by clicking 'Confirm'.",
/** /**
* Compile Dialog * Compile Dialog
* *
*/ */
compiledialog_headline: "Error", compiledialog_headline: "Error",
compiledialog_text: "While compiling an error occured. Please check your blocks and try again", compiledialog_text:
"While compiling an error occured. Please check your blocks and try again",
/** /**
* Buttons * Buttons
@@ -105,8 +126,6 @@ export const UI = {
button_tutorial_overview: "Tutorial overview", button_tutorial_overview: "Tutorial overview",
button_login: "Login", button_login: "Login",
/** /**
* *
*/ */
@@ -118,50 +137,47 @@ export const UI = {
*/ */
settings_head: "Settings", settings_head: "Settings",
settings_language: "Language", settings_language: "Language",
settings_language_text: "Selection of the language applies to the entire application. A distinction can be made between German and English.", settings_language_text:
"Selection of the language applies to the entire application. A distinction can be made between German and English.",
settings_language_de: "German", settings_language_de: "German",
settings_language_en: "English", settings_language_en: "English",
settings_renderer: "Renderer", settings_renderer: "Renderer",
settings_renderer_text: "The selected renderer determines the appearance of the blocks. A distinction can be made between 'Geras' and 'Zelos', whereby 'Zelos' is particularly suitable for a touch application.", settings_renderer_text:
"The selected renderer determines the appearance of the blocks. A distinction can be made between 'Geras' and 'Zelos', whereby 'Zelos' is particularly suitable for a touch application.",
settings_statistics: "Statistics", settings_statistics: "Statistics",
settings_statistics_text: "The display of statistics on the usage of the blocks above the workspace can be shown or hidden.", settings_statistics_text:
"The display of statistics on the usage of the blocks above the workspace can be shown or hidden.",
settings_statistics_on: "On", settings_statistics_on: "On",
settings_statistics_off: "Off", settings_statistics_off: "Off",
/** /**
* 404 * 404
*/ */
notfound_head: "The page you requested cannot be found.", notfound_head: "The page you requested cannot be found.",
notfound_text: "The page you are looking for may have been removed, its name changed, or it may be temporarily unavailable.", notfound_text:
"The page you are looking for may have been removed, its name changed, or it may be temporarily unavailable.",
/** /**
* Labels * Labels
*/ */
labels_donotshowagain: 'Do not show dialog again', labels_donotshowagain: "Do not show dialog again",
labels_here: 'here', labels_here: "here",
labels_username: 'Email or username', labels_username: "Email or username",
labels_password: "Password", labels_password: "Password",
/**
* Badges
*/
badges_explaination: "An overview of all badges received in the Blockly for senseBox context can be found ",
badges_ASSIGNE_BADGE_SUCCESS_01: "Congratulations! You have received the badge ",
badges_ASSIGNE_BADGE_SUCCESS_02: ".",
/** /**
* Tutorials * Tutorials
*/ */
tutorials_assessment_task: "Task", tutorials_assessment_task: "Task",
tutorials_hardware_head: "For the implementation you need the following hardware:", tutorials_hardware_head:
tutorials_hardware_moreInformation: "You can find more information about the hardware component.", "For the implementation you need the following hardware:",
tutorials_hardware_moreInformation:
"You can find more information about the hardware component.",
tutorials_hardware_here: "here", tutorials_hardware_here: "here",
tutorials_requirements: "Before continuing with this tutorial, you should have successfully completed the following tutorials:", tutorials_requirements:
"Before continuing with this tutorial, you should have successfully completed the following tutorials:",
/** /**
* Tutorial Builder * Tutorial Builder
@@ -170,24 +186,24 @@ export const UI = {
builder_solution: "Solution", builder_solution: "Solution",
builder_solution_submit: "Submit Solution", builder_solution_submit: "Submit Solution",
builder_example_submit: "Submit example", builder_example_submit: "Submit example",
builder_comment: "Note: You can delete the initial setup() or infinite loop() block. Additionally, it is possible to select only any block, among others, without displaying it as disabled.", builder_comment:
"Note: You can delete the initial setup() or infinite loop() block. Additionally, it is possible to select only any block, among others, without displaying it as disabled.",
builder_hardware_order: "Note that the order of selection is authoritative.", builder_hardware_order: "Note that the order of selection is authoritative.",
builder_hardware_helper: "Select at least one hardware component.", builder_hardware_helper: "Select at least one hardware component.",
builder_requirements_head: "Requirements.", builder_requirements_head: "Requirements.",
builder_requirements_order: "Note that the order of ticking is authoritative.", builder_requirements_order:
"Note that the order of ticking is authoritative.",
/** /**
* Login * Login
*/ */
login_head: "Login", login_head: "Login",
login_osem_account_01: "You need to have an ", login_osem_account_01: "You need to have an ",
login_osem_account_02: "Account to login", login_osem_account_02: "Account to login",
login_lostpassword: "Lost your password?", login_lostpassword: "Lost your password?",
login_createaccount: "If you don't have an openSenseMap account please register on ", login_createaccount:
"If you don't have an openSenseMap account please register on ",
/** /**
* Navbar * Navbar
@@ -200,7 +216,6 @@ export const UI = {
navbar_menu: "Menu", navbar_menu: "Menu",
navbar_login: "Login", navbar_login: "Login",
navbar_mybadges: "myBadges",
navbar_account: "Account", navbar_account: "Account",
navbar_logout: "Logout", navbar_logout: "Logout",
navbar_settings: "Settings", navbar_settings: "Settings",
@@ -212,9 +227,6 @@ export const UI = {
codeviewer_arduino: "Arduino Source Code", codeviewer_arduino: "Arduino Source Code",
codeviewer_xml: "XML Blocks", codeviewer_xml: "XML Blocks",
/** /**
* Overlay * Overlay
*/ */
@@ -223,7 +235,6 @@ export const UI = {
compile_overlay_text: "Then copy it to your senseBox MCU", compile_overlay_text: "Then copy it to your senseBox MCU",
compile_overlay_help: "You need help? Have a look here: ", compile_overlay_help: "You need help? Have a look here: ",
/** /**
* Tooltip Viewer * Tooltip Viewer
*/ */
@@ -232,4 +243,9 @@ export const UI = {
tooltip_moreInformation: "More informations can be found ", tooltip_moreInformation: "More informations can be found ",
tooltip_hint: "Select a Block to show the hint", tooltip_hint: "Select a Block to show the hint",
} /**
* IDEDrawer
*/
drawer_ideerror_head: "Oops something went wrong",
drawer_ideerror_text: "An error occurred while compiling, check your blocks",
};
File diff suppressed because it is too large Load Diff
+180 -44
View File
@@ -1,30 +1,43 @@
import React from 'react'; import React from "react";
import { Block, Value, Field, Shadow, Category } from '../'; import { Block, Value, Field, Shadow, Category } from "../";
import { getColour } from '../helpers/colour' import { getColour } from "../helpers/colour";
import '@blockly/block-plus-minus'; import "@blockly/block-plus-minus";
import { TypedVariableModal } from '@blockly/plugin-typed-variable-modal'; import { TypedVariableModal } from "@blockly/plugin-typed-variable-modal";
import * as Blockly from 'blockly/core'; import * as Blockly from "blockly/core";
class Toolbox extends React.Component { class Toolbox extends React.Component {
componentDidUpdate() { componentDidUpdate() {
this.props.workspace.registerToolboxCategoryCallback('CREATE_TYPED_VARIABLE', this.createFlyout); this.props.workspace.registerToolboxCategoryCallback(
"CREATE_TYPED_VARIABLE",
this.createFlyout
);
const typedVarModal = new TypedVariableModal(this.props.workspace, 'callbackName', [['SHORT_NUMBER', 'char'], ['NUMBER', 'int'], ['DECIMAL', 'float'], ['TEXT', 'String'], ['ARRAY', 'Array'], ['CHARACTER', 'char'], ['BOOLEAN', 'boolean'], ['NULL', 'void'], ['UNDEF', 'undefined']]); const typedVarModal = new TypedVariableModal(
this.props.workspace,
"callbackName",
[
[`${Blockly.Msg.variable_SHORT_NUMBER}`, "char"],
[`${Blockly.Msg.variable_NUMBER}`, "int"],
[`${Blockly.Msg.variable_LONG}`, "long"],
[`${Blockly.Msg.variable_DECIMAL}`, "float"],
[`${Blockly.Msg.variables_TEXT}`, "String"],
[`${Blockly.Msg.variables_ARRAY}`, "Array"],
[`${Blockly.Msg.variables_CHARACTER}`, "char"],
[`${Blockly.Msg.variables_BOOLEAN}`, "boolean"],
[`${Blockly.Msg.variables_NULL}`, "void"],
[`${Blockly.Msg.variables_UNDEF}`, "undefined"],
]
);
typedVarModal.init(); typedVarModal.init();
} }
createFlyout(workspace) { createFlyout(workspace) {
let xmlList = []; let xmlList = [];
// Add your button and give it a callback name. // Add your button and give it a callback name.
const button = document.createElement('button'); const button = document.createElement("button");
button.setAttribute('text', 'Create Typed Variable'); button.setAttribute("text", "Create Typed Variable");
button.setAttribute('callbackKey', 'callbackName'); button.setAttribute("callbackKey", "callbackName");
xmlList.push(button); xmlList.push(button);
@@ -33,12 +46,20 @@ class Toolbox extends React.Component {
const blockList = Blockly.VariablesDynamic.flyoutCategoryBlocks(workspace); const blockList = Blockly.VariablesDynamic.flyoutCategoryBlocks(workspace);
xmlList = xmlList.concat(blockList); xmlList = xmlList.concat(blockList);
return xmlList; return xmlList;
}; }
render() { render() {
return ( return (
<xml xmlns="https://developers.google.com/blockly/xml" id="blockly" style={{ display: 'none' }} ref={this.props.toolbox}> <xml
<Category name={Blockly.Msg.toolbox_sensors} colour={getColour().sensebox}> xmlns="https://developers.google.com/blockly/xml"
id="blockly"
style={{ display: "none" }}
ref={this.props.toolbox}
>
<Category
name={Blockly.Msg.toolbox_sensors}
colour={getColour().sensebox}
>
<Block type="sensebox_sensor_temp_hum" /> <Block type="sensebox_sensor_temp_hum" />
<Block type="sensebox_sensor_uv_light" /> <Block type="sensebox_sensor_uv_light" />
<Block type="sensebox_sensor_bmx055_accelerometer" /> <Block type="sensebox_sensor_bmx055_accelerometer" />
@@ -54,7 +75,21 @@ class Toolbox extends React.Component {
<Block type="sensebox_sensor_watertemperature" /> <Block type="sensebox_sensor_watertemperature" />
{/* <Block type="sensebox_windspeed" /> */} {/* <Block type="sensebox_windspeed" /> */}
<Block type="sensebox_soundsensor_dfrobot" /> <Block type="sensebox_soundsensor_dfrobot" />
</Category > <Block type="sensebox_multiplexer_init">
<Value name="nrChannels">
<Block type="math_number">
<Field name="NUM">1</Field>
</Block>
</Value>
</Block>
<Block type="sensebox_multiplexer_changeChannel">
<Value name="Channel">
<Block type="math_number">
<Field name="NUM">1</Field>
</Block>
</Value>
</Block>
</Category>
<Category name="WIFI" colour={getColour().sensebox}> <Category name="WIFI" colour={getColour().sensebox}>
<Block type="sensebox_wifi" /> <Block type="sensebox_wifi" />
<Block type="sensebox_startap" /> <Block type="sensebox_startap" />
@@ -157,19 +192,16 @@ class Toolbox extends React.Component {
<Field name="TEXT">Unit</Field> <Field name="TEXT">Unit</Field>
</Block> </Block>
</Value> </Value>
</Block > </Block>
<Block type="sensebox_display_plotDisplay"> <Block type="sensebox_display_plotDisplay">
<Value name="Title"> <Value name="Title">
<Block type="text"> <Block type="text"></Block>
</Block>
</Value> </Value>
<Value name="YLabel"> <Value name="YLabel">
<Block type="text"> <Block type="text"></Block>
</Block>
</Value> </Value>
<Value name="XLabel"> <Value name="XLabel">
<Block type="text"> <Block type="text"></Block>
</Block>
</Value> </Value>
<Value name="XRange1"> <Value name="XRange1">
<Block type="math_number"> <Block type="math_number">
@@ -261,16 +293,32 @@ class Toolbox extends React.Component {
</Block> </Block>
<Block type="sensebox_send_to_osem" /> <Block type="sensebox_send_to_osem" />
</Category> </Category>
<Category id="catSenseBoxOutput_LoRa" name=" LoRa" colour={getColour().sensebox}> <Category
<Category id="catSenseBoxOutput_LoRa_activation" name=" Aktivierung" colour={getColour().sensebox}> id="catSenseBoxOutput_LoRa"
name=" LoRa"
colour={getColour().sensebox}
>
<Category
id="catSenseBoxOutput_LoRa_activation"
name=" Aktivierung"
colour={getColour().sensebox}
>
<Block type="sensebox_lora_initialize_otaa" /> <Block type="sensebox_lora_initialize_otaa" />
<Block type="sensebox_lora_initialize_abp" /> <Block type="sensebox_lora_initialize_abp" />
</Category> </Category>
<Category id="catSenseBoxOutput_LoRa_loramessage" name=" Lora Message" colour={getColour().sensebox}> <Category
id="catSenseBoxOutput_LoRa_loramessage"
name=" Lora Message"
colour={getColour().sensebox}
>
<Block type="sensebox_lora_message_send" /> <Block type="sensebox_lora_message_send" />
<Block type="sensebox_send_lora_sensor_value" /> <Block type="sensebox_send_lora_sensor_value" />
</Category> </Category>
<Category id="catSenseBoxOutput_Map" name=" TTN Mapper" colour={getColour().sensebox}> <Category
id="catSenseBoxOutput_Map"
name=" TTN Mapper"
colour={getColour().sensebox}
>
<Block type="sensebox_lora_ttn_mapper"> <Block type="sensebox_lora_ttn_mapper">
<Value name="Latitude"> <Value name="Latitude">
<Block type="sensebox_gps"> <Block type="sensebox_gps">
@@ -299,7 +347,11 @@ class Toolbox extends React.Component {
</Value> </Value>
</Block> </Block>
</Category> </Category>
<Category id="catSenseBoxOutput_LoRa_cayenne" name=" Cayenne LPP" colour={getColour().sensebox}> <Category
id="catSenseBoxOutput_LoRa_cayenne"
name=" Cayenne LPP"
colour={getColour().sensebox}
>
<Block type="sensebox_lora_cayenne_send" /> <Block type="sensebox_lora_cayenne_send" />
<Block type="sensebox_lora_cayenne_temperature" /> <Block type="sensebox_lora_cayenne_temperature" />
<Block type="sensebox_lora_cayenne_humidity" /> <Block type="sensebox_lora_cayenne_humidity" />
@@ -310,7 +362,35 @@ class Toolbox extends React.Component {
<Block type="sensebox_lora_cayenne_gps" /> <Block type="sensebox_lora_cayenne_gps" />
</Category> </Category>
</Category> </Category>
<Category id="webserver" name="Webserver" colour={getColour().webserver}> <Category id="phyphox" name="Phyphox" colour={getColour().phyphox}>
<Block type="sensebox_phyphox_init"></Block>
<Block type="sensebox_phyphox_experiment">
<Value name="view">
<Block type="sensebox_phyphox_graph">
<Value name="channel0">
<Block type="sensebox_phyphox_timestamp"></Block>
</Value>
<Value name="channel1">
<Block type="sensebox_phyphox_channel"></Block>
</Value>
</Block>
</Value>
</Block>
<Block type="sensebox_phyphox_experiment_send">
<Value name="sendValues">
<Block type="sensebox_phyphox_sendchannel"></Block>
</Value>
</Block>
<Block type="sensebox_phyphox_graph"></Block>
<Block type="sensebox_phyphox_timestamp"></Block>
<Block type="sensebox_phyphox_channel"></Block>
<Block type="sensebox_phyphox_sendchannel"></Block>
</Category>
<Category
id="webserver"
name="Webserver"
colour={getColour().webserver}
>
<Block type="sensebox_initialize_http_server"></Block> <Block type="sensebox_initialize_http_server"></Block>
<Block type="sensebox_http_on_client_connect"></Block> <Block type="sensebox_http_on_client_connect"></Block>
<Block type="sensebox_ip_address"></Block> <Block type="sensebox_ip_address"></Block>
@@ -338,7 +418,11 @@ class Toolbox extends React.Component {
<Block type="logic_boolean" /> <Block type="logic_boolean" />
<Block type="switch_case" /> <Block type="switch_case" />
</Category> </Category>
<Category id="loops" name={Blockly.Msg.toolbox_loops} colour={getColour().loops}> <Category
id="loops"
name={Blockly.Msg.toolbox_loops}
colour={getColour().loops}
>
<Block type="controls_repeat_ext"> <Block type="controls_repeat_ext">
<Value name="TIMES"> <Value name="TIMES">
<Block type="math_number"> <Block type="math_number">
@@ -353,13 +437,13 @@ class Toolbox extends React.Component {
<Field name="NUM">1</Field> <Field name="NUM">1</Field>
</Block> </Block>
</Value> </Value>
<Value name="TO" > <Value name="TO">
<Block type="math_number" > <Block type="math_number">
<Field name="NUM">10</Field> <Field name="NUM">10</Field>
</Block> </Block>
</Value> </Value>
<Value name="BY" > <Value name="BY">
<Block Type="math_number" > <Block Type="math_number">
<Field name="NUM">1</Field> <Field name="NUM">1</Field>
</Block> </Block>
</Value> </Value>
@@ -377,7 +461,11 @@ class Toolbox extends React.Component {
<Block type="text_length" /> <Block type="text_length" />
<Block type="text_isEmpty" /> <Block type="text_isEmpty" />
</Category> </Category>
<Category id="time" name={Blockly.Msg.toolbox_time} colour={getColour().time}> <Category
id="time"
name={Blockly.Msg.toolbox_time}
colour={getColour().time}
>
<Block type="time_delay"> <Block type="time_delay">
<Value name="DELAY_TIME_MILI"> <Value name="DELAY_TIME_MILI">
<Block type="math_number"> <Block type="math_number">
@@ -396,8 +484,48 @@ class Toolbox extends React.Component {
<Block type="time_micros"></Block> <Block type="time_micros"></Block>
<Block type="infinite_loop"></Block> <Block type="infinite_loop"></Block>
<Block type="sensebox_interval_timer"></Block> <Block type="sensebox_interval_timer"></Block>
<Block type="sensebox_rtc_init"></Block>
<Block type="sensebox_rtc_set">
<Value name="second">
<Block type="math_number">
<Field name="NUM">00</Field>
</Block>
</Value>
<Value name="minutes">
<Block type="math_number">
<Field name="NUM">00</Field>
</Block>
</Value>
<Value name="hour">
<Block type="math_number">
<Field name="NUM">00</Field>
</Block>
</Value>
<Value name="day">
<Block type="math_number">
<Field name="NUM">01</Field>
</Block>
</Value>
<Value name="month">
<Block type="math_number">
<Field name="NUM">01</Field>
</Block>
</Value>
<Value name="year">
<Block type="math_number">
<Field name="NUM">1970</Field>
</Block>
</Value>
</Block>
{/* <Block type="sensebox_rtc_set_ntp"></Block> */}
<Block type="sensebox_rtc_get"></Block>
<Block type="sensebox_rtc_get_timestamp"></Block>
</Category> </Category>
<Category id="math" name={Blockly.Msg.toolbox_math} colour={getColour().math}> <Category
id="math"
name={Blockly.Msg.toolbox_math}
colour={getColour().math}
>
<Block type="math_number"></Block> <Block type="math_number"></Block>
<Block type="math_arithmetic"></Block> <Block type="math_arithmetic"></Block>
<Block type="math_single"></Block> <Block type="math_single"></Block>
@@ -450,13 +578,21 @@ class Toolbox extends React.Component {
</Block> </Block>
<Block type="io_notone"></Block> <Block type="io_notone"></Block>
</Category> </Category>
<Category name={Blockly.Msg.toolbox_variables} colour={getColour().variables} custom="CREATE_TYPED_VARIABLE"></Category> <Category
<Category name="Arrays" colour={getColour().arrays} > name={Blockly.Msg.toolbox_variables}
colour={getColour().variables}
custom="CREATE_TYPED_VARIABLE"
></Category>
<Category name="Arrays" colour={getColour().arrays}>
<Block type="lists_create_empty" /> <Block type="lists_create_empty" />
<Block type="array_getIndex" /> <Block type="array_getIndex" />
<Block type="lists_length" /> <Block type="lists_length" />
</Category> </Category>
<Category name={Blockly.Msg.toolbox_functions} colour={getColour().procedures} custom="PROCEDURE"></Category> <Category
name={Blockly.Msg.toolbox_functions}
colour={getColour().procedures}
custom="PROCEDURE"
></Category>
<sep></sep> <sep></sep>
<Category name={Blockly.Msg.toolbox_io} colour={getColour().io}> <Category name={Blockly.Msg.toolbox_io} colour={getColour().io}>
<Block type="io_digitalwrite"></Block> <Block type="io_digitalwrite"></Block>
@@ -489,7 +625,7 @@ class Toolbox extends React.Component {
*/} */}
</xml> </xml>
); );
}; }
} }
export default Toolbox; export default Toolbox;
-4
View File
@@ -15,7 +15,6 @@ class Content extends Component {
componentDidMount() { componentDidMount() {
if (this.props.language === 'de_DE') { if (this.props.language === 'de_DE') {
console.log("change Language")
Blockly.setLocale(De); Blockly.setLocale(De);
} else if (this.props.language === 'en_US') { } else if (this.props.language === 'en_US') {
Blockly.setLocale(En); Blockly.setLocale(En);
@@ -23,13 +22,10 @@ class Content extends Component {
} }
componentDidUpdate(props) { componentDidUpdate(props) {
console.log(this.props.language)
if (props.language !== this.props.language) { if (props.language !== this.props.language) {
if (this.props.language === 'de_DE') { if (this.props.language === 'de_DE') {
console.log("change Language")
Blockly.setLocale(De); Blockly.setLocale(De);
} else if (this.props.language === 'en_US') { } else if (this.props.language === 'en_US') {
console.log("change Language")
Blockly.setLocale(En); Blockly.setLocale(En);
} }
} }
+14 -6
View File
@@ -77,7 +77,7 @@ class Home extends Component {
componentWillUnmount() { componentWillUnmount() {
this.props.clearStats(); this.props.clearStats();
this.props.workspaceName(null); // this.props.workspaceName(null);
} }
onChange = () => { onChange = () => {
@@ -112,10 +112,17 @@ class Home extends Component {
</Tooltip> </Tooltip>
<TrashcanButtons /> <TrashcanButtons />
<div className='blocklyWindow'> <div className='blocklyWindow'>
{this.props.project ? {this.props.project ? (
< BlocklyWindow blocklyCSS={{ height: '80vH' }} initialXml={this.props.project.xml} /> <BlocklyWindow
: < BlocklyWindow blocklyCSS={{ height: '80vH' }} /> blocklyCSS={{ height: "80vH" }}
} initialXml={this.props.project.xml}
/>
) : (
<BlocklyWindow
blocklyCSS={{ height: "80vH" }}
initialXml={this.props.workspaceCode?.xml}
/>
)}
</div> </div>
</Grid> </Grid>
{this.state.codeOn ? {this.state.codeOn ?
@@ -146,7 +153,8 @@ Home.propTypes = {
const mapStateToProps = state => ({ const mapStateToProps = state => ({
message: state.message, message: state.message,
statistics: state.general.statistics statistics: state.general.statistics,
workspaceCode: state.workspace.code
}); });
+68 -25
View File
@@ -1,49 +1,92 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import { withRouter } from 'react-router-dom'; import { withRouter } from "react-router-dom";
import Container from '@material-ui/core/Container'; import Container from "@material-ui/core/Container";
class Impressum extends Component { class Impressum extends Component {
render() { render() {
return ( return (
<Container fixed> <Container fixed>
<div style={{ margin: '0px 24px 0px 24px' }}> <div style={{ margin: "0px 24px 0px 24px" }}>
<h1>Impressum</h1> <h1>Impressum</h1>
<h2>Angaben gemäß § 5 TMG:</h2> <h2>Angaben gemäß § 5 TMG:</h2>
Institut für Geoinformatik<br /> Institut für Geoinformatik
<br />
Heisenbergstraße 2<br /> Heisenbergstraße 2<br />
Geo 1<br /> Geo 1<br />
48149 Münster 48149 Münster
<h2>Kontakt:</h2> <h2>Kontakt:</h2>
E-Mail: <a href="mailto:info@mybadges.org!">info@mybadges.org</a> E-Mail: <a href="mailto:info@msensebox.de">info@msensebox.de</a>
<h2>Verantwortlich für den Inhalt nach § 55 Abs. 2 RStV:</h2> <h2>Verantwortlich für den Inhalt nach § 55 Abs. 2 RStV:</h2>
Geschäftsführende Direktorin Prof. Dr. Angela Schwering<br /> Geschäftsführende Direktorin Prof. Dr. Angela Schwering
<br />
Heisenbergstraße 2<br /> Heisenbergstraße 2<br />
Geo 1<br /> Geo 1<br />
48149 Münster 48149 Münster
<h2>Streitschlichtung</h2> <h2>Streitschlichtung</h2>
Die Europäische Kommission stellt eine Plattform zur Online-Streitbeilegung (OS) bereit: <a href="https://ec.europa.eu/consumers/odr" target="_blank" rel="noopener noreferrer">https://ec.europa.eu/consumers/odr</a>.<br /> Die Europäische Kommission stellt eine Plattform zur
Unsere E-Mail-Adresse finden Sie oben im Impressum.<br /> Online-Streitbeilegung (OS) bereit:{" "}
<p>Wir sind nicht bereit oder verpflichtet, an Streitbeilegungsverfahren vor einer Verbraucherschlichtungsstelle teilzunehmen.</p> <a
href="https://ec.europa.eu/consumers/odr"
target="_blank"
rel="noopener noreferrer"
>
https://ec.europa.eu/consumers/odr
</a>
.<br />
Unsere E-Mail-Adresse finden Sie oben im Impressum.
<br />
<p>
Wir sind nicht bereit oder verpflichtet, an
Streitbeilegungsverfahren vor einer Verbraucherschlichtungsstelle
teilzunehmen.
</p>
<h3>Haftung für Inhalte</h3> <h3>Haftung für Inhalte</h3>
Als Diensteanbieter sind wir gemäß § 7 Abs.1 TMG für eigene Inhalte auf diesen Seiten nach den allgemeinen Gesetzen verantwortlich. Nach §§ 8 bis 10 TMG sind wir als Diensteanbieter jedoch nicht verpflichtet, übermittelte oder gespeicherte fremde Informationen zu überwachen oder nach Umständen zu forschen, die auf eine rechtswidrige Tätigkeit hinweisen. Als Diensteanbieter sind wir gemäß § 7 Abs.1 TMG für eigene Inhalte
<p>Verpflichtungen zur Entfernung oder Sperrung der Nutzung von Informationen nach den allgemeinen Gesetzen bleiben hiervon unberührt. Eine diesbezügliche Haftung ist jedoch erst ab dem Zeitpunkt der Kenntnis einer konkreten Rechtsverletzung möglich. Bei Bekanntwerden von entsprechenden Rechtsverletzungen werden wir diese Inhalte umgehend entfernen.</p> auf diesen Seiten nach den allgemeinen Gesetzen verantwortlich. Nach
§§ 8 bis 10 TMG sind wir als Diensteanbieter jedoch nicht
verpflichtet, übermittelte oder gespeicherte fremde Informationen zu
überwachen oder nach Umständen zu forschen, die auf eine rechtswidrige
Tätigkeit hinweisen.
<p>
Verpflichtungen zur Entfernung oder Sperrung der Nutzung von
Informationen nach den allgemeinen Gesetzen bleiben hiervon
unberührt. Eine diesbezügliche Haftung ist jedoch erst ab dem
Zeitpunkt der Kenntnis einer konkreten Rechtsverletzung möglich. Bei
Bekanntwerden von entsprechenden Rechtsverletzungen werden wir diese
Inhalte umgehend entfernen.
</p>
<h3>Haftung für Links</h3> <h3>Haftung für Links</h3>
Unser Angebot enthält Links zu externen Websites Dritter, auf deren Inhalte wir keinen Einfluss haben. Deshalb können wir für diese fremden Inhalte auch keine Gewähr übernehmen. Für die Inhalte der verlinkten Seiten ist stets der jeweilige Anbieter oder Betreiber der Seiten verantwortlich. Die verlinkten Seiten wurden zum Zeitpunkt der Verlinkung auf mögliche Rechtsverstöße überprüft. Rechtswidrige Inhalte waren zum Zeitpunkt der Verlinkung nicht erkennbar. Unser Angebot enthält Links zu externen Websites Dritter, auf deren
<p>Eine permanente inhaltliche Kontrolle der verlinkten Seiten ist jedoch ohne konkrete Anhaltspunkte einer Rechtsverletzung nicht zumutbar. Bei Bekanntwerden von Rechtsverletzungen werden wir derartige Links umgehend entfernen.</p> Inhalte wir keinen Einfluss haben. Deshalb können wir für diese
fremden Inhalte auch keine Gewähr übernehmen. Für die Inhalte der
verlinkten Seiten ist stets der jeweilige Anbieter oder Betreiber der
Seiten verantwortlich. Die verlinkten Seiten wurden zum Zeitpunkt der
Verlinkung auf mögliche Rechtsverstöße überprüft. Rechtswidrige
Inhalte waren zum Zeitpunkt der Verlinkung nicht erkennbar.
<p>
Eine permanente inhaltliche Kontrolle der verlinkten Seiten ist
jedoch ohne konkrete Anhaltspunkte einer Rechtsverletzung nicht
zumutbar. Bei Bekanntwerden von Rechtsverletzungen werden wir
derartige Links umgehend entfernen.
</p>
<h3>Urheberrecht</h3> <h3>Urheberrecht</h3>
Die durch die Seitenbetreiber erstellten Inhalte und Werke auf diesen Seiten unterliegen dem deutschen Urheberrecht. Die Vervielfältigung, Bearbeitung, Verbreitung und jede Art der Verwertung außerhalb der Grenzen des Urheberrechtes bedürfen der schriftlichen Zustimmung des jeweiligen Autors bzw. Erstellers. Downloads und Kopien dieser Seite sind nur für den privaten, nicht kommerziellen Gebrauch gestattet. Die durch die Seitenbetreiber erstellten Inhalte und Werke auf diesen
<p>Soweit die Inhalte auf dieser Seite nicht vom Betreiber erstellt wurden, werden die Urheberrechte Dritter beachtet. Insbesondere werden Inhalte Dritter als solche gekennzeichnet. Sollten Sie trotzdem auf eine Urheberrechtsverletzung aufmerksam werden, bitten wir um einen entsprechenden Hinweis. Bei Bekanntwerden von Rechtsverletzungen werden wir derartige Inhalte umgehend entfernen.</p> Seiten unterliegen dem deutschen Urheberrecht. Die Vervielfältigung,
Bearbeitung, Verbreitung und jede Art der Verwertung außerhalb der
Grenzen des Urheberrechtes bedürfen der schriftlichen Zustimmung des
jeweiligen Autors bzw. Erstellers. Downloads und Kopien dieser Seite
sind nur für den privaten, nicht kommerziellen Gebrauch gestattet.
<p>
Soweit die Inhalte auf dieser Seite nicht vom Betreiber erstellt
wurden, werden die Urheberrechte Dritter beachtet. Insbesondere
werden Inhalte Dritter als solche gekennzeichnet. Sollten Sie
trotzdem auf eine Urheberrechtsverletzung aufmerksam werden, bitten
wir um einen entsprechenden Hinweis. Bei Bekanntwerden von
Rechtsverletzungen werden wir derartige Inhalte umgehend entfernen.
</p>
</div> </div>
</Container> </Container>
); );
}; }
} }
export default withRouter(Impressum); export default withRouter(Impressum);
+237 -104
View File
@@ -1,136 +1,177 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { Link } from 'react-router-dom'; import { Link } from "react-router-dom";
import { logout } from '../actions/authActions'; import { logout } from "../actions/authActions";
import senseboxLogo from './sensebox_logo.svg'; import senseboxLogo from "./sensebox_logo.svg";
import { withRouter } from 'react-router-dom'; import { withRouter } from "react-router-dom";
import { withStyles } from '@material-ui/core/styles'; import { withStyles } from "@material-ui/core/styles";
import Drawer from '@material-ui/core/Drawer'; import Drawer from "@material-ui/core/Drawer";
import AppBar from '@material-ui/core/AppBar'; import AppBar from "@material-ui/core/AppBar";
import Toolbar from '@material-ui/core/Toolbar'; import Toolbar from "@material-ui/core/Toolbar";
import List from '@material-ui/core/List'; import List from "@material-ui/core/List";
import Typography from '@material-ui/core/Typography'; import Typography from "@material-ui/core/Typography";
import Divider from '@material-ui/core/Divider'; import Divider from "@material-ui/core/Divider";
import IconButton from '@material-ui/core/IconButton'; import IconButton from "@material-ui/core/IconButton";
import ListItem from '@material-ui/core/ListItem'; import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from '@material-ui/core/ListItemIcon'; import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from '@material-ui/core/ListItemText'; import ListItemText from "@material-ui/core/ListItemText";
import LinearProgress from '@material-ui/core/LinearProgress'; import LinearProgress from "@material-ui/core/LinearProgress";
import Tour from 'reactour' import Tour from "reactour";
import { home, assessment } from './Tour'; import { home, assessment } from "./Tour";
import { faBars, faChevronLeft, faLayerGroup, faSignInAlt, faSignOutAlt, faCertificate, faUserCircle, faQuestionCircle, faCog, faChalkboardTeacher, faTools, faLightbulb } from "@fortawesome/free-solid-svg-icons"; import {
faBars,
faChevronLeft,
faLayerGroup,
faSignInAlt,
faSignOutAlt,
faUserCircle,
faQuestionCircle,
faCog,
faChalkboardTeacher,
faTools,
faLightbulb,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Blockly from 'blockly' import * as Blockly from "blockly";
import Tooltip from '@material-ui/core/Tooltip'; import Tooltip from "@material-ui/core/Tooltip";
const styles = (theme) => ({ const styles = (theme) => ({
drawerWidth: { drawerWidth: {
// color: theme.palette.primary.main, // color: theme.palette.primary.main,
width: window.innerWidth < 600 ? '100%' : '240px', width: window.innerWidth < 600 ? "100%" : "240px",
borderRight: `1px solid ${theme.palette.primary.main}` borderRight: `1px solid ${theme.palette.primary.main}`,
}, },
appBarColor: { appBarColor: {
backgroundColor: theme.palette.primary.main backgroundColor: theme.palette.primary.main,
}, },
tourButton: { tourButton: {
marginleft: 'auto', marginleft: "auto",
marginright: '30px', marginright: "30px",
} },
}); });
class Navbar extends Component { class Navbar extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
open: false, open: false,
isTourOpen: false isTourOpen: false,
}; };
} }
toggleDrawer = () => { toggleDrawer = () => {
this.setState({ open: !this.state.open }); this.setState({ open: !this.state.open });
} };
openTour = () => { openTour = () => {
this.setState({ isTourOpen: true }); this.setState({ isTourOpen: true });
};
}
closeTour = () => { closeTour = () => {
this.setState({ isTourOpen: false }); this.setState({ isTourOpen: false });
} };
render() { render() {
var isHome = /^\/(\/.*$|$)/g.test(this.props.location.pathname); var isHome = /^\/(\/.*$|$)/g.test(this.props.location.pathname);
var isTutorial = /^\/tutorial(\/.*$|$)/g.test(this.props.location.pathname); var isTutorial = /^\/tutorial(\/.*$|$)/g.test(this.props.location.pathname);
var isAssessment = /^\/tutorial\/.{1,}$/g.test(this.props.location.pathname) && var isAssessment =
!this.props.tutorialIsLoading && this.props.tutorial && /^\/tutorial\/.{1,}$/g.test(this.props.location.pathname) &&
this.props.tutorial.steps[this.props.activeStep].type === 'task'; !this.props.tutorialIsLoading &&
this.props.tutorial &&
this.props.tutorial.steps[this.props.activeStep].type === "task";
return ( return (
<div> <div>
<AppBar <AppBar
position="relative" position="relative"
style={{ height: '50px', marginBottom: this.props.tutorialIsLoading || this.props.projectIsLoading ? '0px' : '30px', boxShadow: this.props.tutorialIsLoading || this.props.projectIsLoading ? 'none' : '0px 2px 4px -1px rgba(0,0,0,0.2),0px 4px 5px 0px rgba(0,0,0,0.14),0px 1px 10px 0px rgba(0,0,0,0.12)' }} style={{
height: "50px",
marginBottom:
this.props.tutorialIsLoading || this.props.projectIsLoading
? "0px"
: "30px",
boxShadow:
this.props.tutorialIsLoading || this.props.projectIsLoading
? "none"
: "0px 2px 4px -1px rgba(0,0,0,0.2),0px 4px 5px 0px rgba(0,0,0,0.14),0px 1px 10px 0px rgba(0,0,0,0.12)",
}}
classes={{ root: this.props.classes.appBarColor }} classes={{ root: this.props.classes.appBarColor }}
> >
<Toolbar style={{ height: '50px', minHeight: '50px', padding: 0, color: 'white' }}> <Toolbar
style={{
height: "50px",
minHeight: "50px",
padding: 0,
color: "white",
}}
>
<IconButton <IconButton
color="inherit" color="inherit"
onClick={this.toggleDrawer} onClick={this.toggleDrawer}
style={{ margin: '0 10px' }} style={{ margin: "0 10px" }}
className="MenuButton" className="MenuButton"
> >
<FontAwesomeIcon icon={faBars} /> <FontAwesomeIcon icon={faBars} />
</IconButton> </IconButton>
<Link to={"/"} style={{ textDecoration: 'none', color: 'inherit' }}> <Link to={"/"} style={{ textDecoration: "none", color: "inherit" }}>
<Typography variant="h6" noWrap> <Typography variant="h6" noWrap>
senseBox Blockly senseBox Blockly
</Typography> </Typography>
</Link> </Link>
<Link to={"/"} style={{ marginLeft: '10px' }}> <Link to={"/"} style={{ marginLeft: "10px" }}>
<img src={senseboxLogo} alt="senseBox-Logo" width="30" /> <img src={senseboxLogo} alt="senseBox-Logo" width="30" />
</Link> </Link>
{isTutorial ? {isTutorial ? (
<Link to={"/tutorial"} style={{ textDecoration: 'none', color: 'inherit', marginLeft: '10px' }}> <Link
to={"/tutorial"}
style={{
textDecoration: "none",
color: "inherit",
marginLeft: "10px",
}}
>
<Typography variant="h6" noWrap> <Typography variant="h6" noWrap>
Tutorial Tutorial
</Typography> </Typography>
</Link> : null} </Link>
{isHome ? ) : null}
<Tooltip title='Hilfe starten' arrow> {isHome ? (
<Tooltip title="Hilfe starten" arrow>
<IconButton <IconButton
color="inherit" color="inherit"
className={`openTour ${this.props.classes.button}`} className={`openTour ${this.props.classes.button}`}
onClick={() => { this.openTour(); }} onClick={() => {
style={{ margin: '0 30px 0 auto' }} this.openTour();
}}
style={{ margin: "0 30px 0 auto" }}
> >
<FontAwesomeIcon icon={faQuestionCircle} /> <FontAwesomeIcon icon={faQuestionCircle} />
</IconButton> </IconButton>
</Tooltip> </Tooltip>
: null} ) : null}
{isAssessment ? {isAssessment ? (
<Tooltip title='Hilfe starten' arrow> <Tooltip title="Hilfe starten" arrow>
<IconButton <IconButton
color="inherit" color="inherit"
className={`openTour ${this.props.classes.button}`} className={`openTour ${this.props.classes.button}`}
onClick={() => { this.openTour(); }} onClick={() => {
style={{ margin: '0 30px 0 auto' }} this.openTour();
}}
style={{ margin: "0 30px 0 auto" }}
> >
<FontAwesomeIcon icon={faQuestionCircle} /> <FontAwesomeIcon icon={faQuestionCircle} />
</IconButton> </IconButton>
</Tooltip> </Tooltip>
: null} ) : null}
<Tour <Tour
steps={isHome ? home() : assessment()} steps={isHome ? home() : assessment()}
isOpen={this.state.isTourOpen} isOpen={this.state.isTourOpen}
onRequestClose={() => { this.closeTour(); }} onRequestClose={() => {
this.closeTour();
}}
/> />
</Toolbar> </Toolbar>
</AppBar> </AppBar>
@@ -142,71 +183,161 @@ class Navbar extends Component {
classes={{ paper: this.props.classes.drawerWidth }} classes={{ paper: this.props.classes.drawerWidth }}
ModalProps={{ keepMounted: true }} // Better open performance on mobile. ModalProps={{ keepMounted: true }} // Better open performance on mobile.
> >
<div style={{ height: '50px', cursor: 'pointer', color: 'white', padding: '0 22px' }} className={this.props.classes.appBarColor} onClick={this.toggleDrawer}> <div
<div style={{ display: ' table-cell', verticalAlign: 'middle', height: 'inherit', width: '0.1%' }}> style={{
<Typography variant="h6" style={{ display: 'inline' }}> height: "50px",
cursor: "pointer",
color: "white",
padding: "0 22px",
}}
className={this.props.classes.appBarColor}
onClick={this.toggleDrawer}
>
<div
style={{
display: " table-cell",
verticalAlign: "middle",
height: "inherit",
width: "0.1%",
}}
>
<Typography variant="h6" style={{ display: "inline" }}>
{Blockly.Msg.navbar_menu} {Blockly.Msg.navbar_menu}
</Typography> </Typography>
<div style={{ float: 'right' }}> <div style={{ float: "right" }}>
<FontAwesomeIcon icon={faChevronLeft} /> <FontAwesomeIcon icon={faChevronLeft} />
</div> </div>
</div> </div>
</div> </div>
<List> <List>
{[{ text: Blockly.Msg.navbar_tutorials, icon: faChalkboardTeacher, link: "/tutorial" }, {[
{ text: Blockly.Msg.navbar_tutorialbuilder, icon: faTools, link: "/tutorial/builder", restriction: this.props.user && this.props.user.blocklyRole !== 'user' && this.props.isAuthenticated }, {
{ text: Blockly.Msg.navbar_gallery, icon: faLightbulb, link: "/gallery" }, text: Blockly.Msg.navbar_tutorials,
{ text: Blockly.Msg.navbar_projects, icon: faLayerGroup, link: "/project", restriction: this.props.isAuthenticated }].map((item, index) => { icon: faChalkboardTeacher,
if (item.restriction || Object.keys(item).filter(attribute => attribute === 'restriction').length === 0) { link: "/tutorial",
},
{
text: Blockly.Msg.navbar_tutorialbuilder,
icon: faTools,
link: "/tutorial/builder",
restriction:
this.props.user &&
this.props.user.blocklyRole !== "user" &&
this.props.isAuthenticated,
},
{
text: Blockly.Msg.navbar_gallery,
icon: faLightbulb,
link: "/gallery",
},
{
text: Blockly.Msg.navbar_projects,
icon: faLayerGroup,
link: "/project",
restriction: this.props.isAuthenticated,
},
].map((item, index) => {
if (
item.restriction ||
Object.keys(item).filter(
(attribute) => attribute === "restriction"
).length === 0
) {
return ( return (
<Link to={item.link} key={index} style={{ textDecoration: 'none', color: 'inherit' }}> <Link
to={item.link}
key={index}
style={{ textDecoration: "none", color: "inherit" }}
>
<ListItem button onClick={this.toggleDrawer}> <ListItem button onClick={this.toggleDrawer}>
<ListItemIcon><FontAwesomeIcon icon={item.icon} /></ListItemIcon> <ListItemIcon>
<FontAwesomeIcon icon={item.icon} />
</ListItemIcon>
<ListItemText primary={item.text} /> <ListItemText primary={item.text} />
</ListItem> </ListItem>
</Link> </Link>
); );
} else {
return null;
} }
else { })}
return(
null
)
}
}
)}
</List> </List>
<Divider classes={{ root: this.props.classes.appBarColor }} style={{ marginTop: 'auto' }} /> <Divider
classes={{ root: this.props.classes.appBarColor }}
style={{ marginTop: "auto" }}
/>
<List> <List>
{[{ text: Blockly.Msg.navbar_login, icon: faSignInAlt, link: '/user/login', restriction: !this.props.isAuthenticated }, {[
{ text: Blockly.Msg.navbar_account, icon: faUserCircle, link: '/user', restriction: this.props.isAuthenticated }, {
{ text: Blockly.Msg.navbar_mybadges, icon: faCertificate, link: '/user/badge', restriction: this.props.isAuthenticated }, text: Blockly.Msg.navbar_login,
{ text: Blockly.Msg.navbar_logout, icon: faSignOutAlt, function: this.props.logout, restriction: this.props.isAuthenticated }, icon: faSignInAlt,
{ text: 'FAQ', icon: faQuestionCircle, link: "/faq" }, link: "/user/login",
{ text: Blockly.Msg.navbar_settings, icon: faCog, link: "/settings" }].map((item, index) => { restriction: !this.props.isAuthenticated,
if (item.restriction || Object.keys(item).filter(attribute => attribute === 'restriction').length === 0) { },
{
text: Blockly.Msg.navbar_account,
icon: faUserCircle,
link: "/user",
restriction: this.props.isAuthenticated,
},
{
text: Blockly.Msg.navbar_logout,
icon: faSignOutAlt,
function: this.props.logout,
restriction: this.props.isAuthenticated,
},
{ text: "FAQ", icon: faQuestionCircle, link: "/faq" },
{
text: Blockly.Msg.navbar_settings,
icon: faCog,
link: "/settings",
},
].map((item, index) => {
if (
item.restriction ||
Object.keys(item).filter(
(attribute) => attribute === "restriction"
).length === 0
) {
return ( return (
<Link to={item.link} key={index} style={{ textDecoration: 'none', color: 'inherit' }}> <Link
<ListItem button onClick={item.function ? () => { item.function(); this.toggleDrawer(); } : this.toggleDrawer}> to={item.link}
<ListItemIcon><FontAwesomeIcon icon={item.icon} /></ListItemIcon> key={index}
style={{ textDecoration: "none", color: "inherit" }}
>
<ListItem
button
onClick={
item.function
? () => {
item.function();
this.toggleDrawer();
}
: this.toggleDrawer
}
>
<ListItemIcon>
<FontAwesomeIcon icon={item.icon} />
</ListItemIcon>
<ListItemText primary={item.text} /> <ListItemText primary={item.text} />
</ListItem> </ListItem>
</Link> </Link>
); );
} else {
return null;
} }
else { })}
return(
null
)
}
}
)}
</List> </List>
</Drawer> </Drawer>
{this.props.tutorialIsLoading || this.props.projectIsLoading ? {this.props.tutorialIsLoading || this.props.projectIsLoading ? (
<LinearProgress style={{ marginBottom: '30px', boxShadow: '0px 2px 4px -1px rgba(0,0,0,0.2),0px 4px 5px 0px rgba(0,0,0,0.14),0px 1px 10px 0px rgba(0,0,0,0.12)' }} /> <LinearProgress
: null} style={{
marginBottom: "30px",
boxShadow:
"0px 2px 4px -1px rgba(0,0,0,0.2),0px 4px 5px 0px rgba(0,0,0,0.14),0px 1px 10px 0px rgba(0,0,0,0.12)",
}}
/>
) : null}
</div> </div>
); );
} }
@@ -218,10 +349,10 @@ Navbar.propTypes = {
isAuthenticated: PropTypes.bool.isRequired, isAuthenticated: PropTypes.bool.isRequired,
user: PropTypes.object, user: PropTypes.object,
tutorial: PropTypes.object.isRequired, tutorial: PropTypes.object.isRequired,
activeStep: PropTypes.number.isRequired activeStep: PropTypes.number.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
tutorialIsLoading: state.tutorial.progress, tutorialIsLoading: state.tutorial.progress,
projectIsLoading: state.project.progress, projectIsLoading: state.project.progress,
isAuthenticated: state.auth.isAuthenticated, isAuthenticated: state.auth.isAuthenticated,
@@ -230,4 +361,6 @@ const mapStateToProps = state => ({
activeStep: state.tutorial.activeStep, activeStep: state.tutorial.activeStep,
}); });
export default connect(mapStateToProps, { logout })(withStyles(styles, { withTheme: true })(withRouter(Navbar))); export default connect(mapStateToProps, { logout })(
withStyles(styles, { withTheme: true })(withRouter(Navbar))
);
-2
View File
@@ -56,8 +56,6 @@ class Project extends Component {
getProject = () => { getProject = () => {
var id = this.props.location.pathname.replace(/\/[a-z]{1,}\//, ''); var id = this.props.location.pathname.replace(/\/[a-z]{1,}\//, '');
var param = this.props.location.pathname.replace(`/${id}`, '').replace('/', ''); var param = this.props.location.pathname.replace(`/${id}`, '').replace('/', '');
console.log('param', param);
console.log(id);
this.props.getProject(param, id); this.props.getProject(param, id);
} }
+206 -72
View File
@@ -1,57 +1,76 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { getProjects, resetProject } from '../../actions/projectActions'; import { getProjects, resetProject } from "../../actions/projectActions";
import { clearMessages } from '../../actions/messageActions'; import { clearMessages } from "../../actions/messageActions";
import { Link, withRouter } from 'react-router-dom'; import { Link, withRouter } from "react-router-dom";
import Breadcrumbs from '../Breadcrumbs'; import Breadcrumbs from "../Breadcrumbs";
import BlocklyWindow from '../Blockly/BlocklyWindow'; import BlocklyWindow from "../Blockly/BlocklyWindow";
import Snackbar from '../Snackbar'; import Snackbar from "../Snackbar";
import WorkspaceFunc from '../Workspace/WorkspaceFunc'; import WorkspaceFunc from "../Workspace/WorkspaceFunc";
import { withStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import Divider from "@material-ui/core/Divider";
import Typography from "@material-ui/core/Typography";
import Backdrop from "@material-ui/core/Backdrop";
import CircularProgress from "@material-ui/core/CircularProgress";
import Dialog from "../Dialog";
import Button from "@material-ui/core/Button";
import { initialXml } from "../Blockly/initialXml";
import {diffAsXml} from 'diff-js-xml';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Divider from '@material-ui/core/Divider';
import Typography from '@material-ui/core/Typography';
import Backdrop from '@material-ui/core/Backdrop';
import CircularProgress from '@material-ui/core/CircularProgress';
const styles = (theme) => ({ const styles = (theme) => ({
link: { link: {
color: theme.palette.primary.main, color: theme.palette.primary.main,
textDecoration: 'none', textDecoration: "none",
'&:hover': { "&:hover": {
color: theme.palette.primary.main, color: theme.palette.primary.main,
textDecoration: 'underline' textDecoration: "underline",
} },
} },
}); });
class ProjectHome extends Component { class ProjectHome extends Component {
state = { state = {
snackbar: false, snackbar: false,
type: '', type: "",
key: '', key: "",
message: '' message: "",
} dialog: false,
};
componentDidMount() { componentDidMount() {
var type = this.props.location.pathname.replace('/', ''); var type = this.props.location.pathname.replace("/", "");
this.props.getProjects(type); this.props.getProjects(type);
if (this.props.message) { if (this.props.message) {
if (this.props.message.id === 'PROJECT_DELETE_SUCCESS') { if (this.props.message.id === "PROJECT_DELETE_SUCCESS") {
this.setState({ snackbar: true, key: Date.now(), message: `Dein Projekt wurde erfolgreich gelöscht.`, type: 'success' }); this.setState({
} snackbar: true,
else if (this.props.message.id === 'GALLERY_DELETE_SUCCESS') { key: Date.now(),
this.setState({ snackbar: true, key: Date.now(), message: `Dein Galerie-Projekt wurde erfolgreich gelöscht.`, type: 'success' }); message: `Dein Projekt wurde erfolgreich gelöscht.`,
} type: "success",
else if (this.props.message.id === 'GET_PROJECT_FAIL') { });
this.setState({ snackbar: true, key: Date.now(), message: `Dein angefragtes ${type === 'gallery' ? 'Galerie-' : ''}Projekt konnte nicht gefunden werden.`, type: 'error' }); } else if (this.props.message.id === "GALLERY_DELETE_SUCCESS") {
this.setState({
snackbar: true,
key: Date.now(),
message: `Dein Galerie-Projekt wurde erfolgreich gelöscht.`,
type: "success",
});
} else if (this.props.message.id === "GET_PROJECT_FAIL") {
this.setState({
snackbar: true,
key: Date.now(),
message: `Dein angefragtes ${
type === "gallery" ? "Galerie-" : ""
}Projekt konnte nicht gefunden werden.`,
type: "error",
});
} }
} }
} }
@@ -59,14 +78,23 @@ class ProjectHome extends Component {
componentDidUpdate(props) { componentDidUpdate(props) {
if (props.location.pathname !== this.props.location.pathname) { if (props.location.pathname !== this.props.location.pathname) {
this.setState({ snackbar: false }); this.setState({ snackbar: false });
this.props.getProjects(this.props.location.pathname.replace('/', '')); this.props.getProjects(this.props.location.pathname.replace("/", ""));
} }
if (props.message !== this.props.message) { if (props.message !== this.props.message) {
if (this.props.message.id === 'PROJECT_DELETE_SUCCESS') { if (this.props.message.id === "PROJECT_DELETE_SUCCESS") {
this.setState({ snackbar: true, key: Date.now(), message: `Dein Projekt wurde erfolgreich gelöscht.`, type: 'success' }); this.setState({
} snackbar: true,
else if (this.props.message.id === 'GALLERY_DELETE_SUCCESS') { key: Date.now(),
this.setState({ snackbar: true, key: Date.now(), message: `Dein Galerie-Projekt wurde erfolgreich gelöscht.`, type: 'success' }); message: `Dein Projekt wurde erfolgreich gelöscht.`,
type: "success",
});
} else if (this.props.message.id === "GALLERY_DELETE_SUCCESS") {
this.setState({
snackbar: true,
key: Date.now(),
message: `Dein Galerie-Projekt wurde erfolgreich gelöscht.`,
type: "success",
});
} }
} }
} }
@@ -77,69 +105,171 @@ class ProjectHome extends Component {
} }
render() { render() {
var data = this.props.location.pathname === '/project' ? 'Projekte' : 'Galerie'; var data =
this.props.location.pathname === "/project" ? "Projekte" : "Galerie";
return ( return (
<div> <div>
<Breadcrumbs content={[{ link: this.props.location.pathname, title: data }]} /> <Breadcrumbs
content={[{ link: this.props.location.pathname, title: data }]}
/>
<h1>{data}</h1> <h1>{data}</h1>
{this.props.progress ? {this.props.progress ? (
<Backdrop open invisible> <Backdrop open invisible>
<CircularProgress color="primary" /> <CircularProgress color="primary" />
</Backdrop> </Backdrop>
: ) : (
<div> <div>
{this.props.projects.length > 0 ? {this.props.projects.length > 0 ? (
<Grid container spacing={2}> <Grid container spacing={2}>
{this.props.projects.map((project, i) => { {this.props.projects.map((project, i) => {
return ( return (
<Grid item xs={12} sm={6} md={4} xl={3} key={i}> <Grid item xs={12} sm={6} md={4} xl={3} key={i}>
<Paper style={{ padding: '1rem', position: 'relative', overflow: 'hidden' }}> <Paper
<Link to={`/${data === 'Projekte' ? 'project' : 'gallery'}/${project._id}`} style={{ textDecoration: 'none', color: 'inherit' }}> style={{
padding: "1rem",
position: "relative",
overflow: "hidden",
}}
>
<div
onClick={async () => {
const isCodeDifferent = new Promise((resolve) => {
// resolve successfully when there is no existing workspace XML code
if(!this.props.workspaceCode.xml) {
resolve(false)
return
}
// get difference of XML
// TODO: check if code of project is different to workspace code
diffAsXml(
this.props.workspaceCode.xml,
initialXml,
undefined,
undefined,
(result) => {
resolve(result.length !== 0);
}
)
}
);
const showDialog = await isCodeDifferent;
if (showDialog)
this.setState({
dialog: true,
});
else {
this.props.history.push(
`/${
data === "Projekte" ? "project" : "gallery"
}/${project._id}`
);
}
}}
style={{ textDecoration: "none", color: "inherit" }}
>
<h3 style={{ marginTop: 0 }}>{project.title}</h3> <h3 style={{ marginTop: 0 }}>{project.title}</h3>
<Divider style={{ marginTop: '1rem', marginBottom: '10px' }} /> <Divider
style={{ marginTop: "1rem", marginBottom: "10px" }}
/>
<BlocklyWindow <BlocklyWindow
svg svg
blockDisabled blockDisabled
readOnly
initialXml={project.xml} initialXml={project.xml}
/> />
<Typography variant='body2' style={{ fontStyle: 'italic', margin: 0, marginTop: '-10px' }}>{project.description}</Typography> <Typography
</Link> variant="body2"
{this.props.user && this.props.user.email === project.creator ? style={{
fontStyle: "italic",
margin: 0,
marginTop: "-10px",
}}
>
{project.description}
</Typography>
</div>
{this.props.user &&
this.props.user.email === project.creator ? (
<div> <div>
<Divider style={{ marginTop: '10px', marginBottom: '10px' }} /> <Divider
<div style={{ float: 'right' }}> style={{
marginTop: "10px",
marginBottom: "10px",
}}
/>
<div style={{ float: "right" }}>
<WorkspaceFunc <WorkspaceFunc
multiple multiple
project={project} project={project}
projectType={this.props.location.pathname.replace('/', '')} projectType={this.props.location.pathname.replace(
"/",
""
)}
/> />
</div> </div>
</div> </div>
: null} ) : null}
</Paper> </Paper>
</Grid> </Grid>
) );
})} })}
</Grid> </Grid>
: <div> ) : (
<Typography style={{ marginBottom: '10px' }}>Es sind aktuell keine Projekte vorhanden.</Typography> <div>
{this.props.location.pathname.replace('/', '') === 'project' ? <Typography style={{ marginBottom: "10px" }}>
<Typography>Erstelle jetzt dein <Link to={'/'} className={this.props.classes.link}>eigenes Projekt</Link> oder lasse dich von Projektbeispielen in der <Link to={'/gallery'} className={this.props.classes.link}>Galerie</Link> inspirieren.</Typography> Es sind aktuell keine Projekte vorhanden.
: null} </Typography>
{this.props.location.pathname.replace("/", "") === "project" ? (
<Typography>
Erstelle jetzt dein{" "}
<Link to={"/"} className={this.props.classes.link}>
eigenes Projekt
</Link>{" "}
oder lasse dich von Projektbeispielen in der{" "}
<Link to={"/gallery"} className={this.props.classes.link}>
Galerie
</Link>{" "}
inspirieren.
</Typography>
) : null}
</div> </div>
} )}
</div> </div>
} )}
<Snackbar <Snackbar
open={this.state.snackbar} open={this.state.snackbar}
message={this.state.message} message={this.state.message}
type={this.state.type} type={this.state.type}
key={this.state.key} key={this.state.key}
/> />
<Dialog
open={this.state.dialog}
title="Achtung"
actions={
<React.Fragment>
<Button
onClick={() => {
this.setState({ dialog: false });
// TODO: navigate to project
}}
>
Verwerfen
</Button>
<Button onClick={() => {}} color="primary">
Speichern
</Button>
</React.Fragment>
}
>
Möchtest du deinen bisherigen Code als Projekt speichern?
</Dialog>
</div> </div>
); );
}; }
} }
ProjectHome.propTypes = { ProjectHome.propTypes = {
@@ -149,15 +279,19 @@ ProjectHome.propTypes = {
projects: PropTypes.array.isRequired, projects: PropTypes.array.isRequired,
progress: PropTypes.bool.isRequired, progress: PropTypes.bool.isRequired,
user: PropTypes.object, user: PropTypes.object,
message: PropTypes.object.isRequired message: PropTypes.object.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
projects: state.project.projects, projects: state.project.projects,
progress: state.project.progress, progress: state.project.progress,
user: state.auth.user, user: state.auth.user,
message: state.message message: state.message,
workspaceCode: state.workspace.code,
}); });
export default connect(mapStateToProps, {
export default connect(mapStateToProps, { getProjects, resetProject, clearMessages })(withStyles(styles, { withTheme: true })(withRouter(ProjectHome))); getProjects,
resetProject,
clearMessages,
})(withStyles(styles, { withTheme: true })(withRouter(ProjectHome)));
+25 -31
View File
@@ -1,40 +1,38 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { visitPage } from '../../actions/generalActions'; import { visitPage } from "../../actions/generalActions";
import { Route, Switch, withRouter } from 'react-router-dom'; import { Route, Switch, withRouter } from "react-router-dom";
import PublicRoute from './PublicRoute'; import PublicRoute from "./PublicRoute";
import PrivateRoute from './PrivateRoute'; import PrivateRoute from "./PrivateRoute";
import PrivateRouteCreator from './PrivateRouteCreator'; import PrivateRouteCreator from "./PrivateRouteCreator";
import IsLoggedRoute from './IsLoggedRoute'; import IsLoggedRoute from "./IsLoggedRoute";
import Home from '../Home'; import Home from "../Home";
import Tutorial from '../Tutorial/Tutorial'; import Tutorial from "../Tutorial/Tutorial";
import TutorialHome from '../Tutorial/TutorialHome'; import TutorialHome from "../Tutorial/TutorialHome";
import Builder from '../Tutorial/Builder/Builder'; import Builder from "../Tutorial/Builder/Builder";
import NotFound from '../NotFound'; import NotFound from "../NotFound";
import ProjectHome from '../Project/ProjectHome'; import ProjectHome from "../Project/ProjectHome";
import Project from '../Project/Project'; import Project from "../Project/Project";
import Settings from '../Settings/Settings'; import Settings from "../Settings/Settings";
import Impressum from '../Impressum'; import Impressum from "../Impressum";
import Privacy from '../Privacy'; import Privacy from "../Privacy";
import Login from '../User/Login'; import Login from "../User/Login";
import Account from '../User/Account'; import Account from "../User/Account";
import MyBadges from '../User/MyBadges'; import News from "../News";
import News from '../News' import Faq from "../Faq";
import Faq from '../Faq'
class Routes extends Component { class Routes extends Component {
componentDidUpdate() { componentDidUpdate() {
this.props.visitPage(); this.props.visitPage();
} }
render() { render() {
return ( return (
<div style={{ margin: '0 22px' }}> <div style={{ margin: "0 22px" }}>
<Switch> <Switch>
<PublicRoute path="/" exact> <PublicRoute path="/" exact>
<Home /> <Home />
@@ -74,9 +72,6 @@ class Routes extends Component {
<PrivateRoute path="/user" exact> <PrivateRoute path="/user" exact>
<Account /> <Account />
</PrivateRoute> </PrivateRoute>
<PrivateRoute path="/user/badge" exact>
<MyBadges />
</PrivateRoute>
{/* settings */} {/* settings */}
<PublicRoute path="/settings" exact> <PublicRoute path="/settings" exact>
<Settings /> <Settings />
@@ -98,7 +93,6 @@ class Routes extends Component {
<PublicRoute> <PublicRoute>
<NotFound /> <NotFound />
</PublicRoute> </PublicRoute>
</Switch> </Switch>
</div> </div>
); );
@@ -106,7 +100,7 @@ class Routes extends Component {
} }
Home.propTypes = { Home.propTypes = {
visitPage: PropTypes.func.isRequired visitPage: PropTypes.func.isRequired,
}; };
export default connect(null, { visitPage })(withRouter(Routes)); export default connect(null, { visitPage })(withRouter(Routes));
+72 -30
View File
@@ -1,20 +1,20 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { workspaceName } from '../../actions/workspaceActions'; import { workspaceName } from "../../actions/workspaceActions";
import BlocklyWindow from '../Blockly/BlocklyWindow'; import BlocklyWindow from "../Blockly/BlocklyWindow";
import CodeViewer from '../CodeViewer'; import CodeViewer from "../CodeViewer";
import WorkspaceFunc from '../Workspace/WorkspaceFunc'; import WorkspaceFunc from "../Workspace/WorkspaceFunc";
import withWidth, { isWidthDown } from '@material-ui/core/withWidth'; import withWidth, { isWidthDown } from "@material-ui/core/withWidth";
import Grid from '@material-ui/core/Grid'; import Grid from "@material-ui/core/Grid";
import Card from '@material-ui/core/Card'; import Card from "@material-ui/core/Card";
import Typography from '@material-ui/core/Typography'; import Typography from "@material-ui/core/Typography";
import * as Blockly from 'blockly' import * as Blockly from "blockly";
import { initialXml } from "../Blockly/initialXml";
class Assessment extends Component { class Assessment extends Component {
componentDidMount() { componentDidMount() {
this.props.workspaceName(this.props.name); this.props.workspaceName(this.props.name);
} }
@@ -28,48 +28,90 @@ class Assessment extends Component {
render() { render() {
var tutorialId = this.props.tutorial._id; var tutorialId = this.props.tutorial._id;
var currentTask = this.props.step; var currentTask = this.props.step;
var status = this.props.status.filter(status => status._id === tutorialId)[0]; var status = this.props.status.filter(
var taskIndex = status.tasks.findIndex(task => task._id === currentTask._id); (status) => status._id === tutorialId
)[0];
var taskIndex = status.tasks.findIndex(
(task) => task._id === currentTask._id
);
var statusTask = status.tasks[taskIndex]; var statusTask = status.tasks[taskIndex];
return ( return (
<div className="assessmentDiv" style={{ width: '100%' }}> <div className="assessmentDiv" style={{ width: "100%" }}>
<Typography variant='h4' style={{ float: 'left', marginBottom: '5px', height: '40px', display: 'table' }}>{currentTask.headline}</Typography> <Typography
<div style={{ float: 'right', height: '40px' }}><WorkspaceFunc assessment /></div> variant="h4"
<Grid container spacing={2} style={{ marginBottom: '5px' }}> style={{
float: "left",
marginBottom: "5px",
height: "40px",
display: "table",
}}
>
{currentTask.headline}
</Typography>
<div style={{ float: "right", height: "40px" }}>
<WorkspaceFunc assessment />
</div>
<Grid container spacing={2} style={{ marginBottom: "5px" }}>
<Grid item xs={12} md={6} lg={8}> <Grid item xs={12} md={6} lg={8}>
<BlocklyWindow <BlocklyWindow
initialXml={statusTask ? statusTask.xml ? statusTask.xml : null : null} initialXml={initialXml}
blockDisabled blockDisabled
blocklyCSS={{ height: '65vH' }} blocklyCSS={{ height: "65vH" }}
/> />
</Grid> </Grid>
<Grid item xs={12} md={6} lg={4} style={isWidthDown('sm', this.props.width) ? { height: 'max-content' } : {}}> <Grid
<Card style={{ height: 'calc(50% - 30px)', padding: '10px', marginBottom: '10px' }}> item
<Typography variant='h5'>{Blockly.Msg.tutorials_assessment_task}</Typography> xs={12}
md={6}
lg={4}
style={
isWidthDown("sm", this.props.width)
? { height: "max-content" }
: {}
}
>
<Card
style={{
height: "calc(50% - 30px)",
padding: "10px",
marginBottom: "10px",
}}
>
<Typography variant="h5">
{Blockly.Msg.tutorials_assessment_task}
</Typography>
<Typography>{currentTask.text}</Typography> <Typography>{currentTask.text}</Typography>
</Card> </Card>
<div style={isWidthDown('sm', this.props.width) ? { height: '500px' } : { height: '50%' }}> <div
style={
isWidthDown("sm", this.props.width)
? { height: "500px" }
: { height: "50%" }
}
>
<CodeViewer /> <CodeViewer />
</div> </div>
</Grid> </Grid>
</Grid> </Grid>
</div> </div>
); );
}; }
} }
Assessment.propTypes = { Assessment.propTypes = {
status: PropTypes.array.isRequired, status: PropTypes.array.isRequired,
change: PropTypes.number.isRequired, change: PropTypes.number.isRequired,
workspaceName: PropTypes.func.isRequired, workspaceName: PropTypes.func.isRequired,
tutorial: PropTypes.object.isRequired tutorial: PropTypes.object.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
change: state.tutorial.change, change: state.tutorial.change,
status: state.tutorial.status, status: state.tutorial.status,
tutorial: state.tutorial.tutorials[0] tutorial: state.tutorial.tutorials[0],
}); });
export default connect(mapStateToProps, { workspaceName })(withWidth()(Assessment)); export default connect(mapStateToProps, { workspaceName })(
withWidth()(Assessment)
);
-119
View File
@@ -1,119 +0,0 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { assigneBadge } from '../../actions/tutorialActions';
import Dialog from '../Dialog';
import { Link } from 'react-router-dom';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import Avatar from '@material-ui/core/Avatar';
import * as Blockly from 'blockly';
const styles = (theme) => ({
link: {
color: theme.palette.primary.main,
textDecoration: 'none',
'&:hover': {
color: theme.palette.primary.main,
textDecoration: 'underline'
}
}
});
class Badge extends Component {
state = {
open: false,
title: '',
content: ''
};
componentDidUpdate(props) {
if (this.props.message.id === 'TUTORIAL_CHECK_SUCCESS') {
if (this.props.tutorial.badge) {
// is connected to MyBadges?
if (this.props.isAuthenticated && this.props.user && this.props.user.badge) {
if (this.props.user.badges && !this.props.user.badges.includes(this.props.tutorial.badge)) {
if (this.isSuccess()) {
this.props.assigneBadge(this.props.tutorial.badge);
}
}
}
}
}
if (props.message !== this.props.message) {
if (this.props.message.id === 'ASSIGNE_BADGE_SUCCESS') {
this.setState({ title: `Badge: ${this.props.message.msg.name}`, content: `${Blockly.Msg.badges_ASSIGNE_BADGE_SUCCESS_01} ${this.props.message.msg.name} ${Blockly.Msg.badges_ASSIGNE_BADGE_SUCCESS_02}`, open: true });
}
}
}
isSuccess = () => {
var tutorialId = this.props.tutorial._id;
var status = this.props.status.filter(status => status._id === tutorialId)[0];
var tasks = status.tasks;
var success = tasks.filter(task => task.type === 'success').length / tasks.length;
if (success === 1) {
return true;
}
return false;
}
toggleDialog = () => {
this.setState({ open: !this.state, title: '', content: '' });
}
render() {
return (
<Dialog
style={{ zIndex: 99999999 }}
open={this.state.open}
title={this.state.title}
content={this.state.content}
onClose={() => { this.toggleDialog(); }}
onClick={() => { this.toggleDialog(); }}
button={Blockly.Msg.button_close}
>
<div style={{ marginTop: '10px' }}>
<Paper style={{ textAlign: 'center' }}>
{this.props.message.msg.image && this.props.message.msg.image.path ?
<Avatar src={`${process.env.REACT_APP_MYBADGES}/media/${this.props.message.msg.image.path}`} style={{ width: '200px', height: '200px', marginLeft: 'auto', marginRight: 'auto' }} />
: <Avatar style={{ width: '200px', height: '200px', marginLeft: 'auto', marginRight: 'auto' }}></Avatar>}
<Typography variant='h6' style={{ display: 'flex', cursor: 'default', paddingBottom: '6px' }}>
<div style={{ flexGrow: 1, marginLeft: '10px', marginRight: '10px' }}>{this.props.message.msg.name}</div>
</Typography>
</Paper>
<Typography style={{ marginTop: '10px' }}>
{Blockly.Msg.badges_explaination}<Link to={'/user/badge'} className={this.props.classes.link}>{Blockly.Msg.labels_here}</Link>.
</Typography>
</div>
</Dialog>
);
};
}
Badge.propTypes = {
assigneBadge: PropTypes.func.isRequired,
status: PropTypes.array.isRequired,
change: PropTypes.number.isRequired,
tutorial: PropTypes.object.isRequired,
user: PropTypes.object,
isAuthenticated: PropTypes.bool.isRequired,
message: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
change: state.tutorial.change,
status: state.tutorial.status,
tutorial: state.tutorial.tutorials[0],
user: state.auth.user,
isAuthenticated: state.auth.isAuthenticated,
message: state.message
});
export default connect(mapStateToProps, { assigneBadge })(withStyles(styles, { withTheme: true })(Badge));
-190
View File
@@ -1,190 +0,0 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { tutorialBadge, deleteProperty, setError, deleteError } from '../../../actions/tutorialBuilderActions';
import axios from 'axios';
import { withStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import FormHelperText from '@material-ui/core/FormHelperText';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import IconButton from '@material-ui/core/IconButton';
import OutlinedInput from '@material-ui/core/OutlinedInput';
import InputLabel from '@material-ui/core/InputLabel';
import FormControl from '@material-ui/core/FormControl';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faTimes } from "@fortawesome/free-solid-svg-icons";
const styles = (theme) => ({
errorColor: {
color: `${theme.palette.error.dark} !important`
},
errorColorShrink: {
color: `rgba(0, 0, 0, 0.54) !important`
},
errorBorder: {
borderColor: `${theme.palette.error.dark} !important`
}
});
class Badge extends Component {
constructor(props){
super(props);
this.state={
checked: props.badge ? true : false,
badgeName: '',
filteredBadges: [],
badges: []
};
}
componentDidMount(){
this.getBadges();
}
componentDidUpdate(props){
if(props.badge !== this.props.badge){
this.setState({ checked: this.props.badge !== undefined ? true : false, badgeName: this.props.badge ? this.state.badges.filter(badge => badge._id === this.props.badge)[0].name : '' });
}
}
getBadges = () => {
axios.get(`${process.env.REACT_APP_MYBADGES_API}/badge`)
.then(res => {
this.setState({badges: res.data.badges, badgeName: this.props.badge ? res.data.badges.filter(badge => badge._id === this.props.badge)[0].name : '' });
})
.catch(err => {
console.log(err);
});
};
deleteBadge = () => {
this.setState({ filteredBadges: [], badgeName: '' });
this.props.tutorialBadge(null);
this.props.setError(this.props.index, 'badge');
};
setBadge = (badge) => {
this.setState({ filteredBadges: [] });
this.props.tutorialBadge(badge._id);
this.props.deleteError(this.props.index, 'badge');
};
onChange = e => {
this.setState({ badgeName: e.target.value });
};
onChangeBadge = e => {
if(e.target.value && this.props.badge === null){
var filteredBadges = this.state.badges.filter(badge => new RegExp(e.target.value, 'i').test(badge.name));
if(filteredBadges.length < 1){
filteredBadges = ['Keine Übereinstimmung gefunden.'];
}
this.setState({filteredBadges: filteredBadges});
}
else {
this.setState({filteredBadges: []});
}
};
onChangeSwitch = (value) => {
var oldValue = this.state.checked;
this.setState({checked: value});
if(oldValue !== value){
if(value){
this.props.setError(this.props.index, 'badge');
this.props.tutorialBadge(null);
} else {
this.props.deleteError(this.props.index, 'badge');
this.props.tutorialBadge(undefined);
}
}
}
render() {
return (
<div style={{marginBottom: '10px', padding: '18.5px 14px', borderRadius: '25px', border: '1px solid lightgrey', width: 'calc(100% - 28px)'}}>
<FormControlLabel
labelPlacement="end"
label={"Badge"}
control={
<Switch
checked={this.state.checked}
onChange={(e) => this.onChangeSwitch(e.target.checked)}
color="primary"
/>
}
/>
{this.state.checked ?
<div style={{marginTop: '10px'}}>
<FormControl variant="outlined" fullWidth>
<InputLabel
htmlFor={'badge'}
classes={{shrink: this.props.error ? this.props.classes.errorColorShrink : null}}
>
{'Badge'}
</InputLabel>
<OutlinedInput
style={{borderRadius: '25px'}}
classes={{notchedOutline: this.props.error ? this.props.classes.errorBorder : null}}
error={this.props.error}
value={this.state.badgeName}
label={'Badge'}
id={'badge'}
disabled={this.props.badge}
onChange={(e) => this.onChange(e)}
onInput={(e) => this.onChangeBadge(e)}
fullWidth={true}
endAdornment={
<IconButton
onClick={this.deleteBadge}
edge="end"
>
<FontAwesomeIcon size='xs' icon={faTimes} />
</IconButton>
}
/>
{this.props.error && this.state.filteredBadges.length === 0 ?
<FormHelperText className={this.props.classes.errorColor}>Wähle ein Badge aus.</FormHelperText>
: null}
</FormControl>
<List style={{paddingTop: 0}}>
{this.state.filteredBadges.map((badge, i) => (
badge === 'Keine Übereinstimmung gefunden.' ?
<ListItem button key={i} onClick={this.deleteBadge} style={{border: '1px solid rgba(0, 0, 0, 0.23)', borderRadius: '25px'}}>
<ListItemText>{badge}</ListItemText>
</ListItem>
:
<ListItem button key={i} onClick={() => {this.setBadge(badge)}} style={{border: '1px solid rgba(0, 0, 0, 0.23)', borderRadius: '25px'}}>
<ListItemText>{`${badge.name}`}</ListItemText>
</ListItem>
))}
</List>
</div>
: null}
</div>
);
};
}
Badge.propTypes = {
tutorialBadge: PropTypes.func.isRequired,
deleteProperty: PropTypes.func.isRequired,
setError: PropTypes.func.isRequired,
deleteError: PropTypes.func.isRequired,
badge: PropTypes.string.isRequired
};
const mapStateToProps = state => ({
badge: state.builder.badge,
change: state.builder.change
});
export default connect(mapStateToProps, { tutorialBadge, deleteProperty, setError, deleteError })(withStyles(styles, {withTheme: true})(Badge));
+392 -186
View File
@@ -1,67 +1,75 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { checkError, readJSON, jsonString, progress, tutorialId, resetTutorial as resetTutorialBuilder} from '../../../actions/tutorialBuilderActions'; import {
import { getTutorials, resetTutorial, deleteTutorial, tutorialProgress } from '../../../actions/tutorialActions'; checkError,
import { clearMessages } from '../../../actions/messageActions'; readJSON,
jsonString,
progress,
tutorialId,
resetTutorial as resetTutorialBuilder,
} from "../../../actions/tutorialBuilderActions";
import {
getTutorials,
resetTutorial,
deleteTutorial,
tutorialProgress,
} from "../../../actions/tutorialActions";
import { clearMessages } from "../../../actions/messageActions";
import axios from 'axios'; import axios from "axios";
import { withRouter } from 'react-router-dom'; import { withRouter } from "react-router-dom";
import Breadcrumbs from "../../Breadcrumbs";
import Textfield from "./Textfield";
import Step from "./Step";
import Dialog from "../../Dialog";
import Snackbar from "../../Snackbar";
import Breadcrumbs from '../../Breadcrumbs'; import { withStyles } from "@material-ui/core/styles";
import Badge from './Badge'; import Button from "@material-ui/core/Button";
import Textfield from './Textfield'; import Backdrop from "@material-ui/core/Backdrop";
import Step from './Step'; import CircularProgress from "@material-ui/core/CircularProgress";
import Dialog from '../../Dialog'; import Divider from "@material-ui/core/Divider";
import Snackbar from '../../Snackbar'; import FormHelperText from "@material-ui/core/FormHelperText";
import Radio from "@material-ui/core/Radio";
import { withStyles } from '@material-ui/core/styles'; import RadioGroup from "@material-ui/core/RadioGroup";
import Button from '@material-ui/core/Button'; import FormControlLabel from "@material-ui/core/FormControlLabel";
import Backdrop from '@material-ui/core/Backdrop'; import InputLabel from "@material-ui/core/InputLabel";
import CircularProgress from '@material-ui/core/CircularProgress'; import MenuItem from "@material-ui/core/MenuItem";
import Divider from '@material-ui/core/Divider'; import FormControl from "@material-ui/core/FormControl";
import FormHelperText from '@material-ui/core/FormHelperText'; import Select from "@material-ui/core/Select";
import Radio from '@material-ui/core/Radio';
import RadioGroup from '@material-ui/core/RadioGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
const styles = (theme) => ({ const styles = (theme) => ({
backdrop: { backdrop: {
zIndex: theme.zIndex.drawer + 1, zIndex: theme.zIndex.drawer + 1,
color: '#fff', color: "#fff",
}, },
errorColor: { errorColor: {
color: theme.palette.error.dark color: theme.palette.error.dark,
}, },
errorButton: { errorButton: {
marginTop: '5px', marginTop: "5px",
height: '40px', height: "40px",
backgroundColor: theme.palette.error.dark, backgroundColor: theme.palette.error.dark,
'&:hover': { "&:hover": {
backgroundColor: theme.palette.error.dark backgroundColor: theme.palette.error.dark,
} },
} },
}); });
class Builder extends Component { class Builder extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
tutorial: 'new', tutorial: "new",
open: false, open: false,
title: '', title: "",
content: '', content: "",
string: false, string: false,
snackbar: false, snackbar: false,
key: '', key: "",
message: '' message: "",
}; };
this.inputRef = React.createRef(); this.inputRef = React.createRef();
} }
@@ -70,27 +78,38 @@ class Builder extends Component {
this.props.tutorialProgress(); this.props.tutorialProgress();
// retrieve tutorials only if a potential user is loaded - authentication // retrieve tutorials only if a potential user is loaded - authentication
// is finished (success or failed) // is finished (success or failed)
if(!this.props.authProgress){ if (!this.props.authProgress) {
this.props.getTutorials(); this.props.getTutorials();
} }
} }
componentDidUpdate(props, state) { componentDidUpdate(props, state) {
if(props.authProgress !== this.props.authProgress && !this.props.authProgress){ if (
props.authProgress !== this.props.authProgress &&
!this.props.authProgress
) {
// authentication is completed // authentication is completed
this.props.getTutorials(); this.props.getTutorials();
} }
if(props.message !== this.props.message){ if (props.message !== this.props.message) {
if(this.props.message.id === 'GET_TUTORIALS_FAIL'){ if (this.props.message.id === "GET_TUTORIALS_FAIL") {
// alert(this.props.message.msg); // alert(this.props.message.msg);
this.props.clearMessages(); this.props.clearMessages();
} } else if (this.props.message.id === "TUTORIAL_DELETE_SUCCESS") {
else if (this.props.message.id === 'TUTORIAL_DELETE_SUCCESS') { this.onChange("new");
this.onChange('new'); this.setState({
this.setState({ snackbar: true, key: Date.now(), message: `Das Tutorial wurde erfolgreich gelöscht.`, type: 'success' }); snackbar: true,
} key: Date.now(),
else if (this.props.message.id === 'TUTORIAL_DELETE_FAIL') { message: `Das Tutorial wurde erfolgreich gelöscht.`,
this.setState({ snackbar: true, key: Date.now(), message: `Fehler beim Löschen des Tutorials. Versuche es noch einmal.`, type: 'error' }); type: "success",
});
} else if (this.props.message.id === "TUTORIAL_DELETE_FAIL") {
this.setState({
snackbar: true,
key: Date.now(),
message: `Fehler beim Löschen des Tutorials. Versuche es noch einmal.`,
type: "error",
});
} }
} }
} }
@@ -105,22 +124,32 @@ class Builder extends Component {
uploadJsonFile = (jsonFile) => { uploadJsonFile = (jsonFile) => {
this.props.progress(true); this.props.progress(true);
if (jsonFile.type !== 'application/json') { if (jsonFile.type !== "application/json") {
this.props.progress(false); this.props.progress(false);
this.setState({ open: true, string: false, title: 'Unzulässiger Dateityp', content: 'Die übergebene Datei entspricht nicht dem geforderten Format. Es sind nur JSON-Dateien zulässig.' }); this.setState({
} open: true,
else { string: false,
title: "Unzulässiger Dateityp",
content:
"Die übergebene Datei entspricht nicht dem geforderten Format. Es sind nur JSON-Dateien zulässig.",
});
} else {
var reader = new FileReader(); var reader = new FileReader();
reader.readAsText(jsonFile); reader.readAsText(jsonFile);
reader.onloadend = () => { reader.onloadend = () => {
this.readJson(reader.result, true); this.readJson(reader.result, true);
}; };
} }
} };
uploadJsonString = () => { uploadJsonString = () => {
this.setState({ open: true, string: true, title: 'JSON-String einfügen', content: '' }); this.setState({
} open: true,
string: true,
title: "JSON-String einfügen",
content: "",
});
};
readJson = (jsonString, isFile) => { readJson = (jsonString, isFile) => {
try { try {
@@ -129,173 +158,255 @@ class Builder extends Component {
result.steps = [{}]; result.steps = [{}];
} }
this.props.readJSON(result); this.props.readJSON(result);
this.setState({ snackbar: true, key: Date.now(), message: `${isFile ? 'Die übergebene JSON-Datei' : 'Der übergebene JSON-String'} wurde erfolgreich übernommen.`, type: 'success' }); this.setState({
snackbar: true,
key: Date.now(),
message: `${
isFile ? "Die übergebene JSON-Datei" : "Der übergebene JSON-String"
} wurde erfolgreich übernommen.`,
type: "success",
});
} catch (err) { } catch (err) {
this.props.progress(false); this.props.progress(false);
this.props.jsonString(''); this.props.jsonString("");
this.setState({ open: true, string: false, title: 'Ungültiges JSON-Format', content: `${isFile ? 'Die übergebene Datei' : 'Der übergebene String'} enthält nicht valides JSON. Bitte überprüfe ${isFile ? 'die JSON-Datei' : 'den JSON-String'} und versuche es erneut.` }); this.setState({
} open: true,
string: false,
title: "Ungültiges JSON-Format",
content: `${
isFile ? "Die übergebene Datei" : "Der übergebene String"
} enthält nicht valides JSON. Bitte überprüfe ${
isFile ? "die JSON-Datei" : "den JSON-String"
} und versuche es erneut.`,
});
} }
};
checkSteps = (steps) => { checkSteps = (steps) => {
if (!(steps && steps.length > 0)) { if (!(steps && steps.length > 0)) {
return false; return false;
} }
return true; return true;
} };
toggle = () => { toggle = () => {
this.setState({ open: !this.state }); this.setState({ open: !this.state });
} };
onChange = (value) => { onChange = (value) => {
this.props.resetTutorialBuilder(); this.props.resetTutorialBuilder();
this.props.tutorialId(''); this.props.tutorialId("");
this.setState({ tutorial: value }); this.setState({ tutorial: value });
} };
onChangeId = (value) => { onChangeId = (value) => {
this.props.tutorialId(value); this.props.tutorialId(value);
if (this.state.tutorial === 'change') { if (this.state.tutorial === "change") {
this.props.progress(true); this.props.progress(true);
var tutorial = this.props.tutorials.filter(tutorial => tutorial._id === value)[0]; var tutorial = this.props.tutorials.filter(
(tutorial) => tutorial._id === value
)[0];
this.props.readJSON(tutorial); this.props.readJSON(tutorial);
this.setState({ snackbar: true, key: Date.now(), message: `Das ausgewählte Tutorial "${tutorial.title}" wurde erfolgreich übernommen.`, type: 'success' }); this.setState({
} snackbar: true,
key: Date.now(),
message: `Das ausgewählte Tutorial "${tutorial.title}" wurde erfolgreich übernommen.`,
type: "success",
});
} }
};
resetFull = () => { resetFull = () => {
this.props.resetTutorialBuilder(); this.props.resetTutorialBuilder();
this.setState({ snackbar: true, key: Date.now(), message: `Das Tutorial wurde erfolgreich zurückgesetzt.`, type: 'success' }); this.setState({
snackbar: true,
key: Date.now(),
message: `Das Tutorial wurde erfolgreich zurückgesetzt.`,
type: "success",
});
window.scrollTo(0, 0); window.scrollTo(0, 0);
} };
resetTutorial = () => { resetTutorial = () => {
var tutorial = this.props.tutorials.filter(tutorial => tutorial._id === this.props.id)[0]; var tutorial = this.props.tutorials.filter(
(tutorial) => tutorial._id === this.props.id
)[0];
this.props.readJSON(tutorial); this.props.readJSON(tutorial);
this.setState({ snackbar: true, key: Date.now(), message: `Das Tutorial ${tutorial.title} wurde erfolgreich auf den ursprünglichen Stand zurückgesetzt.`, type: 'success' }); this.setState({
snackbar: true,
key: Date.now(),
message: `Das Tutorial ${tutorial.title} wurde erfolgreich auf den ursprünglichen Stand zurückgesetzt.`,
type: "success",
});
window.scrollTo(0, 0); window.scrollTo(0, 0);
} };
submit = () => { submit = () => {
var isError = this.props.checkError(); var isError = this.props.checkError();
if (isError) { if (isError) {
this.setState({ snackbar: true, key: Date.now(), message: `Die Angaben für das Tutorial sind nicht vollständig.`, type: 'error' }); this.setState({
snackbar: true,
key: Date.now(),
message: `Die Angaben für das Tutorial sind nicht vollständig.`,
type: "error",
});
window.scrollTo(0, 0); window.scrollTo(0, 0);
return false; return false;
} } else {
else {
// export steps without attribute 'url' // export steps without attribute 'url'
var steps = this.props.steps; var steps = this.props.steps;
var newTutorial = new FormData(); var newTutorial = new FormData();
newTutorial.append('title', this.props.title); newTutorial.append("title", this.props.title);
if(this.props.badge){
newTutorial.append('badge', this.props.badge);
}
steps.forEach((step, i) => { steps.forEach((step, i) => {
if(step._id){ if (step._id) {
newTutorial.append(`steps[${i}][_id]`, step._id); newTutorial.append(`steps[${i}][_id]`, step._id);
} }
newTutorial.append(`steps[${i}][type]`, step.type); newTutorial.append(`steps[${i}][type]`, step.type);
newTutorial.append(`steps[${i}][headline]`, step.headline); newTutorial.append(`steps[${i}][headline]`, step.headline);
newTutorial.append(`steps[${i}][text]`, step.text); newTutorial.append(`steps[${i}][text]`, step.text);
if (i === 0 && step.type === 'instruction') { if (i === 0 && step.type === "instruction") {
if (step.requirements) { // optional if (step.requirements) {
// optional
step.requirements.forEach((requirement, j) => { step.requirements.forEach((requirement, j) => {
newTutorial.append(`steps[${i}][requirements][${j}]`, requirement); newTutorial.append(
`steps[${i}][requirements][${j}]`,
requirement
);
}); });
} }
step.hardware.forEach((hardware, j) => { step.hardware.forEach((hardware, j) => {
newTutorial.append(`steps[${i}][hardware][${j}]`, hardware); newTutorial.append(`steps[${i}][hardware][${j}]`, hardware);
}); });
} }
if (step.xml) { // optional if (step.xml) {
// optional
newTutorial.append(`steps[${i}][xml]`, step.xml); newTutorial.append(`steps[${i}][xml]`, step.xml);
} }
if (step.media) { // optional if (step.media) {
// optional
if (step.media.youtube) { if (step.media.youtube) {
newTutorial.append(`steps[${i}][media][youtube]`, step.media.youtube); newTutorial.append(
`steps[${i}][media][youtube]`,
step.media.youtube
);
} }
if (step.media.picture) { if (step.media.picture) {
newTutorial.append(`steps[${i}][media][picture]`, step.media.picture); newTutorial.append(
`steps[${i}][media][picture]`,
step.media.picture
);
} }
} }
}); });
return newTutorial; return newTutorial;
} }
} };
submitNew = () => { submitNew = () => {
var newTutorial = this.submit(); var newTutorial = this.submit();
if(newTutorial){ if (newTutorial) {
const config = { const config = {
success: res => { success: (res) => {
var tutorial = res.data.tutorial; var tutorial = res.data.tutorial;
this.props.history.push(`/tutorial/${tutorial._id}`); this.props.history.push(`/tutorial/${tutorial._id}`);
}, },
error: err => { error: (err) => {
this.setState({ snackbar: true, key: Date.now(), message: `Fehler beim Erstellen des Tutorials. Versuche es noch einmal.`, type: 'error' }); this.setState({
snackbar: true,
key: Date.now(),
message: `Fehler beim Erstellen des Tutorials. Versuche es noch einmal.`,
type: "error",
});
window.scrollTo(0, 0); window.scrollTo(0, 0);
} },
}; };
axios.post(`${process.env.REACT_APP_BLOCKLY_API}/tutorial/`, newTutorial, config) axios
.then(res => { .post(
`${process.env.REACT_APP_BLOCKLY_API}/tutorial/`,
newTutorial,
config
)
.then((res) => {
res.config.success(res); res.config.success(res);
}) })
.catch(err => { .catch((err) => {
err.config.error(err); err.config.error(err);
}); });
} }
} };
submitUpdate = () => { submitUpdate = () => {
var updatedTutorial = this.submit(); var updatedTutorial = this.submit();
if(updatedTutorial){ if (updatedTutorial) {
const config = { const config = {
success: res => { success: (res) => {
var tutorial = res.data.tutorial; var tutorial = res.data.tutorial;
this.props.history.push(`/tutorial/${tutorial._id}`); this.props.history.push(`/tutorial/${tutorial._id}`);
}, },
error: err => { error: (err) => {
this.setState({ snackbar: true, key: Date.now(), message: `Fehler beim Ändern des Tutorials. Versuche es noch einmal.`, type: 'error' }); this.setState({
snackbar: true,
key: Date.now(),
message: `Fehler beim Ändern des Tutorials. Versuche es noch einmal.`,
type: "error",
});
window.scrollTo(0, 0); window.scrollTo(0, 0);
} },
}; };
axios.put(`${process.env.REACT_APP_BLOCKLY_API}/tutorial/${this.props.id}`, updatedTutorial, config) axios
.then(res => { .put(
`${process.env.REACT_APP_BLOCKLY_API}/tutorial/${this.props.id}`,
updatedTutorial,
config
)
.then((res) => {
res.config.success(res); res.config.success(res);
}) })
.catch(err => { .catch((err) => {
err.config.error(err); err.config.error(err);
}); });
} }
} };
render() { render() {
var filteredTutorials = this.props.tutorials.filter(tutorial => tutorial.creator === this.props.user.email); var filteredTutorials = this.props.tutorials.filter(
(tutorial) => tutorial.creator === this.props.user.email
);
return ( return (
<div> <div>
<Breadcrumbs content={[{ link: '/tutorial', title: 'Tutorial' }, { link: '/tutorial/builder', title: 'Builder' }]} /> <Breadcrumbs
content={[
{ link: "/tutorial", title: "Tutorial" },
{ link: "/tutorial/builder", title: "Builder" },
]}
/>
<h1>Tutorial-Builder</h1> <h1>Tutorial-Builder</h1>
<RadioGroup row value={this.state.tutorial} onChange={(e) => this.onChange(e.target.value)}> <RadioGroup
<FormControlLabel style={{ color: 'black' }} row
value={this.state.tutorial}
onChange={(e) => this.onChange(e.target.value)}
>
<FormControlLabel
style={{ color: "black" }}
value="new" value="new"
control={<Radio color="primary" />} control={<Radio color="primary" />}
label="neues Tutorial erstellen" label="neues Tutorial erstellen"
labelPlacement="end" labelPlacement="end"
/> />
{filteredTutorials.length > 0 ? {filteredTutorials.length > 0 ? (
<div> <div>
<FormControlLabel style={{ color: 'black' }} <FormControlLabel
style={{ color: "black" }}
disabled={this.props.index === 0} disabled={this.props.index === 0}
value="change" value="change"
control={<Radio color="primary" />} control={<Radio color="primary" />}
label="bestehendes Tutorial ändern" label="bestehendes Tutorial ändern"
labelPlacement="end" labelPlacement="end"
/> />
<FormControlLabel style={{ color: 'black' }} <FormControlLabel
style={{ color: "black" }}
disabled={this.props.index === 0} disabled={this.props.index === 0}
value="delete" value="delete"
control={<Radio color="primary" />} control={<Radio color="primary" />}
@@ -303,110 +414,196 @@ class Builder extends Component {
labelPlacement="end" labelPlacement="end"
/> />
</div> </div>
: null} ) : null}
</RadioGroup> </RadioGroup>
<Divider variant='fullWidth' style={{ margin: '10px 0 15px 0' }} /> <Divider variant="fullWidth" style={{ margin: "10px 0 15px 0" }} />
{this.state.tutorial === 'new' ? {this.state.tutorial === "new" ? (
/*upload JSON*/ /*upload JSON*/
<div ref={this.inputRef}> <div ref={this.inputRef}>
<input <input
style={{ display: 'none' }} style={{ display: "none" }}
accept="application/json" accept="application/json"
onChange={(e) => { this.uploadJsonFile(e.target.files[0]) }} onChange={(e) => {
this.uploadJsonFile(e.target.files[0]);
}}
id="open-json" id="open-json"
type="file" type="file"
/> />
<label htmlFor="open-json"> <label htmlFor="open-json">
<Button component="span" style={{ marginRight: '10px', marginBottom: '10px' }} variant='contained' color='primary'>Datei laden</Button> <Button
component="span"
style={{ marginRight: "10px", marginBottom: "10px" }}
variant="contained"
color="primary"
>
Datei laden
</Button>
</label> </label>
<Button style={{ marginRight: '10px', marginBottom: '10px' }} variant='contained' color='primary' onClick={() => this.uploadJsonString()}>String laden</Button> <Button
style={{ marginRight: "10px", marginBottom: "10px" }}
variant="contained"
color="primary"
onClick={() => this.uploadJsonString()}
>
String laden
</Button>
</div> </div>
: <FormControl variant="outlined" style={{ width: '100%' }}> ) : (
<FormControl variant="outlined" style={{ width: "100%" }}>
<InputLabel id="select-outlined-label">Tutorial</InputLabel> <InputLabel id="select-outlined-label">Tutorial</InputLabel>
<Select <Select
color='primary' color="primary"
labelId="select-outlined-label" labelId="select-outlined-label"
value={this.props.id} value={this.props.id}
onChange={(e) => this.onChangeId(e.target.value)} onChange={(e) => this.onChangeId(e.target.value)}
label="Tutorial" label="Tutorial"
> >
{filteredTutorials.map(tutorial => {filteredTutorials.map((tutorial) => (
<MenuItem value={tutorial._id}>{tutorial.title}</MenuItem> <MenuItem value={tutorial._id}>{tutorial.title}</MenuItem>
)} ))}
</Select> </Select>
</FormControl> </FormControl>
}
<Divider variant='fullWidth' style={{ margin: '10px 0 15px 0' }} />
{this.state.tutorial === 'new' || (this.state.tutorial === 'change' && this.props.id !== '') ?
/*Tutorial-Builder-Form*/
<div>
{this.props.error.type ?
<FormHelperText style={{ lineHeight: 'initial' }} className={this.props.classes.errorColor}>{`Ein Tutorial muss mindestens jeweils eine Instruktion und eine Aufgabe enthalten.`}</FormHelperText>
: null}
{/* <Id error={this.props.error.id} value={this.props.id} /> */}
<Textfield value={this.props.title} property={'title'} label={'Titel'} error={this.props.error.title} />
<Badge error={this.props.error.badge}/>
{this.props.steps.map((step, i) =>
<Step step={step} index={i} key={i} />
)} )}
{/*submit or reset*/} <Divider variant="fullWidth" style={{ margin: "10px 0 15px 0" }} />
{this.state.tutorial !== 'delete' ?
<div>
<Divider variant='fullWidth' style={{ margin: '30px 0 10px 0' }} />
{this.state.tutorial === 'new' ?
<div>
<Button style={{ marginRight: '10px', marginTop: '10px' }} variant='contained' color='primary' onClick={() => this.submitNew()}>Tutorial erstellen</Button>
<Button style={{ marginTop: '10px' }} variant='contained' onClick={() => this.resetFull()}>Zurücksetzen</Button>
</div>
: <div>
<Button style={{ marginRight: '10px', marginTop: '10px' }} variant='contained' color='primary' onClick={() => this.submitUpdate()}>Tutorial ändern</Button>
<Button style={{ marginTop: '10px' }} variant='contained' onClick={() => this.resetTutorial()}>Zurücksetzen</Button>
</div>
}
</div>
: null}
<Backdrop className={this.props.classes.backdrop} open={this.props.isProgress}> {this.state.tutorial === "new" ||
(this.state.tutorial === "change" && this.props.id !== "") ? (
/*Tutorial-Builder-Form*/
<div>
{this.props.error.type ? (
<FormHelperText
style={{ lineHeight: "initial" }}
className={this.props.classes.errorColor}
>{`Ein Tutorial muss mindestens jeweils eine Instruktion und eine Aufgabe enthalten.`}</FormHelperText>
) : null}
{/* <Id error={this.props.error.id} value={this.props.id} /> */}
<Textfield
value={this.props.title}
property={"title"}
label={"Titel"}
error={this.props.error.title}
/>
{this.props.steps.map((step, i) => (
<Step step={step} index={i} key={i} />
))}
{/*submit or reset*/}
{this.state.tutorial !== "delete" ? (
<div>
<Divider
variant="fullWidth"
style={{ margin: "30px 0 10px 0" }}
/>
{this.state.tutorial === "new" ? (
<div>
<Button
style={{ marginRight: "10px", marginTop: "10px" }}
variant="contained"
color="primary"
onClick={() => this.submitNew()}
>
Tutorial erstellen
</Button>
<Button
style={{ marginTop: "10px" }}
variant="contained"
onClick={() => this.resetFull()}
>
Zurücksetzen
</Button>
</div>
) : (
<div>
<Button
style={{ marginRight: "10px", marginTop: "10px" }}
variant="contained"
color="primary"
onClick={() => this.submitUpdate()}
>
Tutorial ändern
</Button>
<Button
style={{ marginTop: "10px" }}
variant="contained"
onClick={() => this.resetTutorial()}
>
Zurücksetzen
</Button>
</div>
)}
</div>
) : null}
<Backdrop
className={this.props.classes.backdrop}
open={this.props.isProgress}
>
<CircularProgress color="inherit" /> <CircularProgress color="inherit" />
</Backdrop> </Backdrop>
</div> </div>
: null} ) : null}
{this.state.tutorial === 'delete' && this.props.id !== '' ? {this.state.tutorial === "delete" && this.props.id !== "" ? (
<Button <Button
className={this.props.classes.errorButton} className={this.props.classes.errorButton}
variant='contained' variant="contained"
color='primary' color="primary"
onClick={() => this.props.deleteTutorial()}>Tutorial löschen</Button> onClick={() => this.props.deleteTutorial()}
: null} >
Tutorial löschen
</Button>
) : null}
<Dialog <Dialog
open={this.state.open} open={this.state.open}
maxWidth={this.state.string ? 'md' : 'sm'} maxWidth={this.state.string ? "md" : "sm"}
fullWidth={this.state.string} fullWidth={this.state.string}
title={this.state.title} title={this.state.title}
content={this.state.content} content={this.state.content}
onClose={this.toggle} onClose={this.toggle}
onClick={this.toggle} onClick={this.toggle}
button={'Schließen'} button={"Schließen"}
actions={ actions={
this.state.string ? this.state.string ? (
<div> <div>
<Button disabled={this.props.error.json || this.props.json === ''} variant='contained' onClick={() => { this.toggle(); this.props.progress(true); this.readJson(this.props.json, false); }} color="primary">Bestätigen</Button> <Button
<Button onClick={() => { this.toggle(); this.props.jsonString(''); }} color="primary">Abbrechen</Button> disabled={this.props.error.json || this.props.json === ""}
variant="contained"
onClick={() => {
this.toggle();
this.props.progress(true);
this.readJson(this.props.json, false);
}}
color="primary"
>
Bestätigen
</Button>
<Button
onClick={() => {
this.toggle();
this.props.jsonString("");
}}
color="primary"
>
Abbrechen
</Button>
</div> </div>
: null ) : null
} }
> >
{this.state.string ? {this.state.string ? (
<Textfield value={this.props.json} property={'json'} label={'JSON'} multiline error={this.props.error.json} /> <Textfield
: null} value={this.props.json}
property={"json"}
label={"JSON"}
multiline
error={this.props.error.json}
/>
) : null}
</Dialog> </Dialog>
<Snackbar <Snackbar
@@ -415,10 +612,9 @@ class Builder extends Component {
type={this.state.type} type={this.state.type}
key={this.state.key} key={this.state.key}
/> />
</div> </div>
); );
}; }
} }
Builder.propTypes = { Builder.propTypes = {
@@ -434,7 +630,6 @@ Builder.propTypes = {
resetTutorialBuilder: PropTypes.func.isRequired, resetTutorialBuilder: PropTypes.func.isRequired,
tutorialProgress: PropTypes.func.isRequired, tutorialProgress: PropTypes.func.isRequired,
title: PropTypes.string.isRequired, title: PropTypes.string.isRequired,
badge: PropTypes.string.isRequired,
id: PropTypes.string.isRequired, id: PropTypes.string.isRequired,
steps: PropTypes.array.isRequired, steps: PropTypes.array.isRequired,
change: PropTypes.number.isRequired, change: PropTypes.number.isRequired,
@@ -444,12 +639,11 @@ Builder.propTypes = {
tutorials: PropTypes.array.isRequired, tutorials: PropTypes.array.isRequired,
message: PropTypes.object.isRequired, message: PropTypes.object.isRequired,
user: PropTypes.object.isRequired, user: PropTypes.object.isRequired,
authProgress: PropTypes.bool.isRequired authProgress: PropTypes.bool.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
title: state.builder.title, title: state.builder.title,
badge: state.builder.badge,
id: state.builder.id, id: state.builder.id,
steps: state.builder.steps, steps: state.builder.steps,
change: state.builder.change, change: state.builder.change,
@@ -459,7 +653,19 @@ const mapStateToProps = state => ({
tutorials: state.tutorial.tutorials, tutorials: state.tutorial.tutorials,
message: state.message, message: state.message,
user: state.auth.user, user: state.auth.user,
authProgress: state.auth.progress authProgress: state.auth.progress,
}); });
export default connect(mapStateToProps, { checkError, readJSON, jsonString, progress, tutorialId, resetTutorialBuilder, getTutorials, resetTutorial, tutorialProgress, clearMessages, deleteTutorial })(withStyles(styles, { withTheme: true })(withRouter(Builder))); export default connect(mapStateToProps, {
checkError,
readJSON,
jsonString,
progress,
tutorialId,
resetTutorialBuilder,
getTutorials,
resetTutorial,
tutorialProgress,
clearMessages,
deleteTutorial,
})(withStyles(styles, { withTheme: true })(withRouter(Builder)));
+76 -43
View File
@@ -1,34 +1,39 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { tutorialTitle, tutorialBadge, jsonString, changeContent, setError, deleteError } from '../../../actions/tutorialBuilderActions'; import {
tutorialTitle,
jsonString,
changeContent,
setError,
deleteError,
} from "../../../actions/tutorialBuilderActions";
import { withStyles } from '@material-ui/core/styles'; import { withStyles } from "@material-ui/core/styles";
import OutlinedInput from '@material-ui/core/OutlinedInput'; import OutlinedInput from "@material-ui/core/OutlinedInput";
import InputLabel from '@material-ui/core/InputLabel'; import InputLabel from "@material-ui/core/InputLabel";
import FormControl from '@material-ui/core/FormControl'; import FormControl from "@material-ui/core/FormControl";
import FormHelperText from '@material-ui/core/FormHelperText'; import FormHelperText from "@material-ui/core/FormHelperText";
const styles = theme => ({ const styles = (theme) => ({
multiline: { multiline: {
padding: '18.5px 14px 18.5px 24px' padding: "18.5px 14px 18.5px 24px",
}, },
errorColor: { errorColor: {
color: `${theme.palette.error.dark} !important` color: `${theme.palette.error.dark} !important`,
}, },
errorColorShrink: { errorColorShrink: {
color: `rgba(0, 0, 0, 0.54) !important` color: `rgba(0, 0, 0, 0.54) !important`,
}, },
errorBorder: { errorBorder: {
borderColor: `${theme.palette.error.dark} !important` borderColor: `${theme.palette.error.dark} !important`,
} },
}); });
class Textfield extends Component { class Textfield extends Component {
componentDidMount() {
componentDidMount(){ if (this.props.error) {
if(this.props.error){ if (this.props.property !== "media") {
if(this.props.property !== 'media'){
this.props.deleteError(this.props.index, this.props.property); this.props.deleteError(this.props.index, this.props.property);
} }
} }
@@ -36,38 +41,50 @@ class Textfield extends Component {
handleChange = (e) => { handleChange = (e) => {
var value = e.target.value; var value = e.target.value;
if(this.props.property === 'title'){ if (this.props.property === "title") {
this.props.tutorialTitle(value); this.props.tutorialTitle(value);
} } else if (this.props.property === "json") {
else if(this.props.property === 'json'){
this.props.jsonString(value); this.props.jsonString(value);
} else {
this.props.changeContent(
value,
this.props.index,
this.props.property,
this.props.property2
);
} }
else if(this.props.property === 'badge'){ if (value.replace(/\s/g, "") === "") {
this.props.tutorialBadge(value);
}
else {
this.props.changeContent(value, this.props.index, this.props.property, this.props.property2);
}
if(value.replace(/\s/g,'') === ''){
this.props.setError(this.props.index, this.props.property); this.props.setError(this.props.index, this.props.property);
} } else {
else{
this.props.deleteError(this.props.index, this.props.property); this.props.deleteError(this.props.index, this.props.property);
} }
}; };
render() { render() {
return ( return (
<FormControl variant="outlined" fullWidth style={{marginBottom: '10px'}}> <FormControl
variant="outlined"
fullWidth
style={{ marginBottom: "10px" }}
>
<InputLabel <InputLabel
htmlFor={this.props.property} htmlFor={this.props.property}
classes={{shrink: this.props.error ? this.props.classes.errorColorShrink : null}} classes={{
shrink: this.props.error
? this.props.classes.errorColorShrink
: null,
}}
> >
{this.props.label} {this.props.label}
</InputLabel> </InputLabel>
<OutlinedInput <OutlinedInput
style={{borderRadius: '25px'}} style={{ borderRadius: "25px" }}
classes={{multiline: this.props.classes.multiline, notchedOutline: this.props.error ? this.props.classes.errorBorder : null}} classes={{
multiline: this.props.classes.multiline,
notchedOutline: this.props.error
? this.props.classes.errorBorder
: null,
}}
error={this.props.error} error={this.props.error}
value={this.props.value} value={this.props.value}
label={this.props.label} label={this.props.label}
@@ -77,21 +94,37 @@ class Textfield extends Component {
rowsMax={10} rowsMax={10}
onChange={(e) => this.handleChange(e)} onChange={(e) => this.handleChange(e)}
/> />
{this.props.error ? {this.props.error ? (
this.props.property === 'title' ? <FormHelperText className={this.props.classes.errorColor}>Gib einen Titel für das Tutorial ein.</FormHelperText> this.props.property === "title" ? (
: this.props.property === 'json' ? <FormHelperText className={this.props.classes.errorColor}>Gib einen JSON-String ein und bestätige diesen mit einem Klick auf den entsprechenden Button</FormHelperText> <FormHelperText className={this.props.classes.errorColor}>
: <FormHelperText className={this.props.classes.errorColor}>{this.props.errorText}</FormHelperText> Gib einen Titel für das Tutorial ein.
: null} </FormHelperText>
) : this.props.property === "json" ? (
<FormHelperText className={this.props.classes.errorColor}>
Gib einen JSON-String ein und bestätige diesen mit einem Klick auf
den entsprechenden Button
</FormHelperText>
) : (
<FormHelperText className={this.props.classes.errorColor}>
{this.props.errorText}
</FormHelperText>
)
) : null}
</FormControl> </FormControl>
); );
}; }
} }
Textfield.propTypes = { Textfield.propTypes = {
tutorialTitle: PropTypes.func.isRequired, tutorialTitle: PropTypes.func.isRequired,
tutorialBadge: PropTypes.func.isRequired,
jsonString: PropTypes.func.isRequired, jsonString: PropTypes.func.isRequired,
changeContent: PropTypes.func.isRequired, changeContent: PropTypes.func.isRequired,
}; };
export default connect(null, { tutorialTitle, tutorialBadge, jsonString, changeContent, setError, deleteError })(withStyles(styles, { withTheme: true })(Textfield)); export default connect(null, {
tutorialTitle,
jsonString,
changeContent,
setError,
deleteError,
})(withStyles(styles, { withTheme: true })(Textfield));
+77 -39
View File
@@ -1,57 +1,95 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import Hardware from './Hardware'; import Hardware from "./Hardware";
import Requirement from './Requirement'; import Requirement from "./Requirement";
import BlocklyWindow from '../Blockly/BlocklyWindow'; import BlocklyWindow from "../Blockly/BlocklyWindow";
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import ReactMarkdown from 'react-markdown'
import Grid from "@material-ui/core/Grid";
import Typography from "@material-ui/core/Typography";
import ReactMarkdown from "react-markdown";
class Instruction extends Component { class Instruction extends Component {
render() { render() {
var step = this.props.step; var step = this.props.step;
var isHardware = step.hardware && step.hardware.length > 0; var isHardware = step.hardware && step.hardware.length > 0;
var areRequirements = step.requirements && step.requirements.length > 0; var areRequirements = step.requirements && step.requirements.length > 0;
return ( return (
<div> <div>
<Typography variant='h4' style={{ marginBottom: '5px' }}>{step.headline}</Typography> <Typography variant="h4" style={{ marginBottom: "5px" }}>
<Typography style={isHardware ? {} : { marginBottom: '5px' }}><ReactMarkdown className={'tutorial'} linkTarget={'_blank'} skipHtml={false}>{step.text}</ReactMarkdown></Typography> {step.headline}
{isHardware ? </Typography>
<Hardware picture={step.hardware} /> : null} <Typography style={isHardware ? {} : { marginBottom: "5px" }}>
{areRequirements > 0 ? <ReactMarkdown
<Requirement requirements={step.requirements} /> : null} className={"tutorial"}
{step.media ? linkTarget={"_blank"}
step.media.picture ? skipHtml={false}
<div style={{ display: 'flex', justifyContent: 'center', marginBottom: '5px' }}> >
<img src={`${process.env.REACT_APP_BLOCKLY_API}/media/${step.media.picture.path}`} alt='' style={{ maxHeight: '40vH', maxWidth: '100%' }} /> {step.text}
</div> </ReactMarkdown>
: step.media.youtube ? </Typography>
/*16:9; width: 800px; height: width/16*9=450px*/ {isHardware ? <Hardware picture={step.hardware} /> : null}
<div style={{ maxWidth: '800px', margin: 'auto' }}> {areRequirements > 0 ? (
<div style={{ position: 'relative', height: 0, paddingBottom: 'calc(100% / 16 * 9)' }}> <Requirement requirements={step.requirements} />
<iframe title={step.media.youtube} style={{ position: 'absolute', top: '0', left: '0', width: '100%', maxWidth: '800px', height: '100%', maxHeight: '450px' }} src={`https://www.youtube.com/embed/${step.media.youtube}`} frameBorder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowFullScreen /> ) : null}
</div> {step.media ? (
</div> step.media.picture ? (
: null <div
: null} style={{
{step.xml ? display: "flex",
<Grid container spacing={2} style={{ marginBottom: '5px' }}> justifyContent: "center",
<Grid item xs={12} style={{display: 'flex', justifyContent: 'center'}}> marginBottom: "5px",
<BlocklyWindow }}
svg >
blockDisabled <img
initialXml={step.xml} src={`${process.env.REACT_APP_BLOCKLY_API}/media/${step.media.picture.path}`}
alt=""
style={{ maxHeight: "40vH", maxWidth: "100%" }}
/> />
</div>
) : step.media.youtube ? (
/*16:9; width: 800px; height: width/16*9=450px*/
<div style={{ maxWidth: "800px", margin: "auto" }}>
<div
style={{
position: "relative",
height: 0,
paddingBottom: "calc(100% / 16 * 9)",
}}
>
<iframe
title={step.media.youtube}
style={{
position: "absolute",
top: "0",
left: "0",
width: "100%",
maxWidth: "800px",
height: "100%",
maxHeight: "450px",
}}
src={`https://www.youtube.com/embed/${step.media.youtube}`}
frameBorder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
/>
</div>
</div>
) : null
) : null}
{step.xml ? (
<Grid container spacing={2} style={{ marginBottom: "5px" }}>
<Grid
item
xs={12}
style={{ display: "flex", justifyContent: "center" }}
>
<BlocklyWindow svg blockDisabled initialXml={step.xml} />
</Grid> </Grid>
</Grid> </Grid>
: null} ) : null}
</div> </div>
); );
}; }
} }
export default Instruction; export default Instruction;
+1 -1
View File
@@ -85,7 +85,7 @@ class StepperVertical extends Component {
return ( return (
<Step key={i}> <Step key={i}>
<Tooltip title={step.headline} placement='right' arrow > <Tooltip title={step.headline} placement='right' arrow >
<div style={i === activeStep ? {padding: '5px 0'} : {padding: '5px 0', cursor: 'pointer'}} onClick={i === activeStep ? null : () => {console.log(i); this.props.tutorialStep(i)}}> <div style={i === activeStep ? {padding: '5px 0'} : {padding: '5px 0', cursor: 'pointer'}} onClick={i === activeStep ? null : () => { this.props.tutorialStep(i)}}>
<StepLabel <StepLabel
StepIconComponent={'div'} StepIconComponent={'div'}
classes={{ classes={{
+113 -49
View File
@@ -1,47 +1,51 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { workspaceName } from '../../actions/workspaceActions'; import { workspaceName } from "../../actions/workspaceActions";
import { clearMessages } from '../../actions/messageActions'; import { clearMessages } from "../../actions/messageActions";
import { getTutorial, resetTutorial, tutorialStep,tutorialProgress } from '../../actions/tutorialActions'; import {
getTutorial,
resetTutorial,
tutorialStep,
tutorialProgress,
} from "../../actions/tutorialActions";
import { withRouter } from 'react-router-dom'; import { withRouter } from "react-router-dom";
import Breadcrumbs from '../Breadcrumbs'; import Breadcrumbs from "../Breadcrumbs";
import StepperHorizontal from './StepperHorizontal'; import StepperHorizontal from "./StepperHorizontal";
import StepperVertical from './StepperVertical'; import StepperVertical from "./StepperVertical";
import Instruction from './Instruction'; import Instruction from "./Instruction";
import Assessment from './Assessment'; import Assessment from "./Assessment";
import Badge from './Badge'; import NotFound from "../NotFound";
import NotFound from '../NotFound'; import * as Blockly from "blockly";
import * as Blockly from 'blockly' import { detectWhitespacesAndReturnReadableResult } from "../../helpers/whitespace";
import { detectWhitespacesAndReturnReadableResult } from '../../helpers/whitespace';
import Card from "@material-ui/core/Card";
import Card from '@material-ui/core/Card'; import Button from "@material-ui/core/Button";
import Button from '@material-ui/core/Button';
class Tutorial extends Component { class Tutorial extends Component {
componentDidMount() { componentDidMount() {
this.props.tutorialProgress(); this.props.tutorialProgress();
// retrieve tutorial only if a potential user is loaded - authentication // retrieve tutorial only if a potential user is loaded - authentication
// is finished (success or failed) // is finished (success or failed)
if(!this.props.progress){ if (!this.props.progress) {
console.log(this.props);
this.props.getTutorial(this.props.match.params.tutorialId); this.props.getTutorial(this.props.match.params.tutorialId);
} }
} }
componentDidUpdate(props, state) { componentDidUpdate(props, state) {
if(props.progress !== this.props.progress && !this.props.progress){ if (props.progress !== this.props.progress && !this.props.progress) {
// authentication is completed // authentication is completed
this.props.getTutorial(this.props.match.params.tutorialId); this.props.getTutorial(this.props.match.params.tutorialId);
} } else if (
else if(this.props.tutorial && !this.props.isLoading && this.props.tutorial._id !== this.props.match.params.tutorialId) { this.props.tutorial &&
!this.props.isLoading &&
this.props.tutorial._id !== this.props.match.params.tutorialId
) {
this.props.getTutorial(this.props.match.params.tutorialId); this.props.getTutorial(this.props.match.params.tutorialId);
} }
if (this.props.message.id === 'GET_TUTORIAL_FAIL') { if (this.props.message.id === "GET_TUTORIAL_FAIL") {
alert(this.props.message.msg); alert(this.props.message.msg);
} }
} }
@@ -57,44 +61,97 @@ class Tutorial extends Component {
render() { render() {
return ( return (
<div> <div>
{this.props.isLoading ? null : {this.props.isLoading ? null : !this.props.tutorial ? (
!this.props.tutorial ? this.props.message.id === "GET_TUTORIAL_FAIL" ? (
this.props.message.id === 'GET_TUTORIAL_FAIL' ? <NotFound button={{ title: Blockly.Msg.messages_GET_TUTORIAL_FAIL, link: '/tutorial' }} /> : null <NotFound
: (() => { button={{
title: Blockly.Msg.messages_GET_TUTORIAL_FAIL,
link: "/tutorial",
}}
/>
) : null
) : (
(() => {
var tutorial = this.props.tutorial; var tutorial = this.props.tutorial;
var steps = this.props.tutorial.steps; var steps = this.props.tutorial.steps;
var step = steps[this.props.activeStep]; var step = steps[this.props.activeStep];
var name = `${detectWhitespacesAndReturnReadableResult(tutorial.title)}_${detectWhitespacesAndReturnReadableResult(step.headline)}`; var name = `${detectWhitespacesAndReturnReadableResult(
tutorial.title
)}_${detectWhitespacesAndReturnReadableResult(step.headline)}`;
return ( return (
<div> <div>
<Breadcrumbs content={[{ link: '/tutorial', title: 'Tutorial' }, { link: `/tutorial/${this.props.tutorial._id}`, title: tutorial.title }]} /> <Breadcrumbs
content={[
{ link: "/tutorial", title: "Tutorial" },
{
link: `/tutorial/${this.props.tutorial._id}`,
title: tutorial.title,
},
]}
/>
<StepperHorizontal /> <StepperHorizontal />
<Badge />
<div style={{ display: 'flex' }}> <div style={{ display: "flex" }}>
<StepperVertical steps={steps} /> <StepperVertical steps={steps} />
{/* calc(Card-padding: 10px + Button-height: 35px + Button-marginTop: 15px)*/} {/* calc(Card-padding: 10px + Button-height: 35px + Button-marginTop: 15px)*/}
<Card style={{ padding: '10px 10px 60px 10px', display: 'block', position: 'relative', height: 'max-content', width: '100%' }}> <Card
{step ? style={{
step.type === 'instruction' ? padding: "10px 10px 60px 10px",
display: "block",
position: "relative",
height: "max-content",
width: "100%",
}}
>
{step ? (
step.type === "instruction" ? (
<Instruction step={step} /> <Instruction step={step} />
: <Assessment step={step} name={name} /> // if step.type === 'assessment' ) : (
: null} <Assessment step={step} name={name} />
) // if step.type === 'assessment'
) : null}
<div style={{ marginTop: '20px', position: 'absolute', bottom: '10px' }}> <div
<Button style={{ marginRight: '10px', height: '35px' }} variant='contained' disabled={this.props.activeStep === 0} onClick={() => this.props.tutorialStep(this.props.activeStep - 1)}>Zurück</Button> style={{
<Button style={{ height: '35px' }} variant='contained' color='primary' disabled={this.props.activeStep === tutorial.steps.length - 1} onClick={() => this.props.tutorialStep(this.props.activeStep + 1)}>Weiter</Button> marginTop: "20px",
position: "absolute",
bottom: "10px",
}}
>
<Button
style={{ marginRight: "10px", height: "35px" }}
variant="contained"
disabled={this.props.activeStep === 0}
onClick={() =>
this.props.tutorialStep(this.props.activeStep - 1)
}
>
Zurück
</Button>
<Button
style={{ height: "35px" }}
variant="contained"
color="primary"
disabled={
this.props.activeStep === tutorial.steps.length - 1
}
onClick={() =>
this.props.tutorialStep(this.props.activeStep + 1)
}
>
Weiter
</Button>
</div> </div>
</Card> </Card>
</div> </div>
</div> </div>
) );
})() })()
} )}
</div> </div>
); );
}; }
} }
Tutorial.propTypes = { Tutorial.propTypes = {
@@ -110,17 +167,24 @@ Tutorial.propTypes = {
tutorial: PropTypes.object.isRequired, tutorial: PropTypes.object.isRequired,
isLoading: PropTypes.bool.isRequired, isLoading: PropTypes.bool.isRequired,
message: PropTypes.object.isRequired, message: PropTypes.object.isRequired,
progress: PropTypes.bool.isRequired progress: PropTypes.bool.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
change: state.tutorial.change, change: state.tutorial.change,
status: state.tutorial.status, status: state.tutorial.status,
activeStep: state.tutorial.activeStep, activeStep: state.tutorial.activeStep,
tutorial: state.tutorial.tutorials[0], tutorial: state.tutorial.tutorials[0],
isLoading: state.tutorial.progress, isLoading: state.tutorial.progress,
message: state.message, message: state.message,
progress: state.auth.progress progress: state.auth.progress,
}); });
export default connect(mapStateToProps, { getTutorial, resetTutorial, tutorialStep, tutorialProgress, clearMessages, workspaceName })(withRouter(Tutorial)); export default connect(mapStateToProps, {
getTutorial,
resetTutorial,
tutorialStep,
tutorialProgress,
clearMessages,
workspaceName,
})(withRouter(Tutorial));
+121 -62
View File
@@ -1,77 +1,89 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { login } from '../../actions/authActions' import { login } from "../../actions/authActions";
import { clearMessages } from '../../actions/messageActions' import { clearMessages } from "../../actions/messageActions";
import { withRouter } from 'react-router-dom'; import { withRouter } from "react-router-dom";
import Snackbar from '../Snackbar'; import Snackbar from "../Snackbar";
import Alert from '../Alert'; import Alert from "../Alert";
import Breadcrumbs from '../Breadcrumbs'; import Breadcrumbs from "../Breadcrumbs";
import Button from '@material-ui/core/Button'; import Button from "@material-ui/core/Button";
import IconButton from '@material-ui/core/IconButton'; import IconButton from "@material-ui/core/IconButton";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons"; import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
import TextField from '@material-ui/core/TextField'; import TextField from "@material-ui/core/TextField";
import Divider from '@material-ui/core/Divider'; import Divider from "@material-ui/core/Divider";
import InputAdornment from '@material-ui/core/InputAdornment'; import InputAdornment from "@material-ui/core/InputAdornment";
import CircularProgress from '@material-ui/core/CircularProgress'; import CircularProgress from "@material-ui/core/CircularProgress";
import Link from '@material-ui/core/Link'; import Link from "@material-ui/core/Link";
import * as Blockly from 'blockly' import * as Blockly from "blockly";
export class Login extends Component { export class Login extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
redirect: props.location.state ? props.location.state.from.pathname : null, redirect: props.location.state
email: '', ? props.location.state.from.pathname
password: '', : null,
email: "",
password: "",
snackbar: false, snackbar: false,
type: '', type: "",
key: '', key: "",
message: '', message: "",
showPassword: false showPassword: false,
}; };
} }
componentDidUpdate(props) { componentDidUpdate(props) {
console.log(this.state.redirect);
const { message } = this.props; const { message } = this.props;
if (message !== props.message) { if (message !== props.message) {
if (message.id === 'LOGIN_SUCCESS') { if (message.id === "LOGIN_SUCCESS") {
if (this.state.redirect) { if (this.state.redirect) {
this.props.history.push(this.state.redirect); this.props.history.push(this.state.redirect);
} } else {
else {
this.props.history.goBack(); this.props.history.goBack();
} }
} }
// Check for login error // Check for login error
else if (message.id === 'LOGIN_FAIL') { else if (message.id === "LOGIN_FAIL") {
this.setState({ email: '', password: '', snackbar: true, key: Date.now(), message: Blockly.Msg.messages_LOGIN_FAIL, type: 'error' }); console.log("login fail");
this.setState({
email: "",
password: "",
snackbar: true,
key: Date.now(),
message: Blockly.Msg.messages_LOGIN_FAIL,
type: "error",
});
} }
} }
} }
onChange = e => { onChange = (e) => {
this.setState({ [e.target.name]: e.target.value }); this.setState({ [e.target.name]: e.target.value });
}; };
onSubmit = e => { onSubmit = (e) => {
e.preventDefault(); e.preventDefault();
const { email, password } = this.state; const { email, password } = this.state;
if (email !== '' && password !== '') { if (email !== "" && password !== "") {
// create user object // create user object
const user = { const user = {
email, email,
password password,
}; };
this.props.login(user); this.props.login(user);
} else { } else {
this.setState({ snackbar: true, key: Date.now(), message: Blockly.Msg.messages_login_error, type: 'error' }); this.setState({
snackbar: true,
key: Date.now(),
message: Blockly.Msg.messages_login_error,
type: "error",
});
} }
}; };
@@ -86,12 +98,25 @@ export class Login extends Component {
render() { render() {
return ( return (
<div> <div>
<Breadcrumbs content={[{ link: '/user/login', title: Blockly.Msg.button_login }]} /> <Breadcrumbs
content={[{ link: "/user/login", title: Blockly.Msg.button_login }]}
/>
<div style={{ maxWidth: '500px', marginLeft: 'auto', marginRight: 'auto' }}> <div
style={{ maxWidth: "500px", marginLeft: "auto", marginRight: "auto" }}
>
<h1>{Blockly.Msg.login_head}</h1> <h1>{Blockly.Msg.login_head}</h1>
<Alert> <Alert>
{Blockly.Msg.login_osem_account_01} <Link color='primary' rel="noreferrer" target="_blank" href={'https://opensensemap.org/'}>openSenseMap</Link> {Blockly.Msg.login_osem_account_02}. {Blockly.Msg.login_osem_account_01}{" "}
<Link
color="primary"
rel="noreferrer"
target="_blank"
href={"https://opensensemap.org/"}
>
openSenseMap
</Link>{" "}
{Blockly.Msg.login_osem_account_02}.
</Alert> </Alert>
<Snackbar <Snackbar
open={this.state.snackbar} open={this.state.snackbar}
@@ -100,51 +125,83 @@ export class Login extends Component {
key={this.state.key} key={this.state.key}
/> />
<TextField <TextField
style={{ marginBottom: '10px' }} style={{ marginBottom: "10px" }}
// variant='outlined' // variant='outlined'
type='text' type="text"
label={Blockly.Msg.labels_username} label={Blockly.Msg.labels_username}
name='email' name="email"
value={this.state.email} value={this.state.email}
onChange={this.onChange} onChange={this.onChange}
fullWidth={true} fullWidth={true}
/> />
<TextField <TextField
// variant='outlined' // variant='outlined'
type={this.state.showPassword ? 'text' : 'password'} type={this.state.showPassword ? "text" : "password"}
label={Blockly.Msg.labels_password} label={Blockly.Msg.labels_password}
name='password' name="password"
value={this.state.password} value={this.state.password}
InputProps={{ InputProps={{
endAdornment: endAdornment: (
<InputAdornment <InputAdornment position="end">
position="end"
>
<IconButton <IconButton
onClick={this.handleClickShowPassword} onClick={this.handleClickShowPassword}
onMouseDown={this.handleMouseDownPassword} onMouseDown={this.handleMouseDownPassword}
edge="end" edge="end"
> >
<FontAwesomeIcon size='xs' icon={this.state.showPassword ? faEyeSlash : faEye} /> <FontAwesomeIcon
size="xs"
icon={this.state.showPassword ? faEyeSlash : faEye}
/>
</IconButton> </IconButton>
</InputAdornment> </InputAdornment>
),
}} }}
onChange={this.onChange} onChange={this.onChange}
fullWidth={true} fullWidth={true}
/> />
<p> <p>
<Button color="primary" variant='contained' onClick={this.onSubmit} style={{ width: '100%' }}> <Button
{this.props.progress ? color="primary"
<div style={{ height: '24.5px' }}><CircularProgress color="inherit" size={20} /></div> variant="contained"
: Blockly.Msg.button_login} onClick={this.onSubmit}
style={{ width: "100%" }}
>
{this.props.progress ? (
<div style={{ height: "24.5px" }}>
<CircularProgress color="inherit" size={20} />
</div>
) : (
Blockly.Msg.button_login
)}
</Button> </Button>
</p> </p>
<p style={{ textAlign: 'center', fontSize: '0.8rem' }}> <p style={{ textAlign: "center", fontSize: "0.8rem" }}>
<Link rel="noreferrer" target="_blank" href={'https://opensensemap.org/'} color="primary">{Blockly.Msg.login_lostpassword}</Link> <Link
rel="noreferrer"
target="_blank"
href={"https://opensensemap.org/"}
color="primary"
>
{Blockly.Msg.login_lostpassword}
</Link>
</p> </p>
<Divider variant='fullWidth' /> <Divider variant="fullWidth" />
<p style={{ textAlign: 'center', paddingRight: "34px", paddingLeft: "34px" }}> <p
{Blockly.Msg.login_createaccount}<Link rel="noreferrer" target="_blank" href={'https://opensensemap.org/'}>openSenseMap</Link>. style={{
textAlign: "center",
paddingRight: "34px",
paddingLeft: "34px",
}}
>
{Blockly.Msg.login_createaccount}
<Link
rel="noreferrer"
target="_blank"
href={"https://opensensemap.org/"}
>
openSenseMap
</Link>
.
</p> </p>
</div> </div>
</div> </div>
@@ -156,12 +213,14 @@ Login.propTypes = {
message: PropTypes.object.isRequired, message: PropTypes.object.isRequired,
login: PropTypes.func.isRequired, login: PropTypes.func.isRequired,
clearMessages: PropTypes.func.isRequired, clearMessages: PropTypes.func.isRequired,
progress: PropTypes.bool.isRequired progress: PropTypes.bool.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
message: state.message, message: state.message,
progress: state.auth.progress progress: state.auth.progress,
}); });
export default connect(mapStateToProps, { login, clearMessages })(withRouter(Login)); export default connect(mapStateToProps, { login, clearMessages })(
withRouter(Login)
);
-267
View File
@@ -1,267 +0,0 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { connectMyBadges, disconnectMyBadges } from '../../actions/authActions';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
import Breadcrumbs from '../Breadcrumbs';
import Alert from '../Alert';
import { withStyles } from '@material-ui/core/styles';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import TextField from '@material-ui/core/TextField';
import Divider from '@material-ui/core/Divider';
import InputAdornment from '@material-ui/core/InputAdornment';
import Link from '@material-ui/core/Link';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import Avatar from '@material-ui/core/Avatar';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
const styles = (theme) => ({
root: {
'& label.Mui-focused': {
color: '#aed9c8'
},
'& .MuiOutlinedInput-root': {
'&.Mui-focused fieldset': {
borderColor: '#aed9c8'
},
borderRadius: '0.75rem'
}
},
text: {
fontFamily: [
'"Open Sans"',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
fontSize: 16
}
});
export class MyBadges extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
showPassword: false,
msg: '',
badges: [],
progress: false
};
}
componentDidMount(){
if(this.props.user.badge){
this.getBadges();
}
}
componentDidUpdate(props){
const { message } = this.props;
if (message !== props.message) {
// Check for login error
if(message.id === 'MYBADGES_CONNECT_FAIL'){
this.setState({msg: 'Der Benutzername oder das Passwort ist nicht korrekt.', username: '', password: '', showPassword: false});
}
else if(message.id === 'MYBADGES_CONNECT_SUCCESS'){
this.getBadges();
}
else if(message.id === 'MYBADGES_DISCONNECT_SUCCESS' || message.id === 'MYBADGES_DISCONNECT_FAIL'){
this.setState({progress: false});
}
else {
this.setState({msg: null});
}
}
}
getBadges = () => {
this.setState({progress: true});
const config = {
success: res => {
this.setState({badges: res.data.badges, progress: false});
},
error: err => {
this.setState({progress: false});
}
};
axios.get(`${process.env.REACT_APP_BLOCKLY_API}/user/badge`, config)
.then(res => {
res.config.success(res);
})
.catch(err => {
err.config.error(err);
});
};
onChange = e => {
this.setState({ [e.target.name]: e.target.value, msg: '' });
};
onSubmit = e => {
e.preventDefault();
const {username, password} = this.state;
// create user object
const user = {
username,
password
};
this.props.connectMyBadges(user);
};
handleClickShowPassword = () => {
this.setState({ showPassword: !this.state.showPassword });
};
handleMouseDownPassword = (e) => {
e.preventDefault();
};
render(){
return(
<div>
<Breadcrumbs content={[{ link: '/user/badge', title: 'MyBadges' }]} />
<Grid container spacing={2}>
<Grid item xs={12} style={{margin: '4px'}}>
{!this.props.user.badge ?
<Alert>
Du kannst dein Blockly-Konto mit deinem <Link href={`${process.env.REACT_APP_MYBADGES}`}>MyBadges</Link>-Konto verknüpfen, um Badges erwerben zu können.
</Alert>
: null}
<Paper style={{background: '#fffbf5'}}>
<div style={{display: 'flex', flexDirection: 'row', alignSelf: 'center', justifyContent: 'center', flexWrap: 'wrap'}}>
<div style={!this.props.user.badge ? {margin: '15px 15px 0px 15px'} : {margin: '15px'}}>
<img src={`${process.env.REACT_APP_MYBADGES}/static/media/Logo.d1c71fdf.png`} alt="My Badges" style={{maxWidth: '200px', maxHeight: '200px'}}></img>
</div>
{!this.props.user.badge ?
<div style={{maxWidth: '500px', alignSelf: 'center', textAlign: 'center', margin: '15px'}}>
{this.state.msg ?
<div style={{lineHeight: 1.43, borderRadius: '0.75rem', padding: '14px 16px', marginBottom: '10px', color: 'rgb(97, 26, 21)', backgroundColor: 'rgb(253, 236, 234)', fontFamily: `"Open Sans",BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol"`}}>
{this.state.msg}
</div> : null
}
<TextField
style={{marginBottom: '10px'}}
classes={{root: this.props.classes.root}}
variant='outlined'
type='text'
label='Nutzername'
name='username'
value={this.state.username}
onChange={this.onChange}
fullWidth={true}
/>
<TextField
classes={{root: this.props.classes.root}}
variant='outlined'
type={this.state.showPassword ? 'text' : 'password'}
label='Passwort'
name='password'
value={this.state.password}
InputProps={{
endAdornment:
<InputAdornment
position="end"
>
<IconButton
onClick={this.handleClickShowPassword}
onMouseDown={this.handleMouseDownPassword}
edge="end"
>
<FontAwesomeIcon size='xs' icon={this.state.showPassword ? faEyeSlash : faEye} />
</IconButton>
</InputAdornment>
}}
onChange={this.onChange}
fullWidth={true}
/>
<p>
<Button variant='contained' onClick={this.onSubmit} className={this.props.classes.text} style={{background: '#aed9c8', borderRadius: '0.75rem', width: '100%'}}>
Anmelden
</Button>
</p>
<p className={this.props.classes.text} style={{textAlign: 'center', fontSize: '0.8rem'}}>
<Link style={{color: '#aed9c8'}} href={`${process.env.REACT_APP_MYBADGES}/user/password`}>Passwort vergessen?</Link>
</p>
<Divider variant='fullWidth'/>
<p className={this.props.classes.text} style={{textAlign: 'center', paddingRight: "34px", paddingLeft: "34px"}}>
Du hast noch kein Konto? <Link style={{color: '#aed9c8'}} href={`${process.env.REACT_APP_MYBADGES}/register`}>Registrieren</Link>
</p>
</div>
: <div style={{margin: '15px', alignSelf: 'center'}}>
<Typography style={{fontWeight: 'bold', fontSize: '1.1rem'}}>MyBadges-Konto ist erfolgreich verknüpft.</Typography>
<Button variant='outlined' style={{borderColor: '#aed9c8'}} onClick={() => {this.props.disconnectMyBadges(); this.setState({badges: [], progress: true});}}>Konto trennen</Button>
</div>}
</div>
</Paper>
</Grid>
{this.props.user.badge && !this.state.progress ?
<Grid container item>
<Grid item style={{margin: '4px'}}>
{this.state.badges && this.state.badges.length > 0 ?
<Typography style={{fontWeight: 'bold'}}>
Du hast {this.state.badges.length} {this.state.badges.length === 1 ? 'Badge' : 'Badges'} im Kontext Blockly for senseBox erreicht.
</Typography>
: null}
</Grid>
<Grid container item>
{this.state.badges && this.state.badges.length > 0 ?
this.state.badges.map(badge => (
<Grid item xs={12} sm={6} md={4}>
<Paper style={{margin: '4px', textAlign: 'center'}}>
{badge.image && badge.image.path ?
<Avatar src={`${process.env.REACT_APP_MYBADGES}/media/${badge.image.path}`} style={{width: '200px', height: '200px', marginLeft: 'auto', marginRight: 'auto'}}/>
: <Avatar style={{width: '200px', height: '200px', marginLeft: 'auto', marginRight: 'auto'}}></Avatar>}
<Typography variant='h6' style={{display: 'flex', cursor: 'default', paddingBottom: '6px'}}>
<div style={{flexGrow:1, marginLeft: '10px', marginRight: '10px'}}>{badge.name}</div>
</Typography>
</Paper>
</Grid>
))
:
<Grid item style={{margin: '4px'}}>
<Typography style={{fontWeight: 'bold'}}>
Du hast noch keine Badges im Kontext senseBox for Blockly erreicht.
</Typography>
</Grid>}
</Grid>
</Grid>
: null}
</Grid>
</div>
);
}
}
MyBadges.propTypes = {
connectMyBadges: PropTypes.func.isRequired,
disconnectMyBadges: PropTypes.func.isRequired,
message: PropTypes.object.isRequired,
user: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
message: state.message,
user: state.auth.user
});
export default connect(mapStateToProps, { connectMyBadges, disconnectMyBadges })(withStyles(styles, { withTheme: true })(withRouter(MyBadges)));
+170 -64
View File
@@ -1,127 +1,172 @@
import React, { Component } from 'react'; import React, { Component } from "react";
import PropTypes from 'prop-types'; import PropTypes from "prop-types";
import { connect } from 'react-redux'; import { connect } from "react-redux";
import { workspaceName } from '../../actions/workspaceActions'; import { workspaceName } from "../../actions/workspaceActions";
import { detectWhitespacesAndReturnReadableResult } from '../../helpers/whitespace'; import { detectWhitespacesAndReturnReadableResult } from "../../helpers/whitespace";
import Dialog from '../Dialog';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Backdrop from '@material-ui/core/Backdrop';
import CircularProgress from '@material-ui/core/CircularProgress';
import IconButton from '@material-ui/core/IconButton';
import Tooltip from '@material-ui/core/Tooltip';
import TextField from '@material-ui/core/TextField';
import { withStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import Backdrop from "@material-ui/core/Backdrop";
import CircularProgress from "@material-ui/core/CircularProgress";
import IconButton from "@material-ui/core/IconButton";
import Tooltip from "@material-ui/core/Tooltip";
import Divider from "@material-ui/core/Divider";
import { faClipboardCheck } from "@fortawesome/free-solid-svg-icons"; import { faClipboardCheck } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import * as Blockly from 'blockly/core'; import * as Blockly from "blockly/core";
import Copy from '../copy.svg'; import Copy from "../copy.svg";
import Prism from "prismjs";
import "prismjs/themes/prism.css";
import "prismjs/plugins/line-numbers/prism-line-numbers";
import "prismjs/plugins/line-numbers/prism-line-numbers.css";
import MuiDrawer from "@material-ui/core/Drawer";
const styles = (theme) => ({ const styles = (theme) => ({
backdrop: { backdrop: {
zIndex: theme.zIndex.drawer + 1, zIndex: theme.zIndex.drawer + 1,
color: '#fff', color: "#fff",
}, },
iconButton: { iconButton: {
backgroundColor: theme.palette.button.compile, backgroundColor: theme.palette.button.compile,
color: theme.palette.primary.contrastText, color: theme.palette.primary.contrastText,
width: '40px', width: "40px",
height: '40px', height: "40px",
'&:hover': { "&:hover": {
backgroundColor: theme.palette.button.compile, backgroundColor: theme.palette.button.compile,
color: theme.palette.primary.contrastText, color: theme.palette.primary.contrastText,
} },
}, },
button: { button: {
backgroundColor: theme.palette.button.compile, backgroundColor: theme.palette.button.compile,
color: theme.palette.primary.contrastText, color: theme.palette.primary.contrastText,
'&:hover': { "&:hover": {
backgroundColor: theme.palette.button.compile, backgroundColor: theme.palette.button.compile,
color: theme.palette.primary.contrastText, color: theme.palette.primary.contrastText,
} },
} },
}); });
const Drawer = withStyles((theme) => ({
paperAnchorBottom: {
backgroundColor: "black",
height: "20vH",
},
}))(MuiDrawer);
class Compile extends Component { class Compile extends Component {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
progress: false, progress: false,
open: false, open: false,
file: false, file: false,
title: '', title: "",
content: '', content: "",
name: props.name name: props.name,
error: "",
}; };
} }
componentDidMount() {
Prism.highlightAll();
}
componentDidUpdate(props) { componentDidUpdate(props) {
if (props.name !== this.props.name) { if (props.name !== this.props.name) {
this.setState({ name: this.props.name }); this.setState({ name: this.props.name });
} }
Prism.highlightAll();
} }
compile = () => { compile = () => {
this.setState({ progress: true }); this.setState({ progress: true });
const data = { const data = {
"board": process.env.REACT_APP_BOARD, board: process.env.REACT_APP_BOARD,
"sketch": this.props.arduino sketch: this.props.arduino,
}; };
fetch(`${process.env.REACT_APP_COMPILER_URL}/compile`, { fetch(`${process.env.REACT_APP_COMPILER_URL}/compile`, {
method: "POST", method: "POST",
headers: { 'Content-Type': 'application/json' }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(data) body: JSON.stringify(data),
}) })
.then(response => response.json()) .then((response) => response.json())
.then(data => { .then((data) => {
console.log(data); console.log(data);
if (data.code === "Internal Server Error") {
this.setState({
progress: false,
file: false,
open: true,
title: Blockly.Msg.compiledialog_headline,
content: Blockly.Msg.compiledialog_text,
error: data.message,
});
}
this.setState({ id: data.data.id }, () => { this.setState({ id: data.data.id }, () => {
this.createFileName(); this.createFileName();
}); });
}) })
.catch(err => { .catch((err) => {
console.log(err); console.log(err);
this.setState({ progress: false, file: false, open: true, title: Blockly.Msg.compiledialog_headline, content: Blockly.Msg.compiledialog_text }); //this.setState({ progress: false, file: false, open: true, title: Blockly.Msg.compiledialog_headline, content: Blockly.Msg.compiledialog_text });
}); });
} };
download = () => { download = () => {
const id = this.state.id; const id = this.state.id;
const filename = detectWhitespacesAndReturnReadableResult(this.state.name); const filename = detectWhitespacesAndReturnReadableResult(this.state.name);
this.toggleDialog(); this.toggleDialog();
this.props.workspaceName(this.state.name); this.props.workspaceName(this.state.name);
window.open(`${process.env.REACT_APP_COMPILER_URL}/download?id=${id}&board=${process.env.REACT_APP_BOARD}&filename=${filename}`, '_self'); window.open(
`${process.env.REACT_APP_COMPILER_URL}/download?id=${id}&board=${process.env.REACT_APP_BOARD}&filename=${filename}`,
"_self"
);
this.setState({ progress: false }); this.setState({ progress: false });
} };
toggleDialog = () => { toggleDialog = () => {
this.setState({ open: !this.state, progress: false }); this.setState({ open: !this.state, progress: false });
} };
createFileName = () => { createFileName = () => {
if (this.state.name) { if (this.state.name) {
this.download(); this.download();
} else {
this.setState({
file: true,
open: true,
title: "Projekt kompilieren",
content:
"Bitte gib einen Namen für die Bennenung des zu kompilierenden Programms ein und bestätige diesen mit einem Klick auf 'Eingabe'.",
});
} }
else { };
this.setState({ file: true, open: true, title: 'Projekt kompilieren', content: 'Bitte gib einen Namen für die Bennenung des zu kompilierenden Programms ein und bestätige diesen mit einem Klick auf \'Eingabe\'.' });
}
}
setFileName = (e) => { setFileName = (e) => {
this.setState({ name: e.target.value }); this.setState({ name: e.target.value });
};
toggleDrawer = (anchor, open) => (event) => {
if (
event.type === "keydown" &&
(event.key === "Tab" || event.key === "Shift")
) {
return;
} }
this.setState({ open: false });
};
render() { render() {
return ( return (
<div style={{}}> <div style={{}}>
{this.props.iconButton ? {this.props.iconButton ? (
<Tooltip title={Blockly.Msg.tooltip_compile_code} arrow style={{ marginRight: '5px' }}> <Tooltip
title={Blockly.Msg.tooltip_compile_code}
arrow
style={{ marginRight: "5px" }}
>
<IconButton <IconButton
className={`compileBlocks ${this.props.classes.iconButton}`} className={`compileBlocks ${this.props.classes.iconButton}`}
onClick={() => this.compile()} onClick={() => this.compile()}
@@ -129,21 +174,73 @@ class Compile extends Component {
<FontAwesomeIcon icon={faClipboardCheck} size="l" /> <FontAwesomeIcon icon={faClipboardCheck} size="l" />
</IconButton> </IconButton>
</Tooltip> </Tooltip>
: ) : (
<Button style={{ float: 'right', color: 'white' }} variant="contained" className={this.props.classes.button} onClick={() => this.compile()}> <Button
<FontAwesomeIcon icon={faClipboardCheck} style={{ marginRight: '5px' }} /> Kompilieren style={{ float: "right", color: "white" }}
variant="contained"
className={this.props.classes.button}
onClick={() => this.compile()}
>
<FontAwesomeIcon
icon={faClipboardCheck}
style={{ marginRight: "5px" }}
/>{" "}
Kompilieren
</Button> </Button>
} )}
<Backdrop className={this.props.classes.backdrop} open={this.state.progress}> <Backdrop
<div className='overlay'> className={this.props.classes.backdrop}
open={this.state.progress}
>
<div className="overlay">
<img src={Copy} width="400" alt="copyimage"></img> <img src={Copy} width="400" alt="copyimage"></img>
<h2>{Blockly.Msg.compile_overlay_head}</h2> <h2>{Blockly.Msg.compile_overlay_head}</h2>
<p>{Blockly.Msg.compile_overlay_text}</p> <p>{Blockly.Msg.compile_overlay_text}</p>
<p>{Blockly.Msg.compile_overlay_help}<a href="/faq" target="_blank">FAQ</a></p> <p>
{Blockly.Msg.compile_overlay_help}
<a href="/faq" target="_blank">
FAQ
</a>
</p>
<CircularProgress color="inherit" /> <CircularProgress color="inherit" />
</div> </div>
</Backdrop> </Backdrop>
<Dialog <Drawer
anchor={"bottom"}
open={this.state.open}
onClose={this.toggleDrawer("bottom", false)}
>
<h2
style={{
color: "#4EAF47",
paddingLeft: "1rem",
paddingRight: "1rem",
}}
>
{Blockly.Msg.drawer_ideerror_head}
</h2>
<p
style={{
color: "#4EAF47",
paddingLeft: "1rem",
paddingRight: "1rem",
}}
>
{Blockly.Msg.drawer_ideerror_text}
</p>
<Divider style={{ backgroundColor: "white" }} />
<p
style={{
backgroundColor: "black",
color: "#E47128",
padding: "1rem",
}}
>
{" "}
{`${this.state.error}`}{" "}
</p>
</Drawer>
{/* <Dialog
open={this.state.open} open={this.state.open}
title={this.state.title} title={this.state.title}
content={this.state.content} content={this.state.content}
@@ -156,23 +253,32 @@ class Compile extends Component {
<TextField autoFocus placeholder='Dateiname' value={this.state.name} onChange={this.setFileName} style={{ marginRight: '10px' }} /> <TextField autoFocus placeholder='Dateiname' value={this.state.name} onChange={this.setFileName} style={{ marginRight: '10px' }} />
<Button disabled={!this.state.name} variant='contained' color='primary' onClick={() => this.download()}>Eingabe</Button> <Button disabled={!this.state.name} variant='contained' color='primary' onClick={() => this.download()}>Eingabe</Button>
</div> </div>
: null} :
</Dialog>
<pre className="line-numbers" style={{ paddingBottom: 0, width: '100%', overflow: 'auto', scrollbarWidth: 'thin', height: '100%', margin: '15px 0', paddingTop: 0, whiteSpace: 'pre-wrap', backgroundColor: 'white' }}><code className="language-json">
{`${this.state.error}`}
</code></pre>
</AccordionDetails>
</Accordion>
}
</Dialog> */}
</div> </div>
); );
}; }
} }
Compile.propTypes = { Compile.propTypes = {
arduino: PropTypes.string.isRequired, arduino: PropTypes.string.isRequired,
name: PropTypes.string, name: PropTypes.string,
workspaceName: PropTypes.func.isRequired workspaceName: PropTypes.func.isRequired,
}; };
const mapStateToProps = state => ({ const mapStateToProps = (state) => ({
arduino: state.workspace.code.arduino, arduino: state.workspace.code.arduino,
name: state.workspace.name name: state.workspace.name,
}); });
export default connect(mapStateToProps, { workspaceName })(
export default connect(mapStateToProps, { workspaceName })(withStyles(styles, { withTheme: true })(Compile)); withStyles(styles, { withTheme: true })(Compile)
);
+23 -1
View File
@@ -16,6 +16,8 @@ import Tooltip from '@material-ui/core/Tooltip';
import { faShare } from "@fortawesome/free-solid-svg-icons"; import { faShare } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Dialog from '../Dialog';
import Button from '@material-ui/core/Button';
const styles = (theme) => ({ const styles = (theme) => ({
button: { button: {
@@ -39,12 +41,21 @@ class ResetWorkspace extends Component {
this.inputRef = React.createRef(); this.inputRef = React.createRef();
this.state = { this.state = {
snackbar: false, snackbar: false,
open: false,
type: '', type: '',
key: '', key: '',
message: '', message: '',
}; };
} }
toggleDialog = () => {
this.setState({ open: !this.state});
}
openDialog = () => {
this.setState({open: true});
}
resetWorkspace = () => { resetWorkspace = () => {
const workspace = Blockly.getMainWorkspace(); const workspace = Blockly.getMainWorkspace();
Blockly.Events.disable(); // https://groups.google.com/forum/#!topic/blockly/m7e3g0TC75Y Blockly.Events.disable(); // https://groups.google.com/forum/#!topic/blockly/m7e3g0TC75Y
@@ -69,7 +80,7 @@ class ResetWorkspace extends Component {
<Tooltip title={Blockly.Msg.tooltip_reset_workspace} arrow> <Tooltip title={Blockly.Msg.tooltip_reset_workspace} arrow>
<IconButton <IconButton
className={this.props.classes.button} className={this.props.classes.button}
onClick={() => this.resetWorkspace()} onClick={() => this.openDialog()}
> >
<FontAwesomeIcon icon={faShare} size="xs" flip='horizontal' /> <FontAwesomeIcon icon={faShare} size="xs" flip='horizontal' />
</IconButton> </IconButton>
@@ -81,6 +92,17 @@ class ResetWorkspace extends Component {
type={this.state.type} type={this.state.type}
key={this.state.key} key={this.state.key}
/> />
<Dialog
open={this.state.open}
title={Blockly.Msg.resetDialog_headline}
content={Blockly.Msg.resetDialog_text}
onClose={() => { this.toggleDialog(); }}
onClick={() => { this.toggleDialog(); }}
button={Blockly.Msg.button_cancel}
> <div style={{ marginTop: '10px' }}>
<Button variant='contained' color='primary' onClick={() => { this.resetWorkspace(); this.toggleDialog(); }}>Zurücksetzen</Button>
</div></Dialog>
</div> </div>
); );
}; };
-1
View File
@@ -127,7 +127,6 @@ class SaveProject extends Component {
} }
render() { render() {
console.log(1, this.props);
return ( return (
<div style={this.props.style}> <div style={this.props.style}>
<Tooltip title={this.state.projectType === 'project' ? Blockly.Msg.tooltip_update_project : Blockly.Msg.tooltip_save_project} arrow> <Tooltip title={this.state.projectType === 'project' ? Blockly.Msg.tooltip_update_project : Blockly.Msg.tooltip_save_project} arrow>
+23 -21
View File
@@ -1,59 +1,61 @@
import { MYBADGES_CONNECT, MYBADGES_DISCONNECT, USER_LOADED, USER_LOADING, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL, LOGOUT_SUCCESS, LOGOUT_FAIL, REFRESH_TOKEN_SUCCESS } from '../actions/types'; import {
USER_LOADED,
USER_LOADING,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT_SUCCESS,
LOGOUT_FAIL,
REFRESH_TOKEN_SUCCESS,
} from "../actions/types";
const initialState = { const initialState = {
token: localStorage.getItem('token'), token: localStorage.getItem("token"),
refreshToken: localStorage.getItem('refreshToken'), refreshToken: localStorage.getItem("refreshToken"),
isAuthenticated: null, isAuthenticated: null,
progress: true, progress: true,
user: null user: null,
}; };
export default function foo(state = initialState, action){ export default function foo(state = initialState, action) {
switch(action.type){ switch (action.type) {
case USER_LOADING: case USER_LOADING:
return { return {
...state, ...state,
progress: true progress: true,
}; };
case USER_LOADED: case USER_LOADED:
return { return {
...state, ...state,
isAuthenticated: true, isAuthenticated: true,
progress: false, progress: false,
user: action.payload user: action.payload,
}; };
case LOGIN_SUCCESS: case LOGIN_SUCCESS:
case REFRESH_TOKEN_SUCCESS: case REFRESH_TOKEN_SUCCESS:
localStorage.setItem('token', action.payload.token); localStorage.setItem("token", action.payload.token);
localStorage.setItem('refreshToken', action.payload.refreshToken); localStorage.setItem("refreshToken", action.payload.refreshToken);
return { return {
...state, ...state,
user: action.payload.user, user: action.payload.user,
token: action.payload.token, token: action.payload.token,
refreshToken: action.payload.refreshToken, refreshToken: action.payload.refreshToken,
isAuthenticated: true, isAuthenticated: true,
progress: false progress: false,
};
case MYBADGES_CONNECT:
case MYBADGES_DISCONNECT:
return {
...state,
user: action.payload
}; };
case AUTH_ERROR: case AUTH_ERROR:
case LOGIN_FAIL: case LOGIN_FAIL:
case LOGOUT_SUCCESS: case LOGOUT_SUCCESS:
case LOGOUT_FAIL: case LOGOUT_FAIL:
localStorage.removeItem('token'); localStorage.removeItem("token");
localStorage.removeItem('refreshToken'); localStorage.removeItem("refreshToken");
return { return {
...state, ...state,
token: null, token: null,
refreshToken: null, refreshToken: null,
user: null, user: null,
isAuthenticated: false, isAuthenticated: false,
progress: false progress: false,
}; };
default: default:
return state; return state;
+35 -28
View File
@@ -1,47 +1,54 @@
import { PROGRESS, JSON_STRING, BUILDER_CHANGE, BUILDER_ERROR, BUILDER_TITLE, BUILDER_BADGE, BUILDER_ID, BUILDER_ADD_STEP, BUILDER_DELETE_STEP, BUILDER_CHANGE_STEP,BUILDER_CHANGE_ORDER, BUILDER_DELETE_PROPERTY } from '../actions/types'; import {
PROGRESS,
JSON_STRING,
BUILDER_CHANGE,
BUILDER_ERROR,
BUILDER_TITLE,
BUILDER_ID,
BUILDER_ADD_STEP,
BUILDER_DELETE_STEP,
BUILDER_CHANGE_STEP,
BUILDER_CHANGE_ORDER,
BUILDER_DELETE_PROPERTY,
} from "../actions/types";
const initialState = { const initialState = {
change: 0, change: 0,
progress: false, progress: false,
json: '', json: "",
title: '', title: "",
id: '', id: "",
steps: [ steps: [
{ {
id: 1, id: 1,
type: 'instruction', type: "instruction",
headline: '', headline: "",
text: '', text: "",
hardware: [], hardware: [],
requirements: [] requirements: [],
} },
], ],
error: { error: {
steps: [{}] steps: [{}],
} },
}; };
export default function foo(state = initialState, action){ export default function foo(state = initialState, action) {
switch(action.type){ switch (action.type) {
case BUILDER_CHANGE: case BUILDER_CHANGE:
return { return {
...state, ...state,
change: state.change += 1 change: (state.change += 1),
}; };
case BUILDER_TITLE: case BUILDER_TITLE:
return { return {
...state, ...state,
title: action.payload title: action.payload,
};
case BUILDER_BADGE:
return {
...state,
badge: action.payload
}; };
case BUILDER_ID: case BUILDER_ID:
return { return {
...state, ...state,
id: action.payload id: action.payload,
}; };
case BUILDER_ADD_STEP: case BUILDER_ADD_STEP:
case BUILDER_DELETE_STEP: case BUILDER_DELETE_STEP:
@@ -50,23 +57,23 @@ export default function foo(state = initialState, action){
case BUILDER_DELETE_PROPERTY: case BUILDER_DELETE_PROPERTY:
return { return {
...state, ...state,
steps: action.payload steps: action.payload,
}; };
case BUILDER_ERROR: case BUILDER_ERROR:
return { return {
...state, ...state,
error: action.payload error: action.payload,
} };
case PROGRESS: case PROGRESS:
return { return {
...state, ...state,
progress: action.payload progress: action.payload,
} };
case JSON_STRING: case JSON_STRING:
return { return {
...state, ...state,
json: action.payload json: action.payload,
} };
default: default:
return state; return state;
} }
+9187 -9573
View File
File diff suppressed because it is too large Load Diff