File size: 8,567 Bytes
161e1da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b43ac90
161e1da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
<script>
  import {onMount, tick} from 'svelte';
  import {_} from '../locales';
  import Section from './Section.svelte';
  import Button from './Button.svelte';
  import DropArea from './DropArea.svelte';
  import ComplexMessage from './ComplexMessage.svelte';
  import ImportingProject from './ImportProject.svelte';
  import writablePersistentStore from './persistent-store';
  import {progress, currentTask} from './stores';
  import {UserError} from '../common/errors';
  import getProjectMetadata from './get-project-metadata';
  import loadProject from '../packager/load-project';
  import {extractProjectId, isValidURL, getTitleFromURL} from './url-utils';
  import Task from './task';
  import importExternalProject from './import-external-project';

  const defaultProjectId = '163240';

  const type = writablePersistentStore('SelectProject.type', 'id');
  const projectId = writablePersistentStore('SelectProject.id', defaultProjectId);
  const projectUrl = writablePersistentStore('SelectProject.url', '');

  const projectIdInURL = /^#\d+$/.test(location.hash) ? location.hash.substring(1) : null;
  if (projectIdInURL) {
    $type = 'id';
    $projectId = projectIdInURL;
  }

  let isImportingProject = false;
  importExternalProject({
    onStartImporting: () => {
      isImportingProject = true;
    },
    onCancelImporting: () => {
      isImportingProject = false;
    },
    onFinishImporting: (files) => {
      if (!isImportingProject) {
        // Import was cancelled.
        return;
      }
      $type = 'file';
      isImportingProject = false;
      fileInputElement.files = files;
      setFiles(files);
    }
  });

  export let projectData = null;
  const resetProjectAndCancelTask = () => {
    projectData = null;
    currentTask.abort();
  };

  // Reset project when input changes
  $: $projectId, $type, resetProjectAndCancelTask();

  // just incase some non-number string was stored from older versions
  $projectId = extractProjectId($projectId);

  const getDisplayedProjectURL = () => `https://studio.penguinmod.com/#${$projectId}`;

  const submitOnEnter = (e) => {
    if (e.key === 'Enter') {
      load();
    }
  };
  const handleInput = (e) => {
    $projectId = extractProjectId(e.target.value);
    e.target.value = getDisplayedProjectURL();
  };
  const handleFocus = (e) => {
    e.target.select();
  };

  let fileInputElement;

  const copyFileList = (files) => {
    const transfer = new DataTransfer();
    for (const file of files) {
      transfer.items.add(file);
    }
    return transfer.files;
  };

  // This is used to remember files between reloads in some browsers (currently only Firefox)
  // This element is defined in the HTML of template.ejs because some browsers won't
  // autocomplete file inputs generated by JS.
  const inputForRememberingProjectFile = document.querySelector('.input-for-remembering-project-file');
  if (inputForRememberingProjectFile) {
    // Check for autocompleted files after mount so that fileInputElement is defined.
    onMount(() => {
      const storedFiles = inputForRememberingProjectFile.files;
      if (storedFiles.length) {
        fileInputElement.files = copyFileList(storedFiles);
      }
    });
  }

  const setFiles = (files) => {
    resetProjectAndCancelTask();
    if (fileInputElement.files !== files) {
      fileInputElement.files = files;
    }
    if (inputForRememberingProjectFile) {
      inputForRememberingProjectFile.files = copyFileList(files);
    }
    if (files.length && $type === 'file') {
      // if $type was updated before calling this function, wait for the current task to get
      // cancelled before we start the next one
      tick().then(load);
    }
  };
  const handleDrop = ({detail: dataTransfer}) => {
    const name = dataTransfer.files[0].name;
    if (name.endsWith('.sb') || name.endsWith('.sb2') || name.endsWith('.sb3') || name.endsWith('.pm') || name.endsWith('.pmp') || name.endsWith('.s4s.txt')) {
      $type = 'file';
      setFiles(dataTransfer.files);
    }
  };
  const handleFileInputChange = (e) => {
    setFiles(e.target.files);
  };

  const internalLoad = async (task) => {
    let uniqueId = '';
    let id = null;
    let projectTitle = '';
    let project;

    const progressCallback = (type, a, b) => {
      if (type === 'fetch') {
        task.setProgress(a);
      } else if (type === 'assets') {
        task.setProgressText(
          $_('progress.loadingAssets')
            .replace('{complete}', a)
            .replace('{total}', b)
        );
        task.setProgress(a / b);
      } else if (type === 'compress') {
        task.setProgressText($_('progress.compressingProject'));
        task.setProgress(a);
      }
    };

    if ($type === 'id') {
      id = $projectId;
      if (!id) {
        throw new UserError($_('select.invalidId'));
      }
      uniqueId = `#${id}`;

      task.setProgressText($_('progress.loadingProjectMetadata'));
      const metadata = await getProjectMetadata(id);

      const token = metadata.token;
      projectTitle = metadata.title;

      task.setProgressText($_('progress.loadingProjectData'));
      const {promise: loadProjectPromise, terminate} = await loadProject.fromID(id, token, progressCallback);
      task.whenAbort(terminate);
      project = await loadProjectPromise;
    } else if ($type === 'file') {
      const files = fileInputElement.files;
      const file = files && files[0];
      if (!file) {
        throw new UserError($_('select.noFileSelected'));
      }
      uniqueId = `@${file.name}`;
      projectTitle = file.name;
      task.setProgressText($_('progress.compressingProject'));
      project = await (await loadProject.fromFile(file, progressCallback)).promise;
    } else if ($type === 'url') {
      const url = $projectUrl;
      if (!isValidURL(url)) {
        throw new UserError($_('select.invalidUrl'));
      }
      uniqueId = `$${url}`;
      projectTitle = getTitleFromURL(url);
      task.setProgressText($_('progress.loadingProjectData'));
      project = await (await loadProject.fromURL(url, progressCallback)).promise;
    } else {
      throw new Error('Unknown type');
    }

    return {
      projectId: id,
      uniqueId,
      title: projectTitle,
      project,
    };
  };
  const load = async () => {
    resetProjectAndCancelTask();
    const task = new Task();
    projectData = await task.do(internalLoad(task));
    task.done();
  };
</script>

<style>
  input[type="text"] {
    max-width: 300px;
    flex-grow: 1;
  }
  .options {
    margin: 12px 0;
  }
  .option {
    min-height: 25px;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }
  input[type="text"], input[type="file"] {
    margin-left: 4px;
  }
</style>

{#if isImportingProject}
  <ImportingProject on:cancel={() => {
    isImportingProject = false;
  }} />
{/if}

<DropArea on:drop={handleDrop}>
  <Section accent="#4C97FF">
    <h2>{$_('select.select')}</h2>
    <p>{$_('select.selectHelp')}</p>

    <div class="options">
      <div class="option">
        <label>
          <input type="radio" name="project-type" bind:group={$type} value="id">
          {$_('select.id')}
        </label>
        {#if $type === "id"}
          <input type="text" value={getDisplayedProjectURL()} spellcheck="false" on:keypress={submitOnEnter} on:input={handleInput} on:focus={handleFocus}>
        {/if}
      </div>
      <!-- TurboWarp Desktop looks for the file-input-option class for special handling, so be careful when modifying this. -->
      <div class="option file-input-option">
        <label>
          <input type="radio" name="project-type" bind:group={$type} value="file">
          {$_('select.file')}
        </label>
        <input hidden={$type !== "file"} on:change={handleFileInputChange} bind:this={fileInputElement} type="file" accept=".sb,.sb2,.sb3, .pm, .pmp, .s4s.txt, .goobert">
      </div>
      <div class="option">
        <label>
          <input type="radio" name="project-type" bind:group={$type} value="url">
          {$_('select.url')}
        </label>
        {#if $type === "url"}
          <input type="text" bind:value={$projectUrl} spellcheck="false" placeholder="https://..." on:keypress={submitOnEnter}>
        {/if}
      </div>
    </div>

    {#if $type === "id"}
      <p>
        {$_('select.unsharedProjects')}
      </p>
    {/if}

    <Button on:click={load} text={$_('select.loadProject')} />
  </Section>
</DropArea>

{#if !$progress.visible && !projectData}
  <Section caption>
    <p>{$_('select.loadToContinue')}</p>
  </Section>
{/if}