public.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 (confirmation.value && confirmation.value.length > password.maxLength) {
  102. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  103. } else if (password.value && password.value !== confirmation.value) {
  104. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  105. } else {
  106. confirmation.setCustomValidity('');
  107. }
  108. });
  109. delegate(document, '#user_password,#user_password_confirmation', 'input', () => {
  110. const password = document.getElementById('user_password');
  111. const confirmation = document.getElementById('user_password_confirmation');
  112. if (!confirmation) return;
  113. if (confirmation.value && confirmation.value.length > password.maxLength) {
  114. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  115. } else if (password.value && password.value !== confirmation.value) {
  116. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  117. } else {
  118. confirmation.setCustomValidity('');
  119. }
  120. });
  121. delegate(document, '.custom-emoji', 'mouseover', getEmojiAnimationHandler('data-original'));
  122. delegate(document, '.custom-emoji', 'mouseout', getEmojiAnimationHandler('data-static'));
  123. delegate(document, '.status__content__spoiler-link', 'click', function() {
  124. const statusEl = this.parentNode.parentNode;
  125. if (statusEl.dataset.spoiler === 'expanded') {
  126. statusEl.dataset.spoiler = 'folded';
  127. this.textContent = (new IntlMessageFormat(messages['status.show_more'] || 'Show more', locale)).format();
  128. } else {
  129. statusEl.dataset.spoiler = 'expanded';
  130. this.textContent = (new IntlMessageFormat(messages['status.show_less'] || 'Show less', locale)).format();
  131. }
  132. return false;
  133. });
  134. [].forEach.call(document.querySelectorAll('.status__content__spoiler-link'), (spoilerLink) => {
  135. const statusEl = spoilerLink.parentNode.parentNode;
  136. const message = (statusEl.dataset.spoiler === 'expanded') ? (messages['status.show_less'] || 'Show less') : (messages['status.show_more'] || 'Show more');
  137. spoilerLink.textContent = (new IntlMessageFormat(message, locale)).format();
  138. });
  139. });
  140. delegate(document, '.webapp-btn', 'click', ({ target, button }) => {
  141. if (button !== 0) {
  142. return true;
  143. }
  144. window.location.href = target.href;
  145. return false;
  146. });
  147. delegate(document, '.modal-button', 'click', e => {
  148. e.preventDefault();
  149. let href;
  150. if (e.target.nodeName !== 'A') {
  151. href = e.target.parentNode.href;
  152. } else {
  153. href = e.target.href;
  154. }
  155. window.open(href, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
  156. });
  157. delegate(document, '#account_display_name', 'input', ({ target }) => {
  158. const name = document.querySelector('.card .display-name strong');
  159. if (name) {
  160. if (target.value) {
  161. name.innerHTML = emojify(escapeTextContentForBrowser(target.value));
  162. } else {
  163. name.textContent = target.dataset.default;
  164. }
  165. }
  166. });
  167. delegate(document, '#account_avatar', 'change', ({ target }) => {
  168. const avatar = document.querySelector('.card .avatar img');
  169. const [file] = target.files || [];
  170. const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc;
  171. avatar.src = url;
  172. });
  173. const getProfileAvatarAnimationHandler = (swapTo) => {
  174. //animate avatar gifs on the profile page when moused over
  175. return ({ target }) => {
  176. const swapSrc = target.getAttribute(swapTo);
  177. //only change the img source if autoplay is off and the image src is actually different
  178. if(target.getAttribute('data-autoplay') !== 'true' && target.src !== swapSrc) {
  179. target.src = swapSrc;
  180. }
  181. };
  182. };
  183. delegate(document, 'img#profile_page_avatar', 'mouseover', getProfileAvatarAnimationHandler('data-original'));
  184. delegate(document, 'img#profile_page_avatar', 'mouseout', getProfileAvatarAnimationHandler('data-static'));
  185. delegate(document, '#account_header', 'change', ({ target }) => {
  186. const header = document.querySelector('.card .card__img img');
  187. const [file] = target.files || [];
  188. const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc;
  189. header.src = url;
  190. });
  191. delegate(document, '#account_locked', 'change', ({ target }) => {
  192. const lock = document.querySelector('.card .display-name i');
  193. if (lock) {
  194. if (target.checked) {
  195. delete lock.dataset.hidden;
  196. } else {
  197. lock.dataset.hidden = 'true';
  198. }
  199. }
  200. });
  201. delegate(document, '.input-copy input', 'click', ({ target }) => {
  202. target.focus();
  203. target.select();
  204. target.setSelectionRange(0, target.value.length);
  205. });
  206. delegate(document, '.input-copy button', 'click', ({ target }) => {
  207. const input = target.parentNode.querySelector('.input-copy__wrapper input');
  208. const oldReadOnly = input.readonly;
  209. input.readonly = false;
  210. input.focus();
  211. input.select();
  212. input.setSelectionRange(0, input.value.length);
  213. try {
  214. if (document.execCommand('copy')) {
  215. input.blur();
  216. target.parentNode.classList.add('copied');
  217. setTimeout(() => {
  218. target.parentNode.classList.remove('copied');
  219. }, 700);
  220. }
  221. } catch (err) {
  222. console.error(err);
  223. }
  224. input.readonly = oldReadOnly;
  225. });
  226. delegate(document, '.sidebar__toggle__icon', 'click', () => {
  227. document.querySelector('.sidebar ul').classList.toggle('visible');
  228. });
  229. // Empty the honeypot fields in JS in case something like an extension
  230. // automatically filled them.
  231. delegate(document, '#registration_new_user,#new_user', 'submit', () => {
  232. ['user_website', 'user_confirm_password', 'registration_user_website', 'registration_user_confirm_password'].forEach(id => {
  233. const field = document.getElementById(id);
  234. if (field) {
  235. field.value = '';
  236. }
  237. });
  238. });
  239. }
  240. loadPolyfills()
  241. .then(main)
  242. .then(loadKeyboardExtensions)
  243. .catch(error => {
  244. console.error(error);
  245. });