All files / src/utils commentDraft.ts

100% Statements 10/10
100% Branches 6/6
100% Functions 4/4
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            8x       115x         5x       128x 128x   1x           22x 22x 6x          
// Comments being written, kept for the browser tab's session so they survive
// the composer being closed or the page reloaded — e.g. going to review
// comments when posting needs a few more reviews. Storage can be unavailable
// (private mode, blocked site data): a draft is a convenience, so failures are
// ignored and simply mean no draft.
 
const PREFIX = 'comment-draft:'
 
/** The draft key of a comment, or of a reply to `parentId`, on an item. */
export function commentDraftKey(entityId: string, itemId: string, parentId: string | null): string {
  return `${entityId}:${itemId}:${parentId ?? 'root'}`
}
 
/** The draft key of a comment, or of a reply to `parentId`, on a store pack. */
export function packCommentDraftKey(packId: string, parentId: string | null): string {
  return commentDraftKey('pack', packId, parentId)
}
 
export function readCommentDraft(key: string): string {
  try {
    return sessionStorage.getItem(PREFIX + key) ?? ''
  } catch {
    return ''
  }
}
 
/** Saves the draft, or forgets it when `value` is empty. */
export function writeCommentDraft(key: string, value: string): void {
  try {
    if (value) sessionStorage.setItem(PREFIX + key, value)
    else sessionStorage.removeItem(PREFIX + key)
  } catch {
    // Ignored: see the note at the top
  }
}