1
0

public.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import './public-path';
  2. import escapeTextContentForBrowser from 'escape-html';
  3. import loadPolyfills from '../mastodon/load_polyfills';
  4. import ready from '../mastodon/ready';
  5. import { start } from '../mastodon/common';
  6. import loadKeyboardExtensions from '../mastodon/load_keyboard_extensions';
  7. import 'cocoon-js-vanilla';
  8. start();
  9. window.addEventListener('message', e => {
  10. const data = e.data || {};
  11. if (!window.parent || data.type !== 'setHeight') {
  12. return;
  13. }
  14. ready(() => {
  15. window.parent.postMessage({
  16. type: 'setHeight',
  17. id: data.id,
  18. height: document.getElementsByTagName('html')[0].scrollHeight,
  19. }, '*');
  20. });
  21. });
  22. function main() {
  23. const IntlMessageFormat = require('intl-messageformat').default;
  24. const { timeAgoString } = require('../mastodon/components/relative_timestamp');
  25. const { delegate } = require('@rails/ujs');
  26. const emojify = require('../mastodon/features/emoji/emoji').default;
  27. const { getLocale } = require('../mastodon/locales');
  28. const { messages } = getLocale();
  29. const React = require('react');
  30. const ReactDOM = require('react-dom');
  31. const { createBrowserHistory } = require('history');
  32. const scrollToDetailedStatus = () => {
  33. const history = createBrowserHistory();
  34. const detailedStatuses = document.querySelectorAll('.public-layout .detailed-status');
  35. const location = history.location;
  36. if (detailedStatuses.length === 1 && (!location.state || !location.state.scrolledToDetailedStatus)) {
  37. detailedStatuses[0].scrollIntoView();
  38. history.replace(location.pathname, { ...location.state, scrolledToDetailedStatus: true });
  39. }
  40. };
  41. const getEmojiAnimationHandler = (swapTo) => {
  42. return ({ target }) => {
  43. target.src = target.getAttribute(swapTo);
  44. };
  45. };
  46. ready(() => {
  47. const locale = document.documentElement.lang;
  48. const dateTimeFormat = new Intl.DateTimeFormat(locale, {
  49. year: 'numeric',
  50. month: 'long',
  51. day: 'numeric',
  52. hour: 'numeric',
  53. minute: 'numeric',
  54. });
  55. const dateFormat = new Intl.DateTimeFormat(locale, {
  56. year: 'numeric',
  57. month: 'short',
  58. day: 'numeric',
  59. timeFormat: false,
  60. });
  61. const timeFormat = new Intl.DateTimeFormat(locale, {
  62. timeStyle: 'short',
  63. hour12: false,
  64. });
  65. [].forEach.call(document.querySelectorAll('.emojify'), (content) => {
  66. content.innerHTML = emojify(content.innerHTML);
  67. });
  68. [].forEach.call(document.querySelectorAll('time.formatted'), (content) => {
  69. const datetime = new Date(content.getAttribute('datetime'));
  70. const formattedDate = dateTimeFormat.format(datetime);
  71. content.title = formattedDate;
  72. content.textContent = formattedDate;
  73. });
  74. const isToday = date => {
  75. const today = new Date();
  76. return date.getDate() === today.getDate() &&
  77. date.getMonth() === today.getMonth() &&
  78. date.getFullYear() === today.getFullYear();
  79. };
  80. const todayFormat = new IntlMessageFormat(messages['relative_format.today'] || 'Today at {time}', locale);
  81. [].forEach.call(document.querySelectorAll('time.relative-formatted'), (content) => {
  82. const datetime = new Date(content.getAttribute('datetime'));
  83. let formattedContent;
  84. if (isToday(datetime)) {
  85. const formattedTime = timeFormat.format(datetime);
  86. formattedContent = todayFormat.format({ time: formattedTime });
  87. } else {
  88. formattedContent = dateFormat.format(datetime);
  89. }
  90. content.title = formattedContent;
  91. content.textContent = formattedContent;
  92. });
  93. [].forEach.call(document.querySelectorAll('time.time-ago'), (content) => {
  94. const datetime = new Date(content.getAttribute('datetime'));
  95. const now = new Date();
  96. content.title = dateTimeFormat.format(datetime);
  97. content.textContent = timeAgoString({
  98. formatMessage: ({ id, defaultMessage }, values) => (new IntlMessageFormat(messages[id] || defaultMessage, locale)).format(values),
  99. formatDate: (date, options) => (new Intl.DateTimeFormat(locale, options)).format(date),
  100. }, datetime, now, now.getFullYear(), content.getAttribute('datetime').includes('T'));
  101. });
  102. const reactComponents = document.querySelectorAll('[data-component]');
  103. if (reactComponents.length > 0) {
  104. import(/* webpackChunkName: "containers/media_container" */ '../mastodon/containers/media_container')
  105. .then(({ default: MediaContainer }) => {
  106. [].forEach.call(reactComponents, (component) => {
  107. [].forEach.call(component.children, (child) => {
  108. component.removeChild(child);
  109. });
  110. });
  111. const content = document.createElement('div');
  112. ReactDOM.render(<MediaContainer locale={locale} components={reactComponents} />, content);
  113. document.body.appendChild(content);
  114. scrollToDetailedStatus();
  115. })
  116. .catch(error => {
  117. console.error(error);
  118. scrollToDetailedStatus();
  119. });
  120. } else {
  121. scrollToDetailedStatus();
  122. }
  123. delegate(document, '#registration_user_password_confirmation,#registration_user_password', 'input', () => {
  124. const password = document.getElementById('registration_user_password');
  125. const confirmation = document.getElementById('registration_user_password_confirmation');
  126. if (confirmation.value && confirmation.value.length > password.maxLength) {
  127. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  128. } else if (password.value && password.value !== confirmation.value) {
  129. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  130. } else {
  131. confirmation.setCustomValidity('');
  132. }
  133. });
  134. delegate(document, '#user_password,#user_password_confirmation', 'input', () => {
  135. const password = document.getElementById('user_password');
  136. const confirmation = document.getElementById('user_password_confirmation');
  137. if (!confirmation) return;
  138. if (confirmation.value && confirmation.value.length > password.maxLength) {
  139. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  140. } else if (password.value && password.value !== confirmation.value) {
  141. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  142. } else {
  143. confirmation.setCustomValidity('');
  144. }
  145. });
  146. delegate(document, '.custom-emoji', 'mouseover', getEmojiAnimationHandler('data-original'));
  147. delegate(document, '.custom-emoji', 'mouseout', getEmojiAnimationHandler('data-static'));
  148. delegate(document, '.status__content__spoiler-link', 'click', function() {
  149. const statusEl = this.parentNode.parentNode;
  150. if (statusEl.dataset.spoiler === 'expanded') {
  151. statusEl.dataset.spoiler = 'folded';
  152. this.textContent = (new IntlMessageFormat(messages['status.show_more'] || 'Show more', locale)).format();
  153. } else {
  154. statusEl.dataset.spoiler = 'expanded';
  155. this.textContent = (new IntlMessageFormat(messages['status.show_less'] || 'Show less', locale)).format();
  156. }
  157. return false;
  158. });
  159. [].forEach.call(document.querySelectorAll('.status__content__spoiler-link'), (spoilerLink) => {
  160. const statusEl = spoilerLink.parentNode.parentNode;
  161. const message = (statusEl.dataset.spoiler === 'expanded') ? (messages['status.show_less'] || 'Show less') : (messages['status.show_more'] || 'Show more');
  162. spoilerLink.textContent = (new IntlMessageFormat(message, locale)).format();
  163. });
  164. });
  165. delegate(document, '#account_display_name', 'input', ({ target }) => {
  166. const name = document.querySelector('.card .display-name strong');
  167. if (name) {
  168. if (target.value) {
  169. name.innerHTML = emojify(escapeTextContentForBrowser(target.value));
  170. } else {
  171. name.textContent = target.dataset.default;
  172. }
  173. }
  174. });
  175. delegate(document, '#account_avatar', 'change', ({ target }) => {
  176. const avatar = document.querySelector('.card .avatar img');
  177. const [file] = target.files || [];
  178. const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc;
  179. avatar.src = url;
  180. });
  181. const getProfileAvatarAnimationHandler = (swapTo) => {
  182. //animate avatar gifs on the profile page when moused over
  183. return ({ target }) => {
  184. const swapSrc = target.getAttribute(swapTo);
  185. //only change the img source if autoplay is off and the image src is actually different
  186. if(target.getAttribute('data-autoplay') !== 'true' && target.src !== swapSrc) {
  187. target.src = swapSrc;
  188. }
  189. };
  190. };
  191. delegate(document, 'img#profile_page_avatar', 'mouseover', getProfileAvatarAnimationHandler('data-original'));
  192. delegate(document, 'img#profile_page_avatar', 'mouseout', getProfileAvatarAnimationHandler('data-static'));
  193. delegate(document, '#account_header', 'change', ({ target }) => {
  194. const header = document.querySelector('.card .card__img img');
  195. const [file] = target.files || [];
  196. const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc;
  197. header.src = url;
  198. });
  199. delegate(document, '#account_locked', 'change', ({ target }) => {
  200. const lock = document.querySelector('.card .display-name i');
  201. if (lock) {
  202. if (target.checked) {
  203. delete lock.dataset.hidden;
  204. } else {
  205. lock.dataset.hidden = 'true';
  206. }
  207. }
  208. });
  209. delegate(document, '.input-copy input', 'click', ({ target }) => {
  210. target.focus();
  211. target.select();
  212. target.setSelectionRange(0, target.value.length);
  213. });
  214. delegate(document, '.input-copy button', 'click', ({ target }) => {
  215. const input = target.parentNode.querySelector('.input-copy__wrapper input');
  216. const oldReadOnly = input.readonly;
  217. input.readonly = false;
  218. input.focus();
  219. input.select();
  220. input.setSelectionRange(0, input.value.length);
  221. try {
  222. if (document.execCommand('copy')) {
  223. input.blur();
  224. target.parentNode.classList.add('copied');
  225. setTimeout(() => {
  226. target.parentNode.classList.remove('copied');
  227. }, 700);
  228. }
  229. } catch (err) {
  230. console.error(err);
  231. }
  232. input.readonly = oldReadOnly;
  233. });
  234. const toggleSidebar = () => {
  235. const sidebar = document.querySelector('.sidebar ul');
  236. const toggleButton = document.querySelector('.sidebar__toggle__icon');
  237. if (sidebar.classList.contains('visible')) {
  238. document.body.style.overflow = null;
  239. toggleButton.setAttribute('aria-expanded', false);
  240. } else {
  241. document.body.style.overflow = 'hidden';
  242. toggleButton.setAttribute('aria-expanded', true);
  243. }
  244. toggleButton.classList.toggle('active');
  245. sidebar.classList.toggle('visible');
  246. };
  247. delegate(document, '.sidebar__toggle__icon', 'click', () => {
  248. toggleSidebar();
  249. });
  250. delegate(document, '.sidebar__toggle__icon', 'keydown', e => {
  251. if (e.key === ' ' || e.key === 'Enter') {
  252. e.preventDefault();
  253. toggleSidebar();
  254. }
  255. });
  256. // Empty the honeypot fields in JS in case something like an extension
  257. // automatically filled them.
  258. delegate(document, '#registration_new_user,#new_user', 'submit', () => {
  259. ['user_website', 'user_confirm_password', 'registration_user_website', 'registration_user_confirm_password'].forEach(id => {
  260. const field = document.getElementById(id);
  261. if (field) {
  262. field.value = '';
  263. }
  264. });
  265. });
  266. }
  267. loadPolyfills()
  268. .then(main)
  269. .then(loadKeyboardExtensions)
  270. .catch(error => {
  271. console.error(error);
  272. });