diff --git a/package-lock.json b/package-lock.json index 5f65f91..5312575 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5594,9 +5594,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -5618,9 +5615,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -5642,9 +5636,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -5666,9 +5657,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -5690,9 +5678,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -5714,9 +5699,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -6740,9 +6722,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -6760,9 +6739,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -6780,9 +6756,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -6800,9 +6773,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -10530,9 +10500,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10547,9 +10514,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -10564,9 +10528,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10581,9 +10542,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -10598,9 +10556,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10615,9 +10570,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10632,9 +10584,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -10649,9 +10598,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10666,9 +10612,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -10683,9 +10626,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -15508,15 +15448,6 @@ "url": "https://github.com/sponsors/wooorm" } }, - "node_modules/decode-uri-component": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.2.2.tgz", - "integrity": "sha512-FqUYQ+8o158GyGTrMFJms9qh3CqTKvAqgqsTnkLI8sKu0028orqBhxNMFkFen0zGyg6epACD32pjVk58ngIErQ==", - "license": "MIT", - "engines": { - "node": ">=0.10" - } - }, "node_modules/dedent": { "version": "1.7.2", "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", @@ -20913,13 +20844,6 @@ "node": ">= 6" } }, - "node_modules/hull.js": { - "version": "0.2.10", - "resolved": "https://registry.npmjs.org/hull.js/-/hull.js-0.2.10.tgz", - "integrity": "sha512-UO3W30HxhWgeSpNKCdXt00xkwjRTGmhQaoZNP8ll509Nl+DP9juXE3wRGizihuop08FSB4xtAWIbWSe+RxEoog==", - "deprecated": "This package is unmaintained and vulnerable. Do not use it.", - "license": "BSD" - }, "node_modules/human-signals": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", @@ -25333,9 +25257,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -25357,9 +25278,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -25381,9 +25299,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -25405,9 +25320,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -32738,20 +32650,6 @@ ], "license": "MIT" }, - "node_modules/query-string": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/query-string/-/query-string-5.1.1.tgz", - "integrity": "sha512-gjWOsm2SoGlgLEdAGt7a6slVOk9mGiXmPFMqrEhLQ68rhQuBnpfs3+EmlvqKyxnCo9/PPlF+9MtY02S1aFg+Jw==", - "license": "MIT", - "dependencies": { - "decode-uri-component": "^0.2.0", - "object-assign": "^4.1.0", - "strict-uri-encode": "^1.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/querystringify": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", @@ -36901,15 +36799,6 @@ "safe-buffer": "~5.1.0" } }, - "node_modules/strict-uri-encode": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz", - "integrity": "sha512-R3f198pcvnB+5IpnBlRkphuE9n46WyVl8I39W/ZUTZLz4nqSP/oLYUrcnJrw462Ds8he4YKMov2efsTIw1BDGQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/string_decoder": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", @@ -42572,13 +42461,12 @@ "omggif": "1.0.10", "papaparse": "5.7.0", "prop-types": "15.8.1", - "query-string": "5.1.1", "react-draggable": "3.3.2", "react-ga": "3.3.1", "react-intl": "6.8.9", "react-modal": "3.16.3", "react-popover": "0.5.10", - "react-redux": "8.1.3", + "react-redux": "^8.0.0", "react-responsive": "9.0.2", "react-style-proptype": "3.2.2", "react-tabs": "5.2.0", @@ -44319,7 +44207,7 @@ "dependencies": { "@scratch/scratch-svg-renderer": "15.3.0", "grapheme-breaker": "0.3.2", - "hull.js": "0.2.10", + "hull.js": "0.2.1", "ify-loader": "1.1.0", "linebreak": "0.3.0", "raw-loader": "0.5.1", @@ -44353,6 +44241,13 @@ "scratch-render-fonts": "1.0.258" } }, + "packages/scratch-render/node_modules/hull.js": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/hull.js/-/hull.js-0.2.1.tgz", + "integrity": "sha512-nmZngm5GxX8hmyVOpU8iD8Gr1zivFpjAGVe24uvbUDB0O2sF+Rf6Gn0qKQpchx8MetYoY7DjYqWgb8/Dgerc2A==", + "deprecated": "This package is unmaintained and vulnerable. Do not use it.", + "license": "BSD" + }, "packages/scratch-render/node_modules/raw-loader": { "version": "0.5.1", "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-0.5.1.tgz", diff --git a/package.json b/package.json index c06f979..d6ecba4 100644 --- a/package.json +++ b/package.json @@ -50,5 +50,8 @@ "husky": "8.0.3", "semantic-release": "25.0.9", "ts-node": "10.9.2" + }, + "overrides": { + "hull.js": "0.2.1" } } diff --git a/packages/scratch-gui/competition.webpack.cjs b/packages/scratch-gui/competition.webpack.cjs new file mode 100644 index 0000000..9a39394 --- /dev/null +++ b/packages/scratch-gui/competition.webpack.cjs @@ -0,0 +1,11 @@ +const path = require('node:path'); +const HtmlWebpackPlugin = require('html-webpack-plugin'); +const config = require('./webpack.config.js'); +config.entry = {competition: path.resolve(__dirname, 'src/playground/competition.jsx')}; +config.output = {...config.output, path: path.resolve(__dirname, '../../../../web/editor'), publicPath: '/editor/'}; +config.plugins = config.plugins.filter(plugin => plugin.constructor.name !== 'HtmlWebpackPlugin' && plugin.constructor.name !== 'ProgressPlugin'); +config.plugins.push(new HtmlWebpackPlugin({title: 'Scratch 竞赛编辑器', template: path.resolve(__dirname, 'src/playground/competition.html')})); +config.devtool = false; +config.mode = 'production'; +config.optimization = {...config.optimization, minimize: false}; +module.exports = config; diff --git a/packages/scratch-gui/package.json b/packages/scratch-gui/package.json index 348d148..cf008e8 100644 --- a/packages/scratch-gui/package.json +++ b/packages/scratch-gui/package.json @@ -157,13 +157,12 @@ "omggif": "1.0.10", "papaparse": "5.7.0", "prop-types": "15.8.1", - "query-string": "5.1.1", "react-draggable": "3.3.2", "react-ga": "3.3.1", "react-intl": "6.8.9", "react-modal": "3.16.3", "react-popover": "0.5.10", - "react-redux": "8.1.3", + "react-redux": "^8.0.0", "react-responsive": "9.0.2", "react-style-proptype": "3.2.2", "react-tabs": "5.2.0", diff --git a/packages/scratch-gui/src/components/menu-bar/menu-bar.jsx b/packages/scratch-gui/src/components/menu-bar/menu-bar.jsx index 630fd49..3df6fc1 100644 --- a/packages/scratch-gui/src/components/menu-bar/menu-bar.jsx +++ b/packages/scratch-gui/src/components/menu-bar/menu-bar.jsx @@ -327,10 +327,8 @@ class MenuBar extends React.Component { >
- +
{(this.props.canChangeColorMode || this.props.canChangeLanguage || this.props.canChangeTheme) && ( -
diff --git a/packages/scratch-gui/src/containers/record-modal.jsx b/packages/scratch-gui/src/containers/record-modal.jsx index 3d906c1..75e6701 100644 --- a/packages/scratch-gui/src/containers/record-modal.jsx +++ b/packages/scratch-gui/src/containers/record-modal.jsx @@ -38,13 +38,30 @@ class RecordModal extends React.Component { trimStart: 0, trimEnd: 1 }; + this.competitionFlush = event => { + event.detail.tasks.push(this.commitForCompetition()); + }; + } + componentDidMount () { + window.addEventListener('scratch-competition-flush', this.competitionFlush); + } + componentWillUnmount () { + window.removeEventListener('scratch-competition-flush', this.competitionFlush); + } + async commitForCompetition () { + const tasks = []; + window.dispatchEvent(new CustomEvent('scratch-competition-stop-recording', {detail: {tasks}})); + await Promise.all(tasks); + if (this.competitionEncoding) return this.competitionEncoding; + if (this.state.samples && this.state.samples.length) return this.handleSubmit(); + if (this.state.recording) throw new Error('录音尚未停止,请完成录音后保存'); } handleRecord () { this.setState({recording: true}); } handleStopRecording (samples, sampleRate, levels, trimStart, trimEnd) { if (samples.length > 0) { - this.setState({samples, sampleRate, levels, trimStart, trimEnd, recording: false}); + return new Promise(resolve => this.setState({samples, sampleRate, levels, trimStart, trimEnd, recording: false}, resolve)); } } handlePlay () { @@ -66,7 +83,7 @@ class RecordModal extends React.Component { this.setState({playhead}); } handleSubmit () { - this.setState({encoding: true}, () => { + this.competitionEncoding = new Promise((resolve, reject) => this.setState({encoding: true}, () => { const sampleCount = this.state.samples.length; const startIndex = Math.floor(this.state.trimStart * sampleCount); const endIndex = Math.floor(this.state.trimEnd * sampleCount); @@ -76,8 +93,13 @@ class RecordModal extends React.Component { () => { this.props.onClose(); this.props.onNewSound(); - }); - }); + }).then(resolve, error => { + this.setState({encoding: false}); + this.competitionEncoding = null; + reject(error); + }); + })); + return this.competitionEncoding; } handleCancel () { this.props.onClose(); diff --git a/packages/scratch-gui/src/containers/recording-step.jsx b/packages/scratch-gui/src/containers/recording-step.jsx index cec90ce..f53fd97 100644 --- a/packages/scratch-gui/src/containers/recording-step.jsx +++ b/packages/scratch-gui/src/containers/recording-step.jsx @@ -34,8 +34,13 @@ class RecordingStep extends React.Component { componentDidMount () { this.audioRecorder = new AudioRecorder(); this.audioRecorder.startListening(this.handleStarted, this.handleLevelUpdate, this.handleRecordingError); + this.competitionStop = event => { + if (this.props.recording) event.detail.tasks.push(Promise.resolve(this.handleStopRecording())); + }; + window.addEventListener('scratch-competition-stop-recording', this.competitionStop); } componentWillUnmount () { + window.removeEventListener('scratch-competition-stop-recording', this.competitionStop); this.audioRecorder.dispose(); } handleStarted () { @@ -56,7 +61,7 @@ class RecordingStep extends React.Component { } handleStopRecording () { const {samples, sampleRate, levels, trimStart, trimEnd} = this.audioRecorder.stop(); - this.props.onStopRecording(samples, sampleRate, levels, trimStart, trimEnd); + return this.props.onStopRecording(samples, sampleRate, levels, trimStart, trimEnd); } render () { const { diff --git a/packages/scratch-gui/src/lib/audio/audio-util.js b/packages/scratch-gui/src/lib/audio/audio-util.js index cdd31ad..7639901 100644 --- a/packages/scratch-gui/src/lib/audio/audio-util.js +++ b/packages/scratch-gui/src/lib/audio/audio-util.js @@ -26,7 +26,7 @@ const computeChunkedRMS = function (samples, chunkSize = 1024) { }; const encodeAndAddSoundToVM = function (vm, samples, sampleRate, name, callback) { - WavEncoder.encode({ + return WavEncoder.encode({ sampleRate: sampleRate, channelData: [samples] }).then(wavBuffer => { @@ -53,7 +53,7 @@ const encodeAndAddSoundToVM = function (vm, samples, sampleRate, name, callback) // The VM will update the sound name to a fresh name vmSound.name = name; - vm.addSound(vmSound).then(() => { + return vm.addSound(vmSound).then(() => { if (callback) callback(); }); }); diff --git a/packages/scratch-gui/src/lib/competition-capture.js b/packages/scratch-gui/src/lib/competition-capture.js new file mode 100644 index 0000000..56d6c6b --- /dev/null +++ b/packages/scratch-gui/src/lib/competition-capture.js @@ -0,0 +1,42 @@ +/** Snapshot ordering is shared by the runtime bridge and regression tests. */ +export class CaptureCoordinator { + constructor({vm, flush, waitPending, hashBlob, onDirty}) { + this.vm = vm; + this.flush = flush; + this.waitPending = waitPending; + this.hashBlob = hashBlob; + this.generation = 0; + this.phase = 'LOADING'; + vm.on('PROJECT_CHANGED', () => { + if (this.phase === 'READY') { + this.generation++; + onDirty(this.generation); + } + }); + } + async load(bytes) { + this.phase = 'LOADING'; + await this.waitPending(); + this.vm.stopAll(); + await this.vm.loadProject(bytes); + await this.waitPending(); + const baseline = await this.hashBlob(await this.vm.saveProjectSb3()); + this.generation = 0; + this.phase = 'READY'; + return {captured_generation: 0, content_hash: baseline}; + } + async capture(finalize = false) { + if (this.phase !== 'READY') throw new Error('编辑器尚未完成加载'); + if (finalize) { + await this.flush(); + this.vm.stopAll(); + } + await this.waitPending(); + // saveProjectSb3 synchronously serializes JSON and assets before asynchronous ZIP compression. + const captured_generation = this.generation; + const blobPromise = this.vm.saveProjectSb3(); + const blob = await blobPromise; + const content_hash = await this.hashBlob(blob); + return {blob, captured_generation, content_hash}; + } +} diff --git a/packages/scratch-gui/src/lib/competition-query-string.js b/packages/scratch-gui/src/lib/competition-query-string.js new file mode 100644 index 0000000..12f1419 --- /dev/null +++ b/packages/scratch-gui/src/lib/competition-query-string.js @@ -0,0 +1,19 @@ +// Standards-based parsing for the pinned editor's parse/stringify call sites. +// Repeated keys retain their original order. URLSearchParams bounds malformed decoding. +const parse = value => { + const output = Object.create(null); + for (const [key, item] of new URLSearchParams(value)) { + if (Object.prototype.hasOwnProperty.call(output, key)) output[key] = [].concat(output[key], item); + else output[key] = item; + } + return output; +}; +const stringify = value => { + const params = new URLSearchParams(); + for (const key of Object.keys(value).sort()) { + if (typeof value[key] === 'undefined') continue; + for (const item of [].concat(value[key])) params.append(key, item === null ? '' : String(item)); + } + return params.toString(); +}; +export default {parse, stringify}; diff --git a/packages/scratch-gui/src/lib/detect-locale.js b/packages/scratch-gui/src/lib/detect-locale.js index 942157e..332f576 100644 --- a/packages/scratch-gui/src/lib/detect-locale.js +++ b/packages/scratch-gui/src/lib/detect-locale.js @@ -3,7 +3,7 @@ * Utility function to detect locale from the browser setting or paramenter on the URL. */ -import queryString from 'query-string'; +import queryString from './competition-query-string'; /** * look for language setting in the browser. Check against supported locales. diff --git a/packages/scratch-gui/src/lib/libraries/extensions/index.jsx b/packages/scratch-gui/src/lib/libraries/extensions/index.jsx index 276611d..8a398bd 100644 --- a/packages/scratch-gui/src/lib/libraries/extensions/index.jsx +++ b/packages/scratch-gui/src/lib/libraries/extensions/index.jsx @@ -413,4 +413,4 @@ export default [ ), helpLink: 'https://scratch.mit.edu/wedo' } -]; +].filter(extension => ['music', 'pen'].includes(extension.extensionId)); diff --git a/packages/scratch-gui/src/lib/local-storage.js b/packages/scratch-gui/src/lib/local-storage.js index 0ab82e0..8df60f1 100644 --- a/packages/scratch-gui/src/lib/local-storage.js +++ b/packages/scratch-gui/src/lib/local-storage.js @@ -13,7 +13,7 @@ const getMap = key => { }; const setMap = (key, map) => { - localStorage.setItem(key, JSON.stringify(map)); + try { localStorage.setItem(key, JSON.stringify(map)); } catch { /* Reviewer sandbox denies persistent storage. */ } }; export const getLocalStorageValue = (key, id) => { diff --git a/packages/scratch-gui/src/lib/query-parser-hoc.jsx b/packages/scratch-gui/src/lib/query-parser-hoc.jsx index 2d91a91..e3e1aba 100644 --- a/packages/scratch-gui/src/lib/query-parser-hoc.jsx +++ b/packages/scratch-gui/src/lib/query-parser-hoc.jsx @@ -1,6 +1,6 @@ import React from 'react'; import PropTypes from 'prop-types'; -import queryString from 'query-string'; +import queryString from './competition-query-string'; import {connect} from 'react-redux'; import {detectTutorialId} from './tutorial-from-url'; @@ -16,6 +16,7 @@ const QueryParserHOC = function (WrappedComponent) { class QueryParserComponent extends React.Component { constructor (props) { super(props); + if (location.pathname.startsWith('/editor/')) return; const queryParams = queryString.parse(location.search); const tutorialId = detectTutorialId(queryParams); if (tutorialId) { diff --git a/packages/scratch-gui/src/lib/save-project-to-server.js b/packages/scratch-gui/src/lib/save-project-to-server.js index 8fede93..eb5929b 100644 --- a/packages/scratch-gui/src/lib/save-project-to-server.js +++ b/packages/scratch-gui/src/lib/save-project-to-server.js @@ -1,4 +1,4 @@ -import queryString from 'query-string'; +import queryString from './competition-query-string'; import xhr from 'xhr'; /** diff --git a/packages/scratch-gui/src/lib/settings/color-mode/persistence.js b/packages/scratch-gui/src/lib/settings/color-mode/persistence.js index a26e791..a41fb4a 100644 --- a/packages/scratch-gui/src/lib/settings/color-mode/persistence.js +++ b/packages/scratch-gui/src/lib/settings/color-mode/persistence.js @@ -1,4 +1,5 @@ import cookie from 'cookie'; +import {readPreferenceCookie, writePreferenceCookie} from '../competition-cookie'; import {DEFAULT_MODE, HIGH_CONTRAST_MODE} from '.'; @@ -17,7 +18,7 @@ const systemPreferencesColorMode = () => { }; const detectColorMode = () => { - const obj = cookie.parse(document.cookie) || {}; + const obj = cookie.parse(readPreferenceCookie()) || {}; const colorModeCookie = obj.scratchtheme; if (isValidColorMode(colorModeCookie)) return colorModeCookie; @@ -33,12 +34,12 @@ const persistColorMode = mode => { if (systemPreferencesColorMode() === mode) { // Clear the cookie to represent using the system preferences - document.cookie = `${COOKIE_KEY}=;path=/`; + writePreferenceCookie(`${COOKIE_KEY}=;path=/`); return; } const expires = new Date(new Date().setYear(new Date().getFullYear() + 1)).toUTCString(); - document.cookie = `${COOKIE_KEY}=${mode};expires=${expires};path=/`; + writePreferenceCookie(`${COOKIE_KEY}=${mode};expires=${expires};path=/`); }; export { diff --git a/packages/scratch-gui/src/lib/settings/competition-cookie.js b/packages/scratch-gui/src/lib/settings/competition-cookie.js new file mode 100644 index 0000000..e2f3897 --- /dev/null +++ b/packages/scratch-gui/src/lib/settings/competition-cookie.js @@ -0,0 +1,7 @@ +// Read-only reviewer frames have opaque origins. Preferences remain session-local there. +export const readPreferenceCookie = () => { + try { return document.cookie; } catch { return ''; } +}; +export const writePreferenceCookie = value => { + try { document.cookie = value; } catch { /* Sandboxed reviewer preferences are not persisted. */ } +}; diff --git a/packages/scratch-gui/src/lib/settings/theme/persistence.js b/packages/scratch-gui/src/lib/settings/theme/persistence.js index 968ff50..47f0628 100644 --- a/packages/scratch-gui/src/lib/settings/theme/persistence.js +++ b/packages/scratch-gui/src/lib/settings/theme/persistence.js @@ -1,4 +1,5 @@ import cookie from 'cookie'; +import {readPreferenceCookie, writePreferenceCookie} from '../competition-cookie'; import {DEFAULT_THEME, CAT_BLOCKS_THEME} from '.'; @@ -12,7 +13,7 @@ const isValidTheme = theme => [DEFAULT_THEME, CAT_BLOCKS_THEME].includes(theme); // For now, we'll take the user preference here as-is and switch to default theme if needed, // once we have the user info available. const detectTheme = () => { - const obj = cookie.parse(document.cookie) || {}; + const obj = cookie.parse(readPreferenceCookie()) || {}; const themeCookie = obj[COOKIE_KEY]; if (isValidTheme(themeCookie)) return themeCookie; @@ -26,7 +27,7 @@ const persistTheme = theme => { } const expires = new Date(new Date().setYear(new Date().getFullYear() + 1)).toUTCString(); - document.cookie = `${COOKIE_KEY}=${theme};expires=${expires};path=/`; + writePreferenceCookie(`${COOKIE_KEY}=${theme};expires=${expires};path=/`); }; export { diff --git a/packages/scratch-gui/src/playground/competition.html b/packages/scratch-gui/src/playground/competition.html new file mode 100644 index 0000000..e6c4d44 --- /dev/null +++ b/packages/scratch-gui/src/playground/competition.html @@ -0,0 +1 @@ +Scratch 竞赛编辑器 diff --git a/packages/scratch-gui/src/playground/competition.jsx b/packages/scratch-gui/src/playground/competition.jsx new file mode 100644 index 0000000..3e84b3f --- /dev/null +++ b/packages/scratch-gui/src/playground/competition.jsx @@ -0,0 +1,164 @@ +/* Local competition host integration. See editor/README.md for source and protocol. */ +import React from 'react'; +import ReactDomClient from 'react-dom/client'; +import {ScratchStorage} from '@scratch/scratch-storage'; +import GUI from '../containers/gui.jsx'; +import {EditorState} from '../lib/editor-state'; +import {AppStateProviderHOC} from '../lib/app-state-provider-hoc.jsx'; +import defaultProject from '../lib/default-project'; +import JSZip from 'jszip'; +import {CaptureCoordinator} from '../lib/competition-capture'; +import {setLocales, selectLocale} from '../reducers/locales'; +import './index.css'; + +const channel = 'scratch-competition'; +// location.href retains the editor's URL origin even when window.origin is opaque in a reviewer sandbox. +const parentOrigin = new URL(location.href).origin; +let vm; +let operation = Promise.resolve(); +let coordinator; +const pending = new Set(); +const post = (type, extra = {}) => window.parent.postMessage({channel, type, ...extra}, parentOrigin); +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); +function bounded(promise, milliseconds, message) { + let timer; + return Promise.race([promise, new Promise((resolve, reject) => { + timer = setTimeout(() => reject(new Error(message)), milliseconds); + })]).finally(() => clearTimeout(timer)); +} +function track(method) { + const original = vm[method].bind(vm); + vm[method] = (...args) => { + const result = original(...args); + if (result && typeof result.then === 'function') { + pending.add(result); + result.then(() => pending.delete(result), () => pending.delete(result)); + } + return result; + }; +} +class CompetitionStorage { + constructor() { + this.scratchStorage = new ScratchStorage(); + this.cacheDefault(); + this.scratchStorage.addWebStore([ + this.scratchStorage.AssetType.ImageVector, + this.scratchStorage.AssetType.ImageBitmap, + this.scratchStorage.AssetType.Sound + ], asset => `/editor/library-assets/${asset.assetId}.${asset.dataFormat}`); + } + cacheDefault(translator) { + const storage = this.scratchStorage; + for (const asset of defaultProject(translator)) { + storage.builtinHelper._store(storage.AssetType[asset.assetType], storage.DataFormat[asset.dataFormat], asset.data, asset.id); + } + } + setTranslatorFunction(translator) { this.cacheDefault(translator); } + getLibraryAssetUrl(assetId, dataFormat) { return `/editor/library-assets/${assetId}.${dataFormat}`; } + saveProject() { return Promise.reject(new Error('请使用竞赛系统保存作品')); } +} +const editorState = new EditorState({locale: 'zh-cn'}, () => ({storage: new CompetitionStorage()})); +const messages = editorState.store.getState().locales.messagesByLocale; +editorState.store.dispatch(setLocales({...messages, 'zh-cn': {...messages['zh-cn'], + 'gui.menuBar.settings': '设置', 'gui.aria.settingsMenu': '设置菜单', + 'gui.menuBar.language': '语言', 'gui.aria.languageMenu': '语言菜单', + 'gui.menuBar.theme': '积木主题', 'gui.menuBar.colorMode': '配色模式', + 'gui.theme.default': '默认配色', 'gui.theme.highContrast': '高对比度', + 'gui.theme.dark': '深色', 'gui.blockTheme.default': '默认积木', + 'gui.blockTheme.catBlocks': '小猫积木' +}})); +editorState.store.dispatch(selectLocale('zh-cn')); +const WrappedGUI = AppStateProviderHOC(GUI); +const target = document.createElement('div'); +target.style.height = '100vh'; +document.body.appendChild(target); +GUI.setAppElement(target); + +async function waitPending() { + const deadline = Date.now() + 12000; + while (pending.size) { + if (Date.now() > deadline) throw new Error('素材处理尚未完成'); + await bounded(Promise.all([...pending]), Math.max(1, deadline - Date.now()), '素材处理尚未完成'); + } +} +async function flush() { + const active = document.activeElement; + if (active && typeof active.blur === 'function') active.blur(); + const tasks = []; + window.dispatchEvent(new CustomEvent('scratch-competition-flush', {detail: {tasks}})); + await bounded(Promise.all(tasks), 12000, '画板或录音提交超时,请完成编辑后重试'); + await delay(0); + await waitPending(); +} +const canonical = value => { + if (Array.isArray(value)) return value.map(canonical); + if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])); + return value; +}; +async function hashBlob(blob) { + const zip = await JSZip.loadAsync(await blob.arrayBuffer()); + const parts = []; + for (const name of Object.keys(zip.files).filter(name => !zip.files[name].dir).sort()) { + const content = name === 'project.json' ? new TextEncoder().encode(JSON.stringify(canonical(JSON.parse(await zip.file(name).async('string'))))) : await zip.file(name).async('uint8array'); + const header = new TextEncoder().encode(`${name}\0${content.length}\0`); + parts.push(header, content); + } + const combined = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0)); + let offset = 0; + for (const part of parts) { combined.set(part, offset); offset += part.length; } + const hash = await crypto.subtle.digest('SHA-256', combined); + return Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2, '0')).join(''); +} +async function snapshot(requestId, finalize) { + const result = await coordinator.capture(finalize); + const {blob} = result; + const bytes = new Uint8Array(await blob.arrayBuffer()); + let binary = ''; + for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768)); + post('snapshot', {request_id: requestId, sb3_base64: btoa(binary), captured_generation: result.captured_generation, content_hash: result.content_hash}); +} +window.addEventListener('message', event => { + if (event.origin !== parentOrigin || event.source !== window.parent || !event.data || event.data.channel !== channel) return; + const message = event.data; + if (!['load', 'snapshot', 'capture', 'finalize'].includes(message.type) || typeof message.request_id !== 'string') return; + operation = operation.catch(() => {}).then(async () => { + try { + if (message.type === 'load') { + if (!vm) throw new Error('VM 尚未初始化'); + target.inert = true; + const binary = atob(message.sb3_base64); + const bytes = Uint8Array.from(binary, character => character.charCodeAt(0)); + const baseline = await bounded(coordinator.load(bytes), 20000, '项目加载超时'); + target.inert = false; + post('loaded', {request_id: message.request_id, ...baseline}); + } else await snapshot(message.request_id, message.type === 'finalize'); + } catch (error) { + post('error', {request_id: message.request_id, message: String(error.message || error)}); + } + }); +}); +const initializeVM = instance => { + vm = instance; + ['updateSvg', 'updateBitmap', 'addSound', 'updateSoundBuffer', 'addCostume', 'addBackdrop', + 'addSprite', 'duplicateCostume', 'duplicateSound', 'shareCostumeToTarget', 'shareSoundToTarget'].forEach(method => { + if (typeof vm[method] === 'function') track(method); + }); + const loadExtension = vm.extensionManager.loadExtensionURL.bind(vm.extensionManager); + vm.extensionManager.loadExtensionURL = id => { + if (!['music', 'pen'].includes(id)) return Promise.reject(new Error('本场禁止使用联网或硬件扩展')); + return loadExtension(id); + }; + coordinator = new CaptureCoordinator({vm, flush, waitPending, hashBlob, + onDirty: generation => post('dirty', {generation})}); +}; +let announced = false; +const root = ReactDomClient.createRoot(target); +root.render( { + if (!announced) { announced = true; coordinator.phase = 'READY'; post('ready', {version: '15.3.0', commit: 'ec2ba664fb64e15dd3d9d96dccf57e57bdd0a06f', opaque_origin: window.origin === 'null', secure_context: window.isSecureContext, hash_available: Boolean(crypto.subtle)}); } + }} />); diff --git a/packages/scratch-gui/src/types.d.ts b/packages/scratch-gui/src/types.d.ts index dd3f8e5..00dc614 100644 --- a/packages/scratch-gui/src/types.d.ts +++ b/packages/scratch-gui/src/types.d.ts @@ -9,3 +9,5 @@ declare module '!raw-loader!.*' { } declare module '@scratch/scratch-paint'; +// The pinned monorepo VM package is JavaScript and does not publish declarations. +declare module '@scratch/scratch-vm'; diff --git a/packages/scratch-paint/src/hocs/update-image-hoc.jsx b/packages/scratch-paint/src/hocs/update-image-hoc.jsx index dae756d..fd95fd2 100644 --- a/packages/scratch-paint/src/hocs/update-image-hoc.jsx +++ b/packages/scratch-paint/src/hocs/update-image-hoc.jsx @@ -33,6 +33,18 @@ const UpdateImageHOC = function (WrappedComponent) { 'handleUpdateBitmap', 'handleUpdateVector' ]); + this.competitionFlush = event => { + event.detail.tasks.push(Promise.resolve().then(() => { + if (paper.tool && typeof paper.tool.endTextEdit === 'function') paper.tool.endTextEdit(); + this.handleUpdateImage(true); + })); + }; + } + componentDidMount () { + window.addEventListener('scratch-competition-flush', this.competitionFlush); + } + componentWillUnmount () { + window.removeEventListener('scratch-competition-flush', this.competitionFlush); } /** * @param {?boolean} skipSnapshot True if the call to update image should not trigger saving diff --git a/packages/scratch-render/package.json b/packages/scratch-render/package.json index b71c2e0..f9934b4 100644 --- a/packages/scratch-render/package.json +++ b/packages/scratch-render/package.json @@ -51,7 +51,7 @@ "dependencies": { "@scratch/scratch-svg-renderer": "15.3.0", "grapheme-breaker": "0.3.2", - "hull.js": "0.2.10", + "hull.js": "0.2.1", "ify-loader": "1.1.0", "linebreak": "0.3.0", "raw-loader": "0.5.1", diff --git a/packages/scratch-vm/src/virtual-machine.js b/packages/scratch-vm/src/virtual-machine.js index c23f4a0..a70bbd3 100644 --- a/packages/scratch-vm/src/virtual-machine.js +++ b/packages/scratch-vm/src/virtual-machine.js @@ -932,9 +932,11 @@ class VirtualMachine extends EventEmitter { ); // @todo there should be a better way to get from ImageData to a decodable storage format - canvas.toBlob(blob => { + return new Promise((resolve, reject) => canvas.toBlob(blob => { const reader = new FileReader(); + reader.addEventListener('error', () => reject(new Error('Bitmap encoding failed'))); reader.addEventListener('loadend', () => { + if (reader.error) return; const storage = this.runtime.storage; costume.dataFormat = storage.DataFormat.PNG; costume.bitmapResolution = bitmapResolution; @@ -949,12 +951,15 @@ class VirtualMachine extends EventEmitter { costume.assetId = costume.asset.assetId; costume.md5 = `${costume.assetId}.${costume.dataFormat}`; this.emitTargetsUpdate(); + resolve(); }); // Bitmaps with a zero width or height return null for their blob if (blob){ reader.readAsArrayBuffer(blob); + } else { + reject(new Error('Bitmap encoding produced no data')); } - }); + })); } /**