public.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. start();
  8. window.addEventListener('message', e => {
  9. const data = e.data || {};
  10. if (!window.parent || data.type !== 'setHeight') {
  11. return;
  12. }
  13. ready(() => {
  14. window.parent.postMessage({
  15. type: 'setHeight',
  16. id: data.id,
  17. height: document.getElementsByTagName('html')[0].scrollHeight,
  18. }, '*');
  19. });
  20. });
  21. function main() {
  22. const IntlMessageFormat = require('intl-messageformat').default;
  23. const { timeAgoString } = require('../mastodon/components/relative_timestamp');
  24. const { delegate } = require('@rails/ujs');
  25. const emojify = require('../mastodon/features/emoji/emoji').default;
  26. const { getLocale } = require('../mastodon/locales');
  27. const { messages } = getLocale();
  28. const React = require('react');
  29. const ReactDOM = require('react-dom');
  30. const Rellax = require('rellax');
  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. [].forEach.call(document.querySelectorAll('.emojify'), (content) => {
  56. content.innerHTML = emojify(content.innerHTML);
  57. });
  58. [].forEach.call(document.querySelectorAll('time.formatted'), (content) => {
  59. const datetime = new Date(content.getAttribute('datetime'));
  60. const formattedDate = dateTimeFormat.format(datetime);
  61. content.title = formattedDate;
  62. content.textContent = formattedDate;
  63. });
  64. [].forEach.call(document.querySelectorAll('time.time-ago'), (content) => {
  65. const datetime = new Date(content.getAttribute('datetime'));
  66. const now = new Date();
  67. content.title = dateTimeFormat.format(datetime);
  68. content.textContent = timeAgoString({
  69. formatMessage: ({ id, defaultMessage }, values) => (new IntlMessageFormat(messages[id] || defaultMessage, locale)).format(values),
  70. formatDate: (date, options) => (new Intl.DateTimeFormat(locale, options)).format(date),
  71. }, datetime, now, now.getFullYear(), content.getAttribute('datetime').includes('T'));
  72. });
  73. const reactComponents = document.querySelectorAll('[data-component]');
  74. if (reactComponents.length > 0) {
  75. import(/* webpackChunkName: "containers/media_container" */ '../mastodon/containers/media_container')
  76. .then(({ default: MediaContainer }) => {
  77. [].forEach.call(reactComponents, (component) => {
  78. [].forEach.call(component.children, (child) => {
  79. component.removeChild(child);
  80. });
  81. });
  82. const content = document.createElement('div');
  83. ReactDOM.render(<MediaContainer locale={locale} components={reactComponents} />, content);
  84. document.body.appendChild(content);
  85. scrollToDetailedStatus();
  86. })
  87. .catch(error => {
  88. console.error(error);
  89. scrollToDetailedStatus();
  90. });
  91. } else {
  92. scrollToDetailedStatus();
  93. }
  94. const parallaxComponents = document.querySelectorAll('.parallax');
  95. if (parallaxComponents.length > 0 ) {
  96. new Rellax('.parallax', { speed: -1 });
  97. }
  98. delegate(document, '#registration_user_password_confirmation,#registration_user_password', 'input', () => {
  99. const password = document.getElementById('registration_user_password');
  100. const confirmation = document.getElementById('registration_user_password_confirmation');
  101. if (password.value && password.value !== confirmation.value) {
  102. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  103. } else {
  104. confirmation.setCustomValidity('');
  105. }
  106. });
  107. delegate(document, '#user_password,#user_password_confirmation', 'input', () => {
  108. const password = document.getElementById('user_password');
  109. const confirmation = document.getElementById('user_password_confirmation');
  110. if (!confirmation) return;
  111. if (password.value && password.value !== confirmation.value) {
  112. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  113. } else {
  114. confirmation.setCustomValidity('');
  115. }
  116. });
  117. delegate(document, '.custom-emoji', 'mouseover', getEmojiAnimationHandler('data-original'));
  118. delegate(document, '.custom-emoji', 'mouseout', getEmojiAnimationHandler('data-static'));
  119. delegate(document, '.status__content__spoiler-link', 'click', function() {
  120. const statusEl = this.parentNode.parentNode;
  121. if (statusEl.dataset.spoiler === 'expanded') {
  122. statusEl.dataset.spoiler = 'folded';
  123. this.textContent = (new IntlMessageFormat(messages['status.show_more'] || 'Show more', locale)).format();
  124. } else {
  125. statusEl.dataset.spoiler = 'expanded';
  126. this.textContent = (new IntlMessageFormat(messages['status.show_less'] || 'Show less', locale)).format();
  127. }
  128. return false;
  129. });
  130. [].forEach.call(document.querySelectorAll('.status__content__spoiler-link'), (spoilerLink) => {
  131. const statusEl = spoilerLink.parentNode.parentNode;
  132. const message = (statusEl.dataset.spoiler === 'expanded') ? (messages['status.show_less'] || 'Show less') : (messages['status.show_more'] || 'Show more');
  133. spoilerLink.textContent = (new IntlMessageFormat(message, locale)).format();
  134. });
  135. });
  136. delegate(document, '.webapp-btn', 'click', ({ target, button }) => {
  137. if (button !== 0) {
  138. return true;
  139. }
  140. window.location.href = target.href;
  141. return false;
  142. });
  143. delegate(document, '.modal-button', 'click', e => {
  144. e.preventDefault();
  145. let href;
  146. if (e.target.nodeName !== 'A') {
  147. href = e.target.parentNode.href;
  148. } else {
  149. href = e.target.href;
  150. }
  151. window.open(href, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
  152. });
  153. delegate(document, '#account_display_name', 'input', ({ target }) => {
  154. const name = document.querySelector('.card .display-name strong');
  155. if (name) {
  156. if (target.value) {
  157. name.innerHTML = emojify(escapeTextContentForBrowser(target.value));
  158. } else {
  159. name.textContent = target.dataset.default;
  160. }
  161. }
  162. });
  163. delegate(document, '#account_avatar', 'change', ({ target }) => {
  164. const avatar = document.querySelector('.card .avatar img');
  165. const [file] = target.files || [];
  166. const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc;
  167. avatar.src = url;
  168. });
  169. const getProfileAvatarAnimationHandler = (swapTo) => {
  170. //animate avatar gifs on the profile page when moused over
  171. return ({ target }) => {
  172. const swapSrc = target.getAttribute(swapTo);
  173. //only change the img source if autoplay is off and the image src is actually different
  174. if(target.getAttribute('data-autoplay') !== 'true' && target.src !== swapSrc) {
  175. target.src = swapSrc;
  176. }
  177. };
  178. };
  179. delegate(document, 'img#profile_page_avatar', 'mouseover', getProfileAvatarAnimationHandler('data-original'));
  180. delegate(document, 'img#profile_page_avatar', 'mouseout', getProfileAvatarAnimationHandler('data-static'));
  181. delegate(document, '#account_header', 'change', ({ target }) => {
  182. const header = document.querySelector('.card .card__img img');
  183. const [file] = target.files || [];
  184. const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc;
  185. header.src = url;
  186. });
  187. delegate(document, '#account_locked', 'change', ({ target }) => {
  188. const lock = document.querySelector('.card .display-name i');
  189. if (lock) {
  190. if (target.checked) {
  191. delete lock.dataset.hidden;
  192. } else {
  193. lock.dataset.hidden = 'true';
  194. }
  195. }
  196. });
  197. delegate(document, '.input-copy input', 'click', ({ target }) => {
  198. target.focus();
  199. target.select();
  200. target.setSelectionRange(0, target.value.length);
  201. });
  202. delegate(document, '.input-copy button', 'click', ({ target }) => {
  203. const input = target.parentNode.querySelector('.input-copy__wrapper input');
  204. const oldReadOnly = input.readonly;
  205. input.readonly = false;
  206. input.focus();
  207. input.select();
  208. input.setSelectionRange(0, input.value.length);
  209. try {
  210. if (document.execCommand('copy')) {
  211. input.blur();
  212. target.parentNode.classList.add('copied');
  213. setTimeout(() => {
  214. target.parentNode.classList.remove('copied');
  215. }, 700);
  216. }
  217. } catch (err) {
  218. console.error(err);
  219. }
  220. input.readonly = oldReadOnly;
  221. });
  222. delegate(document, '.sidebar__toggle__icon', 'click', () => {
  223. const target = document.querySelector('.sidebar ul');
  224. if (target.style.display === 'block') {
  225. target.style.display = 'none';
  226. } else {
  227. target.style.display = 'block';
  228. }
  229. });
  230. // Empty the honeypot fields in JS in case something like an extension
  231. // automatically filled them.
  232. delegate(document, '#registration_new_user,#new_user', 'submit', () => {
  233. ['user_website', 'user_confirm_password', 'registration_user_website', 'registration_user_confirm_password'].forEach(id => {
  234. const field = document.getElementById(id);
  235. if (field) {
  236. field.value = '';
  237. }
  238. });
  239. });
  240. }
  241. loadPolyfills()
  242. .then(main)
  243. .then(loadKeyboardExtensions)
  244. .catch(error => {
  245. console.error(error);
  246. });