-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
146 lines (129 loc) · 3.83 KB
/
index.js
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
'use strict';
const editor = new Jodit('#editor', {
buttons: 'bold,italic,underline,strikethrough,eraser,ul,ol,image,file,copyformat,cut,copy,paste,selectall,hr,table,link,paragraph',
uploader: {
insertImageAsBase64URI: true
}
});
const loadDelay = 500;
/** @type {(endpoint: String) => String} */
const api = endpoint => `https://submedit.r2dev2bb8.repl.co${endpoint}`;
const articleTemplate = `
<h2>See also</h2>
<h2>References</h2>
`.trim();
/**
* Makeshift state manager
*
* @template {T}
* @type {(value: T) => [() => T, (newValue: T) => void, (cb: (value: T) => void) => void]}
*/
const useState = value => {
const subscribers = [];
return [
function get() { return value; },
function set(newValue) {
if (newValue == value) return;
value = newValue;
subscribers.forEach(cb => cb(value));
},
function subscribe(cb) {
subscribers.push(cb);
cb(value);
}
]
};
// State
const [articleName, setArticleName, subArticleName] = useState('');
const [articleHTML, setArticleHTML, subArticleHTML] = useState(articleTemplate);
// Computed State
/** @type {() => String} */
const articleMarkdown = () => toMarkdown(articleHTML());
// View
const elements = {
articleTitle: document.querySelector('#article-title'),
uploadButton: document.querySelector('button[name=upload]')
};
subArticleName($name => elements.articleTitle.value = $name);
// Update State
const turndownService = new TurndownService();
const toMarkdown = turndownService.turndown.bind(turndownService);
/** @type {() => String} */
const getArticleName = () => new URLSearchParams(window.location.search)
.get('article')
?.replaceAll('_', ' ')
?? '';
function delayed(cb, int) {
let timeoutId = null;
return (...args) => {
if (timeoutId != null) clearTimeout(timeoutId);
timeoutId = setTimeout(() => cb(...args), int);
}
};
/**
* @template {T}
* @template {E}
* @type {(fn: (arg: T) => Promise<E>) => (arg: T) => Promise<E>}
*/
const asyncMemoize = fn => {
/** @type {Map<T, E>} */
const cache = new Map();
return async arg => {
if (cache.has(arg)) return cache.get(arg);
const result = await fn(arg);
cache.set(arg, result);
return result;
};
};
/** @type {(rawArticle: String) => String} */
const extractArticleHTML = rawArticle => {
const container = document.createElement('div');
container.innerHTML = rawArticle;
return container.querySelector('.article').innerHTML.trim();
};
/** @type {(articleName: String) => Promise<String>} */
const getArticleContents = asyncMemoize(async articleName => {
const articleRoute = `../wiki/en/${articleName.replaceAll(' ', '_')}.html`;
return await fetch(articleRoute)
.then(r => r.text())
.then(extractArticleHTML)
.catch(() => articleTemplate);
});
/** @type {(html: String) => void} */
const initArticleHTML = html => {
const aHTML = articleHTML().trim();
if (aHTML === articleTemplate || aHTML === '') editor.setEditorValue(html);
};
/** @type {(url: String, body: any) => Promise} */
const postJSON = (url, body) => fetch(url, {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(body)
});
const successPopup = () => Swal.fire(
'Upload succeeded',
'We will review your contribution and may accept it.',
'success'
);
const failurePopup = e => Swal.fire(
'Upload failed',
`Error: ${e}`,
'error'
);
setArticleName(getArticleName());
subArticleName($name => getArticleContents($name).then(initArticleHTML));
editor.events.on('change', setArticleHTML);
elements.articleTitle.addEventListener('input', delayed(() => {
setArticleName(elements.articleTitle.value);
}, loadDelay));
elements.uploadButton.addEventListener('click', () => {
postJSON(api('/article'), {
title: articleName(),
body: articleMarkdown()
})
.then(successPopup)
.catch(failurePopup);
});