spec-up-t 1.2.1 → 1.2.2

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,372 +0,0 @@
1
- /**
2
- * @file This file fetches and displays commit hashes by matching elements with `x-term-reference` class against the `allXTrefs` global object.
3
- * Example:
4
- * const allXTrefs = {
5
- "xtrefs": [
6
- {
7
- "externalSpec": "test-1",
8
- "term": "Aal",
9
- "repoUrl": "https://github.com/blockchainbird/spec-up-xref-test-1",
10
- "terms_dir": "spec/term-definitions",
11
- "owner": "blockchainbird",
12
- "repo": "spec-up-xref-test-1",
13
- "site": "https://blockchainbird.github.io/spec-up-xref-test-1/",
14
- "commitHash": [
15
- "f66951f1d378490289caab9c51141b44a0438365",
16
- "content": "[[def: AAL]]:\n\n~ See: [[ref: authenticator assurance level]].\n\n~ This is an addition, for testing purposes.\n"
17
- ]
18
- },
19
- {…}
20
- ]
21
- };
22
- * @author Kor Dwarshuis
23
- * @version 0.0.1
24
- * @license MIT
25
- * @since 2024-06-09
26
- */
27
-
28
-
29
-
30
- function fetchCommitHashes() {
31
-
32
- let tipMap = new WeakMap();
33
-
34
- async function insertGitHubTermRealTime(match, element) {
35
- const div = document.createElement('div');
36
- div.classList.add('fetched-xref-term');
37
- div.classList.add('transcluded-xref-term');
38
- div.innerHTML = "<p class='loadertext'>Loading external reference</p><div class='loader'></div>";
39
- element.parentNode.insertBefore(div, element.nextSibling);
40
-
41
- // Promise.all waits for both termPromise and delayPromise to complete if termPromise finishes within 2000 ms.If termPromise takes longer than 2000 ms, the delay is effectively bypassed because Promise.all only cares about both promises finishing, regardless of the time taken by each.
42
-
43
- // Start fetching the GitHub term asynchronously
44
- const termPromise = fetchGitHubTerm(savedToken, match);
45
-
46
- // Create a delay of 2000 ms
47
- const delayPromise = new Promise(resolve => setTimeout(resolve, 2000));
48
-
49
- // Wait for whichever completes last between termPromise and delayPromise. The square brackets are used for array destructuring. In this context, the code is awaiting the resolution of multiple promises (termPromise and delayPromise) using Promise.all. The result of Promise.all is an array, and the square brackets are used to extract the first element of that array into the variable term.
50
- const [term] = await Promise.all([termPromise, delayPromise]);
51
-
52
- const timestamp = Date.now();
53
- const date = new Date(timestamp);
54
- const options = {
55
- year: 'numeric',
56
- month: 'long',
57
- day: 'numeric',
58
- hour: '2-digit',
59
- minute: '2-digit',
60
- second: '2-digit'
61
- };
62
- const humanReadableDate = date.toLocaleDateString('en-US', options);
63
-
64
- // Now that either both are complete or the term has taken longer than 2000 ms, continue with your code
65
- div.innerHTML = "<p class='transclusion-heading'>Current definition</p><small>" + humanReadableDate + "</small>" + term;
66
- }
67
- // Check if allXTrefs is undefined or does not exist
68
- if (typeof allXTrefs === 'undefined' || allXTrefs === null) {
69
- console.log('allXTrefs is not defined or does not exist. We will continue without it.');
70
- return;
71
- }
72
-
73
- // Load GitHub API token from local storage if it exists
74
- const savedToken = localStorage.getItem('githubToken');
75
-
76
- // Markdown parser, assuming markdown-it and markdown-it-deflist are globally available
77
- const md = window.markdownit().use(window.markdownitDeflist);
78
-
79
- // A: Debounce function to delay execution, so the error message is not displayed too often, since we do not know of often and how many times the error will be triggered.
80
- function debounce(func, wait) {
81
- let timeout;
82
- return function (...args) {
83
- clearTimeout(timeout);
84
- timeout = setTimeout(() => func.apply(this, args), wait);
85
- };
86
- }
87
-
88
- // B: Debounced “GitHub API rate limit exceeded” error message
89
- const debouncedError = debounce(() => {
90
- notyf.error('GitHub API rate limit exceeded. See <a target="_blank" rel="noopener" href="https://blockchainbird.github.io/spec-up-t-website/docs/getting-started/github-token">documentation</a> for more info.');
91
- }, 3000); // Delay in milliseconds
92
-
93
- /**
94
- * Fetches the content of a term file from GitHub using the GitHub API.
95
- * Compares the fetched content with the locally stored version and displays the diff in a modal.
96
- *
97
- * @param {string} savedToken - GitHub API token for authentication
98
- * @param {Object} match - The matched term object containing repository and term information
99
- */
100
- function fetchGitHubContent(savedToken, match) {
101
- // Create a headers object with the Authorization header if a GitHub API token is set
102
- const headers = {};
103
- if (savedToken && savedToken.length > 0) {
104
- headers['Authorization'] = `token ${savedToken}`;
105
- }
106
-
107
- fetch('https://api.github.com/repos/' + match.owner + '/' + match.repo + '/contents/' + match.terms_dir + '/' + match.term.replace(/ /g, '-').toLowerCase() + '.md', { headers: headers })
108
- .then(response => {
109
- if (response.status === 403 && response.headers.get('X-RateLimit-Remaining') === '0') {
110
- const resetTime = new Date(response.headers.get('X-RateLimit-Reset') * 1000);
111
- console.error(`❌ Github API rate limit exceeded. Try again after ${resetTime}. See https://blockchainbird.github.io/spec-up-t-website/docs/getting-started/github-token for more info.`);
112
-
113
- // Call the debounced error function
114
- debouncedError();
115
- return true;
116
- } else {
117
- console.log(`ℹ️ Github API rate limit: ${response.headers.get('X-RateLimit-Remaining')} requests remaining. See https://blockchainbird.github.io/spec-up-t-website/docs/getting-started/github-token for more info.`);
118
- }
119
-
120
- return response.json();
121
- })
122
- .then(data => {
123
- // Decode base64 encoded content
124
- const decodedContent = atob(data.content);
125
-
126
- // Diff the content of the current term-file with the content of stored version
127
- // See https://www.npmjs.com/package/diff , examples
128
- const diff = Diff.diffChars(match.content, decodedContent),
129
- fragment = document.createDocumentFragment();
130
-
131
- diff.forEach((part) => {
132
- // green for additions, red for deletions
133
- // grey for common parts
134
- const color = part.added ? 'green' :
135
- part.removed ? 'red' : 'grey';
136
-
137
- const backgroundColor = part.added ? '#ddd' :
138
- part.removed ? '#ddd' : 'white';
139
-
140
- span = document.createElement('span');
141
- span.style.color = color;
142
- span.style.backgroundColor = backgroundColor;
143
-
144
- span.appendChild(document
145
- .createTextNode(part.value));
146
- fragment.appendChild(span);
147
- });
148
- // Create a temporary container to hold the fragment
149
- const tempContainer = document.createElement('div');
150
- tempContainer.innerHTML = '<h1>Diff xref (local snapshot) and latest version</h1>';
151
- tempContainer.appendChild(fragment);
152
- // Replace newlines with <br> tags
153
- tempContainer.innerHTML = tempContainer.innerHTML.replace(/\n/g, '<br>');
154
- showModal(tempContainer.innerHTML);
155
- })
156
- .catch(error => {
157
- console.error('Error fetching content:', error);
158
- });
159
- }
160
-
161
- async function fetchGitHubTerm(savedToken, match) {
162
- function processSpecUpMarkdown(markdown) {
163
-
164
- // Replace all occurrences of [[def: ]] with ''
165
- const defRegex = /\[\[def: ([^\]]+)\]\]/g;
166
- markdown = markdown.replace(defRegex, '');
167
-
168
- // // Replace all occurrences of [[ref: ]] with <a href="#"></a>
169
- // const refRegex = /\[\[ref: ([^\]]+)\]\]/g;
170
- // markdown = markdown.replace(refRegex, '<a class="x-term-reference" data-local-href="ref:$1">$1</a>');
171
-
172
- return md.render(markdown);
173
- }
174
-
175
- const headers = {};
176
- if (savedToken && savedToken.length > 0) {
177
- headers['Authorization'] = `token ${savedToken}`;
178
- }
179
-
180
- try {
181
- const response = await fetch('https://api.github.com/repos/' + match.owner + '/' + match.repo + '/contents/' + match.terms_dir + '/' + match.term.replace(/ /g, '-').toLowerCase() + '.md', { headers: headers });
182
-
183
- if (response.status === 403 && response.headers.get('X-RateLimit-Remaining') === '0') {
184
- const resetTime = new Date(response.headers.get('X-RateLimit-Reset') * 1000);
185
- console.error(`❌ Github API rate limit exceeded. Try again after ${resetTime}. See https://blockchainbird.github.io/spec-up-t-website/docs/getting-started/github-token for more info.`);
186
-
187
- debouncedError();
188
- return true;
189
- } else {
190
- console.log(`ℹ️ Github API rate limit: ${response.headers.get('X-RateLimit-Remaining')} requests remaining. See https://blockchainbird.github.io/spec-up-t-website/docs/getting-started/github-token for more info.`);
191
- }
192
-
193
- const data = await response.json();
194
- const decodedContent = atob(data.content);
195
- const processedContent = processSpecUpMarkdown(decodedContent);
196
- return processedContent;
197
- } catch (error) {
198
- console.error('Error fetching content:', error);
199
- }
200
- }
201
-
202
- // get all elements with class “x-term-reference”
203
- const elements = document.querySelectorAll('.x-term-reference');
204
-
205
- elements.forEach((element) => {
206
- // Get the value of the data-local-href attribute
207
- const href = element.getAttribute('data-local-href');
208
-
209
- // split href on “:” and create array
210
- const splitHref = href.split(':');
211
-
212
- // allXTrefs is an object that is available in the global scope
213
- allXTrefs.xtrefs.forEach((match) => {
214
-
215
- //TODO: remove toLowerCase() or not?
216
- if (match.externalSpec === splitHref[1] && match.term.toLowerCase() === splitHref[2].toLowerCase()) {
217
-
218
- // If no commit hash is found, display a message and return
219
- if (!match.commitHash) {
220
- /**
221
- * Error message element shown when no cross-reference is found
222
- * Displayed directly after the term reference element
223
- */
224
- const noXTrefFoundMessage = document.createElement('span');
225
- noXTrefFoundMessage.classList.add('no-xref-found-message');
226
- noXTrefFoundMessage.innerHTML = 'No xref found.';
227
- element.parentNode.insertBefore(noXTrefFoundMessage, element.nextSibling);
228
-
229
- return
230
- };
231
-
232
- // To be used in the future
233
- const commitHashShort = match.commitHash && match.commitHash ? match.commitHash.substring(0, 7) : 'No hash';
234
-
235
- // Comment out all UI elements except tooltip
236
-
237
- // Diff of the latest commit hash of a term file and the referenced commit hash
238
-
239
- // Button that links to GitHub comparison between referenced commit and current main branch
240
- // Shows the difference between the referenced version and latest version on GitHub
241
-
242
- const diff = document.createElement('a');
243
- diff.href = 'https://github.com/' + match.owner + '/' + match.repo + '/compare/' + match.commitHash + '../main';
244
- diff.target = '_blank';
245
- diff.rel = 'noopener noreferrer';
246
- diff.classList.add('diff', 'xref-info-links', 'btn');
247
- diff.innerHTML = '<svg icon><use xlink:href="#svg-github"></use></svg> Xref &lt; &gt; <svg icon><use xlink:href="#svg-github"></use></svg> Now';
248
- diff.title = 'A Diff between the current commit hash of the definition and the commit hash referenced when the link was created.';
249
- element.parentNode.insertBefore(diff, element.nextSibling);
250
-
251
- // Latest version of a term-file
252
-
253
- // Button that links to the latest version of the term file on GitHub
254
- // Takes the user to the most current version in the repository
255
-
256
- const latestVersion = document.createElement('a');
257
- latestVersion.href = 'https://github.com/' + match.owner + '/' + match.repo + '/blob/main/' + match.terms_dir + '/' + match.term.replace(/ /g, '-').toLowerCase() + '.md';
258
- latestVersion.target = '_blank';
259
- latestVersion.rel = 'noopener noreferrer';
260
- latestVersion.classList.add('latest-version', 'xref-info-links', 'btn');
261
- latestVersion.innerHTML = '<svg icon><use xlink:href="#svg-github"></use></svg> Now';
262
- latestVersion.title = 'Go to the repo page of the definition‘s latest version.';
263
- diff.parentNode.insertBefore(latestVersion, element.nextSibling);
264
-
265
- // Exact commit hash at the time of referencing the file
266
-
267
- // Button that links to the exact commit version of the term file referenced in the document
268
- // Shows the historical version that was used when creating the reference
269
-
270
- const exactCommitHash = document.createElement('a');
271
- exactCommitHash.href = 'https://github.com/' + match.owner + '/' + match.repo + '/blob/' + match.commitHash + '/' + match.terms_dir + '/' + match.term.replace(/ /g, '-').toLowerCase() + '.md';
272
- exactCommitHash.target = '_blank';
273
- exactCommitHash.rel = 'noopener noreferrer';
274
- exactCommitHash.classList.add('exact-commit-hash', 'xref-info-links', 'btn');
275
- exactCommitHash.innerHTML = '<svg icon><use xlink:href="#svg-github"></use></svg> Xref';
276
- exactCommitHash.title = 'Go to the repo page of the definition‘s version referenced when the link was created.';
277
- latestVersion.parentNode.insertBefore(exactCommitHash, element.nextSibling);
278
-
279
- // Diff of the latest version and the referenced version in a modal
280
-
281
- // Button that opens a modal showing the diff between referenced version and latest version
282
- // Displays changes inline within the current page context
283
-
284
- const showDiffModal = document.createElement('button');
285
- showDiffModal.classList.add('show-diff-modal', 'xref-info-links', 'btn');
286
- showDiffModal.innerHTML = 'Xref &lt; &gt; <svg icon><use xlink:href="#svg-github"></use></svg> Now';
287
- showDiffModal.title = 'Show diff between the latest version and the referenced version';
288
- latestVersion.parentNode.insertBefore(showDiffModal, element.nextSibling);
289
- showDiffModal.addEventListener('click', function (event) {
290
- event.preventDefault();
291
- fetchGitHubContent(savedToken, match);
292
- });
293
-
294
- // The stored version of the term-file
295
- // Button that opens a modal showing only the locally stored version of the term
296
- // Displays the exact content that was stored when the reference was created
297
-
298
- const localStoredTerm = document.createElement('button');
299
- localStoredTerm.classList.add('show-diff-modal', 'xref-info-links', 'btn');
300
- localStoredTerm.innerHTML = 'Xref';
301
- localStoredTerm.title = 'Show the stored version of the term-file';
302
- showDiffModal.parentNode.insertBefore(localStoredTerm, element.nextSibling);
303
-
304
-
305
-
306
- // Replace all occurrences of [[def: ]] with ''
307
- const defRegex = /\[\[def: ([^\]]+)\]\]/g;
308
- match.content = match.content.replace(defRegex, '');
309
-
310
- // const content = md.render(match.content);
311
- const content = match.content;
312
- localStoredTerm.addEventListener('click', function (event) {
313
- event.preventDefault();
314
- showModal(`
315
- <h1>Term definition (local snapshot)</h1>
316
- <table>
317
- <tr>
318
- <th>Commit hash</th>
319
- <td>${match.commitHash}</td>
320
- </tr>
321
- <tr>
322
- <th>Content</th>
323
- <td>${content}</td>
324
- </tr>
325
- </table>
326
- `);
327
- });
328
-
329
- const div = document.createElement('div');
330
- div.classList.add('local-snapshot-xref-term');
331
- div.classList.add('transcluded-xref-term');
332
- div.innerHTML = `<p class='transclusion-heading'>Snapshot</p><p>Commit Hash: ${match.commitHash}</p> ${content}`;
333
- element.parentNode.insertBefore(div, element.nextSibling);
334
-
335
-
336
- // Tooltip functionality
337
- delegateEvent('pointerover', '.x-term-reference', (e, anchor) => {
338
- // Get the matching term from your data
339
- const href = anchor.getAttribute('data-local-href');
340
- const splitHref = href.split(':');
341
-
342
- // Find matching term in allXTrefs
343
- const match = allXTrefs.xtrefs.find(m =>
344
- m.externalSpec === splitHref[1] &&
345
- m.term.toLowerCase() === splitHref[2].toLowerCase());
346
-
347
- if (!match || tipMap.has(anchor)) return;
348
-
349
- // Create tooltip with content
350
- let tip = {
351
- // content: md.render(match.content.replace(/\[\[def: ([^\]]+)\]\]/g, '')),
352
- // content: `<dl>` + md.render(match.content.replace(/\[\[def: ([^\]]+)\]\]/g, '')) + `</dl>`,
353
- content: match.content.replace(/\[\[def: ([^\]]+)\]\]/g, ''),
354
- allowHTML: true,
355
- inlinePositioning: true
356
- };
357
-
358
- if (tip.content) tipMap.set(anchor, tippy(anchor, tip));
359
- }, { passive: true });
360
-
361
- // Keep tooltip functionality active, but comment out real-time content fetch
362
-
363
- insertGitHubTermRealTime(match, element);
364
-
365
- }
366
- });
367
- });
368
- }
369
-
370
- document.addEventListener("DOMContentLoaded", function () {
371
- fetchCommitHashes();
372
- });