@dfosco/storyboard-core 1.17.1 → 1.17.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dfosco/storyboard-core",
3
- "version": "1.17.1",
3
+ "version": "1.17.3",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -53,3 +53,57 @@ export function clearCachedComments(route) {
53
53
  // ignore
54
54
  }
55
55
  }
56
+
57
+ // --- Pending (failed) comments ---
58
+
59
+ const PENDING_PREFIX = 'sb-pending-comments:'
60
+
61
+ /**
62
+ * Save a pending comment that failed to submit.
63
+ * @param {string} route
64
+ * @param {{ id: string, x: number, y: number, text: string, author: object }} comment
65
+ */
66
+ export function savePendingComment(route, comment) {
67
+ try {
68
+ const pending = getPendingComments(route)
69
+ // Replace if same id already exists, else append
70
+ const idx = pending.findIndex(c => c.id === comment.id)
71
+ if (idx >= 0) pending[idx] = comment
72
+ else pending.push(comment)
73
+ localStorage.setItem(PENDING_PREFIX + route, JSON.stringify(pending))
74
+ } catch {
75
+ // ignore
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Get all pending (failed) comments for a route.
81
+ * @param {string} route
82
+ * @returns {Array<{ id: string, x: number, y: number, text: string, author: object }>}
83
+ */
84
+ export function getPendingComments(route) {
85
+ try {
86
+ const raw = localStorage.getItem(PENDING_PREFIX + route)
87
+ return raw ? JSON.parse(raw) : []
88
+ } catch {
89
+ return []
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Remove a pending comment (after successful retry or dismissal).
95
+ * @param {string} route
96
+ * @param {string} pendingId
97
+ */
98
+ export function removePendingComment(route, pendingId) {
99
+ try {
100
+ const pending = getPendingComments(route).filter(c => c.id !== pendingId)
101
+ if (pending.length > 0) {
102
+ localStorage.setItem(PENDING_PREFIX + route, JSON.stringify(pending))
103
+ } else {
104
+ localStorage.removeItem(PENDING_PREFIX + route)
105
+ }
106
+ } catch {
107
+ // ignore
108
+ }
109
+ }
@@ -33,7 +33,7 @@ export {
33
33
  } from './api.js'
34
34
 
35
35
  // Cache
36
- export { getCachedComments, setCachedComments, clearCachedComments } from './commentCache.js'
36
+ export { getCachedComments, setCachedComments, clearCachedComments, savePendingComment, getPendingComments, removePendingComment } from './commentCache.js'
37
37
 
38
38
  // GraphQL client (for advanced use)
39
39
  export { graphql } from './graphql.js'
@@ -34,7 +34,7 @@ export function openAuthModal() {
34
34
  </div>
35
35
  <div class="pa4">
36
36
  <p class="ma0 mb3 lh-copy sb-fg-muted sb-f-sm">
37
- Create a <a class="sb-fg-accent no-underline" href="https://github.com/settings/tokens/new?scopes=repo&description=Storyboard+Comments" target="_blank" rel="noopener">GitHub Personal Access Token</a> with access to <b>github/storyboard</b> repository and <b>Discussions</b> read/write scope. Then enter the token below to sign in and enable commenting features.
37
+ Create a <a class="sb-fg-accent no-underline" href="https://github.com/settings/personal-access-tokens/new" target="_blank" rel="noopener">GitHub Fine-Grained Personal Access Token</a> with access to <b>github/storyboard</b> repository and <b>Discussions</b> read/write scope. Then enter the token below to sign in and enable commenting features.
38
38
  </p>
39
39
  <label class="db mb1 fw5 sb-fg sb-f-sm" for="sb-auth-token-input">Personal Access Token</label>
40
40
  <input class="sb-input w-100 ph3 pv2 br2 f6 code db" id="sb-auth-token-input" type="password"
@@ -139,7 +139,18 @@
139
139
  .sb-comment-window * { scrollbar-width: none; }
140
140
  .sb-comment-window *::-webkit-scrollbar { display: none; }
141
141
  .sb-composer { width: 280px; z-index: 100001; }
142
- .sb-comment-overlay { z-index: 99998; pointer-events: none; }
142
+ .sb-comment-overlay {
143
+ position: absolute;
144
+ top: 0; left: 0; right: 0; bottom: 0;
145
+ z-index: 99998;
146
+ pointer-events: none;
147
+ }
148
+ .sb-comment-mode {
149
+ position: relative;
150
+ }
151
+ .sb-comment-mode .sb-comment-overlay {
152
+ pointer-events: auto;
153
+ }
143
154
  .sb-auth-backdrop { z-index: 100000; background: rgba(0,0,0,0.5); backdrop-filter: blur(4px); }
144
155
  .sb-comments-drawer-backdrop { z-index: 99997; background: rgba(0,0,0,0.4); }
145
156
  .sb-comments-drawer { z-index: 99998; width: 420px; max-width: 90vw; }
@@ -187,6 +198,25 @@
187
198
  border-color: var(--sb-fg-muted);
188
199
  opacity: 0.5;
189
200
  }
201
+ .sb-comment-pin-pending {
202
+ border-color: var(--sb-fg-muted) !important;
203
+ opacity: 0.6;
204
+ animation: sb-pin-pulse 1.2s ease-in-out infinite;
205
+ }
206
+ .sb-comment-pin-failed {
207
+ border-color: var(--sb-fg-danger) !important;
208
+ cursor: pointer;
209
+ animation: sb-pin-shake 0.4s ease-in-out;
210
+ }
211
+ @keyframes sb-pin-pulse {
212
+ 0%, 100% { opacity: 0.6; }
213
+ 50% { opacity: 1; }
214
+ }
215
+ @keyframes sb-pin-shake {
216
+ 0%, 100% { transform: translateX(0); }
217
+ 25% { transform: translateX(-3px); }
218
+ 75% { transform: translateX(3px); }
219
+ }
190
220
 
191
221
  /* Error alert */
192
222
  .sb-error-alert {
@@ -5,7 +5,6 @@
5
5
  * Styled with Tachyons + sb-* custom classes for light/dark mode support.
6
6
  */
7
7
 
8
- import { createComment } from '../api.js'
9
8
  import { getCachedUser } from '../auth.js'
10
9
 
11
10
  /**
@@ -16,7 +15,7 @@ import { getCachedUser } from '../auth.js'
16
15
  * @param {string} route - Current route path
17
16
  * @param {object} [callbacks] - Optional callbacks
18
17
  * @param {() => void} [callbacks.onCancel] - Called when composer is dismissed
19
- * @param {(comment: object) => void} [callbacks.onSubmit] - Called after successful submit
18
+ * @param {(text: string) => void} [callbacks.onSubmitOptimistic] - Called with text for optimistic submission
20
19
  * @returns {{ el: HTMLElement, destroy: () => void }}
21
20
  */
22
21
  export function showComposer(container, xPct, yPct, route, callbacks = {}) {
@@ -47,8 +46,8 @@ export function showComposer(container, xPct, yPct, route, callbacks = {}) {
47
46
  </template>
48
47
  <div class="flex items-center justify-end pa3">
49
48
  <button class="sb-btn-cancel ph3 pv2 br2 f7 fw5 pointer mr1" @click="cancel()">Cancel</button>
50
- <button class="sb-btn-success ph3 pv2 br2 f7 fw5 pointer bn" :disabled="submitting"
51
- @click="submit()" x-text="submitting ? 'Posting…' : 'Comment'">Comment</button>
49
+ <button class="sb-btn-success ph3 pv2 br2 f7 fw5 pointer bn"
50
+ @click="submit()">Comment</button>
52
51
  </div>
53
52
  </div>
54
53
  `
@@ -81,22 +80,13 @@ export function showComposer(container, xPct, yPct, route, callbacks = {}) {
81
80
  submitting: false,
82
81
  error: null,
83
82
 
84
- async submit() {
83
+ submit() {
85
84
  const val = this.text.trim()
86
85
  if (!val) return
87
86
 
88
- this.submitting = true
89
- this.error = null
90
-
91
- try {
92
- const comment = await createComment(route, xPct, yPct, val)
93
- destroy()
94
- callbacks.onSubmit?.(comment)
95
- } catch (err) {
96
- this.error = err.message
97
- this.submitting = false
98
- console.error('[storyboard] Failed to post comment:', err)
99
- }
87
+ // Close composer immediately and hand off to optimistic handler
88
+ destroy()
89
+ callbacks.onSubmitOptimistic?.(val)
100
90
  },
101
91
 
102
92
  cancel() {
@@ -7,10 +7,10 @@
7
7
 
8
8
  import Alpine from 'alpinejs'
9
9
  import { isCommentsEnabled } from '../config.js'
10
- import { isAuthenticated } from '../auth.js'
10
+ import { isAuthenticated, getCachedUser } from '../auth.js'
11
11
  import { toggleCommentMode, setCommentMode, isCommentModeActive, subscribeToCommentMode } from '../commentMode.js'
12
- import { fetchRouteCommentsSummary, fetchCommentDetail, moveComment } from '../api.js'
13
- import { getCachedComments, setCachedComments, clearCachedComments } from '../commentCache.js'
12
+ import { fetchRouteCommentsSummary, fetchCommentDetail, moveComment, createComment } from '../api.js'
13
+ import { getCachedComments, setCachedComments, clearCachedComments, savePendingComment, getPendingComments, removePendingComment } from '../commentCache.js'
14
14
  import { showComposer } from './composer.js'
15
15
  import { openAuthModal } from './authModal.js'
16
16
  import { showCommentWindow, closeCommentWindow } from './commentWindow.js'
@@ -27,17 +27,19 @@ function esc(str) {
27
27
  return d.innerHTML
28
28
  }
29
29
 
30
- function getContentContainer() {
31
- return document.body
32
- }
33
-
34
30
  function ensureOverlay() {
35
31
  if (overlay) return overlay
36
- const container = getContentContainer()
37
32
 
38
33
  overlay = document.createElement('div')
39
- overlay.className = 'sb-comment-overlay absolute top-0 right-0 bottom-0 left-0 pe-none'
40
- container.appendChild(overlay)
34
+ overlay.className = 'sb-comment-overlay'
35
+ document.body.appendChild(overlay)
36
+
37
+ // Click handler for placing comments lives on the overlay itself
38
+ overlay.addEventListener('click', (e) => {
39
+ if (!isCommentModeActive()) return
40
+ if (e.target.closest('.sb-composer') || e.target.closest('.sb-comment-pin') || e.target.closest('.sb-comment-window')) return
41
+ handleOverlayClick(e)
42
+ })
41
43
 
42
44
  return overlay
43
45
  }
@@ -74,6 +76,99 @@ function reloadComments() {
74
76
  loadAndRenderComments()
75
77
  }
76
78
 
79
+ /**
80
+ * Render an optimistic pin immediately after the user submits a comment.
81
+ * Returns callbacks to mark it as succeeded or failed.
82
+ */
83
+ function renderOptimisticPin(ov, xPct, yPct, text, user) {
84
+ const pendingId = `pending-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
85
+ const pin = document.createElement('div')
86
+ pin.className = 'sb-comment-pin sb-comment-pin-pending absolute br-100 sb-bg pointer sb-shadow pe-auto overflow-hidden'
87
+ pin.style.left = `${xPct}%`
88
+ pin.style.top = `${yPct}%`
89
+ pin.title = `${user?.login ?? 'you'}: ${text.slice(0, 80)}`
90
+
91
+ pin.innerHTML = user?.avatarUrl
92
+ ? `<img class="br-100 db sb-pin-img" src="${esc(user.avatarUrl)}" alt="${esc(user.login)}" draggable="false" />`
93
+ : ''
94
+
95
+ ov.appendChild(pin)
96
+ renderedPins.push(pin)
97
+
98
+ return {
99
+ pendingId,
100
+ succeed: () => {
101
+ pin.classList.remove('sb-comment-pin-pending')
102
+ },
103
+ fail: () => {
104
+ pin.classList.remove('sb-comment-pin-pending')
105
+ pin.classList.add('sb-comment-pin-failed')
106
+ pin.title = `⚠ Failed to post — click to retry: ${text.slice(0, 60)}`
107
+
108
+ // Save to localStorage for persistence
109
+ const route = getCurrentRoute()
110
+ savePendingComment(route, { id: pendingId, x: xPct, y: yPct, text, author: user })
111
+
112
+ // Click to retry
113
+ pin.addEventListener('click', async (e) => {
114
+ e.stopPropagation()
115
+ pin.classList.remove('sb-comment-pin-failed')
116
+ pin.classList.add('sb-comment-pin-pending')
117
+ pin.title = 'Retrying…'
118
+ try {
119
+ await createComment(route, xPct, yPct, text)
120
+ removePendingComment(route, pendingId)
121
+ pin.classList.remove('sb-comment-pin-pending')
122
+ reloadComments()
123
+ } catch {
124
+ pin.classList.remove('sb-comment-pin-pending')
125
+ pin.classList.add('sb-comment-pin-failed')
126
+ pin.title = `⚠ Failed to post — click to retry: ${text.slice(0, 60)}`
127
+ }
128
+ })
129
+ },
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Render pins for pending (failed) comments from localStorage.
135
+ */
136
+ function renderPendingPins(ov) {
137
+ const route = getCurrentRoute()
138
+ const pending = getPendingComments(route)
139
+ for (const p of pending) {
140
+ const pin = document.createElement('div')
141
+ pin.className = 'sb-comment-pin sb-comment-pin-failed absolute br-100 sb-bg pointer sb-shadow pe-auto overflow-hidden'
142
+ pin.style.left = `${p.x}%`
143
+ pin.style.top = `${p.y}%`
144
+ pin.title = `⚠ Failed to post — click to retry: ${p.text?.slice(0, 60) ?? ''}`
145
+
146
+ pin.innerHTML = p.author?.avatarUrl
147
+ ? `<img class="br-100 db sb-pin-img" src="${esc(p.author.avatarUrl)}" alt="${esc(p.author.login)}" draggable="false" />`
148
+ : ''
149
+
150
+ pin.addEventListener('click', async (e) => {
151
+ e.stopPropagation()
152
+ pin.classList.remove('sb-comment-pin-failed')
153
+ pin.classList.add('sb-comment-pin-pending')
154
+ pin.title = 'Retrying…'
155
+ try {
156
+ await createComment(route, p.x, p.y, p.text)
157
+ removePendingComment(route, p.id)
158
+ pin.remove()
159
+ reloadComments()
160
+ } catch {
161
+ pin.classList.remove('sb-comment-pin-pending')
162
+ pin.classList.add('sb-comment-pin-failed')
163
+ pin.title = `⚠ Failed to post — click to retry: ${p.text?.slice(0, 60) ?? ''}`
164
+ }
165
+ })
166
+
167
+ ov.appendChild(pin)
168
+ renderedPins.push(pin)
169
+ }
170
+ }
171
+
77
172
  function renderPin(ov, comment, index) {
78
173
  const hue = Math.round((index * 137.5) % 360)
79
174
  const pin = document.createElement('div')
@@ -97,21 +192,19 @@ function renderPin(ov, comment, index) {
97
192
  pin.addEventListener('mousedown', (e) => {
98
193
  if (e.button !== 0) return
99
194
  dragged = false
100
- const container = getContentContainer()
101
- const containerRect = container.getBoundingClientRect()
102
195
  const startX = e.clientX
103
196
  const startY = e.clientY
104
- const startLeft = (parseFloat(pin.style.left) / 100) * containerRect.width
105
- const startTop = (parseFloat(pin.style.top) / 100) * containerRect.height
197
+ const startLeftPct = parseFloat(pin.style.left)
198
+ const startTopPct = parseFloat(pin.style.top)
106
199
 
107
200
  const onMove = (ev) => {
108
201
  const dx = ev.clientX - startX
109
202
  const dy = ev.clientY - startY
110
203
  if (!dragged && Math.abs(dx) < 4 && Math.abs(dy) < 4) return
111
204
  dragged = true
112
- const cr = container.getBoundingClientRect()
113
- const xPct = Math.round(((startLeft + dx) / cr.width) * 1000) / 10
114
- const yPct = Math.round(((startTop + dy) / cr.height) * 1000) / 10
205
+ const xPct = Math.round((startLeftPct + (dx / window.innerWidth) * 100) * 10) / 10
206
+ const docHeight = document.documentElement.scrollHeight
207
+ const yPct = Math.round((startTopPct + (dy / docHeight) * 100) * 10) / 10
115
208
  pin.style.left = `${xPct}%`
116
209
  pin.style.top = `${yPct}%`
117
210
  }
@@ -121,11 +214,11 @@ function renderPin(ov, comment, index) {
121
214
  document.removeEventListener('mouseup', onUp)
122
215
  if (!dragged) return
123
216
 
124
- const cr = container.getBoundingClientRect()
125
217
  const dx = ev.clientX - startX
126
218
  const dy = ev.clientY - startY
127
- const xPct = Math.round(((startLeft + dx) / cr.width) * 1000) / 10
128
- const yPct = Math.round(((startTop + dy) / cr.height) * 1000) / 10
219
+ const xPct = Math.round((startLeftPct + (dx / window.innerWidth) * 100) * 10) / 10
220
+ const docHeight = document.documentElement.scrollHeight
221
+ const yPct = Math.round((startTopPct + (dy / docHeight) * 100) * 10) / 10
129
222
  comment.meta = { ...comment.meta, x: xPct, y: yPct }
130
223
 
131
224
  try {
@@ -183,6 +276,7 @@ function renderCachedPins() {
183
276
  renderPin(ov, comment, i)
184
277
  }
185
278
  })
279
+ renderPendingPins(ov)
186
280
  }
187
281
 
188
282
  async function loadAndRenderComments() {
@@ -206,13 +300,17 @@ async function loadAndRenderComments() {
206
300
  setCachedComments(route, discussion)
207
301
  }
208
302
  clearPins()
209
- if (!discussion?.comments?.length) return
303
+ if (!discussion?.comments?.length) {
304
+ renderPendingPins(ov)
305
+ return
306
+ }
210
307
 
211
308
  discussion.comments.forEach((comment, i) => {
212
309
  if (comment.meta?.x != null && comment.meta?.y != null) {
213
310
  renderPin(ov, comment, i)
214
311
  }
215
312
  })
313
+ renderPendingPins(ov)
216
314
 
217
315
  autoOpenCommentFromUrl(ov, discussion)
218
316
  } catch (err) {
@@ -228,9 +326,9 @@ async function autoOpenCommentFromUrl(ov, discussion) {
228
326
  if (!comment) return
229
327
 
230
328
  if (comment.meta?.y != null) {
231
- const container = getContentContainer()
232
- const yPx = (comment.meta.y / 100) * container.scrollHeight
233
- const viewTop = container.scrollTop || window.scrollY
329
+ const docHeight = document.documentElement.scrollHeight
330
+ const yPx = (comment.meta.y / 100) * docHeight
331
+ const viewTop = window.scrollY
234
332
  const viewBottom = viewTop + window.innerHeight
235
333
  if (yPx < viewTop || yPx > viewBottom) {
236
334
  const scrollTarget = Math.max(0, yPx - window.innerHeight / 3)
@@ -272,17 +370,29 @@ function handleOverlayClick(e) {
272
370
  activeComposer = null
273
371
  }
274
372
 
275
- const container = getContentContainer()
276
- const rect = container.getBoundingClientRect()
277
- const xPct = Math.round(((e.clientX - rect.left) / rect.width) * 1000) / 10
278
- const yPct = Math.round(((e.clientY - rect.top + container.scrollTop) / container.scrollHeight) * 1000) / 10
373
+ // x as percentage of viewport width, y as percentage of full document height
374
+ const xPct = Math.round((e.clientX / window.innerWidth) * 1000) / 10
375
+ const docHeight = document.documentElement.scrollHeight
376
+ const yPct = Math.round(((e.clientY + window.scrollY) / docHeight) * 1000) / 10
279
377
 
280
378
  const ov = ensureOverlay()
281
- activeComposer = showComposer(ov, xPct, yPct, getCurrentRoute(), {
379
+ const route = getCurrentRoute()
380
+ activeComposer = showComposer(ov, xPct, yPct, route, {
282
381
  onCancel: () => { activeComposer = null },
283
- onSubmit: () => {
382
+ onSubmitOptimistic: (text) => {
284
383
  activeComposer = null
285
- reloadComments()
384
+ const user = getCachedUser()
385
+ const opt = renderOptimisticPin(ov, xPct, yPct, text, user)
386
+ // Fire API call in background
387
+ createComment(route, xPct, yPct, text)
388
+ .then(() => {
389
+ opt.succeed()
390
+ reloadComments()
391
+ })
392
+ .catch((err) => {
393
+ console.error('[storyboard] Failed to post comment:', err)
394
+ opt.fail()
395
+ })
286
396
  },
287
397
  })
288
398
  }
@@ -327,17 +437,6 @@ export function mountComments() {
327
437
 
328
438
  subscribeToCommentMode(setBodyCommentMode)
329
439
 
330
- // Click handler for placing comments — uses document so devtools/modals can be excluded
331
- document.addEventListener('click', (e) => {
332
- if (!isCommentModeActive()) return
333
- // Let devtools, modals, drawers, and existing comment UI handle their own clicks
334
- if (e.target.closest('.sb-devtools-wrapper') || e.target.closest('.sb-auth-backdrop') ||
335
- e.target.closest('.sb-comments-drawer') || e.target.closest('.sb-comments-drawer-backdrop') ||
336
- e.target.closest('.sb-composer') || e.target.closest('.sb-comment-pin') ||
337
- e.target.closest('.sb-comment-window')) return
338
- handleOverlayClick(e)
339
- })
340
-
341
440
  window.addEventListener('keydown', (e) => {
342
441
  const tag = e.target.tagName
343
442
  if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || e.target.isContentEditable) {
@@ -21,12 +21,16 @@ vi.mock('../api.js', () => ({
21
21
  fetchRouteCommentsSummary: vi.fn(),
22
22
  fetchCommentDetail: vi.fn(),
23
23
  moveComment: vi.fn(),
24
+ createComment: vi.fn(),
24
25
  }))
25
26
 
26
27
  vi.mock('../commentCache.js', () => ({
27
28
  getCachedComments: vi.fn(() => null),
28
29
  setCachedComments: vi.fn(),
29
30
  clearCachedComments: vi.fn(),
31
+ savePendingComment: vi.fn(),
32
+ getPendingComments: vi.fn(() => []),
33
+ removePendingComment: vi.fn(),
30
34
  }))
31
35
 
32
36
  vi.mock('./composer.js', () => ({
@@ -74,11 +78,15 @@ describe('mount.js', () => {
74
78
  fetchRouteCommentsSummary: vi.fn(),
75
79
  fetchCommentDetail: vi.fn(),
76
80
  moveComment: vi.fn(),
81
+ createComment: vi.fn(),
77
82
  }))
78
83
  vi.doMock('../commentCache.js', () => ({
79
84
  getCachedComments: vi.fn(() => null),
80
85
  setCachedComments: vi.fn(),
81
86
  clearCachedComments: vi.fn(),
87
+ savePendingComment: vi.fn(),
88
+ getPendingComments: vi.fn(() => []),
89
+ removePendingComment: vi.fn(),
82
90
  }))
83
91
  vi.doMock('./composer.js', () => ({ showComposer: vi.fn() }))
84
92
  vi.doMock('./authModal.js', () => ({ openAuthModal: vi.fn() }))