diff --git a/.claude/rules/scratch-gui/e2e-test.md b/.claude/rules/scratch-gui/e2e-test.md index 368612829bb..9e43eb2a166 100644 --- a/.claude/rules/scratch-gui/e2e-test.md +++ b/.claude/rules/scratch-gui/e2e-test.md @@ -62,10 +62,7 @@ expect(await isActiveByTestId(driver, 'ruby-toolbar-mode-furigana')).toBe(true); | `ruby-toolbar-menu-insert-class` | div | クラス挿入(ルビータブのみ) | | `ruby-toolbar-menu-preview` | div | プレビュー(日本語タブでは「ルビーに直したものを確認」) | | `ruby-toolbar-menu-download-japanese` | div | 日本語のプログラムを保存(.txt)。日本語タブのときだけ | -| `ruby-toolbar-menu-settings-heading` | div | 見出し「問題の約束」。日本語タブのときだけ | | `ruby-toolbar-menu-auto-correct-settings` | div | 自動置換設定 | -| `ruby-toolbar-menu-settings-pattern-example` | div | 例示の形(添字は 0 から)。日本語タブのときだけ | -| `ruby-toolbar-menu-settings-pattern-index-from-one` | div | 添字が 1 から始まる問題。日本語タブのときだけ | 日本語モードは、ルビータブのボタンではなく**日本語タブ**(`gui-tab-japanese`)で開く(URL は `?tab=japanese`)。ルビータブのツールバーは、ふりがな・Ruby の 2 つ。 @@ -76,6 +73,18 @@ expect(await isActiveByTestId(driver, 'ruby-toolbar-mode-furigana')).toBe(true); | `gui-tab-ruby` | li | ルビータブ(いつも Ruby で開く) | | `gui-tab-japanese` | li | 日本語タブ(日本語の表示のときだけ。レッスンの `allowDnclMode` が false なら押せない) | | `ruby-tab-language-band` | div | 日本語タブのエディタの上の帯 | +| `ruby-tab-problem-settings` | span | 帯の「問題の約束: 添字は 0 から」(いまの約束) | +| `ruby-tab-problem-settings-change` | button | 帯の「変える」。「問題の約束」のポップアップを開く | + +### 問題の約束のポップアップ (`problem-settings-modal.jsx`) + +| data-testid | 要素 | 説明 | +|------------|------|------| +| `problem-settings-modal-pattern-example` | label | カード「例示の形(添字は 0 から)」(中に radio) | +| `problem-settings-modal-pattern-index-from-one` | label | カード「添字が 1 から始まる問題」(中に radio) | +| `problem-settings-modal-sentences` | div | 選んだパターンでプログラムの先頭に入る文 | +| `problem-settings-modal-cancel` | button | キャンセル(何も変えない) | +| `problem-settings-modal-ok` | button | 決定(選んだパターンで書く。何も選んでいないときは押せない) | ### コンソール拡張機能 (`smalruby-console`) diff --git a/docs/dncl/README.md b/docs/dncl/README.md index f93a580511d..f150e087514 100644 --- a/docs/dncl/README.md +++ b/docs/dncl/README.md @@ -119,12 +119,10 @@ | 行番号と罫線つきでコピー | `ruby-toolbar-menu-copy-problem-form` | 上の「コピー」 | | ルビーに直したものを確認 | `ruby-toolbar-menu-preview` | ルビータブの「ルビースクリプトを確認」と同じ画面。画面の題はメニューと同じ「ルビーに直したものを確認」 | | 日本語のプログラムを保存(.txt) | `ruby-toolbar-menu-download-japanese` | エディタのテキスト(行番号と罫線を付けない形)を、**UTF-8** のテキストファイル `<作品の名前>_<スプライトの名前>_japanese.txt` に保存する。読み込みなおせるように、行番号と罫線は付けない | -| 見出し「問題の約束」 | `ruby-toolbar-menu-settings-heading` | — | -| 例示の形(添字は 0 から) | `ruby-toolbar-menu-settings-pattern-example` | 下の「設定(冒頭の説明文)」 | -| 添字が 1 から始まる問題 | `ruby-toolbar-menu-settings-pattern-index-from-one` | 同上 | | 自動置換設定 | `ruby-toolbar-menu-auto-correct-settings` | ルビータブと同じ | 「ルビースクリプトを保存」と「クラスを挿入」は Ruby のための項目なので、日本語タブには出さない。ルビータブのメニューは変わらない。 +「問題の約束」はメニューに置かず、エディタの上の緑の帯から開く(下の「設定(冒頭の説明文)」)。メニューの中の見出しと項目では、とても大事な設定なのに何のことか分からなかったため。 ### ブロック制限の通知と、すべてのブロックに戻す導線 @@ -179,7 +177,7 @@ | `dncl-array-index-hint.js` | **範囲外の添字の警告**(`findArrayIndexHints`)。1 から始まる添字で書いたときのように配列の範囲外を読む `X[i]` / `X[3]` を見つける。ja-notation の `parse` で読んだ構文木を見る(読めないプログラムには出さない)。`ruby-tab.jsx` が警告マーカー(`gui.rubyTab.dnclArrayIndexHint`)にして、添字が 0 から始まることと直し方を表示する。下の「配列の添字は 0 から」 | | `dncl-index-note.js` | **貼り付けたテキストの「添字は 1 から始まる」の注釈を見つける**(`hasOneBasedIndexNote`)。コメントだけを見る。下の「貼り付け時の添字の設定」 | | `dncl-script-order.js` | ブロックから日本語にするときの**スクリプトの並び**(`rubyInScriptOrder`)。ルビータブの Ruby は関数の定義を先に出すが、日本語タブには書いた順(スクリプトの並び)のまま、スクリプトの間に空の行を入れない Ruby(`RubyGenerator.targetToCode` の `keepScriptOrder`)を作って日本語にする。下の「ブロックを通ったときの並び」 | -| `dncl-settings.js` | **設定のパターン**(`dnclSettingsPatternId` / `dnclWithSettingsPattern` / `dnclWithIndexFromOne`)。冒頭の説明文からいまのパターンを読み、パターンの説明文を書いてプログラムをその設定で表し直す(Ruby を通るので意味は変わらない)。下の「設定(冒頭の説明文)」 | +| `dncl-settings.js` | **設定のパターン**(`dnclSettingsPatternId` / `dnclSettingsSentences` / `dnclWithSettingsPattern` / `dnclWithIndexFromOne`)。冒頭の説明文からいまのパターンを読み、パターンが先頭に書く文を出し(「問題の約束」のポップアップで見せる)、パターンの説明文を書いてプログラムをその設定で表し直す(Ruby を通るので意味は変わらない)。下の「設定(冒頭の説明文)」 | | `dncl-keywords.js` | DNCL キーワード定義(`もし`, `ならば`, `を繰り返す` など)| | `dncl-validator.js` | 日本語モードに無いことばの判定(`findUnsupportedCommands` / `isPostTestLoopLine`)と、その文言・id。ja-notation が読めない行の言いかえ(`ja-notation-errors.js`)が使う。文言と id は Ruby → 日本語の誤りにも使う | | `dncl-source-map.js` | DNCL 行 ↔ Ruby 行のマッピング(エラー位置表示用。詳細は下の「エラー行の対応(ソースマップ)」)| @@ -370,8 +368,9 @@ ja-notation が読めて Ruby になっても、その Ruby がブロックに - `packages/scratch-gui/src/containers/ruby-tab/dncl-green-flag.js` — 日本語タブのあいだ、緑の旗でも日本語のプログラムを動かす判断と、動かすスクリプトの選び方(関数の定義を除く。緑の旗では、ハットのスクリプトと動いているものも除く。`shouldRunJapaneseOnGreenFlag` / `japaneseScriptsToRun` / `japaneseScriptsToStart`) - `packages/scratch-gui/src/containers/ruby-tab/dncl-problem-form-view.js` — 読むモードを Monaco に描く(罫線のデコレーション、行番号 `(01)` の `lineNumbers`、読むモードと書くモードの切りかえ `createProblemFormView`: フォーカス・クリック・入力・5 秒の待ち・貼り付け・`showReadMode` / `toggle`) - `packages/scratch-gui/src/containers/ruby-tab/auto-correct-apply.js` — 自動置換した文を、書きかえがモデルのすべての受け手に届いてから入れる(`applyAutoCorrection`。受け手の中から入れると、エディタのワーカーが例外を出すため)。ルビータブも同じ -- `packages/scratch-gui/src/containers/ruby-tab/dncl-index-setting.js` — 貼り付け時の添字の設定の確認ダイアログと、冒頭への説明文の書きこみ(1 回の Undo。違うところだけを書きかえる `replaceEditorText`。設定のパターンのメニューも使う)(`offerDnclIndexSetting`) -- `packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.jsx` — 日本語タブのツールバー(上の「日本語タブのツールバーとメニュー」)。その他メニューの設定のパターン(`ruby-toolbar-menu-settings-pattern-example` / `ruby-toolbar-menu-settings-pattern-index-from-one`。見出し「問題の約束」の下。いまのパターンに ✓) +- `packages/scratch-gui/src/containers/ruby-tab/dncl-index-setting.js` — 貼り付け時の添字の設定の確認ダイアログと、冒頭への説明文の書きこみ(1 回の Undo。違うところだけを書きかえる `replaceEditorText`。「問題の約束」のポップアップも使う)(`offerDnclIndexSetting`) +- `packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.jsx` — 日本語タブのツールバー(上の「日本語タブのツールバーとメニュー」) +- `packages/scratch-gui/src/components/problem-settings-modal/` — 「問題の約束」のポップアップ(`problem-settings-modal.jsx`)と、緑の帯のいまの約束と「変える」(`problem-settings-band-item.jsx`)。下の「設定(冒頭の説明文)」 - `packages/scratch-gui/src/lib/dncl/dncl-download.js` — 「日本語のプログラムを保存(.txt)」のファイル名(`dnclTextFilename`)と中身(`dnclTextBlob`。UTF-8 のテキスト) #### UI / 状態管理 @@ -416,14 +415,18 @@ DNCL モードは特定のブロックに紐づくものではなく、**Ruby | コメントの記号(`commentMarker`) | `// 「//」から行の終わりまでは,処理の対象とならない。` | `#` | `//` のとき、`//` はコメント(整数の商は `÷`)。`#` もコメントとして読む。Ruby では `#`、日本語に戻すときは `//` で書く | | 論理演算子の説明(`logicNote`) | `# 「and」は「かつ」を意味する論理演算子であり,…` の型の文 | 書かない | 変換は変えない(書き方はいつも `and` / `or` / `not`)。説明文があるかどうかだけを持つ | -- 説明文は手で書いてもよいし、その他メニュー(⋯)の**設定のパターン**(見出し「問題の約束」の下)から選んでもよい(日本語タブのときだけ出る)。 +- 説明文は手で書いてもよいし、**「問題の約束」のポップアップ**で設定のパターンから選んでもよい(日本語タブのときだけ)。 + - エディタの上の緑の帯に、いまの約束を出す: 「日本語(共通テスト用プログラム表記)| 問題の約束: 添字は 0 から 変える」(`ruby-tab-problem-settings`)。冒頭の文がどちらのパターンにもちょうど合わないとき(`//` をコメントにしたときなど)は「そのほか」。帯が狭いときは、言葉の名前のほうを「…」で切って約束を残す。 + - 「変える」(`ruby-tab-problem-settings-change`)でポップアップ(`components/problem-settings-modal/`。自動置換設定と同じ大きさ・作り)を開く。中身は、説明の 2 文、パターンのカード(ラジオ。何が変わるかの小さな例つき)、選んだパターンで**プログラムの先頭に入る文**(`problem-settings-modal-sentences`。何も入らないときは「いまの約束の文は消えます」)、「ほかのコメントはそのまま残ります。」、「キャンセル」「決定」。 + - はじめは、いまのパターンのカードが選ばれている。「そのほか」のときはどれも選ばれておらず、選ぶまで「決定」は押せない。 + - 背の低い画面(授業の PC の 1300×600・スマホの横向き)では、ポップアップを画面の上に寄せ、中身をスクロールできるようにする(共有のモーダルの外側はスクロールしないので、そのままでは「決定」が画面の外に出る)。 - | パターン(メニュー) | 添字 | コメント | 論理演算子の説明 | data-testid | - |---|---|---|---|---| - | 例示の形(添字は 0 から) | 0 から | `#` | 書かない | `ruby-toolbar-menu-settings-pattern-example` | - | 添字が 1 から始まる問題 | 1 から | `#` | 書く(`and` / `or` / `not` の 3 文) | `ruby-toolbar-menu-settings-pattern-index-from-one` | + | パターン(カード) | 例(`Data = [10, 20, 30]` のとき `Data[1]` は) | 添字 | コメント | 論理演算子の説明 | data-testid | + |---|---|---|---|---|---| + | 例示の形(添字は 0 から) | 20 | 0 から | `#` | 書かない | `problem-settings-modal-pattern-example` | + | 添字が 1 から始まる問題 | 10 | 1 から | `#` | 書く(`and` / `or` / `not` の 3 文) | `problem-settings-modal-pattern-index-from-one` | - 選ぶと、冒頭の設定の文を消してパターンの文を先頭に書き(ほかのコメントは残す)、プログラムを Ruby にしてからその設定で日本語に戻す(`dnclWithSettingsPattern`)。意味は変わらないので、添字は書きかわる(0 からで `A[0]` のプログラムを 1 からにすると `A[1]`)。Ruby にできないプログラムは、冒頭の文だけを書きかえる。1 回の Undo で戻る。メニューの ✓ は、冒頭の文がどちらかのパターンにちょうど合うときに付く(`//` をコメントにしたときなどはどちらにも付かない)。 + 「決定」(`problem-settings-modal-ok`)で、冒頭の設定の文を消してパターンの文を先頭に書き(ほかのコメントは残す)、プログラムを Ruby にしてからその設定で日本語に戻す(`dnclWithSettingsPattern`)。意味は変わらないので、添字は書きかわる(0 からで `A[0]` のプログラムを 1 からにすると `A[1]`)。Ruby にできないプログラムは、冒頭の文だけを書きかえる。1 回の Undo で戻る。「キャンセル」(`problem-settings-modal-cancel`)では何も変えない。 - 自動置換(既定でオン)はコメントの中を変えないので、説明文の `,` は `,` のまま残る(`#` と、設定で `//` をコメントにしたときの `//` の後ろ。`「…」` の中の `#` はコメントにしない)。`,` で書いた文も同じ設定として読む。 - 作品を保存して開き直しても設定は残る: 冒頭の文は Ruby のコメントになり、最初のブロックのコメントとして作品に保存される(`test/unit/lib/dncl/dncl-settings-project.test.js` が、ブロックにして保存し、開き直して日本語に戻すと同じ文と設定になることを確かめる)。 - 添字が 1 から始まる設定のプログラムには、範囲外の添字の警告(`dncl-array-index-hint.js`)を出さない。 @@ -689,7 +692,7 @@ Smalruby は **共通テスト用プログラム表記の形のプログラム - `dncl-roundtrip.test.js` — DNCL ↔ Ruby round-trip 安定性 - `dncl-script-order.test.js` — ブロックを通っても書いた順に戻ること(関数をプログラムの後ろに定義した形・先に定義した形)と、ルビータブの Ruby は関数の定義を先に出すこと - `dncl-display-sync.test.js` — ターゲットが変わって Ruby が空ならエディタを空にすること、ブロックを全部消したら空にすること、設定・コメントだけの日本語と誤りのある日本語は空の Ruby で消さないこと -- エディタ側の単体テスト: `packages/scratch-gui/test/unit/containers/ruby-tab/dncl-index-setting.test.js`(注釈なし・設定済みでは聞かない・「いいえ」で何も変えない・「はい」で冒頭に 1 回の編集、違うところだけの書きかえ)、`test/unit/components/ruby-toolbar-settings-pattern.test.jsx`(メニューのパターン・✓・選んだときの呼び出し)、`dncl-problem-form-view.test.js`(罫線のデコレーションの位置・タブの字下げ・空の行の縦線・行番号の桁と欄の幅・読むモードと書くモードの切りかえ: フォーカス・クリック・入力・5 秒の待ち・貼り付け・ボタン・日本語モードの出入り)、`test/unit/components/ruby-toolbar-auto-correct-switch.test.jsx`(自動置換のスイッチ: 両方のタブで `role="switch"`・`aria-checked`・押すと切りかわる)、`test/unit/components/ruby-toolbar-rules-switch.test.jsx`(日本語タブにスプライトを選ぶ部品が無い・スイッチは日本語タブだけ・`role="switch"` と `aria-checked`・フォーカスを動かさない・その他メニューの項目と並び・.txt の保存)、`test/unit/lib/dncl/dncl-download.test.js`(.txt のファイル名と UTF-8)。`marker-navigation.test.js`(誤りの表示を閉じるときにフォーカスを動かさない)。統合テスト `test/integration/dncl-problem-form.test.js`(スイッチ・入力・5 秒の待ち・クリック・貼り付け・緑の旗での切りかえ、読み込み直した直後の 1 回目の実行ボタン、Ruby に戻すと行番号と空白の点が戻ること) +- エディタ側の単体テスト: `packages/scratch-gui/test/unit/containers/ruby-tab/dncl-index-setting.test.js`(注釈なし・設定済みでは聞かない・「いいえ」で何も変えない・「はい」で冒頭に 1 回の編集、違うところだけの書きかえ)、`test/unit/components/problem-settings-modal.test.jsx`(「問題の約束」のポップアップ: はじめに選ばれるカード・先頭に入る文・決定で選んだパターン・キャンセルで変えない・「そのほか」では決定できない。緑の帯のいまの約束と「変える」)、`dncl-problem-form-view.test.js`(罫線のデコレーションの位置・タブの字下げ・空の行の縦線・行番号の桁と欄の幅・読むモードと書くモードの切りかえ: フォーカス・クリック・入力・5 秒の待ち・貼り付け・ボタン・日本語モードの出入り)、`test/unit/components/ruby-toolbar-auto-correct-switch.test.jsx`(自動置換のスイッチ: 両方のタブで `role="switch"`・`aria-checked`・押すと切りかわる)、`test/unit/components/ruby-toolbar-rules-switch.test.jsx`(日本語タブにスプライトを選ぶ部品が無い・スイッチは日本語タブだけ・`role="switch"` と `aria-checked`・フォーカスを動かさない・その他メニューの項目と並び・.txt の保存)、`test/unit/lib/dncl/dncl-download.test.js`(.txt のファイル名と UTF-8)。`marker-navigation.test.js`(誤りの表示を閉じるときにフォーカスを動かさない)。統合テスト `test/integration/dncl-problem-form.test.js`(スイッチ・入力・5 秒の待ち・クリック・貼り付け・緑の旗での切りかえ、読み込み直した直後の 1 回目の実行ボタン、Ruby に戻すと行番号と空白の点が戻ること) - 補完と色分けの単体テスト: `packages/scratch-gui/test/unit/containers/ruby-tab/dncl-snippets.test.js`(スニペットが標準の形(`:` と字下げ 4 つ・閉じのことばの行なし・`繰り返す:`)で、場所を埋めて入れたものがそのまま Ruby とブロックになり、Ruby から同じ日本語に戻ること)、`dncl-mode.test.js`(開始の行の後の字下げ・`and` / `or` / `not`・`繰り返す` の付いたことば・`を返す`・全角の `%` の色分け) - Round-trip テスト (左結合演算子の括弧除去): `packages/scratch-gui/test/unit/lib/ruby-roundtrip-puts-concat.test.js` - ブロック制限 UX の単体テスト: diff --git a/docs/dncl/design.md b/docs/dncl/design.md index 61f0bec3afe..7fc87394a8d 100644 --- a/docs/dncl/design.md +++ b/docs/dncl/design.md @@ -118,7 +118,7 @@ **実装の前に、この往復を確かめる。** - 説明文が無いプログラムは、既定(例示の形)とみなす。 - 決まった文だけを設定として読む。それ以外の文は普通のコメント。 -- 設定を変えるのは、ツールバーのメニュー(パターンを選ぶ)。選ぶと冒頭の説明文を書きかえ、プログラムをその設定で表し直す。 +- 設定を変えるのは、エディタの上の緑の帯の「問題の約束」の「変える」で開くポップアップ(パターンを選ぶ)。選ぶと冒頭の説明文を書きかえ、プログラムをその設定で表し直す。 説明文を手で書きかえてもよい。 ### よくある設定のパターン diff --git a/docs/smalruby-dncl-spec.ja.md b/docs/smalruby-dncl-spec.ja.md index 3b7e1067718..7a16b9b5e36 100644 --- a/docs/smalruby-dncl-spec.ja.md +++ b/docs/smalruby-dncl-spec.ja.md @@ -103,7 +103,7 @@ Data = [3, 1, 2] 表示する(Data[1]) ``` -エディタのその他メニュー(⋯)の見出し「問題の約束」の下の項目で、よくある設定のパターンを選んで書くこともできます([`docs/dncl/README.md`](dncl/README.md)「設定(冒頭の説明文)」)。 +エディタの上の緑の帯の「問題の約束」の「変える」で開くポップアップで、よくある設定のパターンを選んで書くこともできます([`docs/dncl/README.md`](dncl/README.md)「設定(冒頭の説明文)」)。 ### コメント diff --git a/packages/scratch-gui/.prettierignore b/packages/scratch-gui/.prettierignore index 6246fc72f6d..df1e3e2a406 100644 --- a/packages/scratch-gui/.prettierignore +++ b/packages/scratch-gui/.prettierignore @@ -47,6 +47,8 @@ src/components/* # Smalruby-only directories (all contents included) !src/components/auto-correct-modal/ !src/components/auto-correct-modal/** +!src/components/problem-settings-modal/ +!src/components/problem-settings-modal/** !src/components/block-display-modal/ !src/components/block-display-modal/** !src/components/bug-report-consent/ diff --git a/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-band-item.css b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-band-item.css new file mode 100644 index 00000000000..aea48f0a7ea --- /dev/null +++ b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-band-item.css @@ -0,0 +1,25 @@ +/* The rules of the problem stay whole in a narrow band; the name of the language gives way. */ +.item { + display: inline-flex; + align-items: center; + gap: 0.375rem; + align-self: stretch; + flex-shrink: 0; + margin-left: 0.375rem; +} + +.separator { + opacity: 0.7; +} + +.change { + /* The whole height of the band can be pressed, not only the letters. */ + align-self: stretch; + padding: 0 0.375rem; + border: none; + background: none; + color: inherit; + font: inherit; + text-decoration: underline; + cursor: pointer; +} diff --git a/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-band-item.jsx b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-band-item.jsx new file mode 100644 index 00000000000..12cfac264ae --- /dev/null +++ b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-band-item.jsx @@ -0,0 +1,58 @@ +// === Smalruby: This file is Smalruby-specific (the rules of the problem in the green band of the Japanese tab) === +import PropTypes from 'prop-types'; +import React from 'react'; +import { defineMessages, injectIntl } from 'react-intl'; +import intlShape from '../../lib/intlShape.js'; +import styles from './problem-settings-band-item.css'; + +const messages = defineMessages({ + label: { + defaultMessage: 'Rules of the problem: {rules}', + description: 'The rules of the problem the program is written by, in the green band of the Japanese tab', + id: 'gui.problemSettingsBand.label', + }, + example: { + defaultMessage: 'indices from 0', + description: 'The rules of the problem in the green band: the form of the examples', + id: 'gui.problemSettingsBand.example', + }, + indexFromOne: { + defaultMessage: 'indices from 1', + description: 'The rules of the problem in the green band: the indices start at 1', + id: 'gui.problemSettingsBand.indexFromOne', + }, + other: { + defaultMessage: 'other', + description: 'The rules of the problem in the green band: the settings are no pattern', + id: 'gui.problemSettingsBand.other', + }, + change: { + defaultMessage: 'Change', + description: 'Link in the green band of the Japanese tab to open the popup of the rules of the problem', + id: 'gui.problemSettingsBand.change', + }, +}); + +const ProblemSettingsBandItem = ({ intl, patternId, onChange }) => ( + + + + {intl.formatMessage(messages.label, { + rules: intl.formatMessage(messages[patternId] || messages.other), + })} + + + +); + +ProblemSettingsBandItem.propTypes = { + intl: intlShape.isRequired, + patternId: PropTypes.string, + onChange: PropTypes.func.isRequired, +}; + +export default injectIntl(ProblemSettingsBandItem); diff --git a/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-modal.css b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-modal.css new file mode 100644 index 00000000000..2cd82d09a96 --- /dev/null +++ b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-modal.css @@ -0,0 +1,140 @@ +@import '../../css/colors.css'; +@import '../../css/units.css'; + +/* The space over the popup: the 100px of the shared modal, smaller on a short screen. */ +$top-space: 100px; +$top-space-short: 0.5rem; +/* What is not the body: the header and the 4px border on both sides. */ +$frame-height: calc($library-header-height + 8px); + +.modal-content { + width: 360px; + max-width: calc(100vw - 1rem); +} + +/* On a short screen (the class PC of 1300×600, a phone held sideways) the popup + comes up to the top, so that 「決定」 stays on the screen. */ +@media (max-height: 760px) { + .modal-content { + margin-top: $top-space-short; + } +} + +.header { + background-color: $ui-green-2; +} + +.body { + background: $ui-white; /* the overlay must not show through (.claude/rules/scratch-gui/modals.md) */ + padding: 1.25rem; + display: flex; + flex-direction: column; + gap: 0.75rem; + font-size: 0.875rem; + color: hsla(0, 0%, 0%, 0.85); + /* The overlay does not scroll, so the body scrolls when the popup is taller than the screen. */ + max-height: calc(100vh - $top-space - $top-space-short - $frame-height); + overflow-y: auto; +} + +@media (max-height: 760px) { + .body { + max-height: calc(100vh - $top-space-short * 2 - $frame-height); + } +} + +.explanation { + margin: 0; + line-height: 1.6; +} + +.cards { + display: flex; + flex-direction: column; + gap: 0.5rem; +} + +.card { + display: grid; + grid-template-columns: auto 1fr; + gap: 0.125rem 0.5rem; + align-items: center; + padding: 0.5rem 0.625rem; + border: 2px solid hsla(0, 0%, 0%, 0.15); + border-radius: 0.5rem; + cursor: pointer; + user-select: none; +} + +.card-checked { + border-color: $ui-green-2; + background-color: hsla(163, 85%, 40%, 0.1); +} + +.radio { + margin: 0; + accent-color: $ui-green-2; + cursor: pointer; +} + +.card-name { + font-weight: bold; +} + +.card-example { + grid-column: 2; + font-size: 0.8rem; + color: hsla(0, 0%, 0%, 0.6); +} + +.card-example code { + font-family: Monaco, Menlo, Consolas, monospace; + color: hsla(0, 0%, 0%, 0.85); +} + +.note { + font-size: 0.78rem; + color: hsla(0, 0%, 0%, 0.6); +} + +.sentences { + font-family: Monaco, Menlo, Consolas, monospace; + font-size: 0.75rem; + padding: 0.375rem 0.5rem; + border: 1px dashed hsla(0, 0%, 0%, 0.2); + border-radius: 0.375rem; + background-color: hsla(0, 0%, 0%, 0.02); + white-space: pre-wrap; + word-break: break-all; +} + +.button-row { + display: flex; + justify-content: flex-end; + gap: 0.5rem; +} + +.cancel-button, +.ok-button { + padding: 0.5rem 1rem; + border-radius: 0.25rem; + font-weight: bold; + cursor: pointer; +} + +.cancel-button { + border: 1px solid hsla(0, 0%, 0%, 0.15); + background-color: $ui-white; + color: hsla(0, 0%, 0%, 0.85); +} + +.ok-button { + border: none; + background-color: $ui-green-2; + color: $ui-white; +} + +.ok-button:disabled { + opacity: 0.5; + cursor: default; +} diff --git a/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-modal.jsx b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-modal.jsx new file mode 100644 index 00000000000..a43131f9b6c --- /dev/null +++ b/packages/scratch-gui/src/components/problem-settings-modal/problem-settings-modal.jsx @@ -0,0 +1,159 @@ +// === Smalruby: This file is Smalruby-specific (the popup of 「問題の約束」 of the Japanese tab) === +import PropTypes from 'prop-types'; +import React, { useCallback, useState } from 'react'; +import { defineMessages, FormattedMessage, injectIntl } from 'react-intl'; +import Modal from '../../containers/modal.jsx'; +import { dnclSettingsSentences } from '../../lib/dncl/dncl-settings'; +import intlShape from '../../lib/intlShape.js'; +import Box from '../box/box.jsx'; +import styles from './problem-settings-modal.css'; + +const messages = defineMessages({ + title: { + defaultMessage: 'Rules of the problem', + description: 'Title of the popup of the Japanese tab to pick the rules of the problem', + id: 'gui.problemSettingsModal.title', + }, + explanation: { + defaultMessage: + 'A problem of the common test first tells its rules (whether the indices of the arrays start at 0 or at 1, and so on). Pick the rules of the problem you solve.', + description: 'Explanation at the top of the popup of the rules of the problem', + id: 'gui.problemSettingsModal.explanation', + }, + patternExample: { + defaultMessage: 'The form of the examples (indices from 0)', + description: 'A pattern of the rules of the problem: the settings of the examples', + id: 'gui.problemSettingsModal.patternExample', + }, + patternIndexFromOne: { + defaultMessage: 'A problem whose indices start at 1', + description: 'A pattern of the rules of the problem: the indices of the arrays start at 1', + id: 'gui.problemSettingsModal.patternIndexFromOne', + }, + example: { + defaultMessage: 'When {array}, {item} is {value}', + description: 'The small example of what a pattern of the rules of the problem changes', + id: 'gui.problemSettingsModal.example', + }, + sentencesLabel: { + defaultMessage: 'The sentences written at the top of the program:', + description: 'Label over the sentences a pattern writes at the top of the program', + id: 'gui.problemSettingsModal.sentencesLabel', + }, + noSentences: { + defaultMessage: '(Nothing is written. The sentences of the rules now are removed.)', + description: 'Shown when the pattern writes no sentence at the top of the program', + id: 'gui.problemSettingsModal.noSentences', + }, + othersKept: { + defaultMessage: 'The other comments stay as they are.', + description: 'Note that the other comments of the program are kept', + id: 'gui.problemSettingsModal.othersKept', + }, + cancel: { + defaultMessage: 'Cancel', + description: 'Button to close the popup of the rules of the problem without changing them', + id: 'gui.problemSettingsModal.cancel', + }, + ok: { + defaultMessage: 'OK', + description: 'Button to write the program by the rules picked in the popup', + id: 'gui.problemSettingsModal.ok', + }, +}); + +// The patterns in the order shown, with the value of `Data[1]` for `Data = [10, 20, 30]`. +const PATTERNS = [ + { id: 'example', testId: 'example', message: messages.patternExample, value: '20' }, + { id: 'indexFromOne', testId: 'index-from-one', message: messages.patternIndexFromOne, value: '10' }, +]; + +const ProblemSettingsModal = ({ intl, currentPatternId, onDecide, onRequestClose }) => { + // Settings that are no pattern (written by hand) have nothing chosen at first. + const [choice, setChoice] = useState(currentPatternId); + + const handleChange = useCallback((event) => setChoice(event.target.value), []); + const handleDecide = useCallback(() => { + if (choice) onDecide(choice); + }, [choice, onDecide]); + + const sentences = choice ? dnclSettingsSentences(choice) : []; + + return ( + + +

{intl.formatMessage(messages.explanation)}

+
+ {PATTERNS.map((pattern) => ( + + ))} +
+ {choice && ( + <> +
{intl.formatMessage(messages.sentencesLabel)}
+
+ {sentences.length > 0 ? sentences.join('\n') : intl.formatMessage(messages.noSentences)} +
+
{intl.formatMessage(messages.othersKept)}
+ + )} +
+ + +
+
+
+ ); +}; + +ProblemSettingsModal.propTypes = { + intl: intlShape.isRequired, + currentPatternId: PropTypes.string, + onDecide: PropTypes.func.isRequired, + onRequestClose: PropTypes.func.isRequired, +}; + +export default injectIntl(ProblemSettingsModal); diff --git a/packages/scratch-gui/src/components/ruby-toolbar/messages.js b/packages/scratch-gui/src/components/ruby-toolbar/messages.js index c0557db01a6..015f91ce76f 100644 --- a/packages/scratch-gui/src/components/ruby-toolbar/messages.js +++ b/packages/scratch-gui/src/components/ruby-toolbar/messages.js @@ -143,11 +143,6 @@ const messages = defineMessages({ defaultMessage: 'Show the line numbers and the rules, in the form of the test questions', description: 'Tooltip of the switch of the line numbers and the rules of the Japanese mode', }, - problemSettingsHeading: { - id: 'gui.rubyToolbar.problemSettingsHeading', - defaultMessage: 'Rules of the problem', - description: 'Heading in the More menu of the Japanese mode over the patterns of the settings', - }, previewRubyOfJapanese: { id: 'gui.rubyToolbar.previewRubyOfJapanese', defaultMessage: 'Preview the program in Ruby', @@ -158,17 +153,6 @@ const messages = defineMessages({ defaultMessage: 'Save the Japanese program (.txt)', description: 'More menu item of the Japanese mode: save the Japanese program as a text file', }, - settingsPatternExample: { - id: 'gui.rubyToolbar.settingsPatternExample', - defaultMessage: 'The form of the examples (indices from 0)', - description: 'More menu item of the Japanese mode: write the program by the settings of the examples', - }, - settingsPatternIndexFromOne: { - id: 'gui.rubyToolbar.settingsPatternIndexFromOne', - defaultMessage: 'A problem whose indices start at 1', - description: - 'More menu item of the Japanese mode: write the program by the settings of a problem whose indices start at 1', - }, previewRubyScript: { id: 'gui.rubyToolbar.previewRubyScript', defaultMessage: 'Preview Ruby script', diff --git a/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.css b/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.css index f97e4f19196..79fee2219f5 100644 --- a/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.css +++ b/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.css @@ -341,14 +341,6 @@ background-color: $ui-black-transparent; } -.moreMenuHeading { - padding: calc($space / 2) 0.75rem 0; - font-size: 0.75rem; - font-weight: bold; - color: $text-primary-transparent; - white-space: nowrap; -} - /* * スイッチ(Issue #2453): 1 つのものを表示する / しない(使う / 使わない)を、押すたびに入れ替える。 * 「行番号と罫線」と「自動置換」(Issue #2605)で使う。 diff --git a/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.jsx b/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.jsx index adf12f6fa1d..597adaa065c 100644 --- a/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.jsx +++ b/packages/scratch-gui/src/components/ruby-toolbar/ruby-toolbar.jsx @@ -3,7 +3,6 @@ import PropTypes from 'prop-types'; import React, { useState, useCallback, useRef, useEffect } from 'react'; import { useIntl } from 'react-intl'; import analytics from '../../lib/analytics'; -import { dnclSettingsPatternId } from '../../lib/dncl/dncl-settings'; import { isJapaneseLocale } from '../../lib/locale-utils.js'; import { isTouchDevice } from '../../lib/touch-device.js'; import iconAutoCorrect from './icon--auto-correct.svg'; @@ -196,29 +195,6 @@ const RubyToolbar = (props) => { if (props.onCopyProblemForm) props.onCopyProblemForm(); }, [props]); - // === Smalruby: Start of settings patterns of the Japanese mode === - const handleSelectSettingsPattern = useCallback( - (patternId) => { - setShowMoreMenu(false); - if (props.onDismissBubble) props.onDismissBubble(); - if (props.onSelectSettingsPattern) props.onSelectSettingsPattern(patternId); - }, - [props], - ); - const handleSelectExamplePattern = useCallback( - () => handleSelectSettingsPattern('example'), - [handleSelectSettingsPattern], - ); - const handleSelectIndexFromOnePattern = useCallback( - () => handleSelectSettingsPattern('indexFromOne'), - [handleSelectSettingsPattern], - ); - // The pattern the program is written by, read from its sentences when the menu is shown. - const currentPatternId = - showMoreMenu && props.dnclMode && props.editorRef && typeof props.editorRef.getValue === 'function' - ? dnclSettingsPatternId(props.editorRef.getValue()) - : null; - // === Smalruby: End of settings patterns of the Japanese mode === const handlePreviewRubyScript = useCallback(() => { setShowMoreMenu(false); if (props.onDismissBubble) props.onDismissBubble(); @@ -490,34 +466,6 @@ const RubyToolbar = (props) => { {intl.formatMessage(messages.saveJapaneseProgram)}
-
- {intl.formatMessage(messages.problemSettingsHeading)} -
-
- - {currentPatternId === 'example' ? '✓' : ''} - - {intl.formatMessage(messages.settingsPatternExample)} -
-
- - {currentPatternId === 'indexFromOne' ? '✓' : ''} - - {intl.formatMessage(messages.settingsPatternIndexFromOne)} -
-
{autoCorrectSettingsItem}
)} @@ -551,7 +499,6 @@ RubyToolbar.propTypes = { onCopyProblemForm: PropTypes.func, readMode: PropTypes.bool, onToggleReadMode: PropTypes.func, - onSelectSettingsPattern: PropTypes.func, locale: PropTypes.string, }; diff --git a/packages/scratch-gui/src/containers/ruby-tab.jsx b/packages/scratch-gui/src/containers/ruby-tab.jsx index e98772b911c..ee6a0db398b 100644 --- a/packages/scratch-gui/src/containers/ruby-tab.jsx +++ b/packages/scratch-gui/src/containers/ruby-tab.jsx @@ -4,11 +4,13 @@ import { settingsOfSource } from '@smalruby/ja-notation'; import VM from '@smalruby/scratch-vm'; import classNames from 'classnames'; import PropTypes from 'prop-types'; -import React, { useState, useRef, useCallback, useEffect } from 'react'; +import React, { useState, useRef, useCallback, useEffect, useMemo } from 'react'; import { defineMessages, injectIntl } from 'react-intl'; import { connect } from 'react-redux'; import AutoCorrectModal from '../components/auto-correct-modal/auto-correct-modal.jsx'; import cameraIcon from '../components/blocks-screenshot-button/icon--camera.svg'; +import ProblemSettingsBandItem from '../components/problem-settings-modal/problem-settings-band-item.jsx'; +import ProblemSettingsModal from '../components/problem-settings-modal/problem-settings-modal.jsx'; import RubyScriptPreview from '../components/ruby-script-preview/ruby-script-preview.jsx'; import rubyToolbarMessages from '../components/ruby-toolbar/messages.js'; import RubyToolbar from '../components/ruby-toolbar/ruby-toolbar.jsx'; @@ -28,7 +30,7 @@ import { dnclTextBlob, dnclTextFilename } from '../lib/dncl/dncl-download'; import { slashCommentRows, tidyPastedDncl, withDoubleSlashHint } from '../lib/dncl/dncl-paste-tidy'; import { problemFormText } from '../lib/dncl/dncl-problem-form'; import { rubyInScriptOrder } from '../lib/dncl/dncl-script-order'; -import { dnclWithSettingsPattern } from '../lib/dncl/dncl-settings'; +import { dnclSettingsPatternId, dnclWithSettingsPattern } from '../lib/dncl/dncl-settings'; import { stringArithmeticRows } from '../lib/dncl/dncl-string-arithmetic-hint'; import { dnclToRuby, rubyForLeavingDncl } from '../lib/dncl/dncl-to-ruby'; import { @@ -239,6 +241,7 @@ const RubyTab = (props) => { const [autoCorrectEnabled, setAutoCorrectEnabled] = useState(() => loadBool(AUTO_CORRECT_ENABLED_KEY, true)); const [autoCorrectSettings, setAutoCorrectSettings] = useState(loadAutoCorrectSettings); const [showAutoCorrectModal, setShowAutoCorrectModal] = useState(false); + const [showProblemSettingsModal, setShowProblemSettingsModal] = useState(false); const [showScriptPreview, setShowScriptPreview] = useState(false); const [previewCode, setPreviewCode] = useState(''); const [dnclValidating, setDnclValidating] = useState(false); @@ -821,10 +824,11 @@ const RubyTab = (props) => { } }, []); - // A pattern of settings picked from the menu (docs/dncl/design.md 4 章): + // A pattern of settings picked in the popup of 「問題の約束」 (docs/dncl/design.md 4 章): // the sentences at the top are written for it, and the program again by // them, so it means the same. One undo step takes it back. const handleSelectSettingsPattern = useCallback((patternId) => { + setShowProblemSettingsModal(false); if (!editorRef.current || !getPrism()) return; replaceEditorText( editorRef.current, @@ -833,6 +837,21 @@ const RubyTab = (props) => { ); }, []); + const handleOpenProblemSettings = useCallback(() => { + handleDismissBubbleStable(); + setShowProblemSettingsModal(true); + }, [handleDismissBubbleStable]); + + const handleCloseProblemSettings = useCallback(() => { + setShowProblemSettingsModal(false); + }, []); + + // The rules the program is written by, read from the sentences at its top (#2606). + const problemSettingsPatternId = useMemo( + () => (dnclMode ? dnclSettingsPatternId(dnclDisplayCode) : null), + [dnclMode, dnclDisplayCode], + ); + const handleInsertClass = useCallback(() => { if (!editorRef.current) return; const code = editorRef.current.getValue() || ''; @@ -2155,14 +2174,21 @@ const RubyTab = (props) => { onCopyProblemForm={handleCopyProblemForm} readMode={problemFormShown} onToggleReadMode={handleToggleReadMode} - onSelectSettingsPattern={handleSelectSettingsPattern} locale={locale} /> {/* The name of the language over the editor of the Japanese tab (docs/dncl/design.md 1 章) */} {(dnclMode || dnclValidating) && (
- {intl.formatMessage(languageBandMessages.japanese)} + + {intl.formatMessage(languageBandMessages.japanese)} + + {dnclMode && ( + + )}
)}
{ onRequestClose={handleCloseAutoCorrectSettings} /> )} + {showProblemSettingsModal && ( + + )} {showScriptPreview && ( { return pattern ? pattern.id : null; }; +/** + * The sentences a pattern writes at the top of a program (shown in the popup + * of 「問題の約束」 before they are written). + * @param {string} patternId - The id of the pattern. + * @returns {Array} The sentences, with their comment mark. + */ +const dnclSettingsSentences = (patternId) => { + const pattern = SETTINGS_PATTERNS.find((p) => p.id === patternId); + if (!pattern) return []; + return withSettings('', pattern.settings) + .split('\n') + .filter((line) => line !== ''); +}; + /** * The same program written by the settings of a pattern: the sentences at the * top are written for the pattern and the program is written again by them, so @@ -55,4 +69,10 @@ const dnclWithIndexFromOne = (dncl) => { return withSettings(dncl, { ...settings, indexBase: 1 }); }; -export { dnclSettingsPatternId, dnclWithIndexFromOne, dnclWithSettingsPattern, SETTINGS_PATTERNS }; +export { + dnclSettingsPatternId, + dnclSettingsSentences, + dnclWithIndexFromOne, + dnclWithSettingsPattern, + SETTINGS_PATTERNS, +}; diff --git a/packages/scratch-gui/src/locales/en.js b/packages/scratch-gui/src/locales/en.js index 7996c83a71d..c7fcacde4eb 100644 --- a/packages/scratch-gui/src/locales/en.js +++ b/packages/scratch-gui/src/locales/en.js @@ -1752,13 +1752,26 @@ export default { 'gui.rubyToolbar.autoCorrectSwitch': 'Auto-correct', 'gui.rubyToolbar.rulesSwitch': 'Line numbers and rules', 'gui.rubyToolbar.rulesSwitchTitle': 'Show the line numbers and the rules, in the form of the test questions', - 'gui.rubyToolbar.problemSettingsHeading': 'Rules of the problem', + 'gui.problemSettingsModal.title': 'Rules of the problem', + 'gui.problemSettingsModal.explanation': + 'A problem of the common test first tells its rules (whether the indices of the arrays start at 0 or at 1, and so on). Pick the rules of the problem you solve.', + 'gui.problemSettingsModal.patternExample': 'The form of the examples (indices from 0)', + 'gui.problemSettingsModal.patternIndexFromOne': 'A problem whose indices start at 1', + 'gui.problemSettingsModal.example': 'When {array}, {item} is {value}', + 'gui.problemSettingsModal.sentencesLabel': 'The sentences written at the top of the program:', + 'gui.problemSettingsModal.noSentences': '(Nothing is written. The sentences of the rules now are removed.)', + 'gui.problemSettingsModal.othersKept': 'The other comments stay as they are.', + 'gui.problemSettingsModal.cancel': 'Cancel', + 'gui.problemSettingsModal.ok': 'OK', + 'gui.problemSettingsBand.label': 'Rules of the problem: {rules}', + 'gui.problemSettingsBand.example': 'indices from 0', + 'gui.problemSettingsBand.indexFromOne': 'indices from 1', + 'gui.problemSettingsBand.other': 'other', + 'gui.problemSettingsBand.change': 'Change', 'gui.rubyToolbar.previewRubyOfJapanese': 'Preview the program in Ruby', 'gui.rubyToolbar.saveJapaneseProgram': 'Save the Japanese program (.txt)', 'gui.rubyTab.dnclIndexSettingConfirm': 'The pasted program says that its array indices start at 1. Write "すべての配列の添字は 1 から始まる。" at the top of the program, so that the indices start at 1?', - 'gui.rubyToolbar.settingsPatternExample': 'The form of the examples (indices from 0)', - 'gui.rubyToolbar.settingsPatternIndexFromOne': 'A problem whose indices start at 1', 'gui.rubyTab.dnclForbiddenPrefixError': '"{name}" cannot be used in a variable in the Japanese tab.', 'gui.rubyTab.dnclPostTestLoopError': 'A post-test loop (a loop that runs once before it checks the condition) cannot be written in Japanese. Write the first run before the loop, then make it a "〜の間繰り返す" loop. You can write it in the Ruby tab.', diff --git a/packages/scratch-gui/src/locales/ja-Hira.js b/packages/scratch-gui/src/locales/ja-Hira.js index 628a935b1ba..c028968342d 100644 --- a/packages/scratch-gui/src/locales/ja-Hira.js +++ b/packages/scratch-gui/src/locales/ja-Hira.js @@ -2132,13 +2132,26 @@ export default { 'gui.rubyToolbar.autoCorrectSwitch': 'じどうちかん', 'gui.rubyToolbar.rulesSwitch': 'ぎょうばんごうとけいせん', 'gui.rubyToolbar.rulesSwitchTitle': 'ぎょうばんごうとけいせんをひょうじして、もんだいとおなじかたちでよむ', - 'gui.rubyToolbar.problemSettingsHeading': 'もんだいのやくそく', + 'gui.problemSettingsModal.title': 'もんだいのやくそく', + 'gui.problemSettingsModal.explanation': + 'きょうつうテストのもんだいは、はじめにやくそく(はいれつのそえじが 0 からはじまるか 1 からはじまるか など)をかきます。とくもんだいのやくそくにあわせてえらんでください。', + 'gui.problemSettingsModal.patternExample': 'れいじのかたち(そえじは 0 から)', + 'gui.problemSettingsModal.patternIndexFromOne': 'そえじが 1 からはじまるもんだい', + 'gui.problemSettingsModal.example': '{array} のとき {item} は {value}', + 'gui.problemSettingsModal.sentencesLabel': 'プログラムのせんとうにはいるぶん:', + 'gui.problemSettingsModal.noSentences': '(なにもはいりません。いまのやくそくのぶんはきえます)', + 'gui.problemSettingsModal.othersKept': 'ほかのコメントはそのままのこります。', + 'gui.problemSettingsModal.cancel': 'キャンセル', + 'gui.problemSettingsModal.ok': 'けってい', + 'gui.problemSettingsBand.label': 'もんだいのやくそく: {rules}', + 'gui.problemSettingsBand.example': 'そえじは 0 から', + 'gui.problemSettingsBand.indexFromOne': 'そえじは 1 から', + 'gui.problemSettingsBand.other': 'そのほか', + 'gui.problemSettingsBand.change': 'かえる', 'gui.rubyToolbar.previewRubyOfJapanese': 'ルビーになおしたものをかくにん', 'gui.rubyToolbar.saveJapaneseProgram': 'にほんごのプログラムをほぞん(.txt)', 'gui.rubyTab.dnclIndexSettingConfirm': 'はりつけたプログラムには、はいれつのそえじは 1 からはじまるとかいてあります。プログラムのはじめに「すべての配列の添字は 1 から始まる。」とかいて、そえじが 1 からはじまるせっていにしますか?', - 'gui.rubyToolbar.settingsPatternExample': 'れいじのかたち(そえじは 0 から)', - 'gui.rubyToolbar.settingsPatternIndexFromOne': 'そえじが 1 からはじまるもんだい', 'gui.rubyTab.dnclForbiddenPrefixError': 'にほんごタブでは、へんすうに「{name}」はつかえません', 'gui.rubyTab.dnclPostTestLoopError': 'あとではんていするくりかえし(さきに 1 かいうごかしてからじょうけんをたしかめるくりかえし)は、にほんごではかけません。さいしょの 1 かいをループのまえにかいてから、「〜のあいだくりかえす」にしてください。ルビータブではかけます。', diff --git a/packages/scratch-gui/src/locales/ja.js b/packages/scratch-gui/src/locales/ja.js index a7cb63f294f..7939eb27eb6 100644 --- a/packages/scratch-gui/src/locales/ja.js +++ b/packages/scratch-gui/src/locales/ja.js @@ -2081,13 +2081,26 @@ export default { 'gui.rubyToolbar.autoCorrectSwitch': '自動置換', 'gui.rubyToolbar.rulesSwitch': '行番号と罫線', 'gui.rubyToolbar.rulesSwitchTitle': '行番号と罫線を表示して、問題と同じ形で読む', - 'gui.rubyToolbar.problemSettingsHeading': '問題の約束', + 'gui.problemSettingsModal.title': '問題の約束', + 'gui.problemSettingsModal.explanation': + '共通テストの問題は、はじめに約束(配列の添字が 0 から始まるか 1 から始まるか など)を書きます。解く問題の約束に合わせて選んでください。', + 'gui.problemSettingsModal.patternExample': '例示の形(添字は 0 から)', + 'gui.problemSettingsModal.patternIndexFromOne': '添字が 1 から始まる問題', + 'gui.problemSettingsModal.example': '{array} のとき {item} は {value}', + 'gui.problemSettingsModal.sentencesLabel': 'プログラムの先頭に入る文:', + 'gui.problemSettingsModal.noSentences': '(何も入りません。いまの約束の文は消えます)', + 'gui.problemSettingsModal.othersKept': 'ほかのコメントはそのまま残ります。', + 'gui.problemSettingsModal.cancel': 'キャンセル', + 'gui.problemSettingsModal.ok': '決定', + 'gui.problemSettingsBand.label': '問題の約束: {rules}', + 'gui.problemSettingsBand.example': '添字は 0 から', + 'gui.problemSettingsBand.indexFromOne': '添字は 1 から', + 'gui.problemSettingsBand.other': 'そのほか', + 'gui.problemSettingsBand.change': '変える', 'gui.rubyToolbar.previewRubyOfJapanese': 'ルビーに直したものを確認', 'gui.rubyToolbar.saveJapaneseProgram': '日本語のプログラムを保存(.txt)', 'gui.rubyTab.dnclIndexSettingConfirm': '貼り付けたプログラムには、配列の添字は 1 から始まると書いてあります。プログラムの冒頭に「すべての配列の添字は 1 から始まる。」と書いて、添字が 1 から始まる設定にしますか?', - 'gui.rubyToolbar.settingsPatternExample': '例示の形(添字は 0 から)', - 'gui.rubyToolbar.settingsPatternIndexFromOne': '添字が 1 から始まる問題', 'gui.rubyTab.dnclForbiddenPrefixError': '日本語タブでは変数に「{name}」は使えません', 'gui.rubyTab.dnclPostTestLoopError': '後判定の繰り返し(先に 1 回動かしてから条件を確かめる繰り返し)は日本語では書けません。最初の 1 回をループの前に書いてから、「〜の間繰り返す」にしてください。ルビータブでは書けます。', diff --git a/packages/scratch-gui/test/integration/dncl-settings-pattern.test.js b/packages/scratch-gui/test/integration/dncl-settings-pattern.test.js index 0ba8147141f..53fc769e775 100644 --- a/packages/scratch-gui/test/integration/dncl-settings-pattern.test.js +++ b/packages/scratch-gui/test/integration/dncl-settings-pattern.test.js @@ -1,8 +1,9 @@ import path from 'path'; import SeleniumHelper from '../helpers/selenium-helper'; -// The patterns of settings of the Japanese mode (Issue #1757): picking one in -// the more menu writes the sentences at the top and the same program by them. +// The patterns of settings of the Japanese mode (Issue #1757, #2606): picking one in +// the popup of 「問題の約束」 (「変える」 of the green band) writes the sentences at the +// top and the same program by them. // The program is written for this test; no question of the test is used. const seleniumHelper = new SeleniumHelper(); const { getDriver, getLogs, loadUri } = seleniumHelper; @@ -20,15 +21,21 @@ const editorValue = (d) => d.executeScript('return window.monacoEditor.getValue( const waitFor = (d, check, message) => d.wait(check, 10000, message); +const bandText = (d) => + d.executeScript('return document.querySelector(\'[data-testid="ruby-tab-problem-settings"]\').textContent'); + /** - * Open the more menu and pick an item of it, once the menu shows it. + * Open the popup from the green band, pick a pattern and decide. * @param {object} d - The driver. - * @param {string} testId - The item. + * @param {string} id - The pattern (`example`, `index-from-one`). */ -const pickMenuItem = async (d, testId) => { - await clickByTestId(d, 'ruby-toolbar-more-menu'); - await waitFor(d, () => existsByTestId(d, testId), `The menu did not show ${testId}`); - await clickByTestId(d, testId); +const pickPattern = async (d, id) => { + await clickByTestId(d, 'ruby-tab-problem-settings-change'); + const testId = `problem-settings-modal-pattern-${id}`; + await waitFor(d, () => existsByTestId(d, testId), 'The popup did not open'); + await d.executeScript(`document.querySelector('[data-testid="${testId}"] input').click()`); + await clickByTestId(d, 'problem-settings-modal-ok'); + await waitFor(d, async () => !(await existsByTestId(d, testId)), 'The popup did not close'); }; let driver; @@ -54,7 +61,8 @@ describe('Japanese mode: the patterns of settings', () => { ); await driver.executeScript(`window.monacoEditor.setValue(${JSON.stringify(CODE)});`); - await pickMenuItem(driver, 'ruby-toolbar-menu-settings-pattern-index-from-one'); + expect(await bandText(driver)).toContain('添字は 0 から'); + await pickPattern(driver, 'index-from-one'); await waitFor( driver, async () => (await editorValue(driver)).startsWith('# すべての配列の添字は 1 から始まる。'), @@ -65,18 +73,12 @@ describe('Japanese mode: the patterns of settings', () => { expect(value).toContain('# 「and」は「かつ」を意味する論理演算子であり,'); expect(value.endsWith('A = [5, 6]\n表示する(A[1])')).toBe(true); - await clickByTestId(driver, 'ruby-toolbar-more-menu'); await waitFor( driver, - () => existsByTestId(driver, 'ruby-toolbar-menu-settings-pattern-example'), - 'The menu did not open again', + async () => (await bandText(driver)).includes('添字は 1 から'), + 'The band did not show the rules', ); - expect( - await driver.executeScript( - 'return document.querySelector(\'[data-testid="ruby-toolbar-menu-settings-pattern-index-from-one"]\').getAttribute("aria-checked")', - ), - ).toBe('true'); - await clickByTestId(driver, 'ruby-toolbar-menu-settings-pattern-example'); + await pickPattern(driver, 'example'); await waitFor( driver, async () => !(await editorValue(driver)).includes('添字は 1 から始まる'), diff --git a/packages/scratch-gui/test/unit/components/problem-settings-modal.test.jsx b/packages/scratch-gui/test/unit/components/problem-settings-modal.test.jsx new file mode 100644 index 00000000000..3835be2fa96 --- /dev/null +++ b/packages/scratch-gui/test/unit/components/problem-settings-modal.test.jsx @@ -0,0 +1,114 @@ +/* eslint-env jest */ +// 日本語タブの「問題の約束」のポップアップと、緑の帯の「変える」(#2606、docs/dncl/README.md) +import '@testing-library/jest-dom'; +import { fireEvent, render } from '@testing-library/react'; +import React from 'react'; +import { IntlProvider } from 'react-intl'; +import ProblemSettingsBandItem from '../../../src/components/problem-settings-modal/problem-settings-band-item.jsx'; +import ProblemSettingsModal from '../../../src/components/problem-settings-modal/problem-settings-modal.jsx'; +import ja from '../../../src/locales/ja'; + +jest.mock('../../../src/containers/modal.jsx', () => { + const PropTypes = require('prop-types'); + const MockModal = ({ children, contentLabel }) => ( +
+ {children} +
+ ); + MockModal.propTypes = { children: PropTypes.node, contentLabel: PropTypes.string }; + return MockModal; +}); + +const byTestId = (container, id) => container.querySelector(`[data-testid="${id}"]`); + +const renderModal = (overrides = {}) => { + const props = { currentPatternId: 'example', onDecide: jest.fn(), onRequestClose: jest.fn(), ...overrides }; + const utils = render( + + + , + ); + return { ...utils, props }; +}; + +const radio = (container, id) => byTestId(container, `problem-settings-modal-pattern-${id}`).querySelector('input'); + +describe('ProblemSettingsModal', () => { + test('shows the explanation and the two patterns with an example each', () => { + const { container } = renderModal(); + expect(container).toHaveTextContent('解く問題の約束に合わせて選んでください'); + expect(byTestId(container, 'problem-settings-modal-pattern-example')).toHaveTextContent( + '例示の形(添字は 0 から)', + ); + expect(byTestId(container, 'problem-settings-modal-pattern-example')).toHaveTextContent('20'); + expect(byTestId(container, 'problem-settings-modal-pattern-index-from-one')).toHaveTextContent( + '添字が 1 から始まる問題', + ); + expect(byTestId(container, 'problem-settings-modal-pattern-index-from-one')).toHaveTextContent('10'); + }); + + test('the pattern the program is written by is chosen first', () => { + const { container } = renderModal({ currentPatternId: 'indexFromOne' }); + expect(radio(container, 'index-from-one')).toBeChecked(); + expect(radio(container, 'example')).not.toBeChecked(); + }); + + test('shows the sentences the chosen pattern writes at the top', () => { + const { container } = renderModal(); + expect(byTestId(container, 'problem-settings-modal-sentences')).toHaveTextContent('何も入りません'); + fireEvent.click(radio(container, 'index-from-one')); + expect(byTestId(container, 'problem-settings-modal-sentences')).toHaveTextContent( + '# すべての配列の添字は 1 から始まる。', + ); + expect(container).toHaveTextContent('ほかのコメントはそのまま残ります。'); + }); + + test('deciding tells the chosen pattern', () => { + const { container, props } = renderModal(); + fireEvent.click(radio(container, 'index-from-one')); + fireEvent.click(byTestId(container, 'problem-settings-modal-ok')); + expect(props.onDecide).toHaveBeenCalledWith('indexFromOne'); + }); + + test('cancelling changes nothing', () => { + const { container, props } = renderModal(); + fireEvent.click(radio(container, 'index-from-one')); + fireEvent.click(byTestId(container, 'problem-settings-modal-cancel')); + expect(props.onDecide).not.toHaveBeenCalled(); + expect(props.onRequestClose).toHaveBeenCalledTimes(1); + }); + + test('settings that are no pattern have nothing chosen and cannot be decided', () => { + const { container } = renderModal({ currentPatternId: null }); + expect(radio(container, 'example')).not.toBeChecked(); + expect(radio(container, 'index-from-one')).not.toBeChecked(); + expect(byTestId(container, 'problem-settings-modal-ok')).toBeDisabled(); + }); +}); + +describe('ProblemSettingsBandItem', () => { + const renderItem = (overrides = {}) => { + const props = { patternId: 'example', onChange: jest.fn(), ...overrides }; + const utils = render( + + + , + ); + return { ...utils, props }; + }; + + test.each([ + ['example', '問題の約束: 添字は 0 から'], + ['indexFromOne', '問題の約束: 添字は 1 から'], + [null, '問題の約束: そのほか'], + ])('shows the rules of %s', (patternId, text) => { + const { container } = renderItem({ patternId }); + expect(byTestId(container, 'ruby-tab-problem-settings')).toHaveTextContent(text); + }); + + test('「変える」 opens the popup', () => { + const { container, props } = renderItem(); + fireEvent.click(byTestId(container, 'ruby-tab-problem-settings-change')); + expect(props.onChange).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/scratch-gui/test/unit/components/ruby-toolbar-rules-switch.test.jsx b/packages/scratch-gui/test/unit/components/ruby-toolbar-rules-switch.test.jsx index 67cf65800d6..8e500cb0b5b 100644 --- a/packages/scratch-gui/test/unit/components/ruby-toolbar-rules-switch.test.jsx +++ b/packages/scratch-gui/test/unit/components/ruby-toolbar-rules-switch.test.jsx @@ -106,9 +106,6 @@ describe('ruby-toolbar: the more menu', () => { 'ruby-toolbar-menu-copy-problem-form', 'ruby-toolbar-menu-preview', 'ruby-toolbar-menu-download-japanese', - 'ruby-toolbar-menu-settings-heading', - 'ruby-toolbar-menu-settings-pattern-example', - 'ruby-toolbar-menu-settings-pattern-index-from-one', 'ruby-toolbar-menu-auto-correct-settings', ]); }); @@ -123,8 +120,6 @@ describe('ruby-toolbar: the more menu', () => { expect(byTestId(container, 'ruby-toolbar-menu-download-japanese')).toHaveTextContent( '日本語のプログラムを保存(.txt)', ); - expect(byTestId(container, 'ruby-toolbar-menu-settings-heading')).toHaveTextContent('問題の約束'); - expect(byTestId(container, 'ruby-toolbar-menu-settings-pattern-example')).not.toHaveTextContent('設定'); }); test('saving the Japanese program calls its handler and closes the menu', () => { diff --git a/packages/scratch-gui/test/unit/components/ruby-toolbar-settings-pattern.test.jsx b/packages/scratch-gui/test/unit/components/ruby-toolbar-settings-pattern.test.jsx deleted file mode 100644 index bab9cd19ebc..00000000000 --- a/packages/scratch-gui/test/unit/components/ruby-toolbar-settings-pattern.test.jsx +++ /dev/null @@ -1,74 +0,0 @@ -/* eslint-env jest */ -// 日本語モードのメニューで、よくある設定のパターンを選べること(#1757、docs/dncl/design.md 4 章) -import '@testing-library/jest-dom'; -import { fireEvent, render } from '@testing-library/react'; -import React from 'react'; -import { IntlProvider } from 'react-intl'; -import RubyToolbar from '../../../src/components/ruby-toolbar/ruby-toolbar.jsx'; -import ja from '../../../src/locales/ja'; - -const INDEX_FROM_ONE = [ - '# すべての配列の添字は 1 から始まる。', - '# 「and」は「かつ」を意味する論理演算子であり,左右の式がともに真のときにだけ真となる。', - '# 「or」は「または」を意味する論理演算子であり,左右の式の少なくとも一方が真のときに真となる。', - '# 「not」は「でない」を意味する論理演算子であり,右の式が偽のときにだけ真となる。', - 'A = [1]', -].join('\n'); - -const renderToolbar = (overrides = {}) => { - const props = { - locale: 'ja', - onSelectTarget: jest.fn(), - onDismissBubble: jest.fn(), - onSelectSettingsPattern: jest.fn(), - dnclMode: true, - editorRef: { getValue: () => 'A = [1]' }, - ...overrides, - }; - const utils = render( - - - , - ); - fireEvent.click(utils.container.querySelector('[data-testid="ruby-toolbar-more-menu"]')); - return { ...utils, props }; -}; - -const item = (container, id) => container.querySelector(`[data-testid="ruby-toolbar-menu-settings-pattern-${id}"]`); - -describe('ruby-toolbar settings patterns of the Japanese mode', () => { - test('the menu has the two patterns in the Japanese mode', () => { - const { container } = renderToolbar(); - expect(item(container, 'example')).toHaveTextContent(ja['gui.rubyToolbar.settingsPatternExample']); - expect(item(container, 'index-from-one')).toHaveTextContent( - ja['gui.rubyToolbar.settingsPatternIndexFromOne'], - ); - }); - - test('the menu has no pattern out of the Japanese mode', () => { - const { container } = renderToolbar({ dnclMode: false }); - expect(item(container, 'example')).toBeNull(); - expect(item(container, 'index-from-one')).toBeNull(); - }); - - test('the pattern the program is written by is checked', () => { - const { container } = renderToolbar({ editorRef: { getValue: () => INDEX_FROM_ONE } }); - expect(item(container, 'index-from-one')).toHaveAttribute('aria-checked', 'true'); - expect(item(container, 'example')).toHaveAttribute('aria-checked', 'false'); - }); - - test('a program with no sentence is the form of 例示', () => { - const { container } = renderToolbar(); - expect(item(container, 'example')).toHaveAttribute('aria-checked', 'true'); - }); - - test.each([ - ['example', 'example'], - ['index-from-one', 'indexFromOne'], - ])('picking %s tells the pattern and closes the menu', (testId, patternId) => { - const { container, props } = renderToolbar(); - fireEvent.click(item(container, testId)); - expect(props.onSelectSettingsPattern).toHaveBeenCalledWith(patternId); - expect(item(container, 'example')).toBeNull(); - }); -}); diff --git a/packages/scratch-gui/test/unit/lib/dncl/dncl-settings.test.js b/packages/scratch-gui/test/unit/lib/dncl/dncl-settings.test.js index b139d075662..608307b0db6 100644 --- a/packages/scratch-gui/test/unit/lib/dncl/dncl-settings.test.js +++ b/packages/scratch-gui/test/unit/lib/dncl/dncl-settings.test.js @@ -1,5 +1,6 @@ import { dnclSettingsPatternId, + dnclSettingsSentences, dnclWithIndexFromOne, dnclWithSettingsPattern, } from '../../../../src/lib/dncl/dncl-settings'; @@ -51,11 +52,30 @@ describe('dnclWithSettingsPattern', () => { expect(dnclWithSettingsPattern(dncl, 'indexFromOne')).toBe([INDEX_FROM_ONE, ...LOGIC_NOTES, dncl].join('\n')); }); + test('the other comments at the top stay', () => { + const dncl = [INDEX_FROM_ONE, ...LOGIC_NOTES, '# 点数の合計', 'A = [5, 6]'].join('\n'); + expect(dnclWithSettingsPattern(dncl, 'example')).toBe('# 点数の合計\nA = [5, 6]'); + }); + test('an unknown pattern changes nothing', () => { expect(dnclWithSettingsPattern('A = [1]', 'nothing')).toBe('A = [1]'); }); }); +describe('dnclSettingsSentences', () => { + test('the form of 例示 writes no sentence', () => { + expect(dnclSettingsSentences('example')).toEqual([]); + }); + + test('indexes from 1 writes its sentence and the logical operators', () => { + expect(dnclSettingsSentences('indexFromOne')).toEqual([INDEX_FROM_ONE, ...LOGIC_NOTES]); + }); + + test('an unknown pattern writes no sentence', () => { + expect(dnclSettingsSentences('nothing')).toEqual([]); + }); +}); + describe('dnclWithIndexFromOne', () => { test('writes the sentence at the top and keeps the indexes', () => { expect(dnclWithIndexFromOne('# 配列の添字は1から始まるものとする\nA = [1, 2]\n表示する(A[1])')).toBe(