public.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 Rellax = require('rellax');
  32. const { createBrowserHistory } = require('history');
  33. const scrollToDetailedStatus = () => {
  34. const history = createBrowserHistory();
  35. const detailedStatuses = document.querySelectorAll('.public-layout .detailed-status');
  36. const location = history.location;
  37. if (detailedStatuses.length === 1 && (!location.state || !location.state.scrolledToDetailedStatus)) {
  38. detailedStatuses[0].scrollIntoView();
  39. history.replace(location.pathname, { ...location.state, scrolledToDetailedStatus: true });
  40. }
  41. };
  42. const getEmojiAnimationHandler = (swapTo) => {
  43. return ({ target }) => {
  44. target.src = target.getAttribute(swapTo);
  45. };
  46. };
  47. ready(() => {
  48. const locale = document.documentElement.lang;
  49. const dateTimeFormat = new Intl.DateTimeFormat(locale, {
  50. year: 'numeric',
  51. month: 'long',
  52. day: 'numeric',
  53. hour: 'numeric',
  54. minute: 'numeric',
  55. });
  56. [].forEach.call(document.querySelectorAll('.emojify'), (content) => {
  57. content.innerHTML = emojify(content.innerHTML);
  58. });
  59. [].forEach.call(document.querySelectorAll('time.formatted'), (content) => {
  60. const datetime = new Date(content.getAttribute('datetime'));
  61. const formattedDate = dateTimeFormat.format(datetime);
  62. content.title = formattedDate;
  63. content.textContent = formattedDate;
  64. });
  65. [].forEach.call(document.querySelectorAll('time.time-ago'), (content) => {
  66. const datetime = new Date(content.getAttribute('datetime'));
  67. const now = new Date();
  68. content.title = dateTimeFormat.format(datetime);
  69. content.textContent = timeAgoString({
  70. formatMessage: ({ id, defaultMessage }, values) => (new IntlMessageFormat(messages[id] || defaultMessage, locale)).format(values),
  71. formatDate: (date, options) => (new Intl.DateTimeFormat(locale, options)).format(date),
  72. }, datetime, now, now.getFullYear(), content.getAttribute('datetime').includes('T'));
  73. });
  74. const reactComponents = document.querySelectorAll('[data-component]');
  75. if (reactComponents.length > 0) {
  76. import(/* webpackChunkName: "containers/media_container" */ '../mastodon/containers/media_container')
  77. .then(({ default: MediaContainer }) => {
  78. [].forEach.call(reactComponents, (component) => {
  79. [].forEach.call(component.children, (child) => {
  80. component.removeChild(child);
  81. });
  82. });
  83. const content = document.createElement('div');
  84. ReactDOM.render(<MediaContainer locale={locale} components={reactComponents} />, content);
  85. document.body.appendChild(content);
  86. scrollToDetailedStatus();
  87. })
  88. .catch(error => {
  89. console.error(error);
  90. scrollToDetailedStatus();
  91. });
  92. } else {
  93. scrollToDetailedStatus();
  94. }
  95. const parallaxComponents = document.querySelectorAll('.parallax');
  96. if (parallaxComponents.length > 0 ) {
  97. new Rellax('.parallax', { speed: -1 });
  98. }
  99. delegate(document, '#registration_user_password_confirmation,#registration_user_password', 'input', () => {
  100. const password = document.getElementById('registration_user_password');
  101. const confirmation = document.getElementById('registration_user_password_confirmation');
  102. if (confirmation.value && confirmation.value.length > password.maxLength) {
  103. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  104. } else if (password.value && password.value !== confirmation.value) {
  105. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  106. } else {
  107. confirmation.setCustomValidity('');
  108. }
  109. });
  110. delegate(document, '#user_password,#user_password_confirmation', 'input', () => {
  111. const password = document.getElementById('user_password');
  112. const confirmation = document.getElementById('user_password_confirmation');
  113. if (!confirmation) return;
  114. if (confirmation.value && confirmation.value.length > password.maxLength) {
  115. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  116. } else if (password.value && password.value !== confirmation.value) {
  117. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  118. } else {
  119. confirmation.setCustomValidity('');
  120. }
  121. });
  122. delegate(document, '.custom-emoji', 'mouseover', getEmojiAnimationHandler('data-original'));
  123. delegate(document, '.custom-emoji', 'mouseout', getEmojiAnimationHandler('data-static'));
  124. delegate(document, '.status__content__spoiler-link', 'click', function() {
  125. const statusEl = this.parentNode.parentNode;
  126. if (statusEl.dataset.spoiler === 'expanded') {
  127. statusEl.dataset.spoiler = 'folded';
  128. this.textContent = (new IntlMessageFormat(messages['status.show_more'] || 'Show more', locale)).format();
  129. } else {
  130. statusEl.dataset.spoiler = 'expanded';
  131. this.textContent = (new IntlMessageFormat(messages['status.show_less'] || 'Show less', locale)).format();
  132. }
  133. return false;
  134. });
  135. [].forEach.call(document.querySelectorAll('.status__content__spoiler-link'), (spoilerLink) => {
  136. const statusEl = spoilerLink.parentNode.parentNode;
  137. const message = (statusEl.dataset.spoiler === 'expanded') ? (messages['status.show_less'] || 'Show less') : (messages['status.show_more'] || 'Show more');
  138. spoilerLink.textContent = (new IntlMessageFormat(message, locale)).format();
  139. });
  140. });
  141. delegate(document, '.webapp-btn', 'click', ({ target, button }) => {
  142. if (button !== 0) {
  143. return true;
  144. }
  145. window.location.href = target.href;
  146. return false;
  147. });
  148. delegate(document, '.modal-button', 'click', e => {
  149. e.preventDefault();
  150. let href;
  151. if (e.target.nodeName !== 'A') {
  152. href = e.target.parentNode.href;
  153. } else {
  154. href = e.target.href;
  155. }
  156. window.open(href, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
  157. });
  158. delegate(document, '#account_display_name', 'input', ({ target }) => {
  159. const name = document.querySelector('.card .display-name strong');
  160. if (name) {
  161. if (target.value) {
  162. name.innerHTML = emojify(escapeTextContentForBrowser(target.value));
  163. } else {
  164. name.textContent = target.dataset.default;
  165. }
  166. }
  167. });
  168. delegate(document, '#account_avatar', 'change', ({ target }) => {
  169. const avatar = document.querySelector('.card .avatar img');
  170. const [file] = target.files || [];
  171. const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc;
  172. avatar.src = url;
  173. });
  174. const getProfileAvatarAnimationHandler = (swapTo) => {
  175. //animate avatar gifs on the profile page when moused over
  176. return ({ target }) => {
  177. const swapSrc = target.getAttribute(swapTo);
  178. //only change the img source if autoplay is off and the image src is actually different
  179. if(target.getAttribute('data-autoplay') !== 'true' && target.src !== swapSrc) {
  180. target.src = swapSrc;
  181. }
  182. };
  183. };
  184. delegate(document, 'img#profile_page_avatar', 'mouseover', getProfileAvatarAnimationHandler('data-original'));
  185. delegate(document, 'img#profile_page_avatar', 'mouseout', getProfileAvatarAnimationHandler('data-static'));
  186. delegate(document, '#account_header', 'change', ({ target }) => {
  187. const header = document.querySelector('.card .card__img img');
  188. const [file] = target.files || [];
  189. const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc;
  190. header.src = url;
  191. });
  192. delegate(document, '#account_locked', 'change', ({ target }) => {
  193. const lock = document.querySelector('.card .display-name i');
  194. if (lock) {
  195. if (target.checked) {
  196. delete lock.dataset.hidden;
  197. } else {
  198. lock.dataset.hidden = 'true';
  199. }
  200. }
  201. });
  202. delegate(document, '.input-copy input', 'click', ({ target }) => {
  203. target.focus();
  204. target.select();
  205. target.setSelectionRange(0, target.value.length);
  206. });
  207. delegate(document, '.input-copy button', 'click', ({ target }) => {
  208. const input = target.parentNode.querySelector('.input-copy__wrapper input');
  209. const oldReadOnly = input.readonly;
  210. input.readonly = false;
  211. input.focus();
  212. input.select();
  213. input.setSelectionRange(0, input.value.length);
  214. try {
  215. if (document.execCommand('copy')) {
  216. input.blur();
  217. target.parentNode.classList.add('copied');
  218. setTimeout(() => {
  219. target.parentNode.classList.remove('copied');
  220. }, 700);
  221. }
  222. } catch (err) {
  223. console.error(err);
  224. }
  225. input.readonly = oldReadOnly;
  226. });
  227. delegate(document, '.sidebar__toggle__icon', 'click', () => {
  228. document.querySelector('.sidebar ul').classList.toggle('visible');
  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. });