infiniteScroll.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // @license http://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0
  2. // SPDX-License-Identifier: AGPL-3.0-only
  3. function insertBeforeLast(node, elem) {
  4. node.insertBefore(elem, node.childNodes[node.childNodes.length - 2]);
  5. }
  6. function getLoadMore(doc) {
  7. return doc.querySelector(".show-more:not(.timeline-item)");
  8. }
  9. function getHrefs(selector) {
  10. return new Set([...document.querySelectorAll(selector)].map(el => el.getAttribute("href")));
  11. }
  12. function getTweetId(item) {
  13. const m = item.querySelector(".tweet-link")?.getAttribute("href")?.match(/\/status\/(\d+)/);
  14. return m ? m[1] : "";
  15. }
  16. function isDuplicate(item, hrefs) {
  17. return hrefs.has(item.querySelector(".tweet-link")?.getAttribute("href"));
  18. }
  19. const GAP = 10;
  20. class Masonry {
  21. constructor(container) {
  22. this.container = container;
  23. this.colHeights = [];
  24. this.colCounts = [];
  25. this.colCount = 0;
  26. this._lastWidth = 0;
  27. this._colWidthCache = 0;
  28. this._items = [];
  29. this._revealTimer = null;
  30. this.container.classList.add("masonry-active");
  31. let resizeTimer;
  32. window.addEventListener("resize", () => {
  33. clearTimeout(resizeTimer);
  34. resizeTimer = setTimeout(() => this._rebuild(), 50);
  35. });
  36. // Re-sync positions whenever images finish loading and items grow taller.
  37. // Must be set up before _rebuild() so initial items get observed on first pass.
  38. let syncTimer;
  39. this._observer = window.ResizeObserver ? new ResizeObserver(() => {
  40. clearTimeout(syncTimer);
  41. syncTimer = setTimeout(() => this.syncHeights(), 100);
  42. }) : null;
  43. this._rebuild();
  44. }
  45. // Reveal all items and gallery siblings (show-more, top-ref). Idempotent.
  46. _revealAll() {
  47. clearTimeout(this._revealTimer);
  48. for (const item of this._items) item.classList.add("masonry-visible");
  49. for (const el of this.container.parentElement.querySelectorAll(":scope > .show-more, :scope > .top-ref, :scope > .timeline-footer"))
  50. el.classList.add("masonry-visible");
  51. }
  52. // Height-primary, count-as-tiebreaker: handles both tall tweets and unloaded images.
  53. _pickCol() {
  54. return this.colHeights.reduce((min, h, i) => {
  55. const m = this.colHeights[min];
  56. return (h < m || (h === m && this.colCounts[i] < this.colCounts[min])) ? i : min;
  57. }, 0);
  58. }
  59. // Position items using current column state. Updates colHeights, colCounts, container height.
  60. _position(items, heights, colWidth) {
  61. for (let i = 0; i < items.length; i++) {
  62. const col = this._pickCol();
  63. items[i].style.left = `${col * (colWidth + GAP)}px`;
  64. items[i].style.top = `${this.colHeights[col]}px`;
  65. this.colHeights[col] += heights[i] + GAP;
  66. this.colCounts[col]++;
  67. }
  68. this.container.style.height = `${Math.max(0, ...this.colHeights)}px`;
  69. }
  70. // Full reset and re-place all items.
  71. _place(items, heights, n, colWidth) {
  72. this.colHeights = new Array(n).fill(0);
  73. this.colCounts = new Array(n).fill(0);
  74. this.colCount = n;
  75. this._position(items, heights, colWidth);
  76. }
  77. _rebuild() {
  78. const n = Math.max(1, Math.floor(this.container.clientWidth / 350));
  79. const w = this.container.clientWidth;
  80. if (n === this.colCount && w === this._lastWidth) return;
  81. const isFirst = this.colCount === 0;
  82. if (isFirst) {
  83. this._items = [...this.container.querySelectorAll(".timeline-item")];
  84. }
  85. // Sort newest-first by tweet ID (snowflake IDs exceed Number precision, compare as strings).
  86. this._items.sort((a, b) => {
  87. const idA = getTweetId(a), idB = getTweetId(b);
  88. if (idA.length !== idB.length) return idB.length - idA.length;
  89. return idB < idA ? -1 : idB > idA ? 1 : 0;
  90. });
  91. // Pre-set widths BEFORE reading heights so measurements reflect the new column width.
  92. const colWidth = this._colWidthCache = Math.floor((w - GAP * (n - 1)) / n);
  93. for (const item of this._items) item.style.width = `${colWidth}px`;
  94. this._place(this._items, this._items.map(item => item.offsetHeight), n, colWidth);
  95. this._lastWidth = w;
  96. if (isFirst) {
  97. if (this._observer) this._items.forEach(item => this._observer.observe(item));
  98. // Reveal immediately if all images are cached, else wait for syncHeights.
  99. const hasUnloaded = this._items.some(item =>
  100. [...item.querySelectorAll("img")].some(img => !img.complete));
  101. if (hasUnloaded) {
  102. this._revealTimer = setTimeout(() => this._revealAll(), 1000);
  103. } else {
  104. this._revealAll();
  105. }
  106. }
  107. }
  108. // Re-read actual heights and re-place all items. Fixes drift after images load.
  109. syncHeights() {
  110. this._place(this._items, this._items.map(item => item.offsetHeight), this.colCount, this._colWidthCache);
  111. this._revealAll();
  112. }
  113. // Batch-add items in three phases to avoid O(N) reflows:
  114. // 1. writes: set widths, append all — no reads, no reflows
  115. // 2. one read: batch offsetHeight
  116. // 3. writes: assign columns, set left/top
  117. addAll(newItems) {
  118. if (!newItems.length) return;
  119. const colWidth = this._colWidthCache;
  120. for (const item of newItems) {
  121. item.style.width = `${colWidth}px`;
  122. this.container.appendChild(item);
  123. }
  124. this._position(newItems, newItems.map(item => item.offsetHeight), colWidth);
  125. this._items.push(...newItems);
  126. if (this._observer) newItems.forEach(item => this._observer.observe(item));
  127. }
  128. }
  129. document.addEventListener("DOMContentLoaded", function () {
  130. const isTweet = location.pathname.includes("/status/");
  131. const containerClass = isTweet ? ".replies" : ".timeline";
  132. const itemClass = containerClass + " > div:not(.top-ref)";
  133. const html = document.documentElement;
  134. const container = document.querySelector(containerClass);
  135. const masonryEl = container?.querySelector(".gallery-masonry");
  136. const masonry = masonryEl ? new Masonry(masonryEl) : null;
  137. let loading = false;
  138. function handleScroll(failed) {
  139. if (loading || html.scrollTop + html.clientHeight < html.scrollHeight - 3000) return;
  140. const loadMore = getLoadMore(document);
  141. if (!loadMore) return;
  142. loading = true;
  143. loadMore.children[0].text = "Loading...";
  144. const url = new URL(loadMore.children[0].href);
  145. url.searchParams.append("scroll", "true");
  146. fetch(url)
  147. .then(r => {
  148. if (r.status > 299) throw new Error("error");
  149. return r.text();
  150. })
  151. .then(responseText => {
  152. const doc = new DOMParser().parseFromString(responseText, "text/html");
  153. loadMore.remove();
  154. if (masonry) {
  155. masonry.syncHeights();
  156. const newMasonry = doc.querySelector(".gallery-masonry");
  157. if (newMasonry) {
  158. const knownHrefs = getHrefs(".gallery-masonry .tweet-link");
  159. masonry.addAll([...newMasonry.querySelectorAll(".timeline-item")].filter(item => !isDuplicate(item, knownHrefs)));
  160. }
  161. } else {
  162. const knownHrefs = getHrefs(`${itemClass} .tweet-link`);
  163. for (const item of doc.querySelectorAll(itemClass)) {
  164. if (item.className === "timeline-item show-more" || isDuplicate(item, knownHrefs)) continue;
  165. isTweet ? container.appendChild(item) : insertBeforeLast(container, item);
  166. }
  167. }
  168. loading = false;
  169. const newLoadMore = getLoadMore(doc);
  170. if (newLoadMore) {
  171. isTweet ? container.appendChild(newLoadMore) : insertBeforeLast(container, newLoadMore);
  172. if (masonry) newLoadMore.classList.add("masonry-visible");
  173. }
  174. })
  175. .catch(err => {
  176. console.warn("Something went wrong.", err);
  177. if (failed > 3) { loadMore.children[0].text = "Error"; return; }
  178. loading = false;
  179. handleScroll((failed || 0) + 1);
  180. });
  181. }
  182. window.addEventListener("scroll", () => handleScroll());
  183. });
  184. // @license-end