Fix up KeyValue component, fix save issue of Bio, simplify UserProfile

This commit is contained in:
Frank Johnson
2021-09-15 01:53:44 -04:00
parent fc6cded59e
commit 7b2be01430
6 changed files with 245 additions and 240 deletions

View File

@@ -1,38 +1,16 @@
import Svg from 'src/components/Svg/Svg'
interface KeyValueType {
keyName: string
children: React.ReactNode
hide?: boolean
canEdit?: boolean
onEdit?: () => void
isEditable?: boolean
bottom?: boolean
className?: string
interface EditToggleType {
hasPermissionToEdit: boolean
onEdit?: React.MouseEventHandler
isEditing?: boolean
}
const KeyValue = ({
keyName,
children,
hide = false,
canEdit = false,
onEdit,
isEditable = false,
bottom = false,
className = '',
}: KeyValueType) => {
if (!children || hide) return null
return (
<div className={'flex flex-col ' + className}>
<div
className={
'text-ch-blue-400 font-fira-code flex items-center leading-4 text-sm whitespace-nowrap ' +
(bottom ? 'order-2' : '')
}
>
<span className={isEditable ? 'text-ch-blue-300' : ''}>{keyName}</span>
{canEdit &&
(isEditable ? (
const EditToggle = ({
onEdit = () => { console.error('Field declared editable without edit action.') },
isEditing = false,
} : EditToggleType) => (
(isEditing ? (
<button
className="font-fira-sans text-ch-gray-300 items-center ml-4 grid grid-flow-col-dense p-px px-2 gap-2 bg-ch-blue-500 bg-opacity-50 hover:bg-opacity-70 rounded-sm"
id="rename-button"
@@ -45,7 +23,35 @@ const KeyValue = ({
<button onClick={onEdit}>
<Svg name="pencil-solid" className="h-4 w-4 ml-4 mb-2" />
</button>
))}
))
)
interface KeyValueType {
keyName: string
children: React.ReactNode
bottom?: boolean
className?: string
edit?: EditToggleType
}
const KeyValue = ({
keyName,
children,
bottom = false,
className = '',
edit = { hasPermissionToEdit: false },
}: KeyValueType) => {
if (!children) return null
return (
<div className={'flex flex-col ' + className}>
<div
className={
'text-ch-blue-400 font-fira-code flex items-center leading-4 text-sm whitespace-nowrap ' +
(bottom ? 'order-2' : '')
}
>
<span className={edit ? 'text-ch-blue-300' : ''}>{keyName}</span>
{edit && edit.hasPermissionToEdit && <EditToggle {...edit} /> }
</div>
<div className={'text-ch-gray-300 ' + (bottom ? 'mb-1' : 'mt-1')}>
{children}

View File

@@ -33,8 +33,8 @@ const ProjectCard = ({ title, mainImage, user, Reaction, cadPackage }) => (
<div className="flex items-center mt-1">
<div className="w-8 h-8 overflow-hidden rounded-full border border-ch-gray-300 shadow">
<ImageFallback
imageId={user?.image} // http://res.cloudinary.com/irevdev/image/upload/c_scale,w_50/v1/CadHub/bc7smqwo9qqmrloyf9xr
width={80} // http://res.cloudinary.com/irevdev/image/upload/c_scale,w_300/v1/CadHub/bc7smqwo9qqmrloyf9xr
imageId={user?.image}
width={80}
/>
</div>
<div className="ml-3 text-lg text-ch-gray-300 font-fira-sans">

View File

@@ -27,7 +27,7 @@ const ProjectProfile = ({
onComment,
}) => {
const [comment, setComment] = useState('')
const [isEditable, setIsEditable] = useState(false)
const [isEditing, setIsEditing] = useState(false)
const onCommentClear = () => {
onComment(comment)
setComment('')
@@ -36,14 +36,14 @@ const ProjectProfile = ({
const [isReactionsModalOpen, setIsReactionsModalOpen] = useState(false)
const { currentUser } = useAuth()
const editorRef = useRef(null)
const canEdit =
const hasPermissionToEdit =
currentUser?.sub === userProject.id || currentUser?.roles.includes('admin')
const project = userProject?.Project
const emotes = countEmotes(project?.Reaction)
const userEmotes = project?.userReactions.map(({ emote }) => emote)
useEffect(() => {
isEditable &&
!canEdit &&
isEditing &&
!hasPermissionToEdit &&
navigate(
routes.project({
userName: userProject.userName,
@@ -55,7 +55,7 @@ const ProjectProfile = ({
const [newDescription, setNewDescription] = useState(project?.description)
const onDescriptionChange = (description) => setNewDescription(description())
const onEditSaveClick = () => {
if (isEditable) {
if (isEditing) {
onSave(project?.id, { description: newDescription })
return
}
@@ -108,26 +108,27 @@ const ProjectProfile = ({
className="px-3 py-2 rounded"
/>
</div>
<KeyValue
{ (project?.description || hasPermissionToEdit) && <KeyValue
keyName="Description"
hide={!project?.description && !canEdit}
canEdit={canEdit}
onEdit={() => {
if (!isEditable) {
setIsEditable(true)
edit={{
hasPermissionToEdit,
isEditing,
onEdit: () => {
if (!isEditing) {
setIsEditing(true)
} else {
onEditSaveClick()
setIsEditable(false)
setIsEditing(false)
}
},
}}
isEditable={isEditable}
>
<div
id="description-wrap"
name="description"
className={
'markdown-overrides rounded-sm pb-2 mt-2' +
(isEditable ? ' min-h-md' : '')
(isEditing ? ' min-h-md' : '')
}
onClick={(e) =>
e?.target?.id === 'description-wrap' &&
@@ -137,11 +138,11 @@ const ProjectProfile = ({
<Editor
ref={editorRef}
defaultValue={project?.description || ''}
readOnly={!isEditable}
readOnly={!isEditing}
onChange={onDescriptionChange}
/>
</div>
</KeyValue>
</KeyValue> }
<div className="grid grid-flow-col-dense gap-6">
<KeyValue keyName="Created on">
{new Date(project?.createdAt).toDateString()}
@@ -156,10 +157,11 @@ const ProjectProfile = ({
userEmotes={userEmotes}
onEmote={onReaction}
onShowProjectReactions={() => setIsReactionsModalOpen(true)}
className=""
/>
</KeyValue>
<KeyValue keyName="Comments" hide={!currentUser}>
{!isEditable && (
{ currentUser && <KeyValue keyName="Comments">
{!isEditing && (
<>
{currentUser && (
<>
@@ -215,8 +217,8 @@ const ProjectProfile = ({
</ul>
</>
)}
</KeyValue>
{canEdit && (
</KeyValue> }
{hasPermissionToEdit && (
<>
<h4 className="mt-10 text-red-600">Danger Zone</h4>
<Button

View File

@@ -1,45 +1,53 @@
import { useState, useEffect, useRef, useReducer, ReactNode } from 'react'
import { useEffect, useReducer } from 'react'
import { useAuth } from '@redwoodjs/auth'
import { Link, navigate, routes } from '@redwoodjs/router'
import ProjectsOfUser from 'src/components/ProjectsOfUserCell'
import IdeHeader from 'src/components/IdeHeader/IdeHeader'
import Svg from 'src/components/Svg/Svg'
import {
fieldsConfig,
fieldComponents,
fieldReducer,
UserProfileType,
FieldConfigType,
FieldType,
} from './userProfileConfig'
function buildFieldsConfig(fieldsConfig, user) {
Object.entries(fieldsConfig).forEach(
([key, field]: [string, FieldConfigType]) => {
field.currentValue = field.newValue = user[key]
field.name = key
}
)
return fieldsConfig
// This function initializes the state management object for each of the fields
function buildFieldsConfig(fieldsConfig, user, hasPermissionToEdit) {
return Object.fromEntries(Object.keys(fieldsConfig).map(
(key: string): [string, FieldType] => ([key, {
name: key,
currentValue: user[key],
newValue: user[key],
isEditing: false,
hasPermissionToEdit,
}])
))
}
const UserProfile = ({
user,
isEditable,
isEditing,
loading,
onSave,
error,
projects,
}: UserProfileType) => {
const { currentUser } = useAuth()
const hasEditPermission = currentUser?.sub === user.id
const hasPermissionToEdit = currentUser?.sub === user.id
useEffect(() => {
isEditable &&
!hasEditPermission &&
isEditing &&
!hasPermissionToEdit &&
navigate(routes.user({ userName: user.userName }))
}, [currentUser])
const initializedFields = buildFieldsConfig(fieldsConfig, user)
const initializedFields = buildFieldsConfig(fieldComponents, user, hasPermissionToEdit)
const [fields, fieldDispatch] = useReducer(fieldReducer, initializedFields)
const {
name: NameField,
userName: UserNameField,
image: ImageField,
bio: BioField,
createdAt: MemberSinceField,
} = fieldComponents
return (
<>
@@ -65,44 +73,45 @@ const UserProfile = ({
{/* Side panel */}
<section className="bg-ch-gray-760 font-fira-sans p-12 md:overflow-y-auto ch-scrollbar">
<div className="flex gap-6">
{!isEditable && (
{!isEditing && (
<div className="w-28 flex-shrink-0">
<fields.image.component
<ImageField
field={fields.image}
dispatch={fieldDispatch}
user={user}
save={onSave}
hasEditPermission={hasEditPermission}
hasPermissionToEdit={hasPermissionToEdit}
/>
</div>
)}
<div>
<fields.name.component
<NameField
field={fields.name}
dispatch={fieldDispatch}
user={user}
save={onSave}
hasEditPermission={hasEditPermission}
hasPermissionToEdit={hasPermissionToEdit}
/>
<fields.userName.component
<UserNameField
field={fields.userName}
dispatch={fieldDispatch}
user={user}
save={onSave}
hasEditPermission={hasEditPermission}
hasPermissionToEdit={hasPermissionToEdit}
/>
</div>
</div>
<div className="mt-10">
<fields.bio.component
<BioField
field={fields.bio}
dispatch={fieldDispatch}
user={user}
save={onSave}
hasEditPermission={hasEditPermission}
hasPermissionToEdit={hasPermissionToEdit}
/>
</div>
<div className="my-5">
<fields.createdAt.component field={fields.createdAt} />
<MemberSinceField field={fields.createdAt} />
</div>
</section>
{/* Viewer */}

View File

@@ -5,24 +5,42 @@ import Editor from 'rich-markdown-editor'
import ImageUploader from 'src/components/ImageUploader'
import { User } from 'types/graphql'
export const fieldComponents = {
name: NameField,
userName: UserNameField,
image: ImageField,
bio: BioField,
createdAt: MemberSinceField,
}
export interface UserProfileType {
user: User
isEditable: boolean
isEditing: boolean
loading: boolean
error: boolean
onSave: Function
projects: {}[]
}
export interface FieldConfigType {
name?: string // introspection ugh
editable: boolean
component?: ReactNode
needsRef?: boolean
isEditing?: boolean | undefined
onSave?: Function
currentValue?: any
newValue?: any
export interface FieldType {
name: string
currentValue: any
newValue: any
isEditing: boolean
hasPermissionToEdit: boolean
}
export interface FieldComponentPropsType {
field: FieldType
dispatch?: React.Dispatch<Object>
user?: User
save?: Function
hasPermissionToEdit?: boolean
}
interface ProfileKeyValueType extends FieldComponentPropsType {
children: ReactNode
bottom: boolean
}
const ProfileKeyValue = ({
@@ -30,17 +48,18 @@ const ProfileKeyValue = ({
dispatch,
user,
save,
hasEditPermission,
hasPermissionToEdit,
children,
bottom = false,
}) => {
} : ProfileKeyValueType) => {
return (
<KeyValue
(user[field.name] && hasPermissionToEdit) && <KeyValue
keyName={field.name}
hide={!user[field.name] && !hasEditPermission}
canEdit={hasEditPermission}
onEdit={() => {
if (field.isEditing) {
edit={{
hasPermissionToEdit,
isEditing: field.isEditing,
onEdit: () => {
if (field.isEditing && field.currentValue !== field.newValue) {
save(user.userName, { [field.name]: field.newValue })
}
dispatch({
@@ -48,8 +67,8 @@ const ProfileKeyValue = ({
payload: { field: field.name, value: field.newValue },
})
dispatch({ type: 'TOGGLE_EDITING', payload: field.name })
},
}}
isEditable={hasEditPermission && field.isEditing}
bottom={bottom}
className="mb-4"
>
@@ -58,13 +77,9 @@ const ProfileKeyValue = ({
)
}
const bioField: FieldConfigType = {
editable: true,
needsRef: true,
component: (props) => {
function BioField(props) {
const ref = useRef(null)
const { dispatch, field } = props
const { field, dispatch } = props
return (
<ProfileKeyValue {...props}>
@@ -73,7 +88,7 @@ const bioField: FieldConfigType = {
name="bio"
className={
'markdown-overrides rounded-sm pb-2 mt-2' +
(field.isEditable ? ' min-h-md' : '')
(field.isEditing ? ' min-h-md' : '')
}
onClick={(e) =>
e?.target?.id === 'bio-wrap' && ref?.current?.focusAtEnd()
@@ -86,35 +101,27 @@ const bioField: FieldConfigType = {
onChange={(bio) =>
dispatch({
type: 'SET_NEW_VALUE',
payload: { field: field.bio, value: bio() },
payload: { field: 'bio', value: bio() },
})
}
/>
</div>
</ProfileKeyValue>
)
},
}
const createdAtField: FieldConfigType = {
editable: false,
component: (props) => {
const { field } = props
function MemberSinceField(props : FieldComponentPropsType) {
return (
<KeyValue keyName="Member Since">
<p className="text-ch-gray-300">
{new Date(field.currentValue).toLocaleDateString()}
{new Date(props.field.currentValue).toLocaleDateString()}
</p>
</KeyValue>
)
},
}
const imageField: FieldConfigType = {
editable: true,
component: (props) => {
const { field, user, save, hasEditPermission } = props
function ImageField(props : FieldComponentPropsType) {
const { field, user, save, hasPermissionToEdit } = props
return (
<ImageUploader
className="rounded-3xl rounded-tr-none shadow-md border-2 border-ch-gray-300"
@@ -124,17 +131,14 @@ const imageField: FieldConfigType = {
})
}}
aspectRatio={1}
isEditable={hasEditPermission && !field.isEditing}
isEditable={hasPermissionToEdit}
imageUrl={user.image}
width={300}
/>
)
},
}
const nameField: FieldConfigType = {
editable: true,
component: (props) => {
function NameField(props : FieldComponentPropsType) {
const { user, dispatch, field } = props
return (
@@ -148,20 +152,17 @@ const nameField: FieldConfigType = {
onChange={({ target: { value } }) =>
dispatch({
type: 'SET_NEW_VALUE',
payload: { field: field.name, value },
payload: { field: 'name', value },
})
}
isEditable={!field.isEditable}
isEditable={field.isEditing}
/>
)}
</ProfileKeyValue>
)
},
}
const userNameField: FieldConfigType = {
editable: true,
component: (props) => {
function UserNameField(props : FieldComponentPropsType) {
const { dispatch, field } = props
return (
@@ -177,29 +178,14 @@ const userNameField: FieldConfigType = {
onChange={({ target: { value } }) =>
dispatch({
type: 'SET_NEW_VALUE',
payload: { field: field.name, value },
payload: { field: 'userName', value },
})
}
isEditable={!field.isEditable}
isEditable={field.isEditing}
/>
)}
</ProfileKeyValue>
)
},
}
export const fieldsConfig = {
bio: bioField,
createdAt: createdAtField,
id: {
editable: false,
},
image: imageField,
name: nameField,
updatedAt: {
editable: false,
},
userName: userNameField,
}
export function fieldReducer(state, action) {
@@ -210,7 +196,7 @@ export function fieldReducer(state, action) {
[action.payload]: {
...state[action.payload],
isEditing:
state[action.payload].editable && !state[action.payload].isEditing
state[action.payload].hasPermissionToEdit && !state[action.payload].isEditing
? true
: false,
},

View File

@@ -1,11 +1,13 @@
import MainLayout from 'src/layouts/MainLayout'
import EditUserCell from 'src/components/EditUserCell'
import Seo from 'src/components/Seo/Seo'
import { Toaster } from '@redwoodjs/web/toast'
const UserPage = ({ userName }) => {
return (
<>
<Seo title={userName} description="User page" lang="en-US" />
<Toaster timeout={9000} />
<EditUserCell userName={userName} />
</>