embed.tsx 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import './public-path';
  2. import { createRoot } from 'react-dom/client';
  3. import { afterInitialRender } from 'mastodon/../hooks/useRenderSignal';
  4. import { start } from '../mastodon/common';
  5. import { Status } from '../mastodon/features/standalone/status';
  6. import { loadPolyfills } from '../mastodon/polyfills';
  7. import ready from '../mastodon/ready';
  8. start();
  9. function loaded() {
  10. const mountNode = document.getElementById('mastodon-status');
  11. if (mountNode) {
  12. const attr = mountNode.getAttribute('data-props');
  13. if (!attr) return;
  14. const props = JSON.parse(attr) as { id: string; locale: string };
  15. const root = createRoot(mountNode);
  16. root.render(<Status {...props} />);
  17. }
  18. }
  19. function main() {
  20. ready(loaded).catch((error: unknown) => {
  21. console.error(error);
  22. });
  23. }
  24. loadPolyfills()
  25. .then(main)
  26. .catch((error: unknown) => {
  27. console.error(error);
  28. });
  29. interface SetHeightMessage {
  30. type: 'setHeight';
  31. id: string;
  32. height: number;
  33. }
  34. function isSetHeightMessage(data: unknown): data is SetHeightMessage {
  35. if (
  36. data &&
  37. typeof data === 'object' &&
  38. 'type' in data &&
  39. data.type === 'setHeight'
  40. )
  41. return true;
  42. else return false;
  43. }
  44. window.addEventListener('message', (e) => {
  45. // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- typings are not correct, it can be null in very rare cases
  46. if (!e.data || !isSetHeightMessage(e.data) || !window.parent) return;
  47. const data = e.data;
  48. // We use a timeout to allow for the React page to render before calculating the height
  49. afterInitialRender(() => {
  50. window.parent.postMessage(
  51. {
  52. type: 'setHeight',
  53. id: data.id,
  54. height: document.getElementsByTagName('html')[0]?.scrollHeight,
  55. },
  56. '*',
  57. );
  58. });
  59. });