public.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. [].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. delegate(document, '#registration_user_password_confirmation,#registration_user_password', 'input', () => {
  95. const password = document.getElementById('registration_user_password');
  96. const confirmation = document.getElementById('registration_user_password_confirmation');
  97. if (confirmation.value && confirmation.value.length > password.maxLength) {
  98. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  99. } else if (password.value && password.value !== confirmation.value) {
  100. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.mismatching'] || 'Password confirmation does not match', locale)).format());
  101. } else {
  102. confirmation.setCustomValidity('');
  103. }
  104. });
  105. delegate(document, '#user_password,#user_password_confirmation', 'input', () => {
  106. const password = document.getElementById('user_password');
  107. const confirmation = document.getElementById('user_password_confirmation');
  108. if (!confirmation) return;
  109. if (confirmation.value && confirmation.value.length > password.maxLength) {
  110. confirmation.setCustomValidity((new IntlMessageFormat(messages['password_confirmation.exceeds_maxlength'] || 'Password confirmation exceeds the maximum password length', locale)).format());
  111. } else 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, '#account_display_name', 'input', ({ target }) => {
  137. const name = document.querySelector('.card .display-name strong');
  138. if (name) {
  139. if (target.value) {
  140. name.innerHTML = emojify(escapeTextContentForBrowser(target.value));
  141. } else {
  142. name.textContent = target.dataset.default;
  143. }
  144. }
  145. });
  146. delegate(document, '#account_avatar', 'change', ({ target }) => {
  147. const avatar = document.querySelector('.card .avatar img');
  148. const [file] = target.files || [];
  149. const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc;
  150. avatar.src = url;
  151. });
  152. const getProfileAvatarAnimationHandler = (swapTo) => {
  153. //animate avatar gifs on the profile page when moused over
  154. return ({ target }) => {
  155. const swapSrc = target.getAttribute(swapTo);
  156. //only change the img source if autoplay is off and the image src is actually different
  157. if(target.getAttribute('data-autoplay') !== 'true' && target.src !== swapSrc) {
  158. target.src = swapSrc;
  159. }
  160. };
  161. };
  162. delegate(document, 'img#profile_page_avatar', 'mouseover', getProfileAvatarAnimationHandler('data-original'));
  163. delegate(document, 'img#profile_page_avatar', 'mouseout', getProfileAvatarAnimationHandler('data-static'));
  164. delegate(document, '#account_header', 'change', ({ target }) => {
  165. const header = document.querySelector('.card .card__img img');
  166. const [file] = target.files || [];
  167. const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc;
  168. header.src = url;
  169. });
  170. delegate(document, '#account_locked', 'change', ({ target }) => {
  171. const lock = document.querySelector('.card .display-name i');
  172. if (lock) {
  173. if (target.checked) {
  174. delete lock.dataset.hidden;
  175. } else {
  176. lock.dataset.hidden = 'true';
  177. }
  178. }
  179. });
  180. delegate(document, '.input-copy input', 'click', ({ target }) => {
  181. target.focus();
  182. target.select();
  183. target.setSelectionRange(0, target.value.length);
  184. });
  185. delegate(document, '.input-copy button', 'click', ({ target }) => {
  186. const input = target.parentNode.querySelector('.input-copy__wrapper input');
  187. const oldReadOnly = input.readonly;
  188. input.readonly = false;
  189. input.focus();
  190. input.select();
  191. input.setSelectionRange(0, input.value.length);
  192. try {
  193. if (document.execCommand('copy')) {
  194. input.blur();
  195. target.parentNode.classList.add('copied');
  196. setTimeout(() => {
  197. target.parentNode.classList.remove('copied');
  198. }, 700);
  199. }
  200. } catch (err) {
  201. console.error(err);
  202. }
  203. input.readonly = oldReadOnly;
  204. });
  205. delegate(document, '.sidebar__toggle__icon', 'click', () => {
  206. document.querySelector('.sidebar ul').classList.toggle('visible');
  207. });
  208. // Empty the honeypot fields in JS in case something like an extension
  209. // automatically filled them.
  210. delegate(document, '#registration_new_user,#new_user', 'submit', () => {
  211. ['user_website', 'user_confirm_password', 'registration_user_website', 'registration_user_confirm_password'].forEach(id => {
  212. const field = document.getElementById(id);
  213. if (field) {
  214. field.value = '';
  215. }
  216. });
  217. });
  218. }
  219. loadPolyfills()
  220. .then(main)
  221. .then(loadKeyboardExtensions)
  222. .catch(error => {
  223. console.error(error);
  224. });