Remove document content (#1470)

* Merge documentContent and markdownContent

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>

* Add hook for markdown content without frontmatter

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>

* Use hook for export

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>

* Let subcomponent handle the markdown content

Signed-off-by: Tilman Vatteroth <git@tilmanvatteroth.de>
This commit is contained in:
Tilman Vatteroth 2021-09-05 14:27:44 +02:00 committed by GitHub
parent bb0dd4d935
commit 7ec956e5c3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 77 additions and 48 deletions

View file

@ -9,7 +9,6 @@ import { useTranslation } from 'react-i18next'
import { useParams } from 'react-router' import { useParams } from 'react-router'
import { useApplyDarkMode } from '../../hooks/common/use-apply-dark-mode' import { useApplyDarkMode } from '../../hooks/common/use-apply-dark-mode'
import { useDocumentTitleWithNoteTitle } from '../../hooks/common/use-document-title-with-note-title' import { useDocumentTitleWithNoteTitle } from '../../hooks/common/use-document-title-with-note-title'
import { useNoteMarkdownContent } from '../../hooks/common/use-note-markdown-content'
import { updateNoteTitleByFirstHeading } from '../../redux/note-details/methods' import { updateNoteTitleByFirstHeading } from '../../redux/note-details/methods'
import { MotdBanner } from '../common/motd-banner/motd-banner' import { MotdBanner } from '../common/motd-banner/motd-banner'
import { ShowIf } from '../common/show-if/show-if' import { ShowIf } from '../common/show-if/show-if'
@ -23,6 +22,7 @@ import { LoadingNoteAlert } from './LoadingNoteAlert'
import { RendererType } from '../render-page/rendering-message' import { RendererType } from '../render-page/rendering-message'
import { useApplicationState } from '../../hooks/common/use-application-state' import { useApplicationState } from '../../hooks/common/use-application-state'
import { IframeEditorToRendererCommunicatorContextProvider } from '../editor-page/render-context/iframe-editor-to-renderer-communicator-context-provider' import { IframeEditorToRendererCommunicatorContextProvider } from '../editor-page/render-context/iframe-editor-to-renderer-communicator-context-provider'
import { useNoteMarkdownContentWithoutFrontmatter } from '../../hooks/common/use-note-markdown-content-without-frontmatter'
export const DocumentReadOnlyPage: React.FC = () => { export const DocumentReadOnlyPage: React.FC = () => {
useTranslation() useTranslation()
@ -33,7 +33,7 @@ export const DocumentReadOnlyPage: React.FC = () => {
const onFirstHeadingChange = useCallback(updateNoteTitleByFirstHeading, []) const onFirstHeadingChange = useCallback(updateNoteTitleByFirstHeading, [])
const [error, loading] = useLoadNoteFromServer() const [error, loading] = useLoadNoteFromServer()
const markdownContent = useNoteMarkdownContent() const markdownContent = useNoteMarkdownContentWithoutFrontmatter()
const noteDetails = useApplicationState((state) => state.noteDetails) const noteDetails = useApplicationState((state) => state.noteDetails)
return ( return (

View file

@ -0,0 +1,21 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import React from 'react'
import { RenderIframe, RenderIframeProps } from '../renderer-pane/render-iframe'
import { useNoteMarkdownContentWithoutFrontmatter } from '../../../hooks/common/use-note-markdown-content-without-frontmatter'
export type EditorDocumentRendererProps = Omit<RenderIframeProps, 'markdownContent'>
/**
* Renders the markdown content from the global application state with the iframe renderer.
*
* @param props Every property from the {@link RenderIframe} except the markdown content.
*/
export const EditorDocumentRenderer: React.FC<EditorDocumentRendererProps> = (props) => {
const markdownContent = useNoteMarkdownContentWithoutFrontmatter()
return <RenderIframe frameClasses={'h-100 w-100'} markdownContent={markdownContent} {...props} />
}

View file

@ -8,12 +8,7 @@ import React, { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useApplyDarkMode } from '../../hooks/common/use-apply-dark-mode' import { useApplyDarkMode } from '../../hooks/common/use-apply-dark-mode'
import { useDocumentTitleWithNoteTitle } from '../../hooks/common/use-document-title-with-note-title' import { useDocumentTitleWithNoteTitle } from '../../hooks/common/use-document-title-with-note-title'
import { useNoteMarkdownContent } from '../../hooks/common/use-note-markdown-content' import { setCheckboxInMarkdownContent, updateNoteTitleByFirstHeading } from '../../redux/note-details/methods'
import {
setCheckboxInMarkdownContent,
setNoteContent,
updateNoteTitleByFirstHeading
} from '../../redux/note-details/methods'
import { MotdBanner } from '../common/motd-banner/motd-banner' import { MotdBanner } from '../common/motd-banner/motd-banner'
import { ShowIf } from '../common/show-if/show-if' import { ShowIf } from '../common/show-if/show-if'
import { ErrorWhileLoadingNoteAlert } from '../document-read-only-page/ErrorWhileLoadingNoteAlert' import { ErrorWhileLoadingNoteAlert } from '../document-read-only-page/ErrorWhileLoadingNoteAlert'
@ -23,7 +18,6 @@ import { EditorMode } from './app-bar/editor-view-mode'
import { EditorPane } from './editor-pane/editor-pane' import { EditorPane } from './editor-pane/editor-pane'
import { useLoadNoteFromServer } from './hooks/useLoadNoteFromServer' import { useLoadNoteFromServer } from './hooks/useLoadNoteFromServer'
import { useViewModeShortcuts } from './hooks/useViewModeShortcuts' import { useViewModeShortcuts } from './hooks/useViewModeShortcuts'
import { RenderIframe } from './renderer-pane/render-iframe'
import { Sidebar } from './sidebar/sidebar' import { Sidebar } from './sidebar/sidebar'
import { Splitter } from './splitter/splitter' import { Splitter } from './splitter/splitter'
import { DualScrollState, ScrollState } from './synced-scroll/scroll-props' import { DualScrollState, ScrollState } from './synced-scroll/scroll-props'
@ -34,6 +28,7 @@ import { useNotificationTest } from './use-notification-test'
import { IframeEditorToRendererCommunicatorContextProvider } from './render-context/iframe-editor-to-renderer-communicator-context-provider' import { IframeEditorToRendererCommunicatorContextProvider } from './render-context/iframe-editor-to-renderer-communicator-context-provider'
import { useUpdateLocalHistoryEntry } from './hooks/useUpdateLocalHistoryEntry' import { useUpdateLocalHistoryEntry } from './hooks/useUpdateLocalHistoryEntry'
import { useApplicationState } from '../../hooks/common/use-application-state' import { useApplicationState } from '../../hooks/common/use-application-state'
import { EditorDocumentRenderer } from './editor-document-renderer/editor-document-renderer'
export interface EditorPagePathParams { export interface EditorPagePathParams {
id: string id: string
@ -46,10 +41,7 @@ export enum ScrollSource {
export const EditorPage: React.FC = () => { export const EditorPage: React.FC = () => {
useTranslation() useTranslation()
const markdownContent = useNoteMarkdownContent()
const scrollSource = useRef<ScrollSource>(ScrollSource.EDITOR) const scrollSource = useRef<ScrollSource>(ScrollSource.EDITOR)
const documentContent = useApplicationState((state) => state.noteDetails.documentContent)
const editorMode: EditorMode = useApplicationState((state) => state.editorConfig.editorMode) const editorMode: EditorMode = useApplicationState((state) => state.editorConfig.editorMode)
const editorSyncScroll: boolean = useApplicationState((state) => state.editorConfig.syncScroll) const editorSyncScroll: boolean = useApplicationState((state) => state.editorConfig.syncScroll)
@ -98,21 +90,18 @@ export const EditorPage: React.FC = () => {
const leftPane = useMemo( const leftPane = useMemo(
() => ( () => (
<EditorPane <EditorPane
onContentChange={setNoteContent}
content={documentContent}
scrollState={scrollState.editorScrollState} scrollState={scrollState.editorScrollState}
onScroll={onEditorScroll} onScroll={onEditorScroll}
onMakeScrollSource={setEditorToScrollSource} onMakeScrollSource={setEditorToScrollSource}
/> />
), ),
[documentContent, onEditorScroll, scrollState.editorScrollState, setEditorToScrollSource] [onEditorScroll, scrollState.editorScrollState, setEditorToScrollSource]
) )
const rightPane = useMemo( const rightPane = useMemo(
() => ( () => (
<RenderIframe <EditorDocumentRenderer
frameClasses={'h-100 w-100'} frameClasses={'h-100 w-100'}
markdownContent={markdownContent}
onMakeScrollSource={setRendererToScrollSource} onMakeScrollSource={setRendererToScrollSource}
onFirstHeadingChange={updateNoteTitleByFirstHeading} onFirstHeadingChange={updateNoteTitleByFirstHeading}
onTaskCheckedChange={setCheckboxInMarkdownContent} onTaskCheckedChange={setCheckboxInMarkdownContent}
@ -121,7 +110,7 @@ export const EditorPage: React.FC = () => {
rendererType={RendererType.DOCUMENT} rendererType={RendererType.DOCUMENT}
/> />
), ),
[markdownContent, onMarkdownRendererScroll, scrollState.rendererScrollState, setRendererToScrollSource] [onMarkdownRendererScroll, scrollState.rendererScrollState, setRendererToScrollSource]
) )
return ( return (

View file

@ -19,6 +19,8 @@ import { handleUpload } from './upload-handler'
import { handleFilePaste, handleTablePaste, PasteEvent } from './tool-bar/utils/pasteHandlers' import { handleFilePaste, handleTablePaste, PasteEvent } from './tool-bar/utils/pasteHandlers'
import { useApplicationState } from '../../../hooks/common/use-application-state' import { useApplicationState } from '../../../hooks/common/use-application-state'
import './codemirror-imports' import './codemirror-imports'
import { setNoteContent } from '../../../redux/note-details/methods'
import { useNoteMarkdownContent } from '../../../hooks/common/use-note-markdown-content'
export interface EditorPaneProps { export interface EditorPaneProps {
onContentChange: (content: string) => void onContentChange: (content: string) => void
@ -50,13 +52,8 @@ interface DropEvent {
preventDefault: () => void preventDefault: () => void
} }
export const EditorPane: React.FC<EditorPaneProps & ScrollProps> = ({ export const EditorPane: React.FC<ScrollProps> = ({ scrollState, onScroll, onMakeScrollSource }) => {
onContentChange, const markdownContent = useNoteMarkdownContent()
content,
scrollState,
onScroll,
onMakeScrollSource
}) => {
const { t } = useTranslation() const { t } = useTranslation()
const maxLength = useApplicationState((state) => state.config.maxDocumentLength) const maxLength = useApplicationState((state) => state.config.maxDocumentLength)
const smartPasteEnabled = useApplicationState((state) => state.editorConfig.smartPaste) const smartPasteEnabled = useApplicationState((state) => state.editorConfig.smartPaste)
@ -128,10 +125,11 @@ export const EditorPane: React.FC<EditorPaneProps & ScrollProps> = ({
if (value.length <= maxLength) { if (value.length <= maxLength) {
maxLengthWarningAlreadyShown.current = false maxLengthWarningAlreadyShown.current = false
} }
onContentChange(value) setNoteContent(value)
}, },
[onContentChange, maxLength, maxLengthWarningAlreadyShown] [maxLength]
) )
const onEditorDidMount = useCallback( const onEditorDidMount = useCallback(
(mountedEditor: Editor) => { (mountedEditor: Editor) => {
setStatusBarInfo(createStatusInfo(mountedEditor, maxLength)) setStatusBarInfo(createStatusInfo(mountedEditor, maxLength))
@ -204,7 +202,7 @@ export const EditorPane: React.FC<EditorPaneProps & ScrollProps> = ({
<ToolBar editor={editor} /> <ToolBar editor={editor} />
<ControlledCodeMirror <ControlledCodeMirror
className={`overflow-hidden w-100 flex-fill ${ligaturesEnabled ? '' : 'no-ligatures'}`} className={`overflow-hidden w-100 flex-fill ${ligaturesEnabled ? '' : 'no-ligatures'}`}
value={content} value={markdownContent}
options={codeMirrorOptions} options={codeMirrorOptions}
onChange={onChange} onChange={onChange}
onPaste={onPaste} onPaste={onPaste}

View file

@ -10,15 +10,15 @@ import { store } from '../../../redux'
import { Trans, useTranslation } from 'react-i18next' import { Trans, useTranslation } from 'react-i18next'
import { download } from '../../common/download/download' import { download } from '../../common/download/download'
import { SidebarButton } from './sidebar-button' import { SidebarButton } from './sidebar-button'
import { useApplicationState } from '../../../hooks/common/use-application-state' import { useNoteMarkdownContent } from '../../../hooks/common/use-note-markdown-content'
export const ExportMarkdownSidebarEntry: React.FC = () => { export const ExportMarkdownSidebarEntry: React.FC = () => {
const { t } = useTranslation() const { t } = useTranslation()
const documentContent = useApplicationState((state) => state.noteDetails.documentContent) const markdownContent = useNoteMarkdownContent()
const onClick = useCallback(() => { const onClick = useCallback(() => {
const sanitized = sanitize(store.getState().noteDetails.noteTitle) const sanitized = sanitize(store.getState().noteDetails.noteTitle)
download(documentContent, `${sanitized !== '' ? sanitized : t('editor.untitledNote')}.md`, 'text/markdown') download(markdownContent, `${sanitized !== '' ? sanitized : t('editor.untitledNote')}.md`, 'text/markdown')
}, [documentContent, t]) }, [markdownContent, t])
return ( return (
<SidebarButton data-cy={'menu-export-markdown'} onClick={onClick} icon={'file-text'}> <SidebarButton data-cy={'menu-export-markdown'} onClick={onClick} icon={'file-text'}>

View file

@ -0,0 +1,20 @@
/*
* SPDX-FileCopyrightText: 2021 The HedgeDoc developers (see AUTHORS file)
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
import { useNoteMarkdownContent } from './use-note-markdown-content'
import { useApplicationState } from './use-application-state'
import { useMemo } from 'react'
/**
* Extracts the markdown content of the current note from the global application state and removes the frontmatter.
* @return the markdown content of the note without frontmatter
*/
export const useNoteMarkdownContentWithoutFrontmatter = (): string => {
const markdownContent = useNoteMarkdownContent()
const offsetLines = useApplicationState((state) => state.noteDetails.frontmatterRendererInfo.offsetLines)
return useMemo(() => markdownContent.split('\n').slice(offsetLines).join('\n'), [markdownContent, offsetLines])
}

View file

@ -6,6 +6,10 @@
import { useApplicationState } from './use-application-state' import { useApplicationState } from './use-application-state'
/**
* Extracts the markdown content of the current note from the global application state.
* @return the markdown content of the note
*/
export const useNoteMarkdownContent = (): string => { export const useNoteMarkdownContent = (): string => {
return useApplicationState((state) => state.noteDetails.markdownContent) return useApplicationState((state) => state.noteDetails.markdownContent)
} }

View file

@ -9,7 +9,6 @@ import { DateTime } from 'luxon'
import { NoteTextDirection, NoteType } from '../../components/common/note-frontmatter/types' import { NoteTextDirection, NoteType } from '../../components/common/note-frontmatter/types'
export const initialState: NoteDetails = { export const initialState: NoteDetails = {
documentContent: '',
markdownContent: '', markdownContent: '',
rawFrontmatter: '', rawFrontmatter: '',
frontmatterRendererInfo: { frontmatterRendererInfo: {

View file

@ -19,7 +19,7 @@ export const NoteDetailsReducer: Reducer<NoteDetails, NoteDetailsActions> = (
) => { ) => {
switch (action.type) { switch (action.type) {
case NoteDetailsActionType.SET_DOCUMENT_CONTENT: case NoteDetailsActionType.SET_DOCUMENT_CONTENT:
return buildStateFromDocumentContentUpdate(state, action.content) return buildStateFromMarkdownContentUpdate(state, action.content)
case NoteDetailsActionType.UPDATE_NOTE_TITLE_BY_FIRST_HEADING: case NoteDetailsActionType.UPDATE_NOTE_TITLE_BY_FIRST_HEADING:
return buildStateFromFirstHeadingUpdate(state, action.firstHeading) return buildStateFromFirstHeadingUpdate(state, action.firstHeading)
case NoteDetailsActionType.SET_NOTE_DATA_FROM_SERVER: case NoteDetailsActionType.SET_NOTE_DATA_FROM_SERVER:
@ -40,7 +40,7 @@ const TASK_REGEX = /(\s*(?:[-*+]|\d+[.)]) )(\[[ xX]])( .*)/
*/ */
const buildStateFromServerDto = (dto: NoteDto): NoteDetails => { const buildStateFromServerDto = (dto: NoteDto): NoteDetails => {
const newState = convertNoteDtoToNoteDetails(dto) const newState = convertNoteDtoToNoteDetails(dto)
return buildStateFromDocumentContentUpdate(newState, newState.documentContent) return buildStateFromMarkdownContentUpdate(newState, newState.markdownContent)
} }
/** /**
@ -55,13 +55,13 @@ const buildStateFromTaskListUpdate = (
changedLine: number, changedLine: number,
checkboxChecked: boolean checkboxChecked: boolean
): NoteDetails => { ): NoteDetails => {
const lines = state.documentContent.split('\n') const lines = state.markdownContent.split('\n')
const results = TASK_REGEX.exec(lines[changedLine]) const results = TASK_REGEX.exec(lines[changedLine])
if (results) { if (results) {
const before = results[1] const before = results[1]
const after = results[3] const after = results[3]
lines[changedLine] = `${before}[${checkboxChecked ? 'x' : ' '}]${after}` lines[changedLine] = `${before}[${checkboxChecked ? 'x' : ' '}]${after}`
return buildStateFromDocumentContentUpdate(state, lines.join('\n')) return buildStateFromMarkdownContentUpdate(state, lines.join('\n'))
} }
return state return state
} }
@ -69,17 +69,17 @@ const buildStateFromTaskListUpdate = (
/** /**
* Builds a {@link NoteDetails} redux state from a fresh document content. * Builds a {@link NoteDetails} redux state from a fresh document content.
* @param state The previous redux state. * @param state The previous redux state.
* @param documentContent The fresh document content consisting of the frontmatter and markdown part. * @param markdownContent The fresh document content consisting of the frontmatter and markdown part.
* @return An updated {@link NoteDetails} redux state. * @return An updated {@link NoteDetails} redux state.
*/ */
const buildStateFromDocumentContentUpdate = (state: NoteDetails, documentContent: string): NoteDetails => { const buildStateFromMarkdownContentUpdate = (state: NoteDetails, markdownContent: string): NoteDetails => {
const frontmatterExtraction = extractFrontmatter(documentContent) const frontmatterExtraction = extractFrontmatter(markdownContent)
if (!frontmatterExtraction.frontmatterPresent) { if (!frontmatterExtraction.frontmatterPresent) {
return { return {
...state, ...state,
documentContent: documentContent, markdownContent: markdownContent,
markdownContent: documentContent,
rawFrontmatter: '', rawFrontmatter: '',
noteTitle: generateNoteTitle(initialState.frontmatter, state.firstHeading),
frontmatter: initialState.frontmatter, frontmatter: initialState.frontmatter,
frontmatterRendererInfo: initialState.frontmatterRendererInfo frontmatterRendererInfo: initialState.frontmatterRendererInfo
} }
@ -87,8 +87,7 @@ const buildStateFromDocumentContentUpdate = (state: NoteDetails, documentContent
return buildStateFromFrontmatterUpdate( return buildStateFromFrontmatterUpdate(
{ {
...state, ...state,
documentContent: documentContent, markdownContent: markdownContent
markdownContent: documentContent.split('\n').slice(frontmatterExtraction.frontmatterLines).join('\n')
}, },
frontmatterExtraction frontmatterExtraction
) )
@ -113,7 +112,7 @@ const buildStateFromFrontmatterUpdate = (
...state, ...state,
rawFrontmatter: frontmatterExtraction.rawFrontmatterText, rawFrontmatter: frontmatterExtraction.rawFrontmatterText,
frontmatter: frontmatter, frontmatter: frontmatter,
noteTitle: generateNoteTitle(frontmatter), noteTitle: generateNoteTitle(frontmatter, state.firstHeading),
frontmatterRendererInfo: { frontmatterRendererInfo: {
offsetLines: frontmatterExtraction.frontmatterLines, offsetLines: frontmatterExtraction.frontmatterLines,
deprecatedSyntax: frontmatter.deprecatedTagsSyntax, deprecatedSyntax: frontmatter.deprecatedTagsSyntax,
@ -123,6 +122,7 @@ const buildStateFromFrontmatterUpdate = (
} catch (e) { } catch (e) {
return { return {
...state, ...state,
noteTitle: generateNoteTitle(initialState.frontmatter, state.firstHeading),
rawFrontmatter: frontmatterExtraction.rawFrontmatterText, rawFrontmatter: frontmatterExtraction.rawFrontmatterText,
frontmatter: initialState.frontmatter, frontmatter: initialState.frontmatter,
frontmatterRendererInfo: { frontmatterRendererInfo: {
@ -170,8 +170,7 @@ const generateNoteTitle = (frontmatter: NoteFrontmatter, firstHeading?: string)
*/ */
const convertNoteDtoToNoteDetails = (note: NoteDto): NoteDetails => { const convertNoteDtoToNoteDetails = (note: NoteDto): NoteDetails => {
return { return {
documentContent: note.content, markdownContent: note.content,
markdownContent: '',
rawFrontmatter: '', rawFrontmatter: '',
frontmatterRendererInfo: { frontmatterRendererInfo: {
frontmatterInvalid: false, frontmatterInvalid: false,

View file

@ -25,7 +25,6 @@ interface LastChange {
* Redux state containing the currently loaded note with its content and metadata. * Redux state containing the currently loaded note with its content and metadata.
*/ */
export interface NoteDetails { export interface NoteDetails {
documentContent: string
markdownContent: string markdownContent: string
rawFrontmatter: string rawFrontmatter: string
frontmatter: NoteFrontmatter frontmatter: NoteFrontmatter