Skip to content

Commit

Permalink
Create Avatar component (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
germain-gg authored Mar 15, 2023
1 parent 964f2ce commit 688d0f0
Show file tree
Hide file tree
Showing 17 changed files with 568 additions and 12 deletions.
7 changes: 6 additions & 1 deletion jest.config.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@

module.exports = {
"testEnvironment": "jsdom"
"testEnvironment": "jsdom",
setupFilesAfterEnv: ['<rootDir>/src/setupTests.ts'],
"moduleNameMapper": {
"\\.(css|less|scss|sss|styl)$": "<rootDir>/node_modules/jest-css-modules"
}
}
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,10 @@
"@storybook/react": "^7.0.0-beta.62",
"@storybook/react-vite": "^7.0.0-beta.62",
"@storybook/testing-library": "^0.0.14-next.1",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@types/jest": "^29.4.0",
"@types/lodash-es": "^4.17.6",
"@types/node": "^18.14.6",
"@types/react": "^18.0.28",
"@typescript-eslint/eslint-plugin": "^5.54.1",
Expand All @@ -71,6 +73,7 @@
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-storybook": "^0.6.11",
"jest": "^29.5.0",
"jest-css-modules": "^2.1.0",
"jest-environment-jsdom": "^29.5.0",
"storybook": "^7.0.0-beta.62",
"stylelint": "^15.2.0",
Expand All @@ -81,6 +84,8 @@
},
"dependencies": {
"@vector-im/compound-design-tokens": "https://github.com/vector-im/compound-design-tokens#develop",
"classnames": "^2.3.2",
"lodash": "^4.17.21",
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
Expand Down
2 changes: 2 additions & 0 deletions src/@types/custom.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ declare module "*.svg" {
React.SVGAttributes<SVGElement>
>;
}

declare module "*.module.css";
84 changes: 84 additions & 0 deletions src/components/Avatar/Avatar.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
Copyright 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

.avatar {
display: inline-block;
aspect-ratio: 1 / 1;
width: var(--cpd-avatar-size);
line-height: var(--cpd-avatar-size);
text-align: center;
font-size: min(calc(var(--cpd-avatar-size) * 0.75), 60px);
border-radius: var(--cpd-avatar-radius);
text-transform: uppercase;
speak: none;
pointer-events: none;
font-weight: normal;
overflow: hidden;
user-select: none;
}

img.avatar {
object-fit: cover;
overflow: hidden;
}

.avatar:not([src]) {
/* In the future we'd prefer to pass the HEX code as the data attr
and use `attr(data-color)` to avoid the style declaration from below
but this is currently not supported in all browsers */
background: var(--cpd-avatar-background);
color: #fff;
}

.avatar[data-color] {
--cpd-avatar-background: #368bd6; /* TODO: Replace with a compound color */
}

.avatar[data-color="2"] {
--cpd-avatar-background: #ac3ba8; /* TODO: Replace with a compound color */
}

.avatar[data-color="3"] {
--cpd-avatar-background: #03b381; /* TODO: Replace with a compound color */
}

.avatar[data-color="4"] {
--cpd-avatar-background: #e64f7a; /* TODO: Replace with a compound color */
}

.avatar[data-color="5"] {
--cpd-avatar-background: #ff812d; /* TODO: Replace with a compound color */
}

.avatar[data-color="6"] {
--cpd-avatar-background: #2dc2c5; /* TODO: Replace with a compound color */
}

.avatar[data-color="7"] {
--cpd-avatar-background: #5c56f5; /* TODO: Replace with a compound color */
}

.avatar[data-color="8"] {
--cpd-avatar-background: #74d12c; /* TODO: Replace with a compound color */
}

.avatar[data-type="round"] {
--cpd-avatar-radius: 50%;
}

.avatar[data-type="square"] {
--cpd-avatar-radius: 25%;
}
58 changes: 58 additions & 0 deletions src/components/Avatar/Avatar.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
Copyright 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import React from "react";
import { Meta, StoryFn } from "@storybook/react";

import { Avatar as AvatarComponent } from "./Avatar";

export default {
title: "Avatar",
component: AvatarComponent,
argTypes: {},
args: {
name: "Bob",
size: "64px",
id: "@bob:example.org",
src: "https://placekitten.com/200/200",
type: "round",
},
} as Meta<typeof AvatarComponent>;

const Template: StoryFn<typeof AvatarComponent> = (args) => (
<AvatarComponent {...args} />
);

export const Round = Template.bind({});
Round.args = {
type: "round",
};

export const Square = Template.bind({});
Square.args = {
type: "square",
};

export const NoImageFallback = Template.bind({});
NoImageFallback.args = {
src: "",
};

export const LargeNoImageFallback = Template.bind({});
NoImageFallback.args = {
src: "",
size: "128px",
};
75 changes: 75 additions & 0 deletions src/components/Avatar/Avatar.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
Copyright 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import { render, waitFor } from "@testing-library/react";
import React from "react";

import { Avatar } from "./Avatar";

const originalImage = global.Image;

describe("Avatar", () => {
beforeEach(() => {
global.Image = class extends originalImage {
constructor() {
super();
setTimeout(() => {
this.onload?.(new Event("load"));
}, 50);
}
};
});

afterEach(() => {
global.Image = originalImage;
});

it("renders the image-less avatar", () => {
const { asFragment } = render(<Avatar name="Bob" id="@bob:example.org" />);
expect(asFragment()).toMatchSnapshot();
});

it("replaces the placeholder with the actual image", async () => {
const { container } = render(
<Avatar src="./mock.jpg" name="Bob" id="@bob:example.org" />
);

expect(container).toHaveTextContent("B");
await waitFor(() => expect(document.querySelector("img")).not.toBeNull());
});

it("does not split emoji as first letter", () => {
const { container } = render(
<Avatar name="🤓 John" id="@john:example.org" />
);
expect(container).toHaveTextContent("🤓");
});

it.each([
["@bob:example.org", "8"],
["@alice:example.org", "3"],
["@charlie:example.org", "5"],
["@dan:example.org", "8"],
["@elena:example.org", "2"],
["@fanny:example.org", "1"],
])(
"has a deterministic color based on the id passed to it, %s",
(id, colorNumber) => {
const { container } = render(<Avatar name={id} id={id} />);
expect(container.firstChild).toHaveAttribute("data-color", colorNumber);
}
);
});
74 changes: 74 additions & 0 deletions src/components/Avatar/Avatar.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
Copyright 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import classnames from "classnames";
import React, { Suspense } from "react";
import { getInitialLetter } from "../../utils/string";
import { SuspenseImg } from "../../utils/SuspenseImg";
import styles from "./Avatar.module.css";
import { useUsernameColor } from "./useUsernameColor";

type AvatarProps = {
src?: string;
id: string;
name: string;
type?: "square" | "round";
className?: string;
size?: CSSStyleDeclaration["height"];
};

export const Avatar = ({
src,
id,
name = "",
type = "round",
className = "",
size,
}: AvatarProps): JSX.Element => {
const color = useUsernameColor(id);
const style = {
"--cpd-avatar-size": size,
} as React.CSSProperties;
const imagelessAvatar = (
<span
role="img"
aria-label=""
data-type={type}
data-color={color}
className={classnames(styles.avatar, className)}
style={style}
title={id}
>
{getInitialLetter(name)}
</span>
);

return !src ? (
imagelessAvatar
) : (
<Suspense fallback={imagelessAvatar}>
<SuspenseImg
src={src}
className={classnames(styles.avatar, className)}
data-type={type}
style={style}
width={size}
height={size}
title={id}
/>
</Suspense>
);
};
16 changes: 16 additions & 0 deletions src/components/Avatar/__snapshots__/Avatar.test.tsx.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`Avatar renders the image-less avatar 1`] = `
<DocumentFragment>
<span
aria-label=""
class="avatar"
data-color="8"
data-type="round"
role="img"
title="@bob:example.org"
>
B
</span>
</DocumentFragment>
`;
30 changes: 30 additions & 0 deletions src/components/Avatar/useUsernameColor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/*
Copyright 2023 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
* Determines a color to assign to a given username
* @param id - a Matrix username ID
* @returns a hexadecimal color
*/
export function useUsernameColor(id: string): number {
const MIN = 1;
const MAX = 8;
// Sum up the values of all the char codes in the string
const charCodeSum = id.split("").reduce((sum, char) => {
return sum + char.charCodeAt(0);
}, 0);
return (charCodeSum % MAX) + MIN;
}
Loading

0 comments on commit 688d0f0

Please sign in to comment.