1
0
Fork 0
mirror of https://github.com/plankanban/planka.git synced 2025-07-18 20:59:44 +02:00

Add covers for cards

This commit is contained in:
Maksim Eltyshev 2020-04-23 03:02:53 +05:00
parent 6a68ec9c1e
commit 49dc28b0d7
26 changed files with 315 additions and 98 deletions

View file

@ -23,6 +23,7 @@ const Card = React.memo(
name,
dueDate,
timer,
coverUrl,
isPersisted,
notificationsTotal,
users,
@ -63,51 +64,60 @@ const Card = React.memo(
const contentNode = (
<>
{labels.length > 0 && (
<span className={styles.labels}>
{labels.map((label) => (
<span key={label.id} className={classNames(styles.attachment, styles.attachmentLeft)}>
<Label name={label.name} color={label.color} size="tiny" />
</span>
))}
</span>
)}
<div className={styles.name}>{name}</div>
{tasks.length > 0 && <Tasks items={tasks} />}
{(dueDate || timer || notificationsTotal > 0) && (
<span className={styles.attachments}>
{notificationsTotal > 0 && (
<span
className={classNames(
styles.attachment,
styles.attachmentLeft,
styles.notification,
)}
>
{notificationsTotal}
</span>
)}
{dueDate && (
<span className={classNames(styles.attachment, styles.attachmentLeft)}>
<DueDate value={dueDate} size="tiny" />
</span>
)}
{timer && (
<span className={classNames(styles.attachment, styles.attachmentLeft)}>
<Timer startedAt={timer.startedAt} total={timer.total} size="tiny" />
</span>
)}
</span>
)}
{users.length > 0 && (
<span className={classNames(styles.attachments, styles.attachmentsRight)}>
{users.map((user) => (
<span key={user.id} className={classNames(styles.attachment, styles.attachmentRight)}>
<User name={user.name} avatarUrl={user.avatarUrl} size="tiny" />
</span>
))}
</span>
)}
{coverUrl && <img src={coverUrl} alt="" className={styles.cover} />}
<div className={styles.details}>
{labels.length > 0 && (
<span className={styles.labels}>
{labels.map((label) => (
<span
key={label.id}
className={classNames(styles.attachment, styles.attachmentLeft)}
>
<Label name={label.name} color={label.color} size="tiny" />
</span>
))}
</span>
)}
<div className={styles.name}>{name}</div>
{tasks.length > 0 && <Tasks items={tasks} />}
{(dueDate || timer || notificationsTotal > 0) && (
<span className={styles.attachments}>
{notificationsTotal > 0 && (
<span
className={classNames(
styles.attachment,
styles.attachmentLeft,
styles.notification,
)}
>
{notificationsTotal}
</span>
)}
{dueDate && (
<span className={classNames(styles.attachment, styles.attachmentLeft)}>
<DueDate value={dueDate} size="tiny" />
</span>
)}
{timer && (
<span className={classNames(styles.attachment, styles.attachmentLeft)}>
<Timer startedAt={timer.startedAt} total={timer.total} size="tiny" />
</span>
)}
</span>
)}
{users.length > 0 && (
<span className={classNames(styles.attachments, styles.attachmentsRight)}>
{users.map((user) => (
<span
key={user.id}
className={classNames(styles.attachment, styles.attachmentRight)}
>
<User name={user.name} avatarUrl={user.avatarUrl} size="tiny" />
</span>
))}
</span>
)}
</div>
</>
);
@ -121,7 +131,7 @@ const Card = React.memo(
{isPersisted ? (
<>
<Link
to={isPersisted && Paths.CARDS.replace(':id', id)}
to={Paths.CARDS.replace(':id', id)}
className={styles.content}
onClick={handleClick}
>
@ -173,6 +183,7 @@ Card.propTypes = {
name: PropTypes.string.isRequired,
dueDate: PropTypes.instanceOf(Date),
timer: PropTypes.object, // eslint-disable-line react/forbid-prop-types
coverUrl: PropTypes.string,
isPersisted: PropTypes.bool.isRequired,
notificationsTotal: PropTypes.number.isRequired,
/* eslint-disable react/forbid-prop-types */
@ -196,6 +207,7 @@ Card.propTypes = {
Card.defaultProps = {
dueDate: undefined,
timer: undefined,
coverUrl: undefined,
};
export default Card;

View file

@ -68,7 +68,6 @@
.content {
cursor: grab;
display: block;
padding: 6px 8px 0;
}
.content:after {
@ -77,6 +76,15 @@
clear: both;
}
.cover {
border-radius: 3px 3px 0 0;
vertical-align: middle;
}
.details {
padding: 6px 8px 0;
}
.labels {
display: block;
max-width: 100%;

View file

@ -3,7 +3,18 @@ import PropTypes from 'prop-types';
import Item from './Item';
const Attachments = React.memo(({ items, onUpdate, onDelete }) => {
const Attachments = React.memo(({ items, onUpdate, onDelete, onCoverUpdate }) => {
const handleCoverSelect = useCallback(
(id) => {
onCoverUpdate(id);
},
[onCoverUpdate],
);
const handleCoverDeselect = useCallback(() => {
onCoverUpdate(null);
}, [onCoverUpdate]);
const handleUpdate = useCallback(
(id, data) => {
onUpdate(id, data);
@ -25,9 +36,12 @@ const Attachments = React.memo(({ items, onUpdate, onDelete }) => {
key={item.id}
name={item.name}
url={item.url}
thumbnailUrl={item.thumbnailUrl}
coverUrl={item.coverUrl}
createdAt={item.createdAt}
isCover={item.isCover}
isPersisted={item.isPersisted}
onCoverSelect={() => handleCoverSelect(item.id)}
onCoverDeselect={handleCoverDeselect}
onUpdate={(data) => handleUpdate(item.id, data)}
onDelete={() => handleDelete(item.id)}
/>
@ -40,6 +54,7 @@ Attachments.propTypes = {
items: PropTypes.array.isRequired, // eslint-disable-line react/forbid-prop-types
onUpdate: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onCoverUpdate: PropTypes.func.isRequired,
};
export default Attachments;

View file

@ -2,20 +2,44 @@ import React, { useCallback } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { useTranslation } from 'react-i18next';
import { Button, Icon, Loader } from 'semantic-ui-react';
import { Button, Icon, Label, Loader } from 'semantic-ui-react';
import EditPopup from './EditPopup';
import styles from './Item.module.css';
const Item = React.memo(
({ name, url, thumbnailUrl, createdAt, isPersisted, onUpdate, onDelete }) => {
({
name,
url,
coverUrl,
createdAt,
isCover,
isPersisted,
onCoverSelect,
onCoverDeselect,
onUpdate,
onDelete,
}) => {
const [t] = useTranslation();
const handleClick = useCallback(() => {
window.open(url, '_blank');
}, [url]);
const handleToggleCoverClick = useCallback(
(event) => {
event.stopPropagation();
if (isCover) {
onCoverDeselect();
} else {
onCoverSelect();
}
},
[isCover, onCoverSelect, onCoverDeselect],
);
if (!isPersisted) {
return (
<div className={classNames(styles.wrapper, styles.wrapperSubmitting)}>
@ -36,19 +60,46 @@ const Item = React.memo(
<div
className={styles.thumbnail}
style={{
backgroundImage: thumbnailUrl && `url(${thumbnailUrl}`,
backgroundImage: coverUrl && `url(${coverUrl}`,
}}
>
{!thumbnailUrl && <span className={styles.extension}>{extension || '-'}</span>}
{coverUrl ? (
isCover && (
<Label corner="left" size="tiny" icon="star" className={styles.thumbnailLabel} />
)
) : (
<span className={styles.extension}>{extension || '-'}</span>
)}
</div>
<div className={styles.details}>
<span className={styles.name}>{name}</span>
<span className={styles.options}>
<span className={styles.date}>
{t('format:longDateTime', {
postProcess: 'formatDate',
value: createdAt,
})}
</span>
{coverUrl && (
<span className={styles.options}>
<button type="button" className={styles.option} onClick={handleToggleCoverClick}>
<Icon
name="window maximize outline"
flipped="vertically"
size="small"
className={styles.optionIcon}
/>
<span className={styles.optionText}>
{isCover
? t('action.removeCover', {
context: 'title',
})
: t('action.makeCover', {
context: 'title',
})}
</span>
</button>
</span>
)}
</div>
<EditPopup
defaultData={{
@ -69,16 +120,19 @@ const Item = React.memo(
Item.propTypes = {
name: PropTypes.string.isRequired,
url: PropTypes.string,
thumbnailUrl: PropTypes.string,
coverUrl: PropTypes.string,
createdAt: PropTypes.instanceOf(Date),
isCover: PropTypes.bool.isRequired,
isPersisted: PropTypes.bool.isRequired,
onCoverSelect: PropTypes.func.isRequired,
onCoverDeselect: PropTypes.func.isRequired,
onUpdate: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
};
Item.defaultProps = {
url: undefined,
thumbnailUrl: undefined,
coverUrl: undefined,
createdAt: undefined,
};

View file

@ -16,9 +16,16 @@
background-color: rgba(9, 30, 66, 0.08) !important;
}
.date {
display: block;
color: #6b808c;
line-height: 20px;
margin-bottom: 6px;
}
.details {
box-sizing: border-box;
padding: 8px 32px 8px 128px;
padding: 6px 32px 6px 128px;
margin: 0;
min-height: 80px;
z-index: 0;
@ -45,11 +52,31 @@
word-wrap: break-word;
}
.option {
background: none;
border: none;
color: #6b808c;
cursor: pointer;
outline: none;
padding: 0;
}
.option:hover {
color: #172b4d;
}
.optionIcon {
margin-right: 6px !important;
}
.optionText {
text-decoration: underline;
}
.options {
display: block;
color: #6b808c;
line-height: 20px;
margin-bottom: 8px;
}
.thumbnail {
@ -70,6 +97,10 @@
z-index: 1;
}
.thumbnailLabel {
border-color: rgba(255, 255, 255, 0.8) !important;
}
.wrapper {
cursor: pointer;
margin-bottom: 8px;

View file

@ -98,6 +98,15 @@ const CardModal = React.memo(
[onUpdate],
);
const handleCoverUpdate = useCallback(
(newCoverAttachmentId) => {
onUpdate({
coverAttachmentId: newCoverAttachmentId,
});
},
[onUpdate],
);
const handleAttachmentFileSelect = useCallback(
(file) => {
onAttachmentCreate({
@ -278,6 +287,7 @@ const CardModal = React.memo(
items={attachments}
onUpdate={onAttachmentUpdate}
onDelete={onAttachmentDelete}
onCoverUpdate={handleCoverUpdate}
/>
</div>
</div>

View file

@ -34,7 +34,7 @@ const makeMapStateToProps = () => {
const allProjectMemberships = membershipsForCurrentProjectSelector(state);
const allLabels = labelsForCurrentBoardSelector(state);
const { name, dueDate, timer, isPersisted } = cardByIdSelector(state, id);
const { name, dueDate, timer, coverUrl, isPersisted } = cardByIdSelector(state, id);
const users = usersByCardIdSelector(state, id);
const labels = labelsByCardIdSelector(state, id);
@ -47,6 +47,7 @@ const makeMapStateToProps = () => {
name,
dueDate,
timer,
coverUrl,
isPersisted,
notificationsTotal,
users,

View file

@ -156,7 +156,9 @@ export default {
editTitle_title: 'Edit Title',
editUsername_title: 'Edit Username',
logOut_title: 'Log Out',
makeCover_title: 'Make Cover',
remove: 'Remove',
removeCover_title: 'Remove Cover',
removeFromProject: 'Remove from project',
removeMember: 'Remove member',
save: 'Save',

View file

@ -157,7 +157,9 @@ export default {
editTitle: 'Изменить название',
editUsername_title: 'Изменить имя пользователя',
logOut: 'Выйти',
makeCover: 'Сделать обложкой',
remove: 'Убрать',
removeCover: 'Убрать обложку',
removeFromProject: 'Удалить из проекта',
removeMember: 'Удалить участника',
save: 'Сохранить',

View file

@ -8,7 +8,7 @@ export default class extends Model {
static fields = {
id: attr(),
url: attr(),
thumbnailUrl: attr(),
coverUrl: attr(),
name: attr(),
cardId: fk({
to: 'Card',

View file

@ -1,4 +1,4 @@
import { Model, attr, fk, many } from 'redux-orm';
import { Model, attr, fk, many, oneToOne } from 'redux-orm';
import ActionTypes from '../constants/ActionTypes';
import Config from '../constants/Config';
@ -32,6 +32,11 @@ export default class extends Model {
as: 'board',
relatedName: 'cards',
}),
coverAttachmentId: oneToOne({
to: 'Attachment',
as: 'coverAttachment',
relatedName: 'coveredCard',
}),
users: many('User', 'cards'),
labels: many('Label', 'cards'),
};

View file

@ -64,6 +64,7 @@ export const makeCardByIdSelector = () =>
return {
...cardModel.ref,
coverUrl: cardModel.coverAttachment && cardModel.coverAttachment.coverUrl,
isPersisted: !isLocalId(id),
};
},

View file

@ -355,6 +355,7 @@ export const attachmentsForCurrentCardSelector = createSelector(
.toRefArray()
.map((attachment) => ({
...attachment,
isCover: attachment.id === cardModel.coverAttachmentId,
isPersisted: !isLocalId(attachment.id),
}));
},

View file

@ -51,6 +51,7 @@ module.exports = {
const attachment = await sails.helpers.createAttachment(
card,
currentUser,
{
dirname: file.extra.dirname,
filename: file.filename,

View file

@ -27,7 +27,7 @@ module.exports = {
.intercept('pathNotFound', () => Errors.ATTACHMENT_NOT_FOUND);
let { attachment } = attachmentToProjectPath;
const { board, project } = attachmentToProjectPath;
const { card, board, project } = attachmentToProjectPath;
const isUserMemberForProject = await sails.helpers.isUserMemberForProject(
project.id,
@ -38,7 +38,7 @@ module.exports = {
throw Errors.ATTACHMENT_NOT_FOUND; // Forbidden
}
attachment = await sails.helpers.deleteAttachment(attachment, board, this.req);
attachment = await sails.helpers.deleteAttachment(attachment, card, board, this.req);
if (!attachment) {
throw Errors.ATTACHMENT_NOT_FOUND;

View file

@ -20,6 +20,11 @@ module.exports = {
type: 'string',
regex: /^[0-9]+$/,
},
coverAttachmentId: {
type: 'string',
regex: /^[0-9]+$/,
allowNull: true,
},
position: {
type: 'number',
},
@ -91,6 +96,7 @@ module.exports = {
}
const values = _.pick(inputs, [
'coverAttachmentId',
'position',
'name',
'description',

View file

@ -30,28 +30,44 @@ module.exports = {
Buffer.concat(parts.map((part) => (util.isBuffer(part) ? part : Buffer.from(part)))),
);
let thumbnailBuffer;
try {
thumbnailBuffer = await sharp(buffer).resize(240, 240).jpeg().toBuffer();
} catch (error) {} // eslint-disable-line no-empty
try {
const dirname = uuid();
const dirPath = path.join(sails.config.custom.attachmentsPath, dirname);
fs.mkdirSync(dirPath);
const rootPath = path.join(sails.config.custom.attachmentsPath, dirname);
fs.mkdirSync(rootPath);
if (thumbnailBuffer) {
await writeFile(path.join(dirPath, '240.jpg'), thumbnailBuffer);
await writeFile(path.join(rootPath, file.filename), buffer);
const image = sharp(buffer);
let imageMetadata;
try {
imageMetadata = await image.metadata();
} catch (error) {} // eslint-disable-line no-empty
if (imageMetadata) {
let cover256Buffer;
if (imageMetadata.height > imageMetadata.width) {
cover256Buffer = await image.resize(256, 320).jpeg().toBuffer();
} else {
cover256Buffer = await image
.resize({
width: 256,
})
.jpeg()
.toBuffer();
}
const thumbnailsPath = path.join(rootPath, 'thumbnails');
fs.mkdirSync(thumbnailsPath);
await writeFile(path.join(thumbnailsPath, 'cover-256.jpg'), cover256Buffer);
}
await writeFile(path.join(dirPath, file.filename), buffer);
// eslint-disable-next-line no-param-reassign
file.extra = {
dirname,
isImage: !!thumbnailBuffer,
isImage: !!imageMetadata,
};
return done();

View file

@ -4,6 +4,10 @@ module.exports = {
type: 'ref',
required: true,
},
user: {
type: 'ref',
required: true,
},
values: {
type: 'json',
required: true,
@ -17,6 +21,7 @@ module.exports = {
const attachment = await Attachment.create({
...inputs.values,
cardId: inputs.card.id,
userId: inputs.user.id,
}).fetch();
sails.sockets.broadcast(
@ -28,6 +33,16 @@ module.exports = {
inputs.request,
);
if (!inputs.card.coverAttachmentId && attachment.isImage) {
await sails.helpers.updateCard.with({
record: inputs.card,
values: {
coverAttachmentId: attachment.id,
},
request: inputs.request,
});
}
return exits.success(attachment);
},
};

View file

@ -2,10 +2,11 @@ const fs = require('fs');
const path = require('path');
const util = require('util');
const stream = require('stream');
const streamToArray = require('stream-to-array');
const { v4: uuid } = require('uuid');
const sharp = require('sharp');
const pipeline = util.promisify(stream.pipeline);
const writeFile = util.promisify(fs.writeFile);
module.exports = {
sync: true,
@ -25,18 +26,20 @@ module.exports = {
}
firstFileHandled = true;
const resize = sharp().resize(100, 100).jpeg();
const passThrought = new stream.PassThrough();
const buffer = await streamToArray(file).then((parts) =>
Buffer.concat(parts.map((part) => (util.isBuffer(part) ? part : Buffer.from(part)))),
);
try {
await pipeline(file, resize, passThrought);
const square100Buffer = await sharp(buffer).resize(100, 100).jpeg().toBuffer();
const dirname = uuid();
const dirPath = path.join(sails.config.custom.userAvatarsPath, dirname);
fs.mkdirSync(dirPath);
const rootPath = path.join(sails.config.custom.userAvatarsPath, dirname);
fs.mkdirSync(rootPath);
await pipeline(passThrought, fs.createWriteStream(path.join(dirPath, '100.jpg')));
await writeFile(path.join(rootPath, 'original.jpg'), buffer);
await writeFile(path.join(rootPath, 'square-100.jpg'), square100Buffer);
// eslint-disable-next-line no-param-reassign
file.extra = {

View file

@ -7,6 +7,10 @@ module.exports = {
type: 'ref',
required: true,
},
card: {
type: 'ref',
required: true,
},
board: {
type: 'ref',
required: true,
@ -17,6 +21,16 @@ module.exports = {
},
async fn(inputs, exits) {
if (inputs.record.id === inputs.card.coverAttachmentId) {
await sails.helpers.updateCard.with({
record: inputs.card,
values: {
coverAttachmentId: null,
},
request: inputs.request,
});
}
const attachment = await Attachment.archiveOne(inputs.record.id);
if (attachment) {

View file

@ -15,35 +15,43 @@ module.exports = {
},
list: {
type: 'ref',
required: true,
},
user: {
type: 'ref',
required: true,
},
request: {
type: 'ref',
},
},
exits: {
invalidParams: {},
},
async fn(inputs, exits) {
const { isSubscribed, ...values } = inputs.values;
let listId;
if (inputs.toList) {
listId = inputs.toList.id;
if (listId !== inputs.list.id) {
values.listId = listId;
} else {
delete inputs.toList; // eslint-disable-line no-param-reassign
if (!inputs.list || !inputs.user) {
throw 'invalidParams';
}
} else {
listId = inputs.list.id;
if (inputs.toList.id === inputs.list.id) {
delete inputs.toList; // eslint-disable-line no-param-reassign
} else {
values.listId = inputs.toList.id;
}
}
if (!_.isUndefined(isSubscribed) && !inputs.user) {
throw 'invalidParams';
}
if (!_.isUndefined(values.position)) {
const cards = await sails.helpers.getCardsForList(listId, inputs.record.id);
const cards = await sails.helpers.getCardsForList(
values.listId || inputs.record.listId,
inputs.record.id,
);
const { position, repositions } = sails.helpers.insertToPositionables(values.position, cards);

View file

@ -42,14 +42,19 @@ module.exports = {
required: true,
columnName: 'card_id',
},
userId: {
model: 'User',
required: true,
columnName: 'user_id',
},
},
customToJSON() {
return {
..._.omit(this, ['dirname', 'filename', 'isImage']),
url: `${sails.config.custom.attachmentsUrl}/${this.dirname}/${this.filename}`,
thumbnailUrl: this.isImage
? `${sails.config.custom.attachmentsUrl}/${this.dirname}/240.jpg`
coverUrl: this.isImage
? `${sails.config.custom.attachmentsUrl}/${this.dirname}/thumbnails/cover-256.jpg`
: null,
};
},

View file

@ -50,6 +50,10 @@ module.exports = {
required: true,
columnName: 'board_id',
},
coverAttachmentId: {
model: 'Attachment',
columnName: 'cover_attachment_id',
},
subscriptionUsers: {
collection: 'User',
via: 'cardId',

View file

@ -94,7 +94,8 @@ module.exports = {
return {
..._.omit(this, ['password', 'avatarDirname']),
avatarUrl:
this.avatarDirname && `${sails.config.custom.userAvatarsUrl}/${this.avatarDirname}/100.jpg`,
this.avatarDirname &&
`${sails.config.custom.userAvatarsUrl}/${this.avatarDirname}/square-100.jpg`,
};
},
};

View file

@ -6,6 +6,7 @@ module.exports.up = (knex) =>
table.bigInteger('list_id').notNullable();
table.bigInteger('board_id').notNullable();
table.bigInteger('cover_attachment_id');
table.specificType('position', 'double precision').notNullable();
table.text('name').notNullable();

View file

@ -5,6 +5,7 @@ module.exports.up = (knex) =>
table.bigInteger('id').primary().defaultTo(knex.raw('next_id()'));
table.bigInteger('card_id').notNullable();
table.bigInteger('user_id').notNullable();
table.text('dirname').notNullable();
table.text('filename').notNullable();