@kubohiroya/turbowarp-plus-editor-workbench 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,17 @@
1
1
  import { dialogAction, dialogActions } from '@kubohiroya/turbowarp-plus-editor-windows';
2
+ import { checkSaveNameInput, isValidSaveName, saveNameTexts, suggestSaveName } from './save-name.js';
3
+ export { askSaveName, isValidSaveName, suggestSaveName } from './save-name.js';
4
+ /**
5
+ * The titles of the dialogs this package fills, by the File menu command that opens them: `save` is "Save Project"
6
+ * (the save form for a project with no save target yet), `save-as` is "Save a Copy of the Project" and `new` is
7
+ * "Create New Project".
8
+ */
9
+ export function projectFileDialogTitle(command, locale) {
10
+ const ja = locale.startsWith('ja');
11
+ return command === 'new' ? (ja ? '新しいプロジェクトを作成' : 'Create New Project') :
12
+ command === 'save' ? (ja ? 'プロジェクトを保存' : 'Save Project') :
13
+ (ja ? 'プロジェクトのコピーを保存' : 'Save a Copy of the Project');
14
+ }
2
15
  /**
3
16
  * Saving over the last file or into the project folder first collects edits held by other windows,
4
17
  * as Save As does, so a save that does not move the focus to the editor misses nothing. A failed
@@ -20,11 +33,25 @@ export function collectBeforeSaving(storage, folder, collect) {
20
33
  folder: folder?.save ? { ...folder, save: first(folder.save) } : folder
21
34
  };
22
35
  }
23
- export function projectSaveShortcut(storage, folder, saveAs) {
36
+ /**
37
+ * Save Project and Ctrl/⌘+S: overwrite the project's file or save into its folder; with no save target yet, run
38
+ * `saveNew`, which opens the save form whose result becomes the target. Pass the save-to-a-new-place action here,
39
+ * never Save a Copy, or a project without a target would only ever be copied.
40
+ */
41
+ export function projectSaveShortcut(storage, folder, saveNew) {
24
42
  if (storage.canSave)
25
- (storage.overwrite || folder?.save || saveAs)?.();
43
+ (storage.overwrite || folder?.save || saveNew)?.();
26
44
  }
27
- export async function saveProjectAs(storage, name, { current, unchanged, serialize, committed, collect }) {
45
+ /**
46
+ * Saves the project as an SB3: picks the file (or downloads it), collects edits held by other windows, serializes
47
+ * it under the file's title and writes it, then runs `committed`.
48
+ *
49
+ * - `mode: 'copy'` (the default, Save a Copy of the Project): the project stays as it was; its file, folder, title
50
+ * and unsaved state do not change. `storage.copied` runs last.
51
+ * - `mode: 'save'` (Save Project with no save target yet): the file becomes the project's save target through
52
+ * `storage.finish(handle, title, unchanged())`.
53
+ */
54
+ export async function saveProjectAs(storage, name, { current, unchanged, serialize, committed, collect, mode = 'copy' }) {
28
55
  if (!storage.canSave || !current())
29
56
  return false;
30
57
  const filename = name + '.sb3';
@@ -48,7 +75,10 @@ export async function saveProjectAs(storage, name, { current, unchanged, seriali
48
75
  if (!current())
49
76
  return false;
50
77
  committed();
51
- storage.finish(handle, title, unchanged());
78
+ if (mode === 'save')
79
+ storage.finish(handle, title, unchanged ? unchanged() : true);
80
+ else
81
+ storage.copied?.(handle, title);
52
82
  return true;
53
83
  }
54
84
  catch (error) {
@@ -56,8 +86,7 @@ export async function saveProjectAs(storage, name, { current, unchanged, seriali
56
86
  return false;
57
87
  }
58
88
  }
59
- const validRepositoryName = (name) => /^[A-Za-z0-9_.-]{1,100}$/.test(name) &&
60
- name !== '.' && name !== '..' && !/\.git$/i.test(name);
89
+ const validRepositoryName = isValidSaveName;
61
90
  function parseGitHubRepositoryUrl(url) {
62
91
  const match = /^https:\/\/github\.com\/([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9_.-]{1,104})\/?$/i.exec(url.trim());
63
92
  const name = match?.[2].replace(/\.git$/iu, '');
@@ -93,6 +122,9 @@ function createGitHubFields(document, label, provider, report) {
93
122
  const name = document.createElement('input');
94
123
  name.name = 'github-name';
95
124
  name.maxLength = 100;
125
+ // A name the person typed is kept; until then the name follows the suggestion from the form.
126
+ let nameEdited = false;
127
+ name.addEventListener('input', () => { nameEdited = true; });
96
128
  appendField(panel, label('リポジトリ名', 'Repository name'), name);
97
129
  const url = document.createElement('input');
98
130
  url.name = 'github-url';
@@ -142,6 +174,10 @@ function createGitHubFields(document, label, provider, report) {
142
174
  return {
143
175
  panel,
144
176
  get connected() { return account !== null; },
177
+ suggestName(value) {
178
+ if (!nameEdited)
179
+ name.value = value;
180
+ },
145
181
  async connect(open, interaction) {
146
182
  const result = await provider.connectForCreation(interaction);
147
183
  if (!open() || !result)
@@ -161,6 +197,7 @@ function createGitHubFields(document, label, provider, report) {
161
197
  throw invalidDraft(label('https://github.com/所有者/リポジトリ名 の形式で入力してください。', 'Enter a URL in the form https://github.com/owner/repository.'));
162
198
  requestedOwner = parsed.owner;
163
199
  name.value = parsed.name;
200
+ nameEdited = true;
164
201
  url.value = '';
165
202
  if (account)
166
203
  fillOwners(account);
@@ -626,3 +663,317 @@ export function renderExtensionsForm(document, locale, close, add, { list, chang
626
663
  };
627
664
  return form;
628
665
  }
666
+ const deviceFolderReason = (label) => label('このブラウザーでは端末のフォルダを開けません。Chrome か Edge を使うか、ブラウザーに保存したフォルダを開いてください。', 'This browser cannot open folders on your device. Use Chrome or Edge, or open a folder saved in this browser.');
667
+ let newProjectForms = 0;
668
+ /**
669
+ * The Create New Project… form. The in-memory project is selected first, so Create alone does what Create New
670
+ * Project always did. A folder or a GitHub repository also takes a title, and a save name when the title cannot be
671
+ * used as one. `close` receives `created`, or `cancelled` when the person dismissed the form.
672
+ */
673
+ export function renderNewProjectForm(document, locale, options, close) {
674
+ const label = (ja, en) => locale.startsWith('ja') ? ja : en;
675
+ const id = `tw-new-project-${++newProjectForms}`;
676
+ const { browserFolders, deviceFolders, github: githubProvider } = options;
677
+ const workingCopies = [...(deviceFolders !== undefined ? ['device'] : []), ...(browserFolders ? ['browser'] : [])];
678
+ const form = document.createElement('form');
679
+ form.setAttribute('data-new-project-form', '');
680
+ const fields = document.createElement('div');
681
+ const destinations = document.createElement('fieldset');
682
+ const destinationLegend = document.createElement('legend');
683
+ destinationLegend.textContent = label('作成先', 'Create in');
684
+ destinations.append(destinationLegend);
685
+ const radio = (parent, group, value, title, reason) => {
686
+ const input = document.createElement('input');
687
+ input.type = 'radio';
688
+ input.name = group;
689
+ input.value = value;
690
+ const row = document.createElement('label');
691
+ row.append(input, title);
692
+ parent.append(row);
693
+ if (reason) {
694
+ input.disabled = true;
695
+ row.title = reason;
696
+ const note = document.createElement('p');
697
+ note.id = `${id}-${group}-${value}-reason`;
698
+ note.textContent = reason;
699
+ input.setAttribute('aria-describedby', note.id);
700
+ parent.append(note);
701
+ }
702
+ return input;
703
+ };
704
+ const unavailable = deviceFolders === false ? deviceFolderReason(label) : undefined;
705
+ radio(destinations, 'destination', 'memory', label('メモリ上の SB3', 'In memory (SB3)')).checked = true;
706
+ if (browserFolders)
707
+ radio(destinations, 'destination', 'browser', label('ブラウザー内のプロジェクトフォルダ', 'Project folder in this browser'));
708
+ if (deviceFolders !== undefined)
709
+ radio(destinations, 'destination', 'device', label('手元のプロジェクトフォルダ', 'Project folder on this device'), unavailable);
710
+ if (githubProvider && workingCopies.length)
711
+ radio(destinations, 'destination', 'github', label('Git のリモートリポジトリ', 'Git remote repository (GitHub)'));
712
+ fields.append(destinations);
713
+ const title = document.createElement('input');
714
+ title.name = 'title';
715
+ title.maxLength = 100;
716
+ title.value = options.defaultTitle ?? label('新しいプロジェクト', 'Untitled Project');
717
+ const titleField = appendField(fields, label('作品名', 'Project title'), title);
718
+ const texts = saveNameTexts(locale);
719
+ const saveNameBlock = document.createElement('div');
720
+ const saveNameExplanation = document.createElement('p');
721
+ saveNameExplanation.textContent = texts.explanation;
722
+ const saveName = document.createElement('input');
723
+ saveName.name = 'save-name';
724
+ saveName.maxLength = 100;
725
+ saveName.autocomplete = 'off';
726
+ saveName.spellcheck = false;
727
+ const allowed = document.createElement('p');
728
+ allowed.id = `${id}-save-name-allowed`;
729
+ allowed.textContent = texts.allowed;
730
+ saveName.setAttribute('aria-describedby', allowed.id);
731
+ const saveNameError = document.createElement('p');
732
+ saveNameError.setAttribute('role', 'alert');
733
+ saveNameBlock.append(saveNameExplanation);
734
+ const saveNameField = appendField(saveNameBlock, texts.title, saveName);
735
+ saveNameBlock.append(allowed, saveNameError);
736
+ fields.append(saveNameBlock);
737
+ let saveNameEdited = false;
738
+ const status = document.createElement('p');
739
+ status.setAttribute('role', 'alert');
740
+ const report = (message) => { status.textContent = message; };
741
+ const progress = document.createElement('p');
742
+ progress.setAttribute('role', 'status');
743
+ const github = githubProvider && workingCopies.length ?
744
+ createGitHubFields(document, label, githubProvider, report) : null;
745
+ const workingCopy = document.createElement('fieldset');
746
+ if (github) {
747
+ const legend = document.createElement('legend');
748
+ legend.textContent = label('作業用の写しの置き場所', 'Keep the working copy');
749
+ workingCopy.append(legend);
750
+ if (deviceFolders !== undefined)
751
+ radio(workingCopy, 'working-copy', 'device', label('手元のプロジェクトフォルダ', 'Project folder on this device'), unavailable);
752
+ if (browserFolders)
753
+ radio(workingCopy, 'working-copy', 'browser', label('ブラウザー内のプロジェクトフォルダ', 'Project folder in this browser'));
754
+ const preferred = [...workingCopy.querySelectorAll('input')].find(input => !input.disabled);
755
+ if (preferred)
756
+ preferred.checked = true;
757
+ github.panel.append(workingCopy);
758
+ fields.append(github.panel);
759
+ }
760
+ const review = document.createElement('div');
761
+ const device = document.createElement('div');
762
+ const controller = new AbortController();
763
+ let dismissed = false;
764
+ const open = () => !dismissed && form.isConnected;
765
+ const interaction = {
766
+ signal: controller.signal,
767
+ deviceCode({ userCode, verificationUri }) {
768
+ if (!open())
769
+ return;
770
+ const link = document.createElement('a');
771
+ link.href = verificationUri;
772
+ link.target = '_blank';
773
+ link.rel = 'noopener noreferrer';
774
+ link.textContent = label('GitHub で認証する', 'Authorize on GitHub');
775
+ const code = document.createElement('strong');
776
+ code.textContent = userCode;
777
+ device.replaceChildren(link, ' ', code);
778
+ }
779
+ };
780
+ const back = document.createElement('button');
781
+ back.type = 'button';
782
+ back.textContent = label('戻る', 'Back');
783
+ const cancel = document.createElement('button');
784
+ cancel.type = 'button';
785
+ cancel.textContent = label('キャンセル', 'Cancel');
786
+ cancel.setAttribute('data-new-project-cancel', '');
787
+ const submit = document.createElement('button');
788
+ submit.type = 'submit';
789
+ form.append(fields, review, device, progress, status, dialogActions(document, back, dialogAction(cancel, 'cancel'), dialogAction(submit, 'confirm')));
790
+ let busy = false;
791
+ let reviewed = null;
792
+ const finish = (result) => {
793
+ if (dismissed)
794
+ return;
795
+ dismissed = true;
796
+ controller.abort();
797
+ close(result);
798
+ };
799
+ cancel.onclick = () => finish('cancelled');
800
+ const destination = () => (form.querySelector('input[name="destination"]:checked')?.value ??
801
+ 'memory');
802
+ const selectedWorkingCopy = () => workingCopy.querySelector('input:checked')?.value;
803
+ const titleValue = () => title.value.trim();
804
+ const titleUsable = () => isValidSaveName(titleValue());
805
+ const effectiveSaveName = () => titleUsable() ? titleValue() : saveName.value.trim();
806
+ const refresh = () => {
807
+ const selected = destination();
808
+ const reviewing = reviewed !== null;
809
+ fields.hidden = reviewing;
810
+ review.hidden = !reviewing;
811
+ back.hidden = !reviewing;
812
+ back.disabled = busy;
813
+ destinations.disabled = busy || reviewing;
814
+ titleField.hidden = selected === 'memory';
815
+ title.disabled = busy || reviewing || selected === 'memory';
816
+ // Only a folder takes the save name here; for GitHub the repository name is the save name.
817
+ saveNameBlock.hidden = selected === 'memory' || titleUsable();
818
+ saveNameField.hidden = selected === 'github';
819
+ saveName.disabled = busy || reviewing || saveNameBlock.hidden || selected === 'github';
820
+ if (github) {
821
+ github.panel.hidden = selected !== 'github';
822
+ github.panel.disabled = busy || reviewing || github.panel.hidden;
823
+ }
824
+ submit.disabled = busy;
825
+ submit.textContent = selected === 'github' ? (reviewing ? label('リポジトリを作成', 'Create Repository') :
826
+ github.connected ? label('作成内容を確認', 'Review Repository') : label('GitHub へ接続…', 'Connect to GitHub…')) :
827
+ selected === 'device' ? label('フォルダを選んで作成…', 'Choose a Folder and Create…') : label('作成', 'Create');
828
+ };
829
+ const followTitle = () => {
830
+ if (!titleUsable() && !saveNameEdited)
831
+ saveName.value = suggestSaveName(titleValue());
832
+ if (!saveNameBlock.hidden && saveName.value)
833
+ checkSaveNameInput(saveName, saveNameError, locale);
834
+ else {
835
+ saveName.removeAttribute('aria-invalid');
836
+ saveNameError.textContent = '';
837
+ }
838
+ github?.suggestName(effectiveSaveName());
839
+ };
840
+ title.addEventListener('input', () => { report(''); refresh(); followTitle(); });
841
+ saveName.addEventListener('input', () => {
842
+ saveNameEdited = true;
843
+ checkSaveNameInput(saveName, saveNameError, locale);
844
+ github?.suggestName(effectiveSaveName());
845
+ });
846
+ destinations.addEventListener('change', () => { report(''); refresh(); followTitle(); });
847
+ back.onclick = () => {
848
+ reviewed = null;
849
+ report('');
850
+ refresh();
851
+ submit.focus();
852
+ };
853
+ refresh();
854
+ followTitle();
855
+ if (github && document.defaultView?.MutationObserver) {
856
+ const observer = new document.defaultView.MutationObserver(() => {
857
+ if (!open()) {
858
+ observer.disconnect();
859
+ controller.abort();
860
+ }
861
+ });
862
+ observer.observe(document.body, { childList: true, subtree: true });
863
+ }
864
+ const run = async (request) => {
865
+ progress.textContent = label('作成しています…', 'Creating…');
866
+ try {
867
+ const result = await options.createIn(request, controller.signal);
868
+ if (open() && result === 'created')
869
+ finish('created');
870
+ }
871
+ finally {
872
+ if (open())
873
+ progress.textContent = '';
874
+ }
875
+ };
876
+ form.onsubmit = async (event) => {
877
+ event.preventDefault();
878
+ if (!open() || busy)
879
+ return;
880
+ const selected = destination();
881
+ report('');
882
+ if (selected === 'memory' && options.create) {
883
+ options.create();
884
+ finish('created');
885
+ return;
886
+ }
887
+ busy = true;
888
+ refresh();
889
+ let focus = null;
890
+ try {
891
+ if (selected === 'memory') {
892
+ await run({ destination: 'memory' });
893
+ return;
894
+ }
895
+ const projectTitle = titleValue();
896
+ if (!projectTitle) {
897
+ report(label('作品名を入力してください。', 'Enter a project title.'));
898
+ focus = title;
899
+ return;
900
+ }
901
+ if (selected !== 'github') {
902
+ const name = effectiveSaveName();
903
+ if (!isValidSaveName(name)) {
904
+ checkSaveNameInput(saveName, saveNameError, locale);
905
+ report(texts.invalid);
906
+ focus = saveName;
907
+ return;
908
+ }
909
+ await run({ destination: selected, title: projectTitle, saveName: name });
910
+ return;
911
+ }
912
+ if (!reviewed) {
913
+ github.applyUrl();
914
+ if (!github.connected) {
915
+ report(label('GitHub に接続しています…', 'Connecting to GitHub…'));
916
+ if (await github.connect(open, interaction))
917
+ focus = submit;
918
+ if (open())
919
+ report('');
920
+ return;
921
+ }
922
+ const place = selectedWorkingCopy();
923
+ if (!place)
924
+ throw new Error(label('作業用の写しの置き場所を選んでください。', 'Choose where to keep the working copy.'));
925
+ reviewed = github.draft(projectTitle);
926
+ focus = github.review(reviewed, review);
927
+ return;
928
+ }
929
+ await run({ destination: 'github', title: projectTitle, saveName: reviewed.name, draft: reviewed,
930
+ workingCopy: selectedWorkingCopy() });
931
+ }
932
+ catch (error) {
933
+ if (open())
934
+ report(error instanceof Error ? error.message : String(error));
935
+ }
936
+ finally {
937
+ device.replaceChildren();
938
+ busy = false;
939
+ if (open()) {
940
+ refresh();
941
+ focus?.focus();
942
+ }
943
+ }
944
+ };
945
+ return form;
946
+ }
947
+ /**
948
+ * Shows {@link renderNewProjectForm} in a modal dialog and resolves `created` or `cancelled` when it closes.
949
+ * Escape cancels it. Without a document body it resolves `cancelled`.
950
+ */
951
+ export function openNewProjectDialog(document, locale, options) {
952
+ if (!document?.body)
953
+ return Promise.resolve('cancelled');
954
+ return new Promise(resolve => {
955
+ const dialog = document.createElement('dialog');
956
+ dialog.className = 'tw-project-file-dialog';
957
+ dialog.setAttribute('data-new-project-dialog', '');
958
+ const heading = document.createElement('h2');
959
+ heading.textContent = projectFileDialogTitle('new', locale);
960
+ dialog.setAttribute('aria-label', heading.textContent);
961
+ const form = renderNewProjectForm(document, locale, options, result => {
962
+ if (dialog.open && typeof dialog.close === 'function')
963
+ dialog.close();
964
+ dialog.remove();
965
+ resolve(result);
966
+ });
967
+ dialog.addEventListener('cancel', event => {
968
+ event.preventDefault();
969
+ form.querySelector('[data-new-project-cancel]')?.click();
970
+ });
971
+ dialog.append(heading, form);
972
+ document.body.append(dialog);
973
+ if (typeof dialog.showModal === 'function')
974
+ dialog.showModal();
975
+ else
976
+ dialog.setAttribute('open', '');
977
+ form.querySelector('input[name="destination"]:checked')?.focus();
978
+ });
979
+ }
@@ -1,5 +1,5 @@
1
1
  import React from 'react';
2
- import type { Action, FolderActions, ProjectFileStorage } from './project-file-dialogs.js';
2
+ import type { Action, FolderActions, NewProjectChoices, NewProjectRequest, NewProjectResult, ProjectFileStorage } from './project-file-dialogs.js';
3
3
  interface SaveWorkspace {
4
4
  saveScope: 'project' | 'tab';
5
5
  canSaveActive: boolean;
@@ -9,6 +9,7 @@ interface SaveWorkspace {
9
9
  type SaveEntries = {
10
10
  storage: ProjectFileStorage;
11
11
  folder?: FolderActions;
12
+ saveNew?: Action;
12
13
  saveAs?: Action;
13
14
  saveCommit?: Action;
14
15
  };
@@ -23,13 +24,27 @@ export default function ProjectFileMenu({ locale, MenuItem, MenuSection, close,
23
24
  close: Action;
24
25
  workspace?: SaveWorkspace;
25
26
  entries: {
27
+ /** Creates the default project in memory. Without `createIn`, Create New Project calls it directly. */
26
28
  create: Action;
29
+ /**
30
+ * With it, Create New Project… opens the dialog that chooses where to create the project, and calls this
31
+ * for a folder or a GitHub repository (see `renderNewProjectForm`). The in-memory choice still calls `create`.
32
+ */
33
+ createIn?: (request: NewProjectRequest, signal: AbortSignal) => Promise<NewProjectResult>;
34
+ /** What the Create New Project… dialog offers besides the in-memory project. */
35
+ newProject?: NewProjectChoices;
27
36
  newWindow?: Action;
28
37
  open: Action;
29
38
  externalYaml?: React.ReactNode;
30
39
  folder?: FolderActions;
31
40
  openRemote?: Action;
32
41
  storage: ProjectFileStorage;
42
+ /**
43
+ * Save Project for a project with no save target (no file handle, no folder): opens the save form titled
44
+ * `projectFileDialogTitle('save', locale)`, whose file or folder becomes the project's target.
45
+ */
46
+ saveNew?: Action;
47
+ /** Save a Copy of the Project…: writes a copy and never changes the project's target. */
33
48
  saveAs?: Action;
34
49
  saveCommit?: Action;
35
50
  exportProject?: Action;
@@ -1,10 +1,14 @@
1
1
  import React from 'react';
2
2
  import { isMacPlatform } from '@kubohiroya/turbowarp-plus-editor-project-model/project-search-connections';
3
- function saveEntries(locale, { storage, folder, saveAs, saveCommit }) {
3
+ import { openNewProjectDialog } from './project-file-dialogs.js';
4
+ function saveEntries(locale, { storage, folder, saveNew, saveAs, saveCommit }) {
4
5
  const ja = locale.startsWith('ja');
5
6
  return [
6
- ['save', ja ? 'プロジェクトを保存' : 'Save Project', storage.canSave ? storage.overwrite || folder?.save : undefined],
7
- ['save-as', ja ? '名前を変えて保存…' : 'Save As…', storage.canSave ? saveAs : undefined],
7
+ // Overwrites the file or saves into the folder; with no target yet, saveNew picks one that becomes the target.
8
+ ['save', ja ? 'プロジェクトを保存' : 'Save Project',
9
+ storage.canSave ? storage.overwrite || folder?.save || saveNew : undefined],
10
+ // Saves a copy and leaves the project where it is; the command id stays `save-as` for icons and hosts.
11
+ ['save-as', ja ? 'プロジェクトのコピーを保存…' : 'Save a Copy of the Project…', storage.canSave ? saveAs : undefined],
8
12
  ...(saveCommit ? [['save-commit', ja ? '保存してコミット…' : 'Save and Commit…', saveCommit]] : [])
9
13
  ];
10
14
  }
@@ -66,8 +70,14 @@ export default function ProjectFileMenu({ locale, MenuItem, MenuSection, close,
66
70
  showShortcut && React.createElement("kbd", { className: "tw-project-file-menu__shortcut", "aria-hidden": "true" }, mac ? '⌘S' : 'Ctrl+S')));
67
71
  };
68
72
  const e = entries;
73
+ const createIn = e.createIn;
74
+ const createNew = createIn ? ['new', ja ? '新しいプロジェクトを作成…' : 'Create New Project…', () => {
75
+ if (typeof document === 'undefined')
76
+ return;
77
+ void openNewProjectDialog(document, locale, { ...e.newProject, create: e.create, createIn });
78
+ }] : ['new', ja ? '新しいプロジェクトを作成' : 'Create New Project', e.create];
69
79
  return React.createElement(React.Fragment, null,
70
- item(['new', ja ? '新しいプロジェクトを作成' : 'Create New Project', e.create]),
80
+ item(createNew),
71
81
  e.newWindow && item(['window', ja ? '新しいウィンドウ' : 'New Window', e.newWindow]),
72
82
  React.createElement(MenuSection, null,
73
83
  item(['open', ja ? 'SB3ファイルを開く…' : 'Open SB3 File…', e.open]),
@@ -0,0 +1,12 @@
1
+ /** The class of the notice; its styles are in `project-file-menu.css`. */
2
+ export declare const projectNoticeClassName = "tw-project-notice";
3
+ /**
4
+ * Shows a short notice at the bottom of the window that does not block the editor, such as what a title change
5
+ * could not rename. It has a dismiss button (an X with a localized `title` and `aria-label`) and hides itself after
6
+ * `timeout` milliseconds (12 s by default) unless focus is inside it. A new notice replaces the one shown in the same
7
+ * document. Returns a function that removes the notice.
8
+ */
9
+ export declare function showNotice(document: Document, text: string, { locale, timeout }: {
10
+ locale: string;
11
+ timeout?: number;
12
+ }): () => void;
@@ -0,0 +1,56 @@
1
+ /** The class of the notice; its styles are in `project-file-menu.css`. */
2
+ export const projectNoticeClassName = 'tw-project-notice';
3
+ const shown = new WeakMap();
4
+ /**
5
+ * Shows a short notice at the bottom of the window that does not block the editor, such as what a title change
6
+ * could not rename. It has a dismiss button (an X with a localized `title` and `aria-label`) and hides itself after
7
+ * `timeout` milliseconds (12 s by default) unless focus is inside it. A new notice replaces the one shown in the same
8
+ * document. Returns a function that removes the notice.
9
+ */
10
+ export function showNotice(document, text, { locale, timeout = 12000 }) {
11
+ shown.get(document)?.();
12
+ const view = document.defaultView;
13
+ const ja = locale.startsWith('ja');
14
+ const notice = document.createElement('aside');
15
+ notice.className = projectNoticeClassName;
16
+ notice.setAttribute('data-project-tools', '');
17
+ notice.setAttribute('data-testid', 'project-notice-snackbar');
18
+ const message = document.createElement('span');
19
+ message.setAttribute('role', 'status');
20
+ message.setAttribute('aria-atomic', 'true');
21
+ message.textContent = text;
22
+ const dismiss = document.createElement('button');
23
+ dismiss.type = 'button';
24
+ const name = ja ? '閉じる' : 'Dismiss';
25
+ dismiss.title = name;
26
+ dismiss.setAttribute('aria-label', name);
27
+ const svg = 'http://www.w3.org/2000/svg';
28
+ const icon = document.createElementNS(svg, 'svg');
29
+ icon.setAttribute('viewBox', '0 0 16 16');
30
+ icon.setAttribute('width', '16');
31
+ icon.setAttribute('height', '16');
32
+ icon.setAttribute('aria-hidden', 'true');
33
+ const path = document.createElementNS(svg, 'path');
34
+ path.setAttribute('d', 'M4 4l8 8M12 4l-8 8');
35
+ path.setAttribute('stroke', 'currentColor');
36
+ path.setAttribute('stroke-width', '2');
37
+ path.setAttribute('stroke-linecap', 'round');
38
+ icon.append(path);
39
+ dismiss.append(icon);
40
+ notice.append(message, dismiss);
41
+ let timer = 0;
42
+ const remove = () => {
43
+ view?.clearTimeout(timer);
44
+ notice.remove();
45
+ if (shown.get(document) === remove)
46
+ shown.delete(document);
47
+ };
48
+ dismiss.addEventListener('click', remove);
49
+ document.body.append(notice);
50
+ shown.set(document, remove);
51
+ timer = view?.setTimeout(() => {
52
+ if (!notice.contains(document.activeElement))
53
+ remove();
54
+ }, timeout) ?? 0;
55
+ return remove;
56
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Calls `onCommit` with the new title when the person commits an edit of the menu bar's title field
3
+ * ({@link projectTitleFieldClassName}), on Enter or when the field loses focus, as the GUI's own field does. Each
4
+ * edit is reported once. Enter while an IME is composing does not commit, and a title that did not change is not
5
+ * reported. Titles set by loading, a new project or the properties are not edits of the field, so they are not
6
+ * reported either. `readTitle` reads the project title the GUI holds; it is read one tick after the event, once the
7
+ * GUI has written the field's value. Returns a function that stops watching.
8
+ */
9
+ export declare function followProjectTitleCommits(document: Document, { readTitle, onCommit }: {
10
+ readTitle(): string;
11
+ onCommit(title: string): void;
12
+ }): () => void;
13
+ /** Where the open project is saved, for {@link reflectProjectTitle}. */
14
+ export type ProjectTitleLocation = 'browser' | 'device' | 'none';
15
+ export interface ReflectProjectTitleOptions {
16
+ /** The document that shows the save name question. */
17
+ document: Document;
18
+ locale: string;
19
+ /** The title the person committed. */
20
+ title: string;
21
+ /** The project's save name, `''` when it has none. */
22
+ saveName: string;
23
+ /**
24
+ * Where the project is saved: `browser` for a project folder in the browser's own storage, which can be renamed;
25
+ * `device` for a folder on the device, which the browser cannot rename; `none` when it is not saved in a folder.
26
+ */
27
+ location: ProjectTitleLocation;
28
+ /** Whether the folder is bound to a Git repository, whose name does not change. */
29
+ gitBound: boolean;
30
+ /** Renames the project folder in the browser's storage; failures are ignored. Needed for `browser`. */
31
+ renameBrowserFolder?(title: string): Promise<void>;
32
+ /** Sets the project's save name, after the person entered one. */
33
+ setSaveName(name: string): void;
34
+ /** Shows a short notice, such as with {@link showNotice}. */
35
+ notify(text: string): void;
36
+ /**
37
+ * Whether the same project is still open. Checked after each wait, so a title committed just before another
38
+ * project opened does not rename or name the new one. Defaults to always true.
39
+ */
40
+ current?(): boolean;
41
+ }
42
+ /**
43
+ * Reflects a title the person committed in the menu bar on what the project is saved in. A folder in the browser's
44
+ * storage is renamed to the title; a folder on the device and a Git repository keep their names, and a notice says
45
+ * so. When the project is saved in a folder or repository, has no save name and the title cannot be used as one
46
+ * ({@link isValidSaveName}), the person is asked for a save name ({@link askSaveName}). An empty title, or a project
47
+ * that is not saved in a folder, changes nothing.
48
+ */
49
+ export declare function reflectProjectTitle({ document, locale, title, saveName, location, gitBound, renameBrowserFolder, setSaveName, notify, current }: ReflectProjectTitleOptions): Promise<void>;