-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpoem-editor.html
820 lines (763 loc) · 28.4 KB
/
poem-editor.html
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Subliminal</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<link rel="icon" href="Resources/AbbstraktDog.ico">
<link rel="stylesheet" href="./styles.css" />
<script src="./account.js"></script>
<script src="./polyfill.js"></script>
<script src="./editor-document.js"></script>
<script src="./Other/component-registrar.js"></script>
<script src="./Other/notification-template.js"></script>
<script src="./Other/select-template.js"></script>
<script src="./Other/poem-canvas-editor-template.js"></script>
<script src="./server.js"></script>
<link rel="stylesheet" href="./poem-editor.css">
</head>
<body style="max-width: 100%; overflow-x: hidden; overflow-y: auto">
<dialog id="licenseAgreePopup" class="popup" style="width: max(30%, 500px)">
<h2>You're almost there!</h2>
<img src="Resources/Celebration.png" style="width: 100%" />
<p>
When you click submit, your poem will be uploaded publicly to the poem
purgatory. For more information, see the license agreement below.
</p>
<hr/>
<h2 style="cursor: pointer" onclick="licenseAgreement.style.display = licenseAgreement.style.display == 'none' ? 'block' : 'none';">
License agreement +
</h2>
<div style="display: none" id="licenseAgreement">
<p>
All content on this site must be licensed under the Creative Commons
Attribution-NonCommercial-ShareAlike 4.0, in order to make open source
contribution easy, with the underlying source code used to format and
display that content licensed under the GNU GPL-3 license. Summaries
of these licenses are available at CC BY-NC-SA and GPL-3.
</p>
<p>
By uploading your work to this site, you give consent for your poem to
be licensed under Creative Commons
Attribution-NonCommercial-ShareAlike 4.0.
</p>
<p>
You also agree to allow us permission to store and process your work.
We can also accept no responsibility, if you write something that gets
you in trouble with people you know, an institution, or local
government, you agree that you WILLINGLY chose to upload it here. We
accept no responsibility how your work is interpreted, and what
consequences may or may not come as a result of it.
</p>
<p>
You will always be the lone copyright owner of your work, we will
never take ownership of what you made from you, and we will always
comply if you ask for your poem to be modified, and or taken down from
this site.
</p>
</div>
<button class="popup-button" onclick="licenseAgreePopup.close(); uploadCurrent();">
Submit
</button>
</dialog>
<dialog id="builtinFreePopup" class="popup">
<h2>Built-in backgrounds:</h2>
<p>
These backgrounds are free for you to use to jazz up your poem's look!
Drawn and shot by members of the subliminal team.
</p>
<div class="background-grid" onclick="if (event.target == this) return
applyBuiltinBackground(event.target)
builtinFreePopup.close()
">
<div>
<img loading="lazy" src="./Resources/Backgrounds/ChilternsWalk.jpg" />
<div>Taken somewhere in the Chilterns, UK.</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/FinlandIntersection.jpg" />
<div>
Taken at an intersection somewhere between Uusikaupunki and
Helsinki, Finland.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/IsoBoy.jpg" />
<div>
A fish that mysteriously disappeared the next day, Island near
Uusikaupunki, Finland.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/LondonCity.jpg" />
<div>A bridge to the Tate, London, UK.</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/LondonStreets.jpg" />
<div>A day in the city, near Farringdon, London, UK.</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/Portheleven.jpg" />
<div>
It took standing on a rock in the middle of the sea to get this,
Portheleven, UK.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/FalmouthShellCave.jpg" />
<div>
A really old shell cave, in Gyllyngdune Gardens, Falmouth, UK.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/SnowdoniaPath.jpg" />
<div>A long path to mount Snowdon (maybe), Wales, UK.</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/SnowdoniaQuarry.jpg" />
<div>
A spooky snap of quarry taken from a moving vehicle, Snowdonia,
Wales, UK.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/SnowdoniaQuarry2.jpg" />
<div>A sunnier view of the massive quarry, Snowdonia, Wales, UK.</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/SnowdoniaQuarry3.jpg" />
<div>
An atmospheric pee(a)k (punny) of a quarry, Snowdonia, Wales, UK.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/UusikaupunkiHorsepower.jpg" />
<div>
This boat certainly has more than 5 horsepower, Island near
Uusikaupunki, Finland.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/YorkshireMoorRoad.jpg" />
<div>A long, long road, past field and moor, Yorkshire, UK.</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/ChaosDrawing.png" />
<div>
Chaos, for those who want to have a bit of zazz around their stuff.
</div>
</div>
<div>
<img loading="lazy" src="./Resources/Backgrounds/AbbstraktBird.png" />
<div>
Is it a bird? Dog? A secret message of text? All we know is that
this mascot is iconic.
</div>
</div>
</div>
</dialog>
<dialog id="loadPoemPopup" class="popup">
<h2>Load poem:</h2>
<input type="file" multiple="true" id="poemImportInput" accept=".json, .txt" style="display: none">
<div id="loadedContainer" class="vertical-scroll-shadow"></div>
<button class="popup-button" onclick="
poemImportInput.click() // TODO: Use new filesystem access API
for (let file of poemImportInput.files) {
let guid = newGuid()
let reader = new FileReader()
reader.onload = () => {
if (file.name.endsWith('.txt')) {
// TODO: Do a simple \n to our format replacement
let poemData = {
summary: '', //meta description
tags: '', //meta keywords
cWarning: false, //content warning
cWarningAdditions: '', //content warning additional notes
poemName: file.name.split('.txt')[0],
poemAuthor: 'Unknown', //poem header title
poemContent: reader.result, //poem html
pageStyle: 'poem-centre', //poem visual format
pageBackground: '' //poem background image
}
localStorage.setItem(guid, JSON.stringify(poemData))
loadKey(guid)
}
else if (file.name.endsWith('.json')) {
localStorage.setItem(guid, reader.result)
loadKey(guid)
}
else {
console.error('Uploaded poem was not a text (.txt) or JSON (.json) file, can not import!')
}
fetchStorage()
loadPoemPopup.close()
}
reader.readAsText(file)
}
">
Import from local file
</button>
<button class="popup-button" onclick="loadPoemPopup.close()">
Done
</button>
</dialog>
<div class="title-blur" style="z-index: 3">
<div style="display: flex">
<h2 id="poemName" onpaste="event.preventDefault()" onkeydown="
if (event.key === 'Enter') {
event.preventDefault()
return false
}
" style="display: inline; flex-grow: 1; text-align: right" contenteditable="true">
Click On Me to Start Editing
</h2>
<h2 class="centre" style="display: inline"> - By </h2>
<h2 id="poemAuthor" onpaste="event.preventDefault()" onkeydown="
if (event.key === 'Enter') {
event.preventDefault()
return false
}
" style="display: inline; flex-grow: 1; text-align: left" contenteditable="true">
Click On Me to Start Editing
</h2>
</div>
<hr />
<div id="formattingToolbar">
<button class="toolbar-item" style="width: 72px; min-width: 72px" onclick="this.children[1].style.display = this.children[1].style.display == 'block' ? 'none' : 'block'" onblur="this.children[1].style.display = 'none'">
<div>File ⯆</div>
<div class="options" style="width: 140px">
<div onclick=" params.delete('edit')
params.delete('append')
location.href = location.origin + '/poem-editor' + (params ? '?' + params.toString() : '')
">
Open new
</div>
<div onclick="
downloadCurrent()
document.body.appendChild(createFromData('subliminal-notification', { message: 'Successfully downloaded poem data.' }))
">
Download poem
</div>
<div onclick="saveCurrent()
document.body.appendChild(createFromData('subliminal-notification', { message: 'Successfully saved poem' }))
">
Save poem
</div>
<div onclick="loadPoemPopup.showModal()">
Open another
</div>
<div onclick="
if (!side.getAttribute('collapsed') && side.getAttribute('mode') == 'upload') {
licenseAgreePopup.showModal()
}
else {
side.setAttribute('mode', 'upload')
side.removeAttribute('collapsed')
}
">
Upload to site
</div>
</div>
</button>
<button class="toolbar-item" onclick="format('undo', null)" style="width: 72px; min-width: 72px">
<div>↩ undo</div>
</button>
<button class="toolbar-item" onclick="format('redo', null)" style="width: 72px; min-width: 72px">
<div>redo ↪</div>
</button>
<button class="toolbar-item" onclick="editor.addStyle(styleCodes.bold)">
<div style="font-weight: bold">B</div>
</button>
<button class="toolbar-item" onclick="editor.addStyle(styleCodes.italic)">
<div style="font-style: italic">I</div>
</button>
<button class="toolbar-item" onclick="editor.addStyle(styleCodes.monospace)">
<div style="font-family: monospace">C</div>
</button>
<button class="toolbar-item" onclick="editor.addStyle(styleCodes.superscript)">
<div>Sup</div>
</button>
<button class="toolbar-item" onclick="editor.addStyle(styleCodes.subscript)">
<div>Sub</div>
</button>
<button class="toolbar-item" style="position: relative" onclick="formatColourInput.click()">
<input id="formatColourInput" type="color" class="tool colour-tool-item" value="#000" oninput="
editor.addStyle(styleCodes.colour, parseInt(this.value.slice(1), '16'))
formattingColourRect.style.background = this.value
" style="display: none;">
<div id="formattingColourRect"></div>
</button>
<button class="toolbar-item">
<div>🖼️</div>
</button>
<div class="toolbar-item separator"></div>
<button class="toolbar-item" style="width: 112px; min-width: 112px" onclick="this.children[1].style.display = this.children[1].style.display == 'block' ? 'none' : 'block'" onblur="this.children[1].style.display = 'none'">
<div>Page layout ⯆</div>
<div class="options">
<div onclick="changePageStyle('poem-centre')">Poem centre</div>
<div onclick="changePageStyle('poem-centre-wide')">Poem wide</div>
<div onclick="changePageStyle('centre')">Centre</div>
</div>
</button>
<button class="toolbar-item" style="width: 112px; min-width: 112px" onclick="this.children[1].style.display = this.children[1].style.display == 'block' ? 'none' : 'block'" onblur="this.children[1].style.display = 'none'">
<div>Background ⯆</div>
<div class="options">
<div onclick="document.body.style.background = ''">None</div>
<div onclick="document.body.style.background = `url(\'${prompt('Enter the background image URL')}\')`">
From link
</div>
<div style="opacity: 0.6">Upload file</div>
<div onclick="builtinFreePopup.showModal();">
Built-in free
</div>
</div>
</button>
<button class="toolbar-item" onclick=" side.removeAttribute('collapsed')
side.setAttribute('mode', 'rhyme')
" style="width: 132px; min-width: 132px">
<div>Rhyme finder ➕</div>
</button>
<button class="toolbar-item" onclick=" side.removeAttribute('collapsed')
side.setAttribute('mode', 'coauthor')
" style="width: 132px; min-width: 132px">
<div>AI coauthor ➕</div>
</button>
</div>
<hr>
</div>
<dialog id="editorsPopup" class="popup">
<h2>Find someone to invite</h2>
<input type="text" placeholder="Search for user by username" />
<div id="editorsResults" style="height: 500px"></div>
</dialog>
<div class="online-editors">
Online editors:
<div>
<img src="Resources/DefaultAvatar.png" style="border-radius: 100%; background-color: white" width="48" height="48" />
<div style=" padding: 4px;
border-radius: 8px;
background: linear-gradient(lightblue, blue);
color: white;
height: 24px;
position: relative;
align-self: center;
">
You
</div>
</div>
<button style="margin-top: 24px" onclick="">Invite editor</button>
</div>
<div id="main" class="poem-centre">
<poem-canvas-editor id="poemEditor"></poem-canvas-editor>
</div>
<div id="side" class="document-tools" collapsed="false" mode="upload" onclick="
if (side.getAttribute('collapsed')) side.removeAttribute('collapsed')
">
<div class="side-content" upload>
<div>
<div style="display: flex; flex-direction: row; height: 48px">
<p style="margin: 0px; align-self: center">Poem summary:</p>
</div>
<textarea id="summaryArea" type="text" maxlength="160"></textarea>
</div>
<div>
<div style="display: flex; flex-direction: row; height: 48px">
<p style="margin: 0px; align-self: center">Poem tags:</p>
</div>
<div id="tagContainer">
<button add="true" style="line-height: 64px" onclick="addPoemTag(window.prompt('Enter tag you would like to add'))">
<span>+ Add tag</span>
</button>
</div>
</div>
<div>
<div style="display: flex; flex-direction: row; height: 48px">
<p style="margin: 0px; align-self: center">Content Warning:</p>
</div>
<div id="cWarningContainer" style=" background: var(--button-opaque);
border-radius: 8px;
padding: 8px;
">
<input type="checkbox" id="cWarningCheckbox" onchange="cWarningNotesInput.disabled = this.checked ? false : true" />
<label for="cWarningCheckbox"> Enabled</label>
<input type="text" id="cWarningNotesInput" class="popup-input" placeholder="Additional warning notes" style="width: 100%; height: 24px" disabled="" />
</div>
</div>
<button class="popup-button" style="flex-grow: inherit" onclick="licenseAgreePopup.showModal()">
Upload to site
</button>
</div>
<div class="side-content" rhyme>
<p>Poem Rhyme finder:</p>
<input id="rhymeFinderInput" style="font-size: 16px" type="text" class="popup-input" placeholder="Enter word" />
<p style="opacity: 0.6; font-size: 10px">
Use * to match any word ending, or ?? to match anything within a word,
for example pai* (paint, pain), p???t (paint, print)
</p>
<!--TODO: Call rhymeFinderFind(rhymeFinderInput.value, event.target.dataset.api)-->
<subliminal-select placeholder="Word search type">
<option value="ml">Similar meaning</option>
<option value="sl">Sound like</option>
<option value="sp">Spelled similarly</option>
<option value="rel_jjb">Adjectives used to describe</option>
<option value="rel_jja">Nouns described by</option>
<option value="rel_rhy">Perfect rhymes</option>
<option value="rel_nry">Half rhymes</option>
<option value="rel_nry">Homophones</option>
<option value="rel_ant">Antonyms</option>
<option value="rel_nry">Matching consonant</option>
</subliminal-select>
<div id="sideRhymeMatches">
<!--Container for side rhyme match elements-->
</div>
<p style="opacity: 0.6; font-size: 10px">
Credits to datamuse for their fantastic API. https://www.datamuse.com/
</p>
</div>
<div class="side-content" coauthor>
<p>Poem AI coauthor:</p>
<span style="opacity: 0.6">Use the subliminal poem writing AI to help cowrite your work!</span
>
<subliminal-select placeholder="Base the AI's results off of:">
<option>My work so far</option>
<option>Subliminal poems</option>
</subliminal-select>
<button class="popup-button" style="flex-grow: inherit" onclick="alert('An error occurred - please try again later')">
Start coauthor
</button>
</div>
<div class="side-content" close>
<div class="side-close-button" onclick=" side.setAttribute('collapsed', true)
side.setAttribute('mode', 'upload')
event.stopPropagation()
">
<svg xmlns="http://www.w3.org/2000/svg" data-name="icons final" viewBox="0 0 20 20">
<path d="M18.442 2.442l-.884-.884L10 9.116 2.442 1.558l-.884.884L9.116 10l-7.558 7.558.884.884L10 10.884l7.558 7.558.884-.884L10.884 10l7.558-7.558z"></path>
</svg>
</div>
</div>
</div>
<a href="./contents" style="z-index: 1" class="back"> <- Back</a>
</body>
<script>
const params = new URLSearchParams(document.location.search)
const edit = params.get("edit")
const amend = params.get("amend")
const decoder = new TextDecoder()
let currentGuid = ""
let poemTags = []
let network = null
const editor = new EditorDocument("Click On Me to Start Editing", 1.5, 18)
poemEditor.useDocument(editor)
// Make user confirm that they want to leave the page.
window.onbeforeunload = () => true
// format title to subliminal title format, used in poem download files, remove all non-fs friendly chars
function formatDash(text) {
return text
.trim()
.toLowerCase()
.replaceAll(" ", "-")
.replaceAll(/(^\.|[<>:"/\|?*])/g, "");
}
// Save poem with a unique GUID so that we do not encounter overlaps
function newGuid() {
return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11)
.replace(/[018]/g, (char) =>
(char ^(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (char / 4)))).toString(16))
}
let pageToHtml = (text) => {
let htmlObject = document.createElement("body")
htmlObject.innerHTML = text
return htmlObject
};
async function fetchStorage() {
// Clear anything that may already be in the laoded container
while (loadedContainer.firstChild) {
loadedContainer.removeChild(loadedContainer.firstChild)
}
// Fetch poems in localstorage
for (let i = 0; i < localStorage.length; i++) {
if (localStorage.key(i).length != 36) {
console.log(`Could not identify localStorage poem with key ${localStorage.key(i)} as a poem.`)
continue
}
let current = JSON.parse(localStorage.getItem(localStorage.key(i)))
let cardEl = document.createElement("div")
cardEl.className = "poem-card"
cardEl.onclick = () => {
loadKey(localStorage.key(i))
loadPoemPopup.close()
};
let cardTitle = document.createElement("h4")
cardTitle.textContent = current.poemName
cardEl.appendChild(cardTitle)
let cardPreview = document.createElement("p")
cardPreview.className = "poem-preview"
let pContent = null
try {
pContent = current.poemContent
} catch (e) {
continue
}
cardPreview.textContent = pContent
cardEl.appendChild(cardPreview)
loadedContainer.appendChild(cardEl)
}
// If logged in, try to fetch poems from the subliminal cloud
if (localStorage.code) {
let draftPoemIds = await getAccountData().draftPoemIds
for (let id of draftPoemIds) {
let draft = await executeAccountAction(
actionType.GetDraft,
id
).json()
let cardEl = document.createElement("div")
cardEl.className = "poem-card"
cardEl.onclick = async () => {
load(await executeAccountAction(actionType.GetDraft, id).json())
loadPoemPopup.close()
};
let cardTitle = document.createElement("h4")
cardTitle.textContent = draft.poemName
cardEl.appendChild(cardTitle)
let cardPreview = document.createElement("p")
cardPreview.className = "poem-preview"
cardPreview.textContent = draft.poemContent
}
}
}
function saveCurrent() {
let saveData = {
summary: summaryArea.value, //meta description
tags: poemTags.toString(), //meta keywords
cWarning: cWarningCheckbox.checked, //content warning
cWarningAdditions: cWarningNotesInput.value, //content warning additional notes
poemName: poemName.innerText,
poemAuthor: poemAuthor.innerText, //poem header title
poemContent: editor.data, //poem html
pageStyle: main.className, //poem visual format
pageBackground: document.body.style.background //poem background image
}
currentGuid ||= newGuid()
localStorage.setItem(currentGuid, JSON.stringify(saveData))
//Refresh load box with latest poem.
fetchStorage()
}
function loadKey(key) {
currentGuid = key
let poemJson = JSON.parse(localStorage.getItem(key))
load(poemJson)
}
function load(poemJson) {
poemTags = [];
while (!tagContainer.lastElementChild.getAttribute("add")) {
tagContainer.removeChild(tagContainer.lastElementChild)
}
if (poemJson.tags) {
for (let tag of poemJson.tags?.split(",")) {
addPoemTag(tag)
}
}
summaryArea.value = poemJson.summary ?? ""
cWarningCheckbox.checked = poemJson.cWarning ?? ""
cWarningNotesInput.disabled = !poemJson.cWarning
cWarningNotesInput.value = poemJson.cWarningAdditions ?? ""
poemName.innerText = poemJson.poemName ?? "undefined"
poemAuthor.innerText = poemJson.poemAuthor ?? "undefined"
editor.data = poemJson.poemContent ?? "undefined"
document.body.style.background = poemJson.pageBackground ?? ""
changePageStyle(poemJson.pageStyle ?? "poem-centre")
}
//This itelf is just the poem-editor, content will be moved from here to a new template file, and then downloaded
function downloadCurrent() {
saveCurrent()
let el = document.createElement("a")
el.setAttribute("href", "data:text/html;charset=UTF-8," + encodeURIComponent(localStorage.getItem(currentGuid)))
el.setAttribute("download", formatDash(poemName.innerText) + ".json")
el.style.display = "none"
document.body.appendChild(el)
el.click()
document.body.removeChild(el)
}
async function uploadCurrent() {
saveCurrent()
let loadObject = JSON.parse(localStorage.getItem(currentGuid))
await upload(loadObject)
}
async function upload(poemJson) {
if (await isLoggedIn()) {
poemJson.code = localStorage.accountCode
}
fetch(serverBaseAddress + "/purgatory", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(poemJson),
})
.then((res) => {
if (!res.ok) {
console.error("Cricical error in uploading" + res)
licenseAgreePopup.close()
alert("Sorry!\n\nFailed to upload poem to purgatory. Maybe try again...")
return null
}
return res.text()
})
.then((guidResponse) => {
if (guidResponse == null) {
return
}
console.log("Upload sucessful, redirecting.")
window.onbeforeunload = () => {}
window.location.href = "./contents?purgatorynew=" + guidResponse
});
}
function changePageStyle(newStyle) {
main.className = newStyle
poemEditor.updateCanvas()
}
function applyBuiltinBackground(target) {
if (!target.src) return
document.body.style.background = `url('${target.src}')`
}
function addPoemTag(tagName) {
if (!tagName || poemTags.includes(tagName) || poemTags.length >= 5) {
return
}
tagName = tagName.replace(/\W+/g, "").slice(0, 12)
poemTags.push(tagName)
let newTag = document.createElement("button")
let newLabel = document.createElement("span")
newLabel.textContent = tagName
newTag.appendChild(newLabel)
newTag.onclick = () => {
removePoemTag(tagName)
}
tagContainer.appendChild(newTag)
}
function removePoemTag(tagName) {
poemTags.splice(poemTags.indexOf(tagName), 1)
for (let tag of tagContainer.children) {
if (tag.innerText == tagName) tagContainer.removeChild(tag)
}
}
async function fetchPathJson(path) {
return await (
await fetch((path.includes("/") ? window.location.origin : serverBaseAddress + "/purgatory/") + path)
).json()
}
async function amendMode() {
throw new Error("Not implemented")
loadPoemPopup.close()
//Load up amendment poem
let currentJson = await fetchPathJson(amend);
currentJson.amends = amend
/*TODO: Reimplement
originalContent.style.display = "block"
originalContent.style.top = content.offsetTop + "px"
originalContent.style.maxWidth = content.offsetWidth + "px"
originalContent.innerHTML = currentJson.poemContent || ""*/
load(currentJson)
}
async function rhymeFinderFind(word, apiPath) {
let path = "https://api.datamuse.com/words?" + apiPath + "=" + word.replaceAll(" ", "+")
if ((word.includes("*") || word.includes("?")) && apiPath != "sp") {
path += "&sp=" + word
}
let response = await fetch(path);
let matches = response.ok ? await response.json() : []
while (sideRhymeMatches.lastElementChild) {
sideRhymeMatches.removeChild(sideRhymeMatches.lastElementChild)
}
matches.sort((a, b) => a.score > b.score ? -1 : a.score == b.score ? 0 : 1)
for (let match of matches) {
let el = document.createElement("div")
el.textContent = match.word
let score = document.createElement("span")
score.style.opacity = "0.6"
score.textContent = " (" + match.score + " score)"
el.appendChild(score)
sideRhymeMatches.appendChild(el)
}
}
async function getRhymes(word) {
let response = await fetch("https:\/\/rhymebrain.com/talk?function=getRhymes&word=" + word)
return response.ok ? await response.json() : []
}
async function getWordInfo(word) {
let response = await fetch("https://rhymebrain.com/talk?function=getWordInfo&word=" + word)
return response.ok ? await response.json() : null
}
async function spawnRhymePopup(event) {
const findWord = (text, position) => {
const after = text.substring(position).match(/^[a-zA-Z0-9-_]+/)
const before = text.substring(0, position).match(/[a-zA-Z0-9-_]+$/)
return (before || "") + (after || "");
};
// TODO: Fix for new poem editor system
let offset =
document.getSelection().baseOffset ||
document.getSelection().getRangeAt(0).startOffset
let selectedWord = findWord(event.target.textContent, offset)
let rhymes = await getRhymes(selectedWord)
let selectedSyllables = (await getWordInfo(selectedWord))?.syllables || 2
if (offset == null || rhymes == null) return
rhymes.sort((a, b) => Math.abs(selectedSyllables - a.syllables) < Math.abs(selectedSyllables - b.syllables)
? -1
: Math.abs(selectedSyllables - a.syllables) == Math.abs(selectedSyllables - b.syllables) ? 0 : 1)
while (suggestions.lastElementChild) {
suggestions.removeChild(suggestions.lastElementChild)
}
for (let rhyme of rhymes) {
if (!rhyme.word || rhyme.word.length <= 1) continue
let item = document.createElement("div")
item.className = "suggestions-item"
item.innerHTML = `<span>${rhyme.word}</span><span>(${rhyme.syllables} syllable${rhyme.syllables > 1 ? "s" : ""})</span>`
suggestions.appendChild(item)
}
let item = document.createElement("div")
item.className = "suggestions-item"
item.innerHTML = `<span>❤️ </span><span>All credits goes to rhymebrain for their fantastic API. https://rhymebrain.com</span>`
suggestions.appendChild(item)
suggestions.style.display = "block"
suggestions.style.top = event.offsetY + 48 + "px"
suggestions.style.left = event.offsetX + 16 + "px"
suggestions.scrollTo(0, 0)
suggestions.animate([{ maxHeight: "0px" }, { maxHeight: "256px" }], {
duration: 200,
iterations: 1,
fill: "both",
})
}
function appendRhyme(event) {
// TODO: Rhyme
console.log(event)
}
async function editMode() {
loadPoemPopup.close()
let currentJson = await fetchPathJson(edit)
currentJson.edits = edit
load(currentJson)
}
if (amend)
amendMode(); //enter poem amendment mode
else if (edit) editMode();
else fetchStorage(); //Load saved poems from local storage
formattingToolbar.addEventListener("mousemove", (event) => {
for (let button of formattingToolbar.children) {
if (button.className == "separator") continue;
button.style.background =
"radial-gradient(at left " +
(event.screenX - button.offsetLeft) +
"px top " +
(event.screenY - button.offsetTop) +
"px, darkgray, var(--background-opaque)"
}
});
formattingToolbar.addEventListener("mouseleave", (event) => {
for (let button of formattingToolbar.children) {
if (button.className == "separator") continue
button.style.background = "none"
}
});
</script>
</html>