aboutsummaryrefslogtreecommitdiff
path: root/apps/web/components/canvas/twitterCard.tsx
blob: 8cf8e576722b48a64559f9b5bcd4a820d5e82f62 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import {
  BaseBoxShapeUtil,
  HTMLContainer,
  TLBaseShape,
  toDomPrecision,
} from "tldraw";

type ITwitterCardShape = TLBaseShape<
  "Twittercard",
  { w: number; h: number; url: string }
>;

export class twitterCardUtil extends BaseBoxShapeUtil<ITwitterCardShape> {
  static override type = "Twittercard" as const;

  getDefaultProps(): ITwitterCardShape["props"] {
    return {
      w: 500,
      h: 550,
      url: "",
    };
  }

  component(s: ITwitterCardShape) {
    return (
      <HTMLContainer className="flex h-full w-full items-center justify-center">
        <TwitterPost
          url={s.props.url}
          width={s.props.w}
          isInteractive={false}
          height={s.props.h}
        />
      </HTMLContainer>
    );
  }

  indicator(shape: ITwitterCardShape) {
    return <rect width={shape.props.w} height={shape.props.h} />;
  }
}

function TwitterPost({
  isInteractive,
  width,
  height,
  url,
}: {
  isInteractive: boolean;
  width: number;
  height: number;
  url: string;
}) {
  const link = (() => {
    try {
      const urlObj = new URL(url);
      const path = urlObj.pathname;
      return path;
    } catch (error) {
      console.error("Invalid URL", error);
      return null;
    }
  })();

  return (
    <iframe
      className="tl-embed"
      draggable={false}
      width={toDomPrecision(width)}
      height={toDomPrecision(height)}
      seamless
      referrerPolicy="no-referrer-when-downgrade"
      style={{
        pointerEvents: isInteractive ? "all" : "none",
        zIndex: isInteractive ? "" : "-1",
      }}
      srcDoc={`
        <html lang="en">
        <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Document</title>
        </head>
        <body>
          <blockquote data-theme="dark" class="twitter-tweet"><p lang="en" dir="ltr"><a href="https://twitter.com${link}"></a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
        </body>
        </html>`}
    />
  );
}