comments icon indicating copy to clipboard operation
comments copied to clipboard

Strip leading whitespace from HTML strings before creating the element

Open rungta opened this issue 9 months ago • 1 comments

https://github.com/verbb/comments/blob/e0d0f5688026a9f3291b43fa9067c5e50def6cb4/src/resources/src/js/comments.js#L48-L52

Since the function assumes the firstChild to be the relevant DOM node, any leading whitespace in the HTML response (easily introduced, for example, if using a custom Twig template) results in a text node being returned as the element instead of the comment node.

Perhaps the function could use firstElementChild instead of firstChild?

Currently, a JSON response from the comments/comments/save action such as this fails:

{
  "success": true,
  "id": 1545192,
  "comment": { },
  "html": "\n\n\n\n  \n  <article class=\"cc-i\" id=\"comment-1545192\" data-id=\"1545192\" data-site-id=\"1\" data-role=\"comment\" itemprop=\"comment\" itemscope itemtype=\"http://schema.org/UserComments\"> … </article>\n\n  \n\n  ",
  "notice": ""
}

Whereas the following succeeds:

{
  "success": true,
  "id": 1545192,
  "comment": { },
  "html": "<article class=\"cc-i\" id=\"comment-1545192\" data-id=\"1545192\" data-site-id=\"1\" data-role=\"comment\" itemprop=\"comment\" itemscope itemtype=\"http://schema.org/UserComments\"> … </article>",
  "notice": ""
}

rungta avatar Mar 04 '25 19:03 rungta

We'll probably want to revise this for our Comments.js overhaul, but for now firstElementChild should do along with stripping whitespace.

To get this early, run composer require verbb/comments:"dev-craft-5 as 3.0.6".

engram-design avatar Mar 05 '25 03:03 engram-design

Updated in 3.0.7.

engram-design avatar Jul 18 '25 14:07 engram-design