Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: replace AvatarIcon instances with FacePile #11279

Merged
merged 9 commits into from
Oct 20, 2020
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 57 additions & 74 deletions superset-frontend/package-lock.json

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion superset-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@
"re-resizable": "^6.6.1",
"react": "^16.13.1",
"react-ace": "^5.10.0",
"react-avatar": "^3.9.7",
"react-bootstrap": "^0.33.1",
"react-bootstrap-dialog": "^0.13.0",
"react-bootstrap-slider": "2.1.5",
Expand Down
60 changes: 0 additions & 60 deletions superset-frontend/src/components/AvatarIcon.tsx

This file was deleted.

59 changes: 59 additions & 0 deletions superset-frontend/src/components/FacePile/FacePile.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { withKnobs, number } from '@storybook/addon-knobs';
import FacePile from '.';

export default {
title: 'UerStack',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this should probably be FacePile for consistency

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ohh, nice catch

component: FacePile,
decorators: [withKnobs],
};

const firstNames = [
'James',
'Mary',
'John',
'Patricia',
'Mohamed',
'Venkat',
'Lao',
'Robert',
'Jennifer',
'Michael',
'Linda',
];
const lastNames = [
'Smith',
'Johnson',
'Williams',
'Saeed',
'Jones',
'Brown',
'Tzu',
];

const users = [...new Array(10)].map(() => ({
first_name: firstNames[Math.floor(Math.random() * firstNames.length)],
last_name: lastNames[Math.floor(Math.random() * lastNames.length)],
}));

export const SupersetFacePile = () => {
return <FacePile users={users} maxCount={number('maxCount', 4)} />;
};
71 changes: 71 additions & 0 deletions superset-frontend/src/components/FacePile/FacePile.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { styledMount as mount } from 'spec/helpers/theming';

import { Avatar } from 'src/common/components';
import FacePile from '.';
import { getRandomColor } from './utils';

const users = [...new Array(10)].map((_, i) => ({
first_name: 'user',
last_name: `${i}`,
}));

describe('FacePile', () => {
const wrapper = mount(<FacePile users={users} />);

it('is a valid element', () => {
expect(wrapper.find(FacePile)).toExist();
});

it('renders an Avatar', () => {
expect(wrapper.find(Avatar)).toExist();
});

it('hides overflow', () => {
expect(wrapper.find(Avatar).length).toBe(5);
});
});

describe('utils', () => {
describe('getRandomColor', () => {
const colors = ['color1', 'color2', 'color3'];

it('produces the same color for the same input values', () => {
const name = 'foo';
expect(getRandomColor(name, colors)).toEqual(
getRandomColor(name, colors),
);
});

it('produces a different color for different input values', () => {
expect(getRandomColor('foo', colors)).not.toEqual(
getRandomColor('bar', colors),
);
});

it('handles non-ascii input values', () => {
expect(getRandomColor('泰', colors)).toMatchInlineSnapshot(`"color1"`);
expect(getRandomColor('مُحَمَّد‎', colors)).toMatchInlineSnapshot(
`"color2"`,
);
});
});
});
71 changes: 71 additions & 0 deletions superset-frontend/src/components/FacePile/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 { getCategoricalSchemeRegistry, styled } from '@superset-ui/core';
import { Avatar, Tooltip } from 'src/common/components';
import { getRandomColor } from './utils';

interface FacePileProps {
users: { first_name: string; last_name: string }[];
maxCount?: number;
}

const colorList = getCategoricalSchemeRegistry().get()?.colors ?? [];

const StyledAvatar = styled(Avatar)`
width: ${({ theme }) => theme.gridUnit * 6}px;
height: ${({ theme }) => theme.gridUnit * 6}px;
line-height: ${({ theme }) => theme.gridUnit * 6}px;
font-size: ${({ theme }) => theme.typography.sizes.xl}px;
`;

// to apply styling to the maxCount avatar
const StyledGroup = styled(Avatar.Group)`
.ant-avatar {
width: ${({ theme }) => theme.gridUnit * 6}px;
height: ${({ theme }) => theme.gridUnit * 6}px;
line-height: ${({ theme }) => theme.gridUnit * 6}px;
font-size: ${({ theme }) => theme.typography.sizes.xl}px;
}
`;

export default function FacePile({ users, maxCount = 4 }: FacePileProps) {
return (
<StyledGroup maxCount={maxCount}>
{users.map(({ first_name, last_name }) => {
const name = `${first_name} ${last_name}`;
const color = getRandomColor(name, colorList);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this doesn't need to be addressed in this PR, but basing the profile color off the full name seems somewhat flawed to me. If there are naming collisions between people with common full names, then it'll be impossible to tell them apart in the FacePile. This could also cause key collisions below.

I'd recommend refactoring in the future to basing the color off the user id, or a combo of name + user id.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good point, I can add user id to the mix and that should hold us over for a while. Eventually, I think, we'll have profile pictures and make these links so it's easier to differentiate users

return (
<Tooltip key={name} title={name} placement="top">
<StyledAvatar
key={name}
style={{
backgroundColor: color,
borderColor: color,
}}
>
{first_name[0].toLocaleUpperCase()}
{last_name[0].toLocaleUpperCase()}
</StyledAvatar>
</Tooltip>
);
})}
</StyledGroup>
);
}
49 changes: 49 additions & 0 deletions superset-frontend/src/components/FacePile/utils.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/

// https://en.wikipedia.org/wiki/Linear_congruential_generator
function stringAsciiPRNG(value: string, m: number) {
// Xn+1 = (a * Xn + c) % m
// 0 < a < m
// 0 <= c < m
// 0 <= X0 < m

const charCodes = [...value].map(letter => letter.charCodeAt(0));
const len = charCodes.length;

const a = (len % (m - 1)) + 1;
const c = charCodes.reduce((current, next) => current + next) % m;

let random = charCodes[0] % m;

[...new Array(len)].forEach(() => {
random = (a * random + c) % m;
});

return random;
}

export function getRandomColor(sampleValue: string, colorList: string[]) {
// if no value is passed, always return transparent color for consistency
if (!sampleValue) return 'transparent';

// value based random color index,
// ensuring the same sampleValue always resolves to the same color
return colorList[stringAsciiPRNG(sampleValue, colorList.length)];
}
13 changes: 2 additions & 11 deletions superset-frontend/src/views/CRUD/chart/ChartList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { createFetchRelated, createErrorHandler } from 'src/views/CRUD/utils';
import { useListViewResource, useFavoriteStatus } from 'src/views/CRUD/hooks';
import ConfirmStatusChange from 'src/components/ConfirmStatusChange';
import SubMenu, { SubMenuProps } from 'src/components/Menu/SubMenu';
import AvatarIcon from 'src/components/AvatarIcon';
import FacePile from 'src/components/FacePile';
import Icon from 'src/components/Icon';
import FaveStar from 'src/components/FaveStar';
import ListView, {
Expand Down Expand Up @@ -477,16 +477,7 @@ function ChartList(props: ChartListProps) {
imgFallbackURL="/static/assets/images/chart-card-fallback.png"
imgPosition="bottom"
description={t('Last modified %s', chart.changed_on_delta_humanized)}
coverLeft={(chart.owners || []).slice(0, 5).map(owner => (
<AvatarIcon
key={owner.id}
uniqueKey={`${owner.username}-${chart.id}`}
firstName={owner.first_name}
lastName={owner.last_name}
iconSize={24}
textSize={9}
/>
))}
coverLeft={<FacePile users={chart.owners || []} />}
coverRight={
<Label bsStyle="secondary">{chart.datasource_name_text}</Label>
}
Expand Down
26 changes: 4 additions & 22 deletions superset-frontend/src/views/CRUD/dashboard/DashboardList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,8 @@ import { createFetchRelated, createErrorHandler } from 'src/views/CRUD/utils';
import { useListViewResource, useFavoriteStatus } from 'src/views/CRUD/hooks';
import ConfirmStatusChange from 'src/components/ConfirmStatusChange';
import SubMenu, { SubMenuProps } from 'src/components/Menu/SubMenu';
import AvatarIcon from 'src/components/AvatarIcon';
import FacePile from 'src/components/FacePile';
import ListView, { ListViewProps, Filters } from 'src/components/ListView';
import ExpandableList from 'src/components/ExpandableList';
import Owner from 'src/types/Owner';
import withToasts from 'src/messageToasts/enhancers/withToasts';
import Icon from 'src/components/Icon';
Expand Down Expand Up @@ -246,17 +245,9 @@ function DashboardList(props: DashboardListProps) {
{
Cell: ({
row: {
original: { owners },
original: { owners = [] },
},
}: any) => (
<ExpandableList
items={owners.map(
({ first_name: firstName, last_name: lastName }: any) =>
`${firstName} ${lastName}`,
)}
display={2}
/>
),
}: any) => <FacePile users={owners} />,
Header: t('Owners'),
accessor: 'owners',
disableSortBy: true,
Expand Down Expand Up @@ -488,16 +479,7 @@ function DashboardList(props: DashboardListProps) {
'Last modified %s',
dashboard.changed_on_delta_humanized,
)}
coverLeft={(dashboard.owners || []).slice(0, 5).map(owner => (
<AvatarIcon
key={owner.id}
uniqueKey={`${owner.username}-${dashboard.id}`}
firstName={owner.first_name}
lastName={owner.last_name}
iconSize={24}
textSize={9}
/>
))}
coverLeft={<FacePile users={dashboard.owners || []} />}
actions={
<ListViewCard.Actions>
{renderFaveStar(dashboard.id)}
Expand Down
Loading