@kubohiroya/turbowarp-plus-editor-workbench 0.22.0 → 0.24.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.
@@ -38,6 +38,8 @@ const glyphs = {
38
38
  open: 'M5 3h9l5 5v13H5z M14 3v5h5 M12 18v-7 M9 14l3-3 3 3',
39
39
  'project-folder-open': 'M3 6h7l2 2h9l-2 11H3z M3 11h16',
40
40
  'project-folder-open-browser': 'M4 4h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z M3 9h18 M6 6.5h.01 M8.5 6.5h.01 M11 6.5h.01',
41
+ // A remote Git repository: a cloud with an arrow down, fetched onto the device.
42
+ 'git-open-remote': 'M7 18H6.5a4.5 4.5 0 0 1-.5-8.97A6 6 0 0 1 17.5 9a4.5 4.5 0 0 1 0 9H17 M12 12v9 M8.5 17.5 12 21l3.5-3.5',
41
43
  'save-as': 'M4 3h13l3 3v15H4z M8 3v6h8V3 M9 17h6 M12 14v6',
42
44
  download: 'M12 3v12 M7 10l5 5 5-5 M4 17v4h16v-4',
43
45
  package: 'm12 3 8 4v10l-8 4-8-4V7z M4 7l8 4 8-4 M12 11v10 M8 5l8 4',
@@ -1,6 +1,9 @@
1
1
  import {dialogAction, dialogActions} from '@kubohiroya/turbowarp-plus-editor-windows';
2
2
  import type {CreationInteraction, GitHubCreationAccount, GitHubRepositoryDraft, RepositoryCreationControls,
3
3
  RepositoryCreationProgress, RepositoryReceipt} from '@kubohiroya/turbowarp-plus-editor-git/project-repository-creation';
4
+ import {checkSaveNameInput, isValidSaveName, saveNameTexts, suggestSaveName} from './save-name.js';
5
+
6
+ export {askSaveName, isValidSaveName, suggestSaveName} from './save-name.js';
4
7
 
5
8
  export type Action = () => void;
6
9
  // `openBrowser` opens a folder kept in the browser (OPFS), where the host offers one.
@@ -40,10 +43,34 @@ export interface ProjectFileStorage {
40
43
  pick?: (filename: string) => Promise<FileSystemFileHandle>;
41
44
  write(handle: FileSystemFileHandle, serialize: Serialize, current: () => boolean): Promise<void>;
42
45
  download(filename: string, serialize: Serialize, current: () => boolean): Promise<void>;
46
+ /**
47
+ * Called after a copy was written by {@link saveProjectAs} in the `copy` mode, with the file it was written to
48
+ * (`null` for a download) and the title stored in the copy. The host ends its save indicator here. It must not
49
+ * make the copy the current file, change the project title, or mark the project as saved: the project keeps its
50
+ * own file, folder and unsaved changes.
51
+ */
52
+ copied?(handle: FileSystemFileHandle | null, title: string): void;
53
+ /**
54
+ * Called after {@link saveProjectAs} in the `save` mode (Save Project for a project with no save target yet):
55
+ * the written file becomes the project's file (`null` for a download), `title` its title, and `unchanged` says
56
+ * whether the project was not edited while saving, so the host can mark it saved. Never called for a copy.
57
+ */
43
58
  finish(handle: FileSystemFileHandle | null, title: string, unchanged: boolean): void;
44
59
  fail(error: unknown): void;
45
60
  }
46
61
 
62
+ /**
63
+ * The titles of the dialogs this package fills, by the File menu command that opens them: `save` is "Save Project"
64
+ * (the save form for a project with no save target yet), `save-as` is "Save a Copy of the Project" and `new` is
65
+ * "Create New Project".
66
+ */
67
+ export function projectFileDialogTitle(command: 'save' | 'save-as' | 'new', locale: string) {
68
+ const ja = locale.startsWith('ja');
69
+ return command === 'new' ? (ja ? '新しいプロジェクトを作成' : 'Create New Project') :
70
+ command === 'save' ? (ja ? 'プロジェクトを保存' : 'Save Project') :
71
+ (ja ? 'プロジェクトのコピーを保存' : 'Save a Copy of the Project');
72
+ }
73
+
47
74
  /**
48
75
  * Saving over the last file or into the project folder first collects edits held by other windows,
49
76
  * as Save As does, so a save that does not move the focus to the editor misses nothing. A failed
@@ -66,15 +93,31 @@ export function collectBeforeSaving(storage: ProjectFileStorage, folder: FolderA
66
93
  };
67
94
  }
68
95
 
69
- export function projectSaveShortcut(storage: ProjectFileStorage, folder?: FolderActions, saveAs?: Action) {
70
- if (storage.canSave) (storage.overwrite || folder?.save || saveAs)?.();
96
+ /**
97
+ * Save Project and Ctrl/⌘+S: overwrite the project's file or save into its folder; with no save target yet, run
98
+ * `saveNew`, which opens the save form whose result becomes the target. Pass the save-to-a-new-place action here,
99
+ * never Save a Copy, or a project without a target would only ever be copied.
100
+ */
101
+ export function projectSaveShortcut(storage: ProjectFileStorage, folder?: FolderActions, saveNew?: Action) {
102
+ if (storage.canSave) (storage.overwrite || folder?.save || saveNew)?.();
71
103
  }
72
104
 
105
+ /**
106
+ * Saves the project as an SB3: picks the file (or downloads it), collects edits held by other windows, serializes
107
+ * it under the file's title and writes it, then runs `committed`.
108
+ *
109
+ * - `mode: 'copy'` (the default, Save a Copy of the Project): the project stays as it was; its file, folder, title
110
+ * and unsaved state do not change. `storage.copied` runs last.
111
+ * - `mode: 'save'` (Save Project with no save target yet): the file becomes the project's save target through
112
+ * `storage.finish(handle, title, unchanged())`.
113
+ */
73
114
  export async function saveProjectAs(storage: ProjectFileStorage, name: string, {
74
- current, unchanged, serialize, committed, collect
115
+ current, unchanged, serialize, committed, collect, mode = 'copy'
75
116
  }: {
76
117
  current(): boolean;
77
- unchanged(): boolean;
118
+ /** Whether the project was not edited while saving; used by the `save` mode only. */
119
+ unchanged?(): boolean;
120
+ mode?: 'copy' | 'save';
78
121
  serialize<T>(title: string, run: () => T): T;
79
122
  committed(): void;
80
123
  // Collects edits still held by other windows. A failure leaves them there for a retry.
@@ -96,7 +139,8 @@ export async function saveProjectAs(storage: ProjectFileStorage, name: string, {
96
139
  else await storage.download(filename, output, current);
97
140
  if (!current()) return false;
98
141
  committed();
99
- storage.finish(handle, title, unchanged());
142
+ if (mode === 'save') storage.finish(handle, title, unchanged ? unchanged() : true);
143
+ else storage.copied?.(handle, title);
100
144
  return true;
101
145
  } catch (error) {
102
146
  storage.fail(error);
@@ -104,8 +148,7 @@ export async function saveProjectAs(storage: ProjectFileStorage, name: string, {
104
148
  }
105
149
  }
106
150
 
107
- const validRepositoryName = (name: string) => /^[A-Za-z0-9_.-]{1,100}$/.test(name) &&
108
- name !== '.' && name !== '..' && !/\.git$/i.test(name);
151
+ const validRepositoryName = isValidSaveName;
109
152
 
110
153
  function parseGitHubRepositoryUrl(url: string) {
111
154
  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());
@@ -150,6 +193,9 @@ function createGitHubFields(document: Document, label: (ja: string, en: string)
150
193
  const name = document.createElement('input');
151
194
  name.name = 'github-name';
152
195
  name.maxLength = 100;
196
+ // A name the person typed is kept; until then the name follows the suggestion from the form.
197
+ let nameEdited = false;
198
+ name.addEventListener('input', () => {nameEdited = true;});
153
199
  appendField(panel, label('リポジトリ名', 'Repository name'), name);
154
200
  const url = document.createElement('input');
155
201
  url.name = 'github-url';
@@ -199,6 +245,9 @@ function createGitHubFields(document: Document, label: (ja: string, en: string)
199
245
  return {
200
246
  panel,
201
247
  get connected() {return account !== null;},
248
+ suggestName(value: string) {
249
+ if (!nameEdited) name.value = value;
250
+ },
202
251
  async connect(open: () => boolean, interaction: CreationInteraction) {
203
252
  const result = await provider.connectForCreation(interaction);
204
253
  if (!open() || !result) return false;
@@ -216,6 +265,7 @@ function createGitHubFields(document: Document, label: (ja: string, en: string)
216
265
  'Enter a URL in the form https://github.com/owner/repository.'));
217
266
  requestedOwner = parsed.owner;
218
267
  name.value = parsed.name;
268
+ nameEdited = true;
219
269
  url.value = '';
220
270
  if (account) fillOwners(account);
221
271
  },
@@ -664,3 +714,354 @@ export function renderExtensionsForm(document: Document, locale: string, close:
664
714
  };
665
715
  return form;
666
716
  }
717
+
718
+ /** Where Create New Project… puts the new project. */
719
+ export type NewProjectDestination = 'memory' | 'browser' | 'device' | 'github';
720
+
721
+ /**
722
+ * What the new project dialog asks the host to create. `title` is the project title; `saveName` is the name of the
723
+ * folder (and, for GitHub, of the repository: it equals `draft.name`), always a valid save name
724
+ * ({@link isValidSaveName}). For GitHub, `workingCopy` says where the working copy is kept.
725
+ */
726
+ export type NewProjectRequest =
727
+ | {destination: 'memory'}
728
+ | {destination: 'browser' | 'device'; title: string; saveName: string}
729
+ | {destination: 'github'; title: string; saveName: string; draft: GitHubRepositoryDraft; workingCopy: 'browser' | 'device'};
730
+
731
+ /** `created` closes the dialog; `cancelled` (the person cancelled a picker, say) keeps it open with its entries. */
732
+ export type NewProjectResult = 'created' | 'cancelled';
733
+
734
+ export interface NewProjectGitHub {
735
+ // The host can reuse a current session or open sign-in. The form retains its entries either way.
736
+ connectForCreation(interaction: CreationInteraction): Promise<GitHubCreationAccount | null>;
737
+ licenses?: readonly {id: string; label: string}[];
738
+ }
739
+
740
+ /** What the host offers in the new project dialog. Only the in-memory project is always offered. */
741
+ export interface NewProjectChoices {
742
+ /** The localized title of a new project, the initial value of the title field. */
743
+ defaultTitle?: string;
744
+ /** Offers a project folder kept in the browser (OPFS). */
745
+ browserFolders?: boolean;
746
+ /**
747
+ * Offers a project folder on the device: `true` offers it, `false` shows it disabled with the reason (Safari,
748
+ * Firefox), and leaving it out hides it.
749
+ */
750
+ deviceFolders?: boolean;
751
+ /** Offers a new GitHub repository, with its working copy in the browser or on the device. */
752
+ github?: NewProjectGitHub;
753
+ }
754
+
755
+ export interface NewProjectFormOptions extends NewProjectChoices {
756
+ /**
757
+ * Creates the default project in memory, as Create New Project always did. Without it, the in-memory choice
758
+ * calls `createIn({destination: 'memory'})`.
759
+ */
760
+ create?: Action;
761
+ /**
762
+ * Creates the project. Resolves `created` once the new project is open, or `cancelled` to keep the dialog open;
763
+ * rejects with an Error whose message the dialog shows. `signal` aborts when the dialog is dismissed.
764
+ */
765
+ createIn(request: NewProjectRequest, signal: AbortSignal): Promise<NewProjectResult>;
766
+ }
767
+
768
+ const deviceFolderReason = (label: (ja: string, en: string) => string) =>
769
+ label('このブラウザーでは端末のフォルダを開けません。Chrome か Edge を使うか、ブラウザーに保存したフォルダを開いてください。',
770
+ 'This browser cannot open folders on your device. Use Chrome or Edge, or open a folder saved in this browser.');
771
+
772
+ let newProjectForms = 0;
773
+
774
+ /**
775
+ * The Create New Project… form. The in-memory project is selected first, so Create alone does what Create New
776
+ * Project always did. A folder or a GitHub repository also takes a title, and a save name when the title cannot be
777
+ * used as one. `close` receives `created`, or `cancelled` when the person dismissed the form.
778
+ */
779
+ export function renderNewProjectForm(document: Document, locale: string, options: NewProjectFormOptions,
780
+ close: (result: NewProjectResult) => void) {
781
+ const label = (ja: string, en: string) => locale.startsWith('ja') ? ja : en;
782
+ const id = `tw-new-project-${++newProjectForms}`;
783
+ const {browserFolders, deviceFolders, github: githubProvider} = options;
784
+ const workingCopies = [...(deviceFolders !== undefined ? ['device'] : []), ...(browserFolders ? ['browser'] : [])];
785
+ const form = document.createElement('form');
786
+ form.setAttribute('data-new-project-form', '');
787
+ const fields = document.createElement('div');
788
+
789
+ const destinations = document.createElement('fieldset');
790
+ const destinationLegend = document.createElement('legend');
791
+ destinationLegend.textContent = label('作成先', 'Create in');
792
+ destinations.append(destinationLegend);
793
+ const radio = (parent: HTMLElement, group: string, value: string, title: string, reason?: string) => {
794
+ const input = document.createElement('input');
795
+ input.type = 'radio';
796
+ input.name = group;
797
+ input.value = value;
798
+ const row = document.createElement('label');
799
+ row.append(input, title);
800
+ parent.append(row);
801
+ if (reason) {
802
+ input.disabled = true;
803
+ row.title = reason;
804
+ const note = document.createElement('p');
805
+ note.id = `${id}-${group}-${value}-reason`;
806
+ note.textContent = reason;
807
+ input.setAttribute('aria-describedby', note.id);
808
+ parent.append(note);
809
+ }
810
+ return input;
811
+ };
812
+ const unavailable = deviceFolders === false ? deviceFolderReason(label) : undefined;
813
+ radio(destinations, 'destination', 'memory', label('メモリ上の SB3', 'In memory (SB3)')).checked = true;
814
+ if (browserFolders) radio(destinations, 'destination', 'browser',
815
+ label('ブラウザー内のプロジェクトフォルダ', 'Project folder in this browser'));
816
+ if (deviceFolders !== undefined) radio(destinations, 'destination', 'device',
817
+ label('手元のプロジェクトフォルダ', 'Project folder on this device'), unavailable);
818
+ if (githubProvider && workingCopies.length) radio(destinations, 'destination', 'github',
819
+ label('Git のリモートリポジトリ', 'Git remote repository (GitHub)'));
820
+ fields.append(destinations);
821
+
822
+ const title = document.createElement('input');
823
+ title.name = 'title';
824
+ title.maxLength = 100;
825
+ title.value = options.defaultTitle ?? label('新しいプロジェクト', 'Untitled Project');
826
+ const titleField = appendField(fields, label('作品名', 'Project title'), title);
827
+
828
+ const texts = saveNameTexts(locale);
829
+ const saveNameBlock = document.createElement('div');
830
+ const saveNameExplanation = document.createElement('p');
831
+ saveNameExplanation.textContent = texts.explanation;
832
+ const saveName = document.createElement('input');
833
+ saveName.name = 'save-name';
834
+ saveName.maxLength = 100;
835
+ saveName.autocomplete = 'off';
836
+ saveName.spellcheck = false;
837
+ const allowed = document.createElement('p');
838
+ allowed.id = `${id}-save-name-allowed`;
839
+ allowed.textContent = texts.allowed;
840
+ saveName.setAttribute('aria-describedby', allowed.id);
841
+ const saveNameError = document.createElement('p');
842
+ saveNameError.setAttribute('role', 'alert');
843
+ saveNameBlock.append(saveNameExplanation);
844
+ const saveNameField = appendField(saveNameBlock, texts.title, saveName);
845
+ saveNameBlock.append(allowed, saveNameError);
846
+ fields.append(saveNameBlock);
847
+ let saveNameEdited = false;
848
+
849
+ const status = document.createElement('p');
850
+ status.setAttribute('role', 'alert');
851
+ const report = (message: string) => {status.textContent = message;};
852
+ const progress = document.createElement('p');
853
+ progress.setAttribute('role', 'status');
854
+
855
+ const github = githubProvider && workingCopies.length ?
856
+ createGitHubFields(document, label, githubProvider, report) : null;
857
+ const workingCopy = document.createElement('fieldset');
858
+ if (github) {
859
+ const legend = document.createElement('legend');
860
+ legend.textContent = label('作業用の写しの置き場所', 'Keep the working copy');
861
+ workingCopy.append(legend);
862
+ if (deviceFolders !== undefined) radio(workingCopy, 'working-copy', 'device',
863
+ label('手元のプロジェクトフォルダ', 'Project folder on this device'), unavailable);
864
+ if (browserFolders) radio(workingCopy, 'working-copy', 'browser',
865
+ label('ブラウザー内のプロジェクトフォルダ', 'Project folder in this browser'));
866
+ const preferred = [...workingCopy.querySelectorAll<HTMLInputElement>('input')].find(input => !input.disabled);
867
+ if (preferred) preferred.checked = true;
868
+ github.panel.append(workingCopy);
869
+ fields.append(github.panel);
870
+ }
871
+
872
+ const review = document.createElement('div');
873
+ const device = document.createElement('div');
874
+ const controller = new AbortController();
875
+ let dismissed = false;
876
+ const open = () => !dismissed && form.isConnected;
877
+ const interaction: CreationInteraction = {
878
+ signal: controller.signal,
879
+ deviceCode({userCode, verificationUri}) {
880
+ if (!open()) return;
881
+ const link = document.createElement('a');
882
+ link.href = verificationUri;
883
+ link.target = '_blank';
884
+ link.rel = 'noopener noreferrer';
885
+ link.textContent = label('GitHub で認証する', 'Authorize on GitHub');
886
+ const code = document.createElement('strong');
887
+ code.textContent = userCode;
888
+ device.replaceChildren(link, ' ', code);
889
+ }
890
+ };
891
+ const back = document.createElement('button');
892
+ back.type = 'button';
893
+ back.textContent = label('戻る', 'Back');
894
+ const cancel = document.createElement('button');
895
+ cancel.type = 'button';
896
+ cancel.textContent = label('キャンセル', 'Cancel');
897
+ cancel.setAttribute('data-new-project-cancel', '');
898
+ const submit = document.createElement('button');
899
+ submit.type = 'submit';
900
+ form.append(fields, review, device, progress, status,
901
+ dialogActions(document, back, dialogAction(cancel, 'cancel'), dialogAction(submit, 'confirm')));
902
+
903
+ let busy = false;
904
+ let reviewed: GitHubRepositoryDraft | null = null;
905
+ const finish = (result: NewProjectResult) => {
906
+ if (dismissed) return;
907
+ dismissed = true;
908
+ controller.abort();
909
+ close(result);
910
+ };
911
+ cancel.onclick = () => finish('cancelled');
912
+ const destination = () => (form.querySelector<HTMLInputElement>('input[name="destination"]:checked')?.value ??
913
+ 'memory') as NewProjectDestination;
914
+ const selectedWorkingCopy = () => workingCopy.querySelector<HTMLInputElement>('input:checked')?.value as
915
+ 'browser' | 'device' | undefined;
916
+ const titleValue = () => title.value.trim();
917
+ const titleUsable = () => isValidSaveName(titleValue());
918
+ const effectiveSaveName = () => titleUsable() ? titleValue() : saveName.value.trim();
919
+ const refresh = () => {
920
+ const selected = destination();
921
+ const reviewing = reviewed !== null;
922
+ fields.hidden = reviewing;
923
+ review.hidden = !reviewing;
924
+ back.hidden = !reviewing;
925
+ back.disabled = busy;
926
+ destinations.disabled = busy || reviewing;
927
+ titleField.hidden = selected === 'memory';
928
+ title.disabled = busy || reviewing || selected === 'memory';
929
+ // Only a folder takes the save name here; for GitHub the repository name is the save name.
930
+ saveNameBlock.hidden = selected === 'memory' || titleUsable();
931
+ saveNameField.hidden = selected === 'github';
932
+ saveName.disabled = busy || reviewing || saveNameBlock.hidden || selected === 'github';
933
+ if (github) {
934
+ github.panel.hidden = selected !== 'github';
935
+ github.panel.disabled = busy || reviewing || github.panel.hidden;
936
+ }
937
+ submit.disabled = busy;
938
+ submit.textContent = selected === 'github' ? (reviewing ? label('リポジトリを作成', 'Create Repository') :
939
+ github.connected ? label('作成内容を確認', 'Review Repository') : label('GitHub へ接続…', 'Connect to GitHub…')) :
940
+ selected === 'device' ? label('フォルダを選んで作成…', 'Choose a Folder and Create…') : label('作成', 'Create');
941
+ };
942
+ const followTitle = () => {
943
+ if (!titleUsable() && !saveNameEdited) saveName.value = suggestSaveName(titleValue());
944
+ if (!saveNameBlock.hidden && saveName.value) checkSaveNameInput(saveName, saveNameError, locale);
945
+ else {saveName.removeAttribute('aria-invalid'); saveNameError.textContent = '';}
946
+ github?.suggestName(effectiveSaveName());
947
+ };
948
+ title.addEventListener('input', () => {report(''); refresh(); followTitle();});
949
+ saveName.addEventListener('input', () => {
950
+ saveNameEdited = true;
951
+ checkSaveNameInput(saveName, saveNameError, locale);
952
+ github?.suggestName(effectiveSaveName());
953
+ });
954
+ destinations.addEventListener('change', () => {report(''); refresh(); followTitle();});
955
+ back.onclick = () => {
956
+ reviewed = null;
957
+ report('');
958
+ refresh();
959
+ submit.focus();
960
+ };
961
+ refresh();
962
+ followTitle();
963
+ if (github && document.defaultView?.MutationObserver) {
964
+ const observer = new document.defaultView.MutationObserver(() => {
965
+ if (!open()) {observer.disconnect(); controller.abort();}
966
+ });
967
+ observer.observe(document.body, {childList: true, subtree: true});
968
+ }
969
+
970
+ const run = async (request: NewProjectRequest) => {
971
+ progress.textContent = label('作成しています…', 'Creating…');
972
+ try {
973
+ const result = await options.createIn(request, controller.signal);
974
+ if (open() && result === 'created') finish('created');
975
+ } finally {
976
+ if (open()) progress.textContent = '';
977
+ }
978
+ };
979
+ form.onsubmit = async event => {
980
+ event.preventDefault();
981
+ if (!open() || busy) return;
982
+ const selected = destination();
983
+ report('');
984
+ if (selected === 'memory' && options.create) {
985
+ options.create();
986
+ finish('created');
987
+ return;
988
+ }
989
+ busy = true;
990
+ refresh();
991
+ let focus: HTMLElement | null = null;
992
+ try {
993
+ if (selected === 'memory') {await run({destination: 'memory'}); return;}
994
+ const projectTitle = titleValue();
995
+ if (!projectTitle) {
996
+ report(label('作品名を入力してください。', 'Enter a project title.'));
997
+ focus = title;
998
+ return;
999
+ }
1000
+ if (selected !== 'github') {
1001
+ const name = effectiveSaveName();
1002
+ if (!isValidSaveName(name)) {
1003
+ checkSaveNameInput(saveName, saveNameError, locale);
1004
+ report(texts.invalid);
1005
+ focus = saveName;
1006
+ return;
1007
+ }
1008
+ await run({destination: selected, title: projectTitle, saveName: name});
1009
+ return;
1010
+ }
1011
+ if (!reviewed) {
1012
+ github.applyUrl();
1013
+ if (!github.connected) {
1014
+ report(label('GitHub に接続しています…', 'Connecting to GitHub…'));
1015
+ if (await github.connect(open, interaction)) focus = submit;
1016
+ if (open()) report('');
1017
+ return;
1018
+ }
1019
+ const place = selectedWorkingCopy();
1020
+ if (!place) throw new Error(label('作業用の写しの置き場所を選んでください。', 'Choose where to keep the working copy.'));
1021
+ reviewed = github.draft(projectTitle);
1022
+ focus = github.review(reviewed, review);
1023
+ return;
1024
+ }
1025
+ await run({destination: 'github', title: projectTitle, saveName: reviewed.name, draft: reviewed,
1026
+ workingCopy: selectedWorkingCopy()});
1027
+ } catch (error) {
1028
+ if (open()) report(error instanceof Error ? error.message : String(error));
1029
+ } finally {
1030
+ device.replaceChildren();
1031
+ busy = false;
1032
+ if (open()) {refresh(); focus?.focus();}
1033
+ }
1034
+ };
1035
+ return form;
1036
+ }
1037
+
1038
+ /**
1039
+ * Shows {@link renderNewProjectForm} in a modal dialog and resolves `created` or `cancelled` when it closes.
1040
+ * Escape cancels it. Without a document body it resolves `cancelled`.
1041
+ */
1042
+ export function openNewProjectDialog(document: Document, locale: string, options: NewProjectFormOptions):
1043
+ Promise<NewProjectResult> {
1044
+ if (!document?.body) return Promise.resolve('cancelled');
1045
+ return new Promise(resolve => {
1046
+ const dialog = document.createElement('dialog');
1047
+ dialog.className = 'tw-project-file-dialog';
1048
+ dialog.setAttribute('data-new-project-dialog', '');
1049
+ const heading = document.createElement('h2');
1050
+ heading.textContent = projectFileDialogTitle('new', locale);
1051
+ dialog.setAttribute('aria-label', heading.textContent);
1052
+ const form = renderNewProjectForm(document, locale, options, result => {
1053
+ if (dialog.open && typeof dialog.close === 'function') dialog.close();
1054
+ dialog.remove();
1055
+ resolve(result);
1056
+ });
1057
+ dialog.addEventListener('cancel', event => {
1058
+ event.preventDefault();
1059
+ form.querySelector<HTMLButtonElement>('[data-new-project-cancel]')?.click();
1060
+ });
1061
+ dialog.append(heading, form);
1062
+ document.body.append(dialog);
1063
+ if (typeof dialog.showModal === 'function') dialog.showModal();
1064
+ else dialog.setAttribute('open', '');
1065
+ form.querySelector<HTMLInputElement>('input[name="destination"]:checked')?.focus();
1066
+ });
1067
+ }
@@ -92,3 +92,58 @@ ul:has(> li .tw-project-file-menu__item) {
92
92
  font-size: 0.85em;
93
93
  white-space: nowrap;
94
94
  }
95
+
96
+ /* The modal dialogs of the File menu: Create New Project… and the save name. */
97
+ .tw-project-file-dialog {
98
+ box-sizing: border-box;
99
+ inline-size: min(32rem, calc(100vw - 2rem));
100
+ max-block-size: calc(100vh - 2rem);
101
+ padding: 1rem 1.25rem;
102
+ border: 1px solid var(--ui-black-transparent, rgba(0, 0, 0, 0.15));
103
+ border-radius: 0.5rem;
104
+ background-color: var(--ui-modal-background, var(--ui-white, #fff));
105
+ color: var(--text-primary, #575e75);
106
+ overflow: auto;
107
+ }
108
+
109
+ .tw-project-file-dialog::backdrop {
110
+ background-color: rgba(0, 0, 0, 0.4);
111
+ }
112
+
113
+ .tw-project-file-dialog h2 {
114
+ margin: 0 0 0.75rem;
115
+ font-size: 1.125rem;
116
+ }
117
+
118
+ .tw-project-file-dialog fieldset {
119
+ margin: 0 0 0.75rem;
120
+ border: 1px solid var(--ui-black-transparent, rgba(0, 0, 0, 0.15));
121
+ border-radius: 0.25rem;
122
+ }
123
+
124
+ .tw-project-file-dialog label {
125
+ display: flex;
126
+ flex-wrap: wrap;
127
+ align-items: center;
128
+ gap: 0.25rem 0.5rem;
129
+ margin-block: 0.25rem;
130
+ }
131
+
132
+ .tw-project-file-dialog input:not([type="radio"]),
133
+ .tw-project-file-dialog select {
134
+ flex: 1 1 12rem;
135
+ min-inline-size: 0;
136
+ }
137
+
138
+ .tw-project-file-dialog input[aria-invalid="true"] {
139
+ outline: 2px solid var(--error-primary, #ff8c1a);
140
+ }
141
+
142
+ .tw-project-file-dialog p {
143
+ margin-block: 0.25rem;
144
+ }
145
+
146
+ .tw-project-file-dialog [role="alert"]:empty,
147
+ .tw-project-file-dialog [role="status"]:empty {
148
+ display: none;
149
+ }
@@ -1,6 +1,8 @@
1
1
  import React from 'react';
2
2
  import {isMacPlatform} from '@kubohiroya/turbowarp-plus-editor-project-model/project-search-connections';
3
- import type {Action, FolderActions, ProjectFileStorage} from './project-file-dialogs.js';
3
+ import {openNewProjectDialog} from './project-file-dialogs.js';
4
+ import type {Action, FolderActions, NewProjectChoices, NewProjectRequest, NewProjectResult,
5
+ ProjectFileStorage} from './project-file-dialogs.js';
4
6
 
5
7
  type Entry = [command: string, label: string, action: Action | undefined, showShortcut?: boolean, unavailable?: string];
6
8
  interface SaveWorkspace {
@@ -10,13 +12,17 @@ interface SaveWorkspace {
10
12
  subscribeSave(listener: () => void): () => void;
11
13
  }
12
14
 
13
- type SaveEntries = {storage: ProjectFileStorage; folder?: FolderActions; saveAs?: Action; saveCommit?: Action};
15
+ type SaveEntries = {storage: ProjectFileStorage; folder?: FolderActions; saveNew?: Action; saveAs?: Action;
16
+ saveCommit?: Action};
14
17
 
15
- function saveEntries(locale: string, {storage, folder, saveAs, saveCommit}: SaveEntries): Entry[] {
18
+ function saveEntries(locale: string, {storage, folder, saveNew, saveAs, saveCommit}: SaveEntries): Entry[] {
16
19
  const ja = locale.startsWith('ja');
17
20
  return [
18
- ['save', ja ? 'プロジェクトを保存' : 'Save Project', storage.canSave ? storage.overwrite || folder?.save : undefined],
19
- ['save-as', ja ? '名前を変えて保存…' : 'Save As…', storage.canSave ? saveAs : undefined],
21
+ // Overwrites the file or saves into the folder; with no target yet, saveNew picks one that becomes the target.
22
+ ['save', ja ? 'プロジェクトを保存' : 'Save Project',
23
+ storage.canSave ? storage.overwrite || folder?.save || saveNew : undefined],
24
+ // Saves a copy and leaves the project where it is; the command id stays `save-as` for icons and hosts.
25
+ ['save-as', ja ? 'プロジェクトのコピーを保存…' : 'Save a Copy of the Project…', storage.canSave ? saveAs : undefined],
20
26
  ...(saveCommit ? [['save-commit', ja ? '保存してコミット…' : 'Save and Commit…', saveCommit] as Entry] : [])
21
27
  ];
22
28
  }
@@ -70,12 +76,27 @@ export default function ProjectFileMenu({locale, MenuItem, MenuSection, close, e
70
76
  close: Action;
71
77
  workspace?: SaveWorkspace;
72
78
  entries: {
79
+ /** Creates the default project in memory. Without `createIn`, Create New Project calls it directly. */
73
80
  create: Action;
81
+ /**
82
+ * With it, Create New Project… opens the dialog that chooses where to create the project, and calls this
83
+ * for a folder or a GitHub repository (see `renderNewProjectForm`). The in-memory choice still calls `create`.
84
+ */
85
+ createIn?: (request: NewProjectRequest, signal: AbortSignal) => Promise<NewProjectResult>;
86
+ /** What the Create New Project… dialog offers besides the in-memory project. */
87
+ newProject?: NewProjectChoices;
74
88
  newWindow?: Action;
75
89
  open: Action;
76
90
  externalYaml?: React.ReactNode;
77
91
  folder?: FolderActions;
92
+ openRemote?: Action;
78
93
  storage: ProjectFileStorage;
94
+ /**
95
+ * Save Project for a project with no save target (no file handle, no folder): opens the save form titled
96
+ * `projectFileDialogTitle('save', locale)`, whose file or folder becomes the project's target.
97
+ */
98
+ saveNew?: Action;
99
+ /** Save a Copy of the Project…: writes a copy and never changes the project's target. */
79
100
  saveAs?: Action;
80
101
  saveCommit?: Action;
81
102
  exportProject?: Action;
@@ -107,8 +128,13 @@ export default function ProjectFileMenu({locale, MenuItem, MenuSection, close, e
107
128
  </MenuItem>;
108
129
  };
109
130
  const e = entries;
131
+ const createIn = e.createIn;
132
+ const createNew: Entry = createIn ? ['new', ja ? '新しいプロジェクトを作成…' : 'Create New Project…', () => {
133
+ if (typeof document === 'undefined') return;
134
+ void openNewProjectDialog(document, locale, {...e.newProject, create: e.create, createIn});
135
+ }] : ['new', ja ? '新しいプロジェクトを作成' : 'Create New Project', e.create];
110
136
  return <>
111
- {item(['new', ja ? '新しいプロジェクトを作成' : 'Create New Project', e.create])}
137
+ {item(createNew)}
112
138
  {e.newWindow && item(['window', ja ? '新しいウィンドウ' : 'New Window', e.newWindow])}
113
139
  <MenuSection>
114
140
  {item(['open', ja ? 'SB3ファイルを開く…' : 'Open SB3 File…', e.open])}
@@ -119,6 +145,8 @@ export default function ProjectFileMenu({locale, MenuItem, MenuSection, close, e
119
145
  'This browser cannot open folders on your device. Use Chrome or Edge, or open a folder saved in this browser.'])}
120
146
  {e.folder?.openBrowser && item(['project-folder-open-browser',
121
147
  ja ? 'ブラウザーに保存したフォルダを開く…' : 'Open Folder Saved in This Browser…', e.folder.openBrowser])}
148
+ {e.openRemote && item(['git-open-remote',
149
+ ja ? 'Git のリモートリポジトリを開く…' : 'Open Remote Git Repository…', e.openRemote])}
122
150
  {e.git}
123
151
  {e.externalYaml}
124
152
  </MenuSection>