Tiptap updates (#343)

* Reinstantiate editor on changes

We can't dynamically update the content, so we have to recreate the Editor whenever something changes (page loads and updates)

* Fix import

@tiptap/core is different than @tiptap/react, who knew

* Added several Tiptap components

* Added a Remix icon that isn't in remixicon-react

* Add colors for highlights

* Add ToolbarButton component

This is to standardize adding Toolbar icons so it wasn't a miserable mess in the Editor file

* Add extensions and implement ToolbarButton

* Remove unused code

* Use party prop and add keys

We always want to use the party in props until the transformer work is done and our source of truth is more reliable.

Also, we are using keys to ensure that the component reloads on new page.

* Component cleanup

* Always use props.party

* Ensure content gets reset when edits are committed

Here, we do some tactical bandaid fixes to ensure that when the user saves data to the server, the editor will show the freshest data in both editable and read-only mode.

In the Editor, its as easy as calling the setContent command in a useEffect hook when the content changes.

In the party, we are saving party in a state and passing it down to the components via props. This is because the party prop we get from pages is only from the first time the server loaded data, so any edits are not reflected. The app state should have the latest updates, but due to reasons I don't completely understand, it is showing the old state first and then the one we want, causing the Editor to get stuck on old data.

By storing the party in a state, we can populate the state from the server when the component mounts, then update it whenever the user saves data since all party data is saved in that component.

* Fix build errors
This commit is contained in:
Justin Edmund 2023-07-06 02:51:01 -07:00 committed by GitHub
parent 9adcd50519
commit 83bebdb0c2
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 350 additions and 105 deletions

View file

@ -61,6 +61,44 @@
font-style: italic;
}
ul {
padding: 0 $unit-2x;
list-style-type: disc;
}
ol {
padding: 0 $unit-2x;
list-style-type: decimal;
}
h1 {
font-size: $font-xlarge;
font-weight: $medium;
margin: $unit 0;
text-align: left;
}
h2 {
font-size: $font-large;
font-weight: $medium;
margin: $unit 0;
text-align: left;
}
h3 {
font-size: $font-regular;
font-weight: $medium;
margin: $unit 0;
text-align: left;
}
mark {
border-radius: $item-corner-small;
background: var(--highlight-bg);
color: var(--highlight-text);
padding: 1px $unit-fourth;
}
iframe {
background: var(--input-bound-bg);
border-radius: $card-corner;
@ -180,26 +218,6 @@
padding: $unit;
z-index: 10;
button {
background: var(--toolbar-item-bg);
border-radius: $bubble-menu-item-corner;
color: var(--toolbar-item-text);
font-weight: $medium;
font-size: $font-small;
padding: $unit-half $unit;
&:hover {
background: var(--toolbar-item-bg-hover);
color: var(--toolbar-item-text-hover);
cursor: pointer;
}
&.active {
background: var(--toolbar-item-bg-active);
color: var(--toolbar-item-text-active);
}
}
.divider {
background: var(--toolbar-divider-bg);
border-radius: $full-corner;

View file

@ -1,15 +1,29 @@
import { ComponentProps, useCallback } from 'react'
import { ComponentProps, useCallback, useEffect } from 'react'
import { useRouter } from 'next/router'
import { useEditor, EditorContent } from '@tiptap/react'
import StarterKit from '@tiptap/starter-kit'
import Link from '@tiptap/extension-link'
import Highlight from '@tiptap/extension-highlight'
import Typography from '@tiptap/extension-typography'
import Youtube from '@tiptap/extension-youtube'
import CustomMention from '~extensions/CustomMention'
import classNames from 'classnames'
import { mentionSuggestionOptions } from '~utils/mentionSuggestions'
import type { JSONContent } from '@tiptap/core'
import ToolbarButton from '~components/common/ToolbarButton'
import BoldIcon from 'remixicon-react/BoldIcon'
import ItalicIcon from 'remixicon-react/ItalicIcon'
import StrikethroughIcon from 'remixicon-react/StrikethroughIcon'
import UnorderedListIcon from 'remixicon-react/ListUnorderedIcon'
import OrderedListIcon from '~public/icons/remix/list-ordered-2.svg'
import PaintbrushIcon from 'remixicon-react/PaintbrushLineIcon'
import H1Icon from 'remixicon-react/H1Icon'
import H2Icon from 'remixicon-react/H2Icon'
import H3Icon from 'remixicon-react/H3Icon'
import LinkIcon from 'remixicon-react/LinkIcon'
import YoutubeIcon from 'remixicon-react/YoutubeLineIcon'
import styles from './index.module.scss'
interface Props extends ComponentProps<'div'> {
@ -27,9 +41,62 @@ const Editor = ({
onUpdate,
...props
}: Props) => {
// Hooks: Router
const router = useRouter()
const locale = router.locale || 'en'
useEffect(() => {
editor?.commands.setContent(formatContent(content))
}, [content])
// Setup: Editor
const editor = useEditor({
content: formatContent(content),
editable: editable,
editorProps: {
attributes: {
class: classNames(
{
[styles.editor]: true,
[styles.bound]: bound,
},
className?.split(' ').map((c) => styles[c])
),
},
},
extensions: [
StarterKit.configure({
heading: {
levels: [1, 2, 3],
},
}),
Link,
Highlight,
Typography,
CustomMention.configure({
renderLabel({ options, node }) {
return `${node.attrs.id.name[locale] ?? node.attrs.id.granblue_en}`
},
suggestion: mentionSuggestionOptions,
HTMLAttributes: {
class: classNames({
[styles.mention]: true,
}),
},
}),
Youtube.configure({
inline: false,
modestBranding: true,
interfaceLanguage: locale,
}),
],
onUpdate: ({ editor }) => {
const json = editor.getJSON()
if (onUpdate) onUpdate(json)
},
})
// Methods: Convenience
function isJSON(content?: string) {
if (!content) return false
@ -59,46 +126,7 @@ const Editor = ({
}
}
const editor = useEditor({
content: formatContent(content),
editable: editable,
editorProps: {
attributes: {
class: classNames(
{
[styles.editor]: true,
[styles.bound]: bound,
},
className?.split(' ').map((c) => styles[c])
),
},
},
extensions: [
StarterKit,
Link,
CustomMention.configure({
renderLabel({ options, node }) {
return `${node.attrs.id.name[locale] ?? node.attrs.id.granblue_en}`
},
suggestion: mentionSuggestionOptions,
HTMLAttributes: {
class: classNames({
[styles.mention]: true,
}),
},
}),
Youtube.configure({
inline: false,
modestBranding: true,
interfaceLanguage: locale,
}),
],
onUpdate: ({ editor }) => {
const json = editor.getJSON()
if (onUpdate) onUpdate(json)
},
})
// Methods: Actions
const setLink = useCallback(() => {
const previousUrl = editor?.getAttributes('link').href
const url = window.prompt('URL', previousUrl)
@ -131,6 +159,7 @@ const Editor = ({
}
}
// Methods: Rendering
if (!editor) {
return null
}
@ -139,32 +168,84 @@ const Editor = ({
<section className={styles.wrapper}>
{editor && editable === true && (
<nav className={styles.toolbar}>
<button
<ToolbarButton
editor={editor}
action="bold"
icon={<BoldIcon />}
onClick={() => editor.chain().focus().toggleBold().run()}
className={editor.isActive('bold') ? styles.active : ''}
>
bold
</button>
<button
/>
<ToolbarButton
editor={editor}
action="italic"
icon={<ItalicIcon />}
onClick={() => editor.chain().focus().toggleItalic().run()}
className={editor.isActive('italic') ? styles.active : ''}
>
italic
</button>
<button
/>
<ToolbarButton
editor={editor}
action="strike"
icon={<StrikethroughIcon />}
onClick={() => editor.chain().focus().toggleStrike().run()}
className={editor.isActive('strike') ? styles.active : ''}
>
strike
</button>
/>
<ToolbarButton
editor={editor}
action="highlight"
icon={<PaintbrushIcon />}
onClick={() => editor.chain().focus().toggleHighlight().run()}
/>
<div className={styles.divider} />
<button
<ToolbarButton
editor={editor}
action="heading"
level={1}
icon={<H1Icon />}
onClick={() =>
editor.chain().focus().toggleHeading({ level: 1 }).run()
}
/>
<ToolbarButton
editor={editor}
action="heading"
level={2}
icon={<H2Icon />}
onClick={() =>
editor.chain().focus().toggleHeading({ level: 2 }).run()
}
/>
<ToolbarButton
editor={editor}
action="heading"
level={3}
icon={<H3Icon />}
onClick={() =>
editor.chain().focus().toggleHeading({ level: 3 }).run()
}
/>
<div className={styles.divider} />
<ToolbarButton
editor={editor}
action="bulletList"
icon={<UnorderedListIcon />}
onClick={() => editor.chain().focus().toggleBulletList().run()}
/>
<ToolbarButton
editor={editor}
action="orderedList"
icon={<OrderedListIcon />}
onClick={() => editor.chain().focus().toggleOrderedList().run()}
/>
<div className={styles.divider} />
<ToolbarButton
editor={editor}
action="link"
icon={<LinkIcon />}
onClick={setLink}
className={editor.isActive('link') ? styles.active : ''}
>
+ link
</button>
<button onClick={addYoutubeVideo}>+ youtube</button>
/>
<ToolbarButton
editor={editor}
action="youtube"
icon={<YoutubeIcon />}
onClick={addYoutubeVideo}
/>
</nav>
)}
<EditorContent editor={editor} />

View file

@ -0,0 +1,36 @@
.button {
background: var(--toolbar-item-bg);
border-radius: $bubble-menu-item-corner;
color: var(--toolbar-item-text);
display: flex;
align-items: center;
justify-content: center;
font-weight: $medium;
font-size: $font-small;
padding: $unit-half;
&:hover {
background: var(--toolbar-item-bg-hover);
color: var(--toolbar-item-text-hover);
cursor: pointer;
svg {
fill: var(--text-primary);
}
}
&.active {
background: var(--toolbar-item-bg-active);
color: var(--toolbar-item-text-active);
svg {
fill: white;
}
}
svg {
fill: var(--text-tertiary);
height: $unit-2x;
width: $unit-2x;
}
}

View file

@ -0,0 +1,35 @@
import { useTranslation } from 'next-i18next'
import classNames from 'classnames'
import { Editor } from '@tiptap/react'
import Tooltip from '~components/common/Tooltip'
import styles from './index.module.scss'
interface Props {
editor: Editor
action: string
level?: number
icon: React.ReactNode
onClick: () => void
}
const ToolbarIcon = ({ editor, action, level, icon, onClick }: Props) => {
const { t } = useTranslation('common')
const classes = classNames({
[styles.button]: true,
[styles.active]: level
? editor.isActive(action, { level: level })
: editor.isActive(action),
})
return (
<Tooltip content={t(`toolbar.tooltips.${action}`)}>
<button onClick={onClick} className={classes}>
{icon}
</button>
</Tooltip>
)
}
export default ToolbarIcon

View file

@ -466,22 +466,12 @@ const EditPartyModal = ({
}
}
const descriptionField = (
<Textarea
className="editParty"
bound={true}
placeholder={t('modals.edit_team.placeholders.description')}
value={description}
onInput={handleTextAreaChanged}
ref={descriptionInput}
/>
)
const editorField = (
<Editor
bound={true}
content={description}
content={props.party?.description}
editable={true}
key={props.party?.shortcode}
onUpdate={handleEditorUpdate}
/>
)

View file

@ -46,6 +46,7 @@ const Party = (props: Props) => {
// Set up states
const { party } = useSnapshot(appState)
const [updatedParty, setUpdatedParty] = useState<Party | undefined>()
const [editable, setEditable] = useState(false)
const [refresh, setRefresh] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
@ -57,7 +58,10 @@ const Party = (props: Props) => {
useEffect(() => {
const resetState = clonedeep(initialAppState)
appState.grid = resetState.grid
if (props.team) storeParty(props.team)
if (props.team) {
storeParty(props.team)
setUpdatedParty(props.team)
}
}, [])
// Subscribe to app state to listen for account changes and
@ -108,9 +112,11 @@ const Party = (props: Props) => {
let payload = {}
if (details) payload = formatDetailsObject(details)
return await api.endpoints.parties
.create(payload)
.then((response) => storeParty(response.data.party))
return await api.endpoints.parties.create(payload).then((response) => {
storeParty(response.data.party)
setUpdatedParty(response.data.party)
return Promise.resolve(response.data.party)
})
}
async function updateParty(details: DetailsObject) {
@ -119,7 +125,11 @@ const Party = (props: Props) => {
if (props.team && props.team.id) {
return await api.endpoints.parties
.update(props.team.id, payload)
.then((response) => storeParty(response.data.party))
.then((response) => {
storeParty(response.data.party)
setUpdatedParty(response.data.party)
return Promise.resolve(response.data.party)
})
.catch((error) => {
const data = error.response.data
if (data.errors && Object.keys(data.errors).includes('guidebooks')) {
@ -438,7 +448,7 @@ const Party = (props: Props) => {
{errorAlert()}
<PartyHeader
party={props.team}
party={updatedParty}
new={props.new || false}
editable={props.new ? true : party.editable}
raidGroups={props.raidGroups}
@ -452,7 +462,7 @@ const Party = (props: Props) => {
<section id="Party">{currentGrid()}</section>
<PartyFooter
party={props.team}
party={updatedParty}
new={props.new || false}
editable={party.editable}
raidGroups={props.raidGroups}

View file

@ -208,10 +208,13 @@ const PartyFooter = (props: Props) => {
const descriptionSection = (
<>
{partySnapshot &&
partySnapshot.description &&
partySnapshot.description.length > 0 && (
<Editor content={appState.party.description} />
{props.party &&
props.party.description &&
props.party.description.length > 0 && (
<Editor
content={props.party.description}
key={props.party?.shortcode}
/>
)}
{(!partySnapshot || !partySnapshot.description) && (
<section className={styles.noDescription}>

35
package-lock.json generated
View file

@ -20,8 +20,10 @@
"@radix-ui/react-tooltip": "^1.0.3",
"@svgr/webpack": "^6.2.0",
"@tiptap/extension-bubble-menu": "^2.0.3",
"@tiptap/extension-highlight": "^2.0.3",
"@tiptap/extension-link": "^2.0.3",
"@tiptap/extension-mention": "^2.0.3",
"@tiptap/extension-typography": "^2.0.3",
"@tiptap/extension-youtube": "^2.0.3",
"@tiptap/pm": "^2.0.3",
"@tiptap/react": "^2.0.3",
@ -56,6 +58,7 @@
"react-lite-youtube-embed": "^2.3.52",
"react-scroll": "^1.8.5",
"react-string-replace": "^1.1.0",
"remixicon-react": "^1.0.0",
"resolve-url-loader": "^5.0.0",
"sanitize-html": "^2.8.1",
"sass": "^1.61.0",
@ -7229,6 +7232,18 @@
"@tiptap/core": "^2.0.0"
}
},
"node_modules/@tiptap/extension-highlight": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@tiptap/extension-highlight/-/extension-highlight-2.0.3.tgz",
"integrity": "sha512-NrtibY8cZkIjZMQuHRrKd4php+plOvAoSo8g3uVFu275I/Ixt5HqJ53R4voCXs8W8BOBRs2HS2QX8Cjh79XhtA==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "^2.0.0"
}
},
"node_modules/@tiptap/extension-history": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@tiptap/extension-history/-/extension-history-2.0.3.tgz",
@ -7357,6 +7372,18 @@
"@tiptap/core": "^2.0.0"
}
},
"node_modules/@tiptap/extension-typography": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@tiptap/extension-typography/-/extension-typography-2.0.3.tgz",
"integrity": "sha512-5U91O2dffYOvwenWG+zT1N/pnt+RppSlocxs1KaNWFLlI2fgzDTyUyjzygIHGmskStqay2MuvmPnfVABoC+1Gw==",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/ueberdosis"
},
"peerDependencies": {
"@tiptap/core": "^2.0.0"
}
},
"node_modules/@tiptap/extension-youtube": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@tiptap/extension-youtube/-/extension-youtube-2.0.3.tgz",
@ -19306,6 +19333,14 @@
"url": "https://opencollective.com/unified"
}
},
"node_modules/remixicon-react": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/remixicon-react/-/remixicon-react-1.0.0.tgz",
"integrity": "sha512-KOXlc8EdKdujr2f/2idyFSQRjUB8p0HNiWZYBBzRsTRlTXFuSAFfnGq9culNjhCGmc92Jbtfr9OP0MXWvTMdsQ==",
"peerDependencies": {
"react": ">=0.14.0"
}
},
"node_modules/renderkid": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/renderkid/-/renderkid-3.0.0.tgz",

View file

@ -27,8 +27,10 @@
"@radix-ui/react-tooltip": "^1.0.3",
"@svgr/webpack": "^6.2.0",
"@tiptap/extension-bubble-menu": "^2.0.3",
"@tiptap/extension-highlight": "^2.0.3",
"@tiptap/extension-link": "^2.0.3",
"@tiptap/extension-mention": "^2.0.3",
"@tiptap/extension-typography": "^2.0.3",
"@tiptap/extension-youtube": "^2.0.3",
"@tiptap/pm": "^2.0.3",
"@tiptap/react": "^2.0.3",
@ -63,6 +65,7 @@
"react-lite-youtube-embed": "^2.3.52",
"react-scroll": "^1.8.5",
"react-string-replace": "^1.1.0",
"remixicon-react": "^1.0.0",
"resolve-url-loader": "^5.0.0",
"sanitize-html": "^2.8.1",
"sass": "^1.61.0",

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M5.75024 3.5H4.71733L3.25 3.89317V5.44582L4.25002 5.17782L4.25018 8.5H3V10H7V8.5H5.75024V3.5ZM10 4H21V6H10V4ZM10 11H21V13H10V11ZM10 18H21V20H10V18ZM2.875 15.625C2.875 14.4514 3.82639 13.5 5 13.5C6.17361 13.5 7.125 14.4514 7.125 15.625C7.125 16.1106 6.96183 16.5587 6.68747 16.9167L6.68271 16.9229L5.31587 18.5H7V20H3.00012L2.99959 18.8786L5.4717 16.035C5.5673 15.9252 5.625 15.7821 5.625 15.625C5.625 15.2798 5.34518 15 5 15C4.67378 15 4.40573 15.2501 4.37747 15.5688L4.3651 15.875H2.875V15.625Z"></path></svg>

After

Width:  |  Height:  |  Size: 579 B

View file

@ -63,6 +63,12 @@
--toolbar-item-text-hover: #{$toolbar--item--text--light--hover};
--toolbar-item-text-active: #{$toolbar--item--text--light--active};
// Dark - Highlights
--highlight-bg: #{$highlight--bg--light};
--highlight-bg-hover: #{$highlight--bg--light--hover};
--highlight-text: #{$highlight--text--light};
--highlight-text-hover: #{$highlight--text--light--hover};
// Light - Placeholders
--placeholder-bound-bg: #{$placeholder--bound--bg--light};
--placeholder-bound-bg-hover: #{$placeholder--bound--bg--light--hover};
@ -271,6 +277,12 @@
--toolbar-item-text-hover: #{$toolbar--item--text--dark--hover};
--toolbar-item-text-active: #{$toolbar--item--text--dark--active};
// Dark - Highlights
--highlight-bg: #{$highlight--bg--dark};
--highlight-bg-hover: #{$highlight--bg--dark--hover};
--highlight-text: #{$highlight--text--dark};
--highlight-text-hover: #{$highlight--text--dark--hover};
// Dark - Placeholders
--placeholder-bound-bg: #{$placeholder--bound--bg--dark};
--placeholder-bound-bg-hover: #{$placeholder--bound--bg--dark--hover};

View file

@ -79,6 +79,13 @@ $orange-75: #ffb461;
$orange-80: #facea7;
$orange-90: #ffebd9;
// Yellow -- Highlights
$yellow-10: #4d3703;
$yellow-30: #956d11;
$yellow-50: #c8a657;
$yellow-70: #fedc8d;
$yellow-90: #ffed4c;
// Colors -- Interface
$blue: #275dc5;
$red: #ff6161;
@ -96,6 +103,7 @@ $accent--yellow--light: #c89d39;
$accent--yellow--dark: #f9cc64;
$yellow-text-10: #a39200;
$yellow-text-20: #ffed4c;
$highlight-yellow: #ffed4c55;
$accent--yellow--00: #463805;
$accent--yellow--20: #7f6a00;
@ -383,6 +391,19 @@ $toolbar--item--text--dark--hover: $grey-90;
$toolbar--item--text--light--active: $grey-100;
$toolbar--item--text--dark--active: $grey-00;
// Color Definitions: Highlights
$highlight--bg--light: $yellow-70;
$highlight--bg--dark: $yellow-50;
$highlight--bg--light--hover: $yellow-50;
$highlight--bg--dark--hover: $yellow-70;
$highlight--text--light: $yellow-30;
$highlight--text--dark: $yellow-10;
$highlight--text--light--hover: $yellow-10;
$highlight--text--dark--hover: $yellow-30;
// Color Definitions: Element Toggle
$toggle--bg--light: $grey-90;
$toggle--bg--dark: $grey-15;