diff --git a/apps/mobile/app.json b/apps/mobile/app.json index 5f3679d..5a66a2d 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -28,12 +28,21 @@ "expo-splash-screen", { "backgroundColor": "#faf9f5", - "dark": { "backgroundColor": "#121110" }, + "dark": { + "backgroundColor": "#121110" + }, "image": "./assets/images/splash-icon.png", "imageWidth": 76 } ], - "expo-sqlite" + "expo-sqlite", + "expo-image", + [ + "expo-image-picker", + { + "photosPermission": "DailyNote adds the photos you pick to the note you are writing. They are copied into the app and stay on this device." + } + ] ], "experiments": { "typedRoutes": true, diff --git a/apps/mobile/package.json b/apps/mobile/package.json index c973df7..b29b575 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -20,8 +20,11 @@ "expo": "~57.0.8", "expo-constants": "~57.0.7", "expo-crypto": "~57.0.1", + "expo-file-system": "~57.0.1", "expo-font": "~57.0.1", "expo-haptics": "~57.0.1", + "expo-image": "~57.0.1", + "expo-image-picker": "~57.0.7", "expo-linking": "~57.0.4", "expo-router": "~57.0.9", "expo-splash-screen": "~57.0.5", diff --git a/apps/mobile/src/app/index.tsx b/apps/mobile/src/app/index.tsx index 21c3c4c..7d4c9f0 100644 --- a/apps/mobile/src/app/index.tsx +++ b/apps/mobile/src/app/index.tsx @@ -1,12 +1,23 @@ -import { hasCommitmentTag, parseHashtags } from '@dailynote/core'; +import { + documentToText, + hasCommitmentTag, + insertImage, + isEmptyDocument, + paragraph, + parseHashtags, + serializeDocument, + setAlign, + toggleBullet, + type Block, +} from '@dailynote/core'; import { Link } from 'expo-router'; import { useCallback, useEffect, useRef, useState } from 'react'; import { KeyboardAvoidingView, Platform, Pressable, + ScrollView, Text, - TextInput, View, } from 'react-native'; import Animated, { @@ -18,6 +29,9 @@ import Animated, { } from 'react-native-reanimated'; import { SafeAreaView } from 'react-native-safe-area-context'; +import { BlockEditor, type BlockEditorHandle } from '@/components/block-editor'; +import { BlockToolbar } from '@/components/block-toolbar'; +import { pickImage } from '@/lib/attachments'; import { todayHeading } from '@/lib/format'; import { haptics } from '@/lib/haptics'; import * as motion from '@/lib/motion'; @@ -35,13 +49,18 @@ import { useTheme } from '@/theme'; export default function Composer() { const theme = useTheme(); const { create, promote, notes } = useNotes(); - const inputRef = useRef(null); - const [body, setBody] = useState(''); + const [blocks, setBlocks] = useState(() => [paragraph()]); + const [focused, setFocused] = useState(null); + const editor = useRef(null); const [saving, setSaving] = useState(false); + // Bumped after a save: remounting the editor is what clears it and returns + // the caret to a fresh title, since autoFocus only fires on mount. + const [draft, setDraft] = useState(0); + const body = documentToText(blocks); const tags = parseHashtags(body); const willCommit = hasCommitmentTag(body); - const canSave = body.trim().length > 0 && !saving; + const canSave = !isEmptyDocument(blocks) && !saving; // Save pill: springs between its disabled and enabled state instead of // snapping, and dips under the finger while pressed. @@ -81,20 +100,22 @@ export default function Composer() { })); const save = useCallback(async () => { - if (body.trim().length === 0 || saving) return; + if (isEmptyDocument(blocks) || saving) return; setSaving(true); try { - const note = await create(body); + // Both representations are written together: the document is the note, + // `body` is the plain text everything else reads off it. + const note = await create(body, { doc: serializeDocument(blocks) }); // Writing #do promotes the note to a commitment on the spot -- no extra // tap, because the tap is what stops people from doing it. if (hasCommitmentTag(body)) await promote(note.id); haptics.tap(); - setBody(''); - inputRef.current?.focus(); + setBlocks([paragraph()]); + setDraft((count) => count + 1); } finally { setSaving(false); } - }, [body, saving, create, promote]); + }, [blocks, body, saving, create, promote]); return ( @@ -138,18 +159,24 @@ export default function Composer() { {todayHeading()} - + + + ) : null} + + { + if (focused === null) return; + setBlocks(toggleBullet(blocks, focused)); + // The toolbar took the tap; give the caret straight back so the + // keyboard never drops and the next word goes where it should. + editor.current?.restoreFocus(); + }} + onAlign={(align) => { + if (focused === null) return; + setBlocks(setAlign(blocks, focused, align)); + editor.current?.restoreFocus(); + }} + onAddImage={async () => { + const picked = await pickImage(); + if (picked === null) return; + // Functional update: the picker is a round trip through another + // screen, and `blocks` here is from before it opened. + setBlocks((current) => insertImage(current, focused, picked)); + }} + /> diff --git a/apps/mobile/src/app/note/[id].tsx b/apps/mobile/src/app/note/[id].tsx index b40ca53..81bef0d 100644 --- a/apps/mobile/src/app/note/[id].tsx +++ b/apps/mobile/src/app/note/[id].tsx @@ -1,25 +1,37 @@ -import { threadOf, type Note } from '@dailynote/core'; +import { + insertImage, + parseDocument, + setAlign, + threadOf, + toggleBullet, + type Block, + type Note, +} from '@dailynote/core'; import { Stack, useLocalSearchParams, useRouter } from 'expo-router'; -import { useMemo, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { KeyboardAvoidingView, Platform, Pressable, ScrollView, Text, - TextInput, View, } from 'react-native'; import Animated from 'react-native-reanimated'; +import { BlockEditor, type BlockEditorHandle } from '@/components/block-editor'; +import { BlockToolbar } from '@/components/block-toolbar'; +import { pickImage } from '@/lib/attachments'; import { comesBack, formatDay } from '@/lib/format'; import { haptics } from '@/lib/haptics'; import * as motion from '@/lib/motion'; import { AnimatedPressable } from '@/lib/motion'; import { useNotes } from '@/store/notes-store'; -import { useTheme } from '@/theme'; -/** Note detail: edit the body, promote to a commitment, read the thread. */ +/** How long the writing has to stop before an edit is written to SQLite. */ +const AUTOSAVE_MS = 600; + +/** Note detail: edit the note, promote to a commitment, read the thread. */ export default function NoteDetail() { const { id } = useLocalSearchParams<{ id: string }>(); const { notes } = useNotes(); @@ -36,17 +48,56 @@ export default function NoteDetail() { ); } - // Keyed on the note id so the draft initialises from the stored body once, - // on mount, rather than being synced back by an effect -- store refreshes - // must never clobber what the user is currently typing. + // Keyed on the note id so the draft initialises from storage once, on mount, + // rather than being synced back by an effect -- store refreshes must never + // clobber what the user is currently typing. return ; } function NoteEditor({ note }: { note: Note }) { - const theme = useTheme(); const router = useRouter(); - const { notes, setBody, softDelete, promote } = useNotes(); - const [draft, setDraft] = useState(note.body); + const { notes, setContent, softDelete, promote } = useNotes(); + const [blocks, setBlocks] = useState(() => parseDocument(note.doc, note.body)); + const [focused, setFocused] = useState(null); + const editor = useRef(null); + + // Autosave, because there is no longer one input whose blur means "done": + // with a block per line, blur fires every time the caret moves between them. + // So the note is written once the writing pauses, and again on the way out. + const latest = useRef(blocks); + const unsaved = useRef(false); + const timer = useRef | null>(null); + + const flush = useCallback(() => { + if (!unsaved.current) return; + unsaved.current = false; + void setContent(note.id, latest.current); + }, [note.id, setContent]); + + // Kept in a ref so the unmount effect below can stay on empty deps. `flush` + // closes over `setContent`, whose identity changes on every store refresh -- + // an effect depending on it would re-run its cleanup, and saving from a + // cleanup that fires on every save is a loop. + const flushRef = useRef(flush); + useEffect(() => { + flushRef.current = flush; + }); + + useEffect(() => { + return () => { + if (timer.current !== null) clearTimeout(timer.current); + flushRef.current(); + }; + }, []); + + const change = useCallback((next: Block[]) => { + setBlocks(next); + latest.current = next; + unsaved.current = true; + + if (timer.current !== null) clearTimeout(timer.current); + timer.current = setTimeout(() => flushRef.current(), AUTOSAVE_MS); + }, []); const updates = useMemo( () => threadOf(notes, note.rootId).filter((candidate) => candidate.id !== note.id), @@ -78,21 +129,21 @@ function NoteEditor({ note }: { note: Note }) { }} /> - - + + {formatDay(note.createdAt)} - { - if (draft !== note.body) void setBody(note.id, draft); - }} - multiline - textAlignVertical="top" - className="min-h-[220px] px-5 pt-3 font-serif text-[21px] leading-8 text-ink web:outline-none dark:text-ink-dark" - selectionColor={theme.accent} + {/* The follow-through loop's entry point. Promoting crossfades the @@ -152,6 +203,29 @@ function NoteEditor({ note }: { note: Note }) { ) : null} + + { + if (focused === null) return; + change(toggleBullet(blocks, focused)); + // The toolbar took the tap; give the caret straight back so the + // keyboard never drops and the next word goes where it should. + editor.current?.restoreFocus(); + }} + onAlign={(align) => { + if (focused === null) return; + change(setAlign(blocks, focused, align)); + editor.current?.restoreFocus(); + }} + onAddImage={async () => { + const picked = await pickImage(); + if (picked === null) return; + // `latest` rather than `blocks`: the picker is a round trip through + // another screen, and this closure is from before it opened. + change(insertImage(latest.current, focused, picked)); + }} + /> ); } diff --git a/apps/mobile/src/components/block-editor.tsx b/apps/mobile/src/components/block-editor.tsx new file mode 100644 index 0000000..62c7463 --- /dev/null +++ b/apps/mobile/src/components/block-editor.tsx @@ -0,0 +1,403 @@ +import { + bullet, + isTextBlock, + paragraph, + removeBlock, + type Align, + type Block, + type ImageBlock, + type TextBlock, +} from '@dailynote/core'; +import { Image } from 'expo-image'; +import { useCallback, useEffect, useImperativeHandle, useRef, useState, type Ref } from 'react'; +import { + Platform, + Pressable, + Text, + TextInput, + useWindowDimensions, + type NativeSyntheticEvent, + type TextInputKeyPressEventData, + type TextInputSelectionChangeEventData, +} from 'react-native'; +import Animated from 'react-native-reanimated'; + +import { attachmentUri } from '@/lib/attachments'; +import { haptics } from '@/lib/haptics'; +import * as motion from '@/lib/motion'; +import { useTheme } from '@/theme'; + +/** + * The writing surface: one `TextInput` per block. + * + * A single multiline input cannot give a line its own alignment, hang a bullet + * in a gutter, or hold an image between two paragraphs -- so a note is a column + * of blocks, each editable in place, and what you see is what is stored. + * + * Two interactions do the structural work, and both are deliberately driven by + * text rather than key events, because key events are the unreliable part of + * React Native's text input on Android: + * + * - **Enter splits.** The newline arrives through `onChangeText`, and the block + * is cut at the caret. A multi-line paste splits into as many blocks. + * - **Backspace at the start merges** with the block above, which is the one + * place `onKeyPress` is needed -- there is no other signal for it. + * + * The first paragraph is the note's title. Not a separate field: the first line + * has always been the title (`deriveTitle`), so this makes it *look* like what + * it already was. + */ + +/** How long a blur waits before it counts, so moving block to block is quiet. */ +const BLUR_GRACE_MS = 80; + +/** The writing surface's horizontal padding, doubled. Images fit inside it. */ +const GUTTERS = 40; + +/** Tall enough to read, short enough that a portrait photo is not a scroll. */ +const MAX_IMAGE_HEIGHT = 420; + +/** Where a block sits in its row when it is narrower than the line. */ +const ROW_ITEMS: Record = { + left: 'flex-start', + center: 'center', + right: 'flex-end', +}; + +export interface BlockEditorProps { + blocks: Block[]; + onChange: (blocks: Block[]) => void; + /** Shown in the title block while the note is empty. */ + placeholder?: string; + autoFocus?: boolean; + /** Which block the caret is in, so a toolbar knows what it is acting on. */ + onFocusChange?: (index: number | null) => void; + ref?: Ref; +} + +export interface BlockEditorHandle { + /** Returns the caret to where it was. For a toolbar that stole the focus. */ + restoreFocus: () => void; +} + +interface Caret { + id: string; + offset: number; +} + +export function BlockEditor({ + blocks, + onChange, + placeholder, + autoFocus, + onFocusChange, + ref, +}: BlockEditorProps) { + const theme = useTheme(); + + const inputs = useRef(new Map()); + /** Last known caret per block, so a keystroke knows where it landed. */ + const selections = useRef(new Map()); + + // Where the caret must go after a structural edit. Held in state for one + // render: passing `selection` to a TextInput takes control of it, so it is + // released as soon as the input reports the position back. + const [caret, setCaret] = useState(null); + + useEffect(() => { + if (caret === null) return; + inputs.current.get(caret.id)?.focus(); + }, [caret]); + + // The block the caret is in. Cleared on a short delay, because moving + // between two blocks blurs one before it focuses the next -- clearing + // immediately would flicker the toolbar off and back on every time. + const focused = useRef(null); + const blurTimer = useRef | null>(null); + + useEffect(() => { + return () => { + if (blurTimer.current !== null) clearTimeout(blurTimer.current); + }; + }, []); + + const report = useCallback( + (id: string | null) => { + focused.current = id; + if (onFocusChange === undefined) return; + onFocusChange(id === null ? null : blocks.findIndex((block) => block.id === id)); + }, + [blocks, onFocusChange], + ); + + useImperativeHandle( + ref, + () => ({ + restoreFocus() { + const id = focused.current; + if (id === null) return; + const selection = selections.current.get(id); + setCaret({ id, offset: selection?.start ?? 0 }); + }, + }), + [], + ); + + const focusLast = useCallback(() => { + const last = [...blocks].reverse().find(isTextBlock); + if (last === undefined) return; + setCaret({ id: last.id, offset: last.text.length }); + }, [blocks]); + + const changeText = useCallback( + (index: number, text: string) => { + const block = blocks[index]; + if (block === undefined || !isTextBlock(block)) return; + + if (!text.includes('\n')) { + const next = [...blocks]; + next[index] = { ...block, text }; + onChange(next); + return; + } + + // Enter on an empty bullet ends the list rather than adding another + // empty one -- the way out of a list is the same key that built it. + if (block.type === 'bullet' && block.text.length === 0 && text === '\n') { + const next = [...blocks]; + next[index] = { ...block, type: 'paragraph' }; + onChange(next); + return; + } + + // A newline appeared: cut the block at the caret. The new blocks inherit + // this one's type and alignment, so a list goes on being a list and a run + // of centred lines stays centred. + const parts = text.split('\n'); + const make = block.type === 'bullet' ? bullet : paragraph; + const created = parts.slice(1).map((part) => make(part, block.align)); + + const next = [...blocks]; + next.splice(index, 1, { ...block, text: parts[0]! }, ...created); + onChange(next); + + setCaret(caretAfterInsert(block, text, selections.current.get(block.id), parts, created)); + }, + [blocks, onChange], + ); + + const keyPress = useCallback( + (index: number, event: NativeSyntheticEvent) => { + if (event.nativeEvent.key !== 'Backspace') return; + + const block = blocks[index]; + if (block === undefined || !isTextBlock(block)) return; + + // Only when there is nothing to the left to delete. + const selection = selections.current.get(block.id); + if (selection === undefined || selection.start !== 0 || selection.end !== 0) return; + + // This keystroke is the structural edit, and nothing else. Without this + // the web build also deletes a character: the default action runs after + // the re-render, by which time the caret sits mid-text somewhere else. A + // no-op on native, where the caret was at 0 with nothing before it. + event.preventDefault(); + + const next = [...blocks]; + + // Backspace leaves the list before it starts deleting text, so the first + // press un-bullets the line instead of joining it to the one above. + if (block.type === 'bullet') { + next[index] = { ...block, type: 'paragraph' }; + onChange(next); + return; + } + + if (index === 0) return; + const above = blocks[index - 1]!; + + if (!isTextBlock(above)) { + // Backspacing into an image deletes the image, which is what the + // gesture means -- there is nothing to merge text into. + next.splice(index - 1, 1); + onChange(next); + return; + } + + // Merge upward, keeping the block above so the caret has somewhere that + // already exists to land, at the seam between the two texts. + next.splice(index - 1, 2, { ...above, text: above.text + block.text }); + onChange(next); + setCaret({ id: above.id, offset: above.text.length }); + }, + [blocks, onChange], + ); + + const selectionChange = useCallback( + (block: TextBlock, event: NativeSyntheticEvent) => { + selections.current.set(block.id, event.nativeEvent.selection); + // The requested position has been applied; hand the caret back to the user. + if (caret?.id === block.id) setCaret(null); + }, + [caret], + ); + + return ( + <> + {blocks.map((block, index) => { + if (block.type === 'image') { + return ( + { + haptics.tap(); + onChange(removeBlock(blocks, index)); + }} + /> + ); + } + + // Only a plain first line is the title. Bullet the top line and it + // becomes an ordinary list item, which is what it now is. + const isTitle = index === 0 && block.type === 'paragraph'; + + return ( + + {block.type === 'bullet' ? ( + // A fixed gutter rather than a character in the text: the marker + // is structure, so it cannot be typed over, and a line that wraps + // hangs under the first word instead of under the dot. + + • + + ) : null} + + { + inputs.current.set(block.id, input); + }} + value={block.text} + onChangeText={(text) => changeText(index, text)} + onKeyPress={(event) => keyPress(index, event)} + onSelectionChange={(event) => selectionChange(block, event)} + onFocus={() => report(block.id)} + onBlur={() => { + if (blurTimer.current !== null) clearTimeout(blurTimer.current); + blurTimer.current = setTimeout(() => { + if (focused.current === block.id) report(null); + }, BLUR_GRACE_MS); + }} + selection={caret?.id === block.id ? { start: caret.offset, end: caret.offset } : undefined} + autoFocus={autoFocus && isTitle} + multiline + // A multiline input grows with its content on iOS and Android, + // but react-native-web renders `