aboutsummaryrefslogtreecommitdiff
path: root/lume/src/_components/MastodonShare.tsx
blob: 57e84b37b346772720d3921688e41c6538c3175a (plain)
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
import { useState } from "npm:preact/hooks";

const u = (url = "", params = {}) => {
  let result = new URL(url, window.location.href);
  Object.entries(params).forEach((kv) => {
    let [k, v] = kv;
    result.searchParams.set(k, v as string);
  });
  return result.toString();
};

export interface MastodonShareButtonProps {
  title: string;
  url: string;
  series?: string;
  tags: string;
}

export default function MastodonShareButton({
  title,
  url,
  series,
  tags,
}: MastodonShareButtonProps) {
  let defaultURL = localStorage["mastodon_instance"];

  if (defaultURL == undefined) {
    defaultURL = "";
  }

  const tootTemplate = `${title}

${url}

${series ? "#" + series + " " : ""}${
    tags ? tags.map((x) => "#" + x).join(" ") : ""
  } @cadey@pony.social`;

  const [getURL, setURL] = useState(defaultURL);
  const [getToot, setToot] = useState(tootTemplate);

  return (
    <div>
      <details>
        <summary>Share on Mastodon</summary>
        <span>{"Instance URL (https://mastodon.example)"}</span>
        <br />
        <input
          type="text"
          placeholder="https://pony.social"
          value={defaultURL}
          oninput={(e) => setURL(e.target.value)}
        />
        <br />
        <textarea rows={6} cols={40} oninput={(e) => setToot(e.target.value)}>
          {getToot()}
        </textarea>
        <br />
        <button
          onclick={() => {
            let instanceURL = getURL;

            if (!instanceURL.startsWith("https://")) {
              instanceURL = `https://${instanceURL}`;
            }

            localStorage["mastodon_instance"] = instanceURL;
            const text = getToot;
            const mastodonURL = u(instanceURL + "/share", {
              text,
              visibility: "public",
            });
            console.log({ text, mastodonURL });
            window.open(mastodonURL, "_blank");
          }}
        >
          Share
        </button>
      </details>
    </div>
  );
}