main.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. import { setupPopovers } from './popover.js';
  2. import { setupMasonries } from './masonry.js';
  3. import { throttledDebounce, isElementVisible, openURLInNewTab } from './utils.js';
  4. async function fetchPageContent(pageData) {
  5. // TODO: handle non 200 status codes/time outs
  6. // TODO: add retries
  7. const response = await fetch(`${pageData.baseURL}/api/pages/${pageData.slug}/content/`);
  8. const content = await response.text();
  9. return content;
  10. }
  11. function setupCarousels() {
  12. const carouselElements = document.getElementsByClassName("carousel-container");
  13. if (carouselElements.length == 0) {
  14. return;
  15. }
  16. for (let i = 0; i < carouselElements.length; i++) {
  17. const carousel = carouselElements[i];
  18. carousel.classList.add("show-right-cutoff");
  19. const itemsContainer = carousel.getElementsByClassName("carousel-items-container")[0];
  20. const determineSideCutoffs = () => {
  21. if (itemsContainer.scrollLeft != 0) {
  22. carousel.classList.add("show-left-cutoff");
  23. } else {
  24. carousel.classList.remove("show-left-cutoff");
  25. }
  26. if (Math.ceil(itemsContainer.scrollLeft) + itemsContainer.clientWidth < itemsContainer.scrollWidth) {
  27. carousel.classList.add("show-right-cutoff");
  28. } else {
  29. carousel.classList.remove("show-right-cutoff");
  30. }
  31. }
  32. const determineSideCutoffsRateLimited = throttledDebounce(determineSideCutoffs, 20, 100);
  33. itemsContainer.addEventListener("scroll", determineSideCutoffsRateLimited);
  34. window.addEventListener("resize", determineSideCutoffsRateLimited);
  35. afterContentReady(determineSideCutoffs);
  36. }
  37. }
  38. const minuteInSeconds = 60;
  39. const hourInSeconds = minuteInSeconds * 60;
  40. const dayInSeconds = hourInSeconds * 24;
  41. const monthInSeconds = dayInSeconds * 30;
  42. const yearInSeconds = monthInSeconds * 12;
  43. function relativeTimeSince(timestamp) {
  44. const delta = Math.round((Date.now() / 1000) - timestamp);
  45. if (delta < minuteInSeconds) {
  46. return "1m";
  47. }
  48. if (delta < hourInSeconds) {
  49. return Math.floor(delta / minuteInSeconds) + "m";
  50. }
  51. if (delta < dayInSeconds) {
  52. return Math.floor(delta / hourInSeconds) + "h";
  53. }
  54. if (delta < monthInSeconds) {
  55. return Math.floor(delta / dayInSeconds) + "d";
  56. }
  57. if (delta < yearInSeconds) {
  58. return Math.floor(delta / monthInSeconds) + "mo";
  59. }
  60. return Math.floor(delta / yearInSeconds) + "y";
  61. }
  62. function updateRelativeTimeForElements(elements)
  63. {
  64. for (let i = 0; i < elements.length; i++)
  65. {
  66. const element = elements[i];
  67. const timestamp = element.dataset.dynamicRelativeTime;
  68. if (timestamp === undefined)
  69. continue
  70. element.textContent = relativeTimeSince(timestamp);
  71. }
  72. }
  73. function setupSearchBoxes() {
  74. const searchWidgets = document.getElementsByClassName("search");
  75. if (searchWidgets.length == 0) {
  76. return;
  77. }
  78. for (let i = 0; i < searchWidgets.length; i++) {
  79. const widget = searchWidgets[i];
  80. const defaultSearchUrl = widget.dataset.defaultSearchUrl;
  81. const newTab = widget.dataset.newTab === "true";
  82. const inputElement = widget.getElementsByClassName("search-input")[0];
  83. const bangElement = widget.getElementsByClassName("search-bang")[0];
  84. const bangs = widget.querySelectorAll(".search-bangs > input");
  85. const bangsMap = {};
  86. const kbdElement = widget.getElementsByTagName("kbd")[0];
  87. let currentBang = null;
  88. let lastQuery = "";
  89. for (let j = 0; j < bangs.length; j++) {
  90. const bang = bangs[j];
  91. bangsMap[bang.dataset.shortcut] = bang;
  92. }
  93. const handleKeyDown = (event) => {
  94. if (event.key == "Escape") {
  95. inputElement.blur();
  96. return;
  97. }
  98. if (event.key == "Enter") {
  99. const input = inputElement.value.trim();
  100. let query;
  101. let searchUrlTemplate;
  102. if (currentBang != null) {
  103. query = input.slice(currentBang.dataset.shortcut.length + 1);
  104. searchUrlTemplate = currentBang.dataset.url;
  105. } else {
  106. query = input;
  107. searchUrlTemplate = defaultSearchUrl;
  108. }
  109. if (query.length == 0 && currentBang == null) {
  110. return;
  111. }
  112. const url = searchUrlTemplate.replace("!QUERY!", encodeURIComponent(query));
  113. if (newTab && !event.ctrlKey || !newTab && event.ctrlKey) {
  114. window.open(url, '_blank').focus();
  115. } else {
  116. window.location.href = url;
  117. }
  118. lastQuery = query;
  119. inputElement.value = "";
  120. return;
  121. }
  122. if (event.key == "ArrowUp" && lastQuery.length > 0) {
  123. inputElement.value = lastQuery;
  124. return;
  125. }
  126. };
  127. const changeCurrentBang = (bang) => {
  128. currentBang = bang;
  129. bangElement.textContent = bang != null ? bang.dataset.title : "";
  130. }
  131. const handleInput = (event) => {
  132. const value = event.target.value.trim();
  133. if (value in bangsMap) {
  134. changeCurrentBang(bangsMap[value]);
  135. return;
  136. }
  137. const words = value.split(" ");
  138. if (words.length >= 2 && words[0] in bangsMap) {
  139. changeCurrentBang(bangsMap[words[0]]);
  140. return;
  141. }
  142. changeCurrentBang(null);
  143. };
  144. inputElement.addEventListener("focus", () => {
  145. document.addEventListener("keydown", handleKeyDown);
  146. document.addEventListener("input", handleInput);
  147. });
  148. inputElement.addEventListener("blur", () => {
  149. document.removeEventListener("keydown", handleKeyDown);
  150. document.removeEventListener("input", handleInput);
  151. });
  152. document.addEventListener("keydown", (event) => {
  153. if (['INPUT', 'TEXTAREA'].includes(document.activeElement.tagName)) return;
  154. if (event.key != "s") return;
  155. inputElement.focus();
  156. event.preventDefault();
  157. });
  158. kbdElement.addEventListener("mousedown", () => {
  159. requestAnimationFrame(() => inputElement.focus());
  160. });
  161. }
  162. }
  163. function setupDynamicRelativeTime() {
  164. const elements = document.querySelectorAll("[data-dynamic-relative-time]");
  165. const updateInterval = 60 * 1000;
  166. let lastUpdateTime = Date.now();
  167. updateRelativeTimeForElements(elements);
  168. const updateElementsAndTimestamp = () => {
  169. updateRelativeTimeForElements(elements);
  170. lastUpdateTime = Date.now();
  171. };
  172. const scheduleRepeatingUpdate = () => setInterval(updateElementsAndTimestamp, updateInterval);
  173. if (document.hidden === undefined) {
  174. scheduleRepeatingUpdate();
  175. return;
  176. }
  177. let timeout = scheduleRepeatingUpdate();
  178. document.addEventListener("visibilitychange", () => {
  179. if (document.hidden) {
  180. clearTimeout(timeout);
  181. return;
  182. }
  183. const delta = Date.now() - lastUpdateTime;
  184. if (delta >= updateInterval) {
  185. updateElementsAndTimestamp();
  186. timeout = scheduleRepeatingUpdate();
  187. return;
  188. }
  189. timeout = setTimeout(() => {
  190. updateElementsAndTimestamp();
  191. timeout = scheduleRepeatingUpdate();
  192. }, updateInterval - delta);
  193. });
  194. }
  195. function setupGroups() {
  196. const groups = document.getElementsByClassName("widget-type-group");
  197. if (groups.length == 0) {
  198. return;
  199. }
  200. for (let g = 0; g < groups.length; g++) {
  201. const group = groups[g];
  202. const titles = group.getElementsByClassName("widget-header")[0].children;
  203. const tabs = group.getElementsByClassName("widget-group-contents")[0].children;
  204. let current = 0;
  205. for (let t = 0; t < titles.length; t++) {
  206. const title = titles[t];
  207. if (title.dataset.titleUrl !== undefined) {
  208. title.addEventListener("mousedown", (event) => {
  209. if (event.button != 1) {
  210. return;
  211. }
  212. openURLInNewTab(title.dataset.titleUrl);
  213. event.preventDefault();
  214. });
  215. }
  216. title.addEventListener("click", () => {
  217. if (t == current) {
  218. if (title.dataset.titleUrl !== undefined) {
  219. openURLInNewTab(title.dataset.titleUrl);
  220. }
  221. return;
  222. }
  223. for (let i = 0; i < titles.length; i++) {
  224. titles[i].classList.remove("widget-group-title-current");
  225. tabs[i].classList.remove("widget-group-content-current");
  226. }
  227. if (current < t) {
  228. tabs[t].dataset.direction = "right";
  229. } else {
  230. tabs[t].dataset.direction = "left";
  231. }
  232. current = t;
  233. title.classList.add("widget-group-title-current");
  234. tabs[t].classList.add("widget-group-content-current");
  235. });
  236. }
  237. }
  238. }
  239. function setupLazyImages() {
  240. const images = document.querySelectorAll("img[loading=lazy]");
  241. if (images.length == 0) {
  242. return;
  243. }
  244. function imageFinishedTransition(image) {
  245. image.classList.add("finished-transition");
  246. }
  247. afterContentReady(() => {
  248. setTimeout(() => {
  249. for (let i = 0; i < images.length; i++) {
  250. const image = images[i];
  251. if (image.complete) {
  252. image.classList.add("cached");
  253. setTimeout(() => imageFinishedTransition(image), 1);
  254. } else {
  255. // TODO: also handle error event
  256. image.addEventListener("load", () => {
  257. image.classList.add("loaded");
  258. setTimeout(() => imageFinishedTransition(image), 400);
  259. });
  260. }
  261. }
  262. }, 1);
  263. });
  264. }
  265. function attachExpandToggleButton(collapsibleContainer) {
  266. const showMoreText = "Show more";
  267. const showLessText = "Show less";
  268. let expanded = false;
  269. const button = document.createElement("button");
  270. const icon = document.createElement("span");
  271. icon.classList.add("expand-toggle-button-icon");
  272. const textNode = document.createTextNode(showMoreText);
  273. button.classList.add("expand-toggle-button");
  274. button.append(textNode, icon);
  275. button.addEventListener("click", () => {
  276. expanded = !expanded;
  277. if (expanded) {
  278. collapsibleContainer.classList.add("container-expanded");
  279. button.classList.add("container-expanded");
  280. textNode.nodeValue = showLessText;
  281. return;
  282. }
  283. const topBefore = button.getClientRects()[0].top;
  284. collapsibleContainer.classList.remove("container-expanded");
  285. button.classList.remove("container-expanded");
  286. textNode.nodeValue = showMoreText;
  287. const topAfter = button.getClientRects()[0].top;
  288. if (topAfter > 0)
  289. return;
  290. window.scrollBy({
  291. top: topAfter - topBefore,
  292. behavior: "instant"
  293. });
  294. });
  295. collapsibleContainer.after(button);
  296. return button;
  297. };
  298. function setupCollapsibleLists() {
  299. const collapsibleLists = document.querySelectorAll(".list.collapsible-container");
  300. if (collapsibleLists.length == 0) {
  301. return;
  302. }
  303. for (let i = 0; i < collapsibleLists.length; i++) {
  304. const list = collapsibleLists[i];
  305. if (list.dataset.collapseAfter === undefined) {
  306. continue;
  307. }
  308. const collapseAfter = parseInt(list.dataset.collapseAfter);
  309. if (collapseAfter == -1) {
  310. continue;
  311. }
  312. if (list.children.length <= collapseAfter) {
  313. continue;
  314. }
  315. attachExpandToggleButton(list);
  316. for (let c = collapseAfter; c < list.children.length; c++) {
  317. const child = list.children[c];
  318. child.classList.add("collapsible-item");
  319. child.style.animationDelay = ((c - collapseAfter) * 20).toString() + "ms";
  320. }
  321. }
  322. }
  323. function setupCollapsibleGrids() {
  324. const collapsibleGridElements = document.querySelectorAll(".cards-grid.collapsible-container");
  325. if (collapsibleGridElements.length == 0) {
  326. return;
  327. }
  328. for (let i = 0; i < collapsibleGridElements.length; i++) {
  329. const gridElement = collapsibleGridElements[i];
  330. if (gridElement.dataset.collapseAfterRows === undefined) {
  331. continue;
  332. }
  333. const collapseAfterRows = parseInt(gridElement.dataset.collapseAfterRows);
  334. if (collapseAfterRows == -1) {
  335. continue;
  336. }
  337. const getCardsPerRow = () => {
  338. return parseInt(getComputedStyle(gridElement).getPropertyValue('--cards-per-row'));
  339. };
  340. const button = attachExpandToggleButton(gridElement);
  341. let cardsPerRow;
  342. const resolveCollapsibleItems = () => {
  343. const hideItemsAfterIndex = cardsPerRow * collapseAfterRows;
  344. if (hideItemsAfterIndex >= gridElement.children.length) {
  345. button.style.display = "none";
  346. } else {
  347. button.style.removeProperty("display");
  348. }
  349. let row = 0;
  350. for (let i = 0; i < gridElement.children.length; i++) {
  351. const child = gridElement.children[i];
  352. if (i >= hideItemsAfterIndex) {
  353. child.classList.add("collapsible-item");
  354. child.style.animationDelay = (row * 40).toString() + "ms";
  355. if (i % cardsPerRow + 1 == cardsPerRow) {
  356. row++;
  357. }
  358. } else {
  359. child.classList.remove("collapsible-item");
  360. child.style.removeProperty("animation-delay");
  361. }
  362. }
  363. };
  364. const observer = new ResizeObserver(() => {
  365. if (!isElementVisible(gridElement)) {
  366. return;
  367. }
  368. const newCardsPerRow = getCardsPerRow();
  369. if (cardsPerRow == newCardsPerRow) {
  370. return;
  371. }
  372. cardsPerRow = newCardsPerRow;
  373. resolveCollapsibleItems();
  374. });
  375. afterContentReady(() => observer.observe(gridElement));
  376. }
  377. }
  378. const contentReadyCallbacks = [];
  379. function afterContentReady(callback) {
  380. contentReadyCallbacks.push(callback);
  381. }
  382. const weekDayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  383. const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  384. function makeSettableTimeElement(element, hourFormat) {
  385. const fragment = document.createDocumentFragment();
  386. const hour = document.createElement('span');
  387. const minute = document.createElement('span');
  388. const amPm = document.createElement('span');
  389. fragment.append(hour, document.createTextNode(':'), minute);
  390. if (hourFormat == '12h') {
  391. fragment.append(document.createTextNode(' '), amPm);
  392. }
  393. element.append(fragment);
  394. return (date) => {
  395. const hours = date.getHours();
  396. if (hourFormat == '12h') {
  397. amPm.textContent = hours < 12 ? 'AM' : 'PM';
  398. hour.textContent = hours % 12 || 12;
  399. } else {
  400. hour.textContent = hours < 10 ? '0' + hours : hours;
  401. }
  402. const minutes = date.getMinutes();
  403. minute.textContent = minutes < 10 ? '0' + minutes : minutes;
  404. };
  405. };
  406. function timeInZone(now, zone) {
  407. let timeInZone;
  408. try {
  409. timeInZone = new Date(now.toLocaleString('en-US', { timeZone: zone }));
  410. } catch (e) {
  411. // TODO: indicate to the user that this is an invalid timezone
  412. console.error(e);
  413. timeInZone = now
  414. }
  415. const diffInMinutes = Math.round((timeInZone.getTime() - now.getTime()) / 1000 / 60);
  416. return { time: timeInZone, diffInMinutes: diffInMinutes };
  417. }
  418. function zoneDiffText(diffInMinutes) {
  419. if (diffInMinutes == 0) {
  420. return "";
  421. }
  422. const sign = diffInMinutes < 0 ? "-" : "+";
  423. const signText = diffInMinutes < 0 ? "behind" : "ahead";
  424. diffInMinutes = Math.abs(diffInMinutes);
  425. const hours = Math.floor(diffInMinutes / 60);
  426. const minutes = diffInMinutes % 60;
  427. const hourSuffix = hours == 1 ? "" : "s";
  428. if (minutes == 0) {
  429. return { text: `${sign}${hours}h`, title: `${hours} hour${hourSuffix} ${signText}` };
  430. }
  431. if (hours == 0) {
  432. return { text: `${sign}${minutes}m`, title: `${minutes} minutes ${signText}` };
  433. }
  434. return { text: `${sign}${hours}h~`, title: `${hours} hour${hourSuffix} and ${minutes} minutes ${signText}` };
  435. }
  436. function setupClocks() {
  437. const clocks = document.getElementsByClassName('clock');
  438. if (clocks.length == 0) {
  439. return;
  440. }
  441. const updateCallbacks = [];
  442. for (var i = 0; i < clocks.length; i++) {
  443. const clock = clocks[i];
  444. const hourFormat = clock.dataset.hourFormat;
  445. const localTimeContainer = clock.querySelector('[data-local-time]');
  446. const localDateElement = localTimeContainer.querySelector('[data-date]');
  447. const localWeekdayElement = localTimeContainer.querySelector('[data-weekday]');
  448. const localYearElement = localTimeContainer.querySelector('[data-year]');
  449. const timeZoneContainers = clock.querySelectorAll('[data-time-in-zone]');
  450. const setLocalTime = makeSettableTimeElement(
  451. localTimeContainer.querySelector('[data-time]'),
  452. hourFormat
  453. );
  454. updateCallbacks.push((now) => {
  455. setLocalTime(now);
  456. localDateElement.textContent = now.getDate() + ' ' + monthNames[now.getMonth()];
  457. localWeekdayElement.textContent = weekDayNames[now.getDay()];
  458. localYearElement.textContent = now.getFullYear();
  459. });
  460. for (var z = 0; z < timeZoneContainers.length; z++) {
  461. const timeZoneContainer = timeZoneContainers[z];
  462. const diffElement = timeZoneContainer.querySelector('[data-time-diff]');
  463. const setZoneTime = makeSettableTimeElement(
  464. timeZoneContainer.querySelector('[data-time]'),
  465. hourFormat
  466. );
  467. updateCallbacks.push((now) => {
  468. const { time, diffInMinutes } = timeInZone(now, timeZoneContainer.dataset.timeInZone);
  469. setZoneTime(time);
  470. const { text, title } = zoneDiffText(diffInMinutes);
  471. diffElement.textContent = text;
  472. diffElement.title = title;
  473. });
  474. }
  475. }
  476. const updateClocks = () => {
  477. const now = new Date();
  478. for (var i = 0; i < updateCallbacks.length; i++)
  479. updateCallbacks[i](now);
  480. setTimeout(updateClocks, (60 - now.getSeconds()) * 1000);
  481. };
  482. updateClocks();
  483. }
  484. async function setupPage() {
  485. const pageElement = document.getElementById("page");
  486. const pageContentElement = document.getElementById("page-content");
  487. const pageContent = await fetchPageContent(pageData);
  488. pageContentElement.innerHTML = pageContent;
  489. try {
  490. setupPopovers();
  491. setupClocks()
  492. setupCarousels();
  493. setupSearchBoxes();
  494. setupCollapsibleLists();
  495. setupCollapsibleGrids();
  496. setupGroups();
  497. setupMasonries();
  498. setupDynamicRelativeTime();
  499. setupLazyImages();
  500. } finally {
  501. pageElement.classList.add("content-ready");
  502. for (let i = 0; i < contentReadyCallbacks.length; i++) {
  503. contentReadyCallbacks[i]();
  504. }
  505. setTimeout(() => {
  506. document.body.classList.add("page-columns-transitioned");
  507. }, 300);
  508. }
  509. }
  510. setupPage();