Skip to content
This repository has been archived by the owner on Oct 10, 2024. It is now read-only.

Commit

Permalink
Merge pull request #9 from xmtp/rygine/add-reaction-type
Browse files Browse the repository at this point in the history
Add Reaction content type
  • Loading branch information
rygine authored Jun 22, 2023
2 parents 02a6f08 + c00f455 commit 1c29cc9
Show file tree
Hide file tree
Showing 14 changed files with 405 additions and 8 deletions.
10 changes: 10 additions & 0 deletions packages/content-type-reaction/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
module.exports = {
root: true,
extends: ["custom"],
parserOptions: {
project: "./tsconfig.eslint.json",
},
rules: {
"class-methods-use-this": "off",
},
};
21 changes: 21 additions & 0 deletions packages/content-type-reaction/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 XMTP developers (xmtp.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
78 changes: 78 additions & 0 deletions packages/content-type-reaction/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Reaction content type

This package provides an XMTP content type to support reactions to messages.

### What’s a reaction?

A reaction is a way to respond to messages.

Reactions are repesented as objects with the following keys:

- `reference`: The message ID for the message that is being reacted to
- `action`: The action of the reaction (`added` or `removed`)
- `content`: A string representation of a reaction (e.g. `smile`) to be interpreted by clients

### Create a reaction

```tsx
const reaction: Reaction = {
reference: someMessageID,
action: "added",
content: "smile",
};
```

### Send a reaction

Now that you have a reaction, you can send it:

```tsx
await conversation.messages.send(reaction, {
contentType: ContentTypeReaction,
contentFallback: `[Reaction] ${client.address} reacted to ${someMessage.content} with:\n\n${reaction.content}`,
});
```

Note that we’re using `contentFallback` to enable clients that don't support these content types to still display something. For cases where clients *do* support these types, they can use the content fallback as alt text for accessibility purposes.

### Receive a reaction

Now that you can send a reaction, you need a way to receive a reaction. For example:

```tsx
// Assume `loadLastMessage` is a thing you have
const message: DecodedMessage = await loadLastMessage();

if (!message.contentType.sameAs(ContentTypeReaction)) {
// We do not have a reaction. A topic for another blog post.
return;
}

// We've got a reaction.
const reaction: Reaction = message.content;
```

### Display the reaction

Generally, reactions should be interpreted as emoji. So, `smile` would translate to :smile: in UI clients. That being said, how you ultimately choose to render a reaction is up to you.

## Developing

Run `yarn dev` to build the content type and watch for changes, which will trigger a rebuild.

## Testing

Before running unit tests, start the required Docker container at the root of this repository. For more info, see [Running tests](../../README.md#running-tests).

## Useful commands

- `yarn build`: Builds the content type
- `yarn clean`: Removes `node_modules`, `dist`, and `.turbo` folders
- `yarn dev`: Builds the content type and watches for changes, which will trigger a rebuild
- `yarn format`: Runs prettier format and write changes
- `yarn format:check`: Runs prettier format check
- `yarn lint`: Runs ESLint
- `yarn test:setup`: Starts a necessary docker container for testing
- `yarn test:teardown`: Stops docker container for testing
- `yarn test`: Runs all unit tests
- `yarn typecheck`: Runs `tsc`
94 changes: 94 additions & 0 deletions packages/content-type-reaction/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
{
"name": "@xmtp/content-type-reaction",
"version": "1.0.0",
"description": "An XMTP content type to support reactions to messages",
"author": "XMTP Labs <eng@xmtp.com>",
"license": "MIT",
"type": "module",
"main": "dist/index.cjs",
"module": "dist/index.js",
"types": "dist/index.d.ts",
"browser": "dist/web/index.js",
"exports": {
".": {
"types": "./dist/index.d.ts",
"browser": "./dist/web/index.js",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"sideEffects": false,
"repository": {
"type": "git",
"url": "git@github.com:xmtp/xmtp-js-content-types.git",
"directory": "packages/content-type-reaction"
},
"homepage": "https://github.com/xmtp/xmtp-js-content-types",
"bugs": {
"url": "https://github.com/xmtp/xmtp-js-content-types/issues"
},
"keywords": [
"xmtp",
"messaging",
"web3",
"js",
"ts",
"javascript",
"typescript",
"content-types"
],
"publishConfig": {
"access": "public"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 3 chrome versions",
"last 3 firefox versions",
"last 3 safari versions"
]
},
"scripts": {
"build:node": "tsup",
"build:web": "tsup --platform browser --target esnext",
"build": "yarn clean:build && yarn build:node && yarn build:web",
"clean:build": "rimraf dist",
"clean": "rimraf .turbo node_modules && yarn clean:build",
"dev": "tsup --watch",
"format:base": "prettier --ignore-path ../../.gitignore",
"format:check": "yarn format:base -c .",
"format": "yarn format:base -w .",
"generate:types": "tsup --dts-only",
"lint": "eslint . --ignore-path ../../.gitignore",
"test:jsdom": "NODE_TLS_REJECT_UNAUTHORIZED=0 vitest run --environment jsdom",
"test:node": "NODE_TLS_REJECT_UNAUTHORIZED=0 vitest run --environment node",
"test": "yarn test:node && yarn test:jsdom",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@xmtp/xmtp-js": "^9.1.7"
},
"devDependencies": {
"@types/node": "^18.14.2",
"buffer": "^6.0.3",
"esbuild": "^0.18.2",
"esbuild-plugin-external-global": "^1.0.1",
"eslint": "^8.43.0",
"eslint-config-custom": "workspace:*",
"ethers": "^6.0.8",
"jsdom": "^22.1.0",
"prettier": "^2.8.8",
"rimraf": "^5.0.1",
"tsup": "^7.0.0",
"typescript": "^5.1.3",
"vite": "^4.3.9",
"vitest": "^0.32.2"
},
"peerDependencies": {
"@xmtp/xmtp-js": "^9.1.7"
}
}
52 changes: 52 additions & 0 deletions packages/content-type-reaction/src/Reaction.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Wallet } from "ethers";
import { Client } from "@xmtp/xmtp-js";
import { ContentTypeReaction, ReactionCodec } from "./Reaction";
import type { Reaction } from "./Reaction";

describe("ReactionContentType", () => {
it("has the right content type", () => {
expect(ContentTypeReaction.authorityId).toBe("xmtp.org");
expect(ContentTypeReaction.typeId).toBe("reaction");
expect(ContentTypeReaction.versionMajor).toBe(1);
expect(ContentTypeReaction.versionMinor).toBe(0);
});

it("can send a reaction", async () => {
const aliceWallet = Wallet.createRandom();
const aliceClient = await Client.create(aliceWallet, { env: "local" });
aliceClient.registerCodec(new ReactionCodec());
await aliceClient.publishUserContact();

const bobWallet = Wallet.createRandom();
const bobClient = await Client.create(bobWallet, { env: "local" });
bobClient.registerCodec(new ReactionCodec());
await bobClient.publishUserContact();

const conversation = await aliceClient.conversations.newConversation(
bobWallet.address,
);

const originalMessage = await conversation.send("test");

const reaction: Reaction = {
action: "added",
content: "smile",
reference: originalMessage.id,
};

await conversation.send(reaction, { contentType: ContentTypeReaction });

const bobConversation = await bobClient.conversations.newConversation(
aliceWallet.address,
);
const messages = await bobConversation.messages();

expect(messages.length).toBe(2);

const reactionMessage = messages[1];
const messageContent = reactionMessage.content as Reaction;
expect(messageContent.action).toBe("added");
expect(messageContent.content).toBe("smile");
expect(messageContent.reference).toBe(originalMessage.id);
});
});
58 changes: 58 additions & 0 deletions packages/content-type-reaction/src/Reaction.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { ContentTypeId } from "@xmtp/xmtp-js";
import type { ContentCodec, EncodedContent } from "@xmtp/xmtp-js";

export const ContentTypeReaction = new ContentTypeId({
authorityId: "xmtp.org",
typeId: "reaction",
versionMajor: 1,
versionMinor: 0,
});

export type Reaction = {
/**
* The message ID for the message that is being reacted to
*/
reference: string;
/**
* The action of the reaction
*/
action: "added" | "removed";
/**
* The content of the reaction
*/
content: string;
};

export type ReactionParameters = Pick<Reaction, "action" | "reference"> & {
encoding: "UTF-8";
};

export class ReactionCodec implements ContentCodec<Reaction> {
get contentType(): ContentTypeId {
return ContentTypeReaction;
}

encode(content: Reaction): EncodedContent<ReactionParameters> {
return {
type: ContentTypeReaction,
parameters: {
encoding: "UTF-8",
action: content.action,
reference: content.reference,
},
content: new TextEncoder().encode(content.content),
};
}

decode(content: EncodedContent<ReactionParameters>): Reaction {
const { encoding } = content.parameters;
if (encoding && encoding !== "UTF-8") {
throw new Error(`unrecognized encoding ${encoding as string}`);
}
return {
action: content.parameters.action,
reference: content.parameters.reference,
content: new TextDecoder().decode(content.content),
};
}
}
2 changes: 2 additions & 0 deletions packages/content-type-reaction/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { ReactionCodec, ContentTypeReaction } from "./Reaction";
export type { Reaction, ReactionParameters } from "./Reaction";
5 changes: 5 additions & 0 deletions packages/content-type-reaction/tsconfig.eslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"include": [".", ".eslintrc.cjs"],
"exclude": ["dist", "node_modules"]
}
5 changes: 5 additions & 0 deletions packages/content-type-reaction/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "tsconfig/build.json",
"include": ["."],
"exclude": ["dist", "node_modules"]
}
35 changes: 35 additions & 0 deletions packages/content-type-reaction/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { defineConfig } from "tsup";
import externalGlobal from "esbuild-plugin-external-global";
import type { Plugin } from "esbuild";

export default defineConfig((options) => {
const esbuildPlugins: Plugin[] = [];

// for the browser bundle, replace `crypto` import with an object that
// returns the browser's built-in crypto library
if (options.platform === "browser") {
esbuildPlugins.push(
externalGlobal.externalGlobalPlugin({
crypto: "{ webcrypto: window.crypto }",
}),
);
}

return {
entry: options.entry ?? ["src/index.ts"],
outDir:
options.outDir ?? (options.platform === "browser" ? "dist/web" : "dist"),
splitting: false,
sourcemap: true,
treeshake: true,
clean: true,
bundle: true,
platform: options.platform ?? "node",
minify: options.platform === "browser",
dts: options.platform !== "browser",
format:
options.format ??
(options.platform === "browser" ? ["esm"] : ["esm", "cjs"]),
esbuildPlugins,
};
});
8 changes: 8 additions & 0 deletions packages/content-type-reaction/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from "vitest/config";

export default defineConfig({
test: {
globals: true,
setupFiles: "./vitest.setup.ts",
},
});
5 changes: 5 additions & 0 deletions packages/content-type-reaction/vitest.setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Buffer } from "buffer";
import { webcrypto } from "crypto";

globalThis.Buffer = Buffer;
globalThis.crypto = webcrypto as unknown as Crypto;
Loading

0 comments on commit 1c29cc9

Please sign in to comment.