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

Add the abillity to change save strategy from auto save to selectable #123

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
27 changes: 22 additions & 5 deletions components/container/edit-container.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import NoteState from 'libs/web/state/note'
import { has } from 'lodash'
import router, { useRouter } from 'next/router'
import { useCallback, useEffect } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import NoteTreeState from 'libs/web/state/tree'
import NoteNav from 'components/note-nav'
import UIState from 'libs/web/state/ui'
Expand All @@ -10,6 +10,7 @@ import useSettingsAPI from 'libs/web/api/settings'
import dynamic from 'next/dynamic'
import { useToast } from 'libs/web/hooks/use-toast'
import DeleteAlert from 'components/editor/delete-alert'
import useRouterWarning from 'libs/web/state/ui/useRouterWarning'

const MainEditor = dynamic(() => import('components/editor/main-editor'))

Expand All @@ -27,11 +28,13 @@ export const EditContainer = () => {
note,
} = NoteState.useContainer()
const { query } = useRouter()
const [isSaved, setSaved] = useState(true)
const pid = query.pid as string
const id = query.id as string
const isNew = has(query, 'new')
const { mutate: mutateSettings } = useSettingsAPI()
const toast = useToast()
const saveRef = useRef<() => void>()

const loadNoteById = useCallback(
async (id: string) => {
Expand Down Expand Up @@ -94,18 +97,32 @@ export const EditContainer = () => {
useEffect(() => {
abortFindNote()
loadNoteById(id)
setSaved(true)
}, [loadNoteById, abortFindNote, id])

useEffect(() => {
updateTitle(note?.title)
}, [note?.title, updateTitle])
updateTitle(`${!isSaved && settings.explicitSave ? '*' : ''}${note?.title}`)
}, [isSaved, note?.title, settings.explicitSave, updateTitle])

useRouterWarning(!isSaved && settings.explicitSave, () => {
return confirm('Warning! You have unsaved changes.')
})

return (
<>
<NoteNav />
<NoteNav
explicitSave={settings.explicitSave}
isSaved={isSaved}
saveRef={saveRef}
/>
<DeleteAlert />
<section className="h-full">
<MainEditor note={note} />
<MainEditor
note={note}
explicitSave={settings.explicitSave}
saveState={setSaved}
saveRef={saveRef}
/>
</section>
</>
)
Expand Down
28 changes: 25 additions & 3 deletions components/editor/editor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { FC, useEffect, useState } from 'react'
import { FC, MutableRefObject, useEffect, useState } from 'react'
import { use100vh } from 'react-div-100vh'
import MarkdownEditor, { Props } from 'rich-markdown-editor'
import { useEditorTheme } from './theme'
Expand All @@ -12,9 +12,18 @@ import { useEmbeds } from './embeds'

export interface EditorProps extends Pick<Props, 'readOnly'> {
isPreview?: boolean
explicitSave?: boolean
saveState?: (state: boolean) => void
saveRef?: MutableRefObject<(() => void) | undefined>
}

const Editor: FC<EditorProps> = ({ readOnly, isPreview }) => {
const Editor: FC<EditorProps> = ({
readOnly,
isPreview,
explicitSave,
saveState,
saveRef,
}) => {
const {
onSearchLink,
onCreateLink,
Expand All @@ -39,14 +48,27 @@ const Editor: FC<EditorProps> = ({ readOnly, isPreview }) => {
setHasMinHeight((backlinks?.length ?? 0) <= 0)
}, [backlinks, isPreview])

useEffect(() => {
const handleKeyDown = () => {
if (editorEl.current?.value) {
onEditorChange(editorEl.current?.value)
saveState && saveState(true)
}
}
if (saveRef) (saveRef as MutableRefObject<() => void>).current = handleKeyDown
}, [saveState, saveRef, editorEl, onEditorChange])

return (
<>
<MarkdownEditor
readOnly={readOnly}
id={note?.id}
ref={editorEl}
value={mounted ? note?.content : ''}
onChange={onEditorChange}
onChange={
explicitSave ? () => saveState && saveState(false) : onEditorChange
}
onSave={explicitSave ? () => (saveRef as MutableRefObject<() => void>)?.current?.() : undefined}
placeholder={dictionary.editorPlaceholder}
theme={editorTheme}
uploadImage={(file) => onUploadImage(file, note?.id)}
Expand Down
4 changes: 3 additions & 1 deletion components/icon-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import {
ExternalLinkIcon,
BookmarkAltIcon,
PuzzleIcon,
ChevronDoubleUpIcon
ChevronDoubleUpIcon,
SaveIcon,
} from '@heroicons/react/outline'

export const ICONS = {
Expand All @@ -40,6 +41,7 @@ export const ICONS = {
BookmarkAlt: BookmarkAltIcon,
Puzzle: PuzzleIcon,
ChevronDoubleUp: ChevronDoubleUpIcon,
Save: SaveIcon,
}

const IconButton = forwardRef<
Expand Down
23 changes: 20 additions & 3 deletions components/note-nav.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import classNames from 'classnames'
import NoteState from 'libs/web/state/note'
import UIState from 'libs/web/state/ui'
import { useCallback, MouseEvent } from 'react'
import { useCallback, MouseEvent, MutableRefObject } from 'react'
import { CircularProgress, Tooltip } from '@material-ui/core'
import NoteTreeState from 'libs/web/state/tree'
import { Breadcrumbs } from '@material-ui/core'
Expand Down Expand Up @@ -33,8 +33,13 @@ const MenuButton = () => {
></IconButton>
)
}
type Props = {
explicitSave?: boolean
isSaved?: boolean
saveRef?: MutableRefObject<(() => void) | undefined>
}

const NoteNav = () => {
const NoteNav = ({ explicitSave, isSaved, saveRef }: Props) => {
const { t } = useI18n()
const { note, loading } = NoteState.useContainer()
const { ua } = UIState.useContainer()
Expand All @@ -61,9 +66,11 @@ const NoteNav = () => {

const handleClickOpenInTree = useCallback(() => {
if (!note) return
showItem(note);
showItem(note)
}, [note, showItem])

const saveNote = useCallback(() => saveRef?.current?.(), [saveRef])

return (
<nav
className={classNames(
Expand All @@ -77,6 +84,16 @@ const NoteNav = () => {
}}
>
{ua.isMobileOnly ? <MenuButton /> : null}

{ua.isMobileOnly && explicitSave ? (
<IconButton
icon="Save"
className="mr-2 active:bg-gray-400"
onClick={saveNote}
disabled={isSaved}
></IconButton>
) : null}

<NavButtonGroup />
<div className="flex-auto ml-4">
{note && (
Expand Down
4 changes: 3 additions & 1 deletion components/portal/link-toolbar/link-toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ const LinkToolbar = () => {
if (!result) {
return
}
const bookmarkUrl = `/api/extract?type=${type}&url=${encodeURIComponent(href)}`
const bookmarkUrl = `/api/extract?type=${type}&url=${encodeURIComponent(
href
)}`
const transaction = state.tr.replaceWith(
result.pos,
result.pos + result.node.nodeSize,
Expand Down
6 changes: 4 additions & 2 deletions components/portal/sidebar-menu/sidebar-menu-item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ interface ItemProps {

export const SidebarMenuItem = forwardRef<HTMLLIElement, ItemProps>(
({ item }, ref) => {
const { settings: { settings } } = UIState.useContainer()
const {
settings: { settings },
} = UIState.useContainer()
const { removeNote, mutateNote } = NoteState.useContainer()
const {
menu: { close, data },
Expand Down Expand Up @@ -66,7 +68,7 @@ export const SidebarMenuItem = forwardRef<HTMLLIElement, ItemProps>(
})
}
}, [close, data, mutateNote])

const toggleWidth = useCallback(() => {
close()
if (data?.id) {
Expand Down
2 changes: 1 addition & 1 deletion components/portal/sidebar-menu/sidebar-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const SidebarMenu: FC = () => {
{
text: t('Toggle width'),
// TODO: or SwitchHorizontal?
icon: <SelectorIcon style={{ transform: "rotate(90deg)" }} />,
icon: <SelectorIcon style={{ transform: 'rotate(90deg)' }} />,
handler: MENU_HANDLER_NAME.TOGGLE_WIDTH,
},
],
Expand Down
34 changes: 34 additions & 0 deletions components/settings/explicit-save.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { FC, useCallback, ChangeEvent } from 'react'
import { MenuItem, TextField } from '@material-ui/core'
import router from 'next/router'
import { defaultFieldConfig } from './settings-container'
import useI18n from 'libs/web/hooks/use-i18n'
import UIState from 'libs/web/state/ui'

export const ExplicitSave: FC = () => {
const { t } = useI18n()
const {
settings: { settings, updateSettings },
} = UIState.useContainer()

const handleChange = useCallback(
async (event: ChangeEvent<HTMLInputElement>) => {
await updateSettings({ explicitSave: Boolean(event.target.value) })
router.reload()
},
[updateSettings]
)

return (
<TextField
{...defaultFieldConfig}
label={t('Save strategy')}
value={settings.explicitSave ? 1 : 0}
onChange={handleChange}
select
>
<MenuItem value={1}>{t('Explicit save (ctrl + s)')}</MenuItem>
<MenuItem value={0}>{t('Auto save')}</MenuItem>
</TextField>
)
}
2 changes: 2 additions & 0 deletions components/settings/settings-container.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { ImportOrExport } from './import-or-export'
import { SnippetInjection } from './snippet-injection'
import useI18n from 'libs/web/hooks/use-i18n'
import { SettingsHeader } from './settings-header'
import { ExplicitSave } from './explicit-save'

export const defaultFieldConfig: TextFieldProps = {
fullWidth: true,
Expand Down Expand Up @@ -36,6 +37,7 @@ export const SettingsContainer: FC = () => {
<Language></Language>
<Theme></Theme>
<EditorWidth></EditorWidth>
<ExplicitSave></ExplicitSave>
<HR />
<SettingsHeader
id="import-and-export"
Expand Down
2 changes: 1 addition & 1 deletion components/sidebar/sidebar-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const SideBarList = () => {
moveItem,
mutateItem,
initLoaded,
collapseAllItems
collapseAllItems,
} = NoteTreeState.useContainer()

const onExpand = useCallback(
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ version: '2'

services:
minio:
image: minio/minio
image: minio/minio:RELEASE.2020-11-12T22-33-34Z
ports:
- '9000:9000'
environment:
Expand Down
7 changes: 6 additions & 1 deletion libs/shared/meta.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,9 @@ export const PAGE_META_KEY = <const>[

export type metaKey = typeof PAGE_META_KEY[number]

export const NUMBER_KEYS: metaKey[] = ['deleted', 'shared', 'pinned', 'editorsize']
export const NUMBER_KEYS: metaKey[] = [
'deleted',
'shared',
'pinned',
'editorsize',
]
8 changes: 7 additions & 1 deletion libs/shared/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export interface Settings {
last_visit?: string
locale: Locale
injection?: string
editorsize: EDITOR_SIZE;
editorsize: EDITOR_SIZE
explicitSave: boolean
}

export const DEFAULT_SETTINGS: Settings = Object.freeze({
Expand All @@ -19,6 +20,7 @@ export const DEFAULT_SETTINGS: Settings = Object.freeze({
sidebar_is_fold: false,
locale: Locale.EN,
editorsize: EDITOR_SIZE.SMALL,
explicitSave: false,
})

export function formatSettings(body: Record<string, any> = {}) {
Expand Down Expand Up @@ -60,5 +62,9 @@ export function formatSettings(body: Record<string, any> = {}) {
settings.editorsize = body.editorsize
}

if (isBoolean(body.explicitSave)) {
settings.explicitSave = body.explicitSave
}

return settings
}
2 changes: 1 addition & 1 deletion libs/web/hooks/use-mounted.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'

const useMounted = () => {
const useMounted = () => {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
Expand Down
36 changes: 36 additions & 0 deletions libs/web/state/ui/useRouterWarning.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import Router from 'next/router'
import { useEffect } from 'react'

export default function useRouterWarning(
changes: boolean,
callback: () => boolean
) {
useEffect(() => {
if (!changes) {
return
}
const routeChangeStartCallback = () => {
const ok = callback()
if (!ok) {
Router.events.emit('routeChangeError')
throw 'Abort route changes due to unsaved changes'
}
}
Router.events.on('routeChangeStart', routeChangeStartCallback)
return () => Router.events.off('routeChangeStart', routeChangeStartCallback)
}, [changes, callback])

useEffect(() => {
if (!changes) {
return
}
const callback = (e: BeforeUnloadEvent) => {
e.preventDefault()
return true
}
window.onbeforeunload = callback
return () => {
window.onbeforeunload = null
}
}, [changes, callback])
}
2 changes: 1 addition & 1 deletion locales/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,4 +116,4 @@
"Warning": "تحذير",
"Warning notice": "إشعار التحذير",
"Write something nice…": "اكتب شيئًا لطيفًا …"
}
}
Loading