public.jsx 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { createRoot } from 'react-dom/client';
  2. import './public-path';
  3. import { IntlMessageFormat } from 'intl-messageformat';
  4. import { defineMessages } from 'react-intl';
  5. import Rails from '@rails/ujs';
  6. import axios from 'axios';
  7. import { throttle } from 'lodash';
  8. import { start } from '../mastodon/common';
  9. import { timeAgoString } from '../mastodon/components/relative_timestamp';
  10. import emojify from '../mastodon/features/emoji/emoji';
  11. import loadKeyboardExtensions from '../mastodon/load_keyboard_extensions';
  12. import { loadLocale, getLocale } from '../mastodon/locales';
  13. import { loadPolyfills } from '../mastodon/polyfills';
  14. import ready from '../mastodon/ready';
  15. import 'cocoon-js-vanilla';
  16. start();
  17. const messages = defineMessages({
  18. usernameTaken: { id: 'username.taken', defaultMessage: 'That username is taken. Try another' },
  19. passwordExceedsLength: { id: 'password_confirmation.exceeds_maxlength', defaultMessage: 'Password confirmation exceeds the maximum password length' },
  20. passwordDoesNotMatch: { id: 'password_confirmation.mismatching', defaultMessage: 'Password confirmation does not match' },
  21. });
  22. window.addEventListener('message', e => {
  23. const data = e.data || {};
  24. if (!window.parent || data.type !== 'setHeight') {
  25. return;
  26. }
  27. ready(() => {
  28. window.parent.postMessage({
  29. type: 'setHeight',
  30. id: data.id,
  31. height: document.getElementsByTagName('html')[0].scrollHeight,
  32. }, '*');
  33. });
  34. });
  35. function loaded() {
  36. const { messages: localeData } = getLocale();
  37. const locale = document.documentElement.lang;
  38. const dateTimeFormat = new Intl.DateTimeFormat(locale, {
  39. year: 'numeric',
  40. month: 'long',
  41. day: 'numeric',
  42. hour: 'numeric',
  43. minute: 'numeric',
  44. });
  45. const dateFormat = new Intl.DateTimeFormat(locale, {
  46. year: 'numeric',
  47. month: 'short',
  48. day: 'numeric',
  49. timeFormat: false,
  50. });
  51. const timeFormat = new Intl.DateTimeFormat(locale, {
  52. timeStyle: 'short',
  53. hour12: false,
  54. });
  55. const formatMessage = ({ id, defaultMessage }, values) => {
  56. const messageFormat = new IntlMessageFormat(localeData[id] || defaultMessage, locale);
  57. return messageFormat.format(values);
  58. };
  59. [].forEach.call(document.querySelectorAll('.emojify'), (content) => {
  60. content.innerHTML = emojify(content.innerHTML);
  61. });
  62. [].forEach.call(document.querySelectorAll('time.formatted'), (content) => {
  63. const datetime = new Date(content.getAttribute('datetime'));
  64. const formattedDate = dateTimeFormat.format(datetime);
  65. content.title = formattedDate;
  66. content.textContent = formattedDate;
  67. });
  68. const isToday = date => {
  69. const today = new Date();
  70. return date.getDate() === today.getDate() &&
  71. date.getMonth() === today.getMonth() &&
  72. date.getFullYear() === today.getFullYear();
  73. };
  74. const todayFormat = new IntlMessageFormat(localeData['relative_format.today'] || 'Today at {time}', locale);
  75. [].forEach.call(document.querySelectorAll('time.relative-formatted'), (content) => {
  76. const datetime = new Date(content.getAttribute('datetime'));
  77. let formattedContent;
  78. if (isToday(datetime)) {
  79. const formattedTime = timeFormat.format(datetime);
  80. formattedContent = todayFormat.format({ time: formattedTime });
  81. } else {
  82. formattedContent = dateFormat.format(datetime);
  83. }
  84. content.title = formattedContent;
  85. content.textContent = formattedContent;
  86. });
  87. [].forEach.call(document.querySelectorAll('time.time-ago'), (content) => {
  88. const datetime = new Date(content.getAttribute('datetime'));
  89. const now = new Date();
  90. const timeGiven = content.getAttribute('datetime').includes('T');
  91. content.title = timeGiven ? dateTimeFormat.format(datetime) : dateFormat.format(datetime);
  92. content.textContent = timeAgoString({
  93. formatMessage,
  94. formatDate: (date, options) => (new Intl.DateTimeFormat(locale, options)).format(date),
  95. }, datetime, now, now.getFullYear(), timeGiven);
  96. });
  97. const reactComponents = document.querySelectorAll('[data-component]');
  98. if (reactComponents.length > 0) {
  99. import(/* webpackChunkName: "containers/media_container" */ '../mastodon/containers/media_container')
  100. .then(({ default: MediaContainer }) => {
  101. [].forEach.call(reactComponents, (component) => {
  102. [].forEach.call(component.children, (child) => {
  103. component.removeChild(child);
  104. });
  105. });
  106. const content = document.createElement('div');
  107. const root = createRoot(content);
  108. root.render(<MediaContainer locale={locale} components={reactComponents} />);
  109. document.body.appendChild(content);
  110. })
  111. .catch(error => {
  112. console.error(error);
  113. });
  114. }
  115. Rails.delegate(document, '#user_account_attributes_username', 'input', throttle(({ target }) => {
  116. if (target.value && target.value.length > 0) {
  117. axios.get('/api/v1/accounts/lookup', { params: { acct: target.value } }).then(() => {
  118. target.setCustomValidity(formatMessage(messages.usernameTaken));
  119. }).catch(() => {
  120. target.setCustomValidity('');
  121. });
  122. } else {
  123. target.setCustomValidity('');
  124. }
  125. }, 500, { leading: false, trailing: true }));
  126. Rails.delegate(document, '#user_password,#user_password_confirmation', 'input', () => {
  127. const password = document.getElementById('user_password');
  128. const confirmation = document.getElementById('user_password_confirmation');
  129. if (!confirmation) return;
  130. if (confirmation.value && confirmation.value.length > password.maxLength) {
  131. confirmation.setCustomValidity(formatMessage(messages.passwordExceedsLength));
  132. } else if (password.value && password.value !== confirmation.value) {
  133. confirmation.setCustomValidity(formatMessage(messages.passwordDoesNotMatch));
  134. } else {
  135. confirmation.setCustomValidity('');
  136. }
  137. });
  138. Rails.delegate(document, '.status__content__spoiler-link', 'click', function() {
  139. const statusEl = this.parentNode.parentNode;
  140. if (statusEl.dataset.spoiler === 'expanded') {
  141. statusEl.dataset.spoiler = 'folded';
  142. this.textContent = (new IntlMessageFormat(localeData['status.show_more'] || 'Show more', locale)).format();
  143. } else {
  144. statusEl.dataset.spoiler = 'expanded';
  145. this.textContent = (new IntlMessageFormat(localeData['status.show_less'] || 'Show less', locale)).format();
  146. }
  147. return false;
  148. });
  149. [].forEach.call(document.querySelectorAll('.status__content__spoiler-link'), (spoilerLink) => {
  150. const statusEl = spoilerLink.parentNode.parentNode;
  151. const message = (statusEl.dataset.spoiler === 'expanded') ? (localeData['status.show_less'] || 'Show less') : (localeData['status.show_more'] || 'Show more');
  152. spoilerLink.textContent = (new IntlMessageFormat(message, locale)).format();
  153. });
  154. }
  155. Rails.delegate(document, '#edit_profile input[type=file]', 'change', ({ target }) => {
  156. const avatar = document.getElementById(target.id + '-preview');
  157. const [file] = target.files || [];
  158. const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc;
  159. avatar.src = url;
  160. });
  161. Rails.delegate(document, '.input-copy input', 'click', ({ target }) => {
  162. target.focus();
  163. target.select();
  164. target.setSelectionRange(0, target.value.length);
  165. });
  166. Rails.delegate(document, '.input-copy button', 'click', ({ target }) => {
  167. const input = target.parentNode.querySelector('.input-copy__wrapper input');
  168. const oldReadOnly = input.readonly;
  169. input.readonly = false;
  170. input.focus();
  171. input.select();
  172. input.setSelectionRange(0, input.value.length);
  173. try {
  174. if (document.execCommand('copy')) {
  175. input.blur();
  176. target.parentNode.classList.add('copied');
  177. setTimeout(() => {
  178. target.parentNode.classList.remove('copied');
  179. }, 700);
  180. }
  181. } catch (err) {
  182. console.error(err);
  183. }
  184. input.readonly = oldReadOnly;
  185. });
  186. const toggleSidebar = () => {
  187. const sidebar = document.querySelector('.sidebar ul');
  188. const toggleButton = document.querySelector('.sidebar__toggle__icon');
  189. if (sidebar.classList.contains('visible')) {
  190. document.body.style.overflow = null;
  191. toggleButton.setAttribute('aria-expanded', 'false');
  192. } else {
  193. document.body.style.overflow = 'hidden';
  194. toggleButton.setAttribute('aria-expanded', 'true');
  195. }
  196. toggleButton.classList.toggle('active');
  197. sidebar.classList.toggle('visible');
  198. };
  199. Rails.delegate(document, '.sidebar__toggle__icon', 'click', () => {
  200. toggleSidebar();
  201. });
  202. Rails.delegate(document, '.sidebar__toggle__icon', 'keydown', e => {
  203. if (e.key === ' ' || e.key === 'Enter') {
  204. e.preventDefault();
  205. toggleSidebar();
  206. }
  207. });
  208. Rails.delegate(document, '.custom-emoji', 'mouseover', ({ target }) => target.src = target.getAttribute('data-original'));
  209. Rails.delegate(document, '.custom-emoji', 'mouseout', ({ target }) => target.src = target.getAttribute('data-static'));
  210. // Empty the honeypot fields in JS in case something like an extension
  211. // automatically filled them.
  212. Rails.delegate(document, '#registration_new_user,#new_user', 'submit', () => {
  213. ['user_website', 'user_confirm_password', 'registration_user_website', 'registration_user_confirm_password'].forEach(id => {
  214. const field = document.getElementById(id);
  215. if (field) {
  216. field.value = '';
  217. }
  218. });
  219. });
  220. function main() {
  221. ready(loaded);
  222. }
  223. loadPolyfills()
  224. .then(loadLocale)
  225. .then(main)
  226. .then(loadKeyboardExtensions)
  227. .catch(error => {
  228. console.error(error);
  229. });