diff --git a/.github/workflows/canvas-audit.yml b/.github/workflows/canvas-audit.yml index 4f1103d..a79b1f3 100644 --- a/.github/workflows/canvas-audit.yml +++ b/.github/workflows/canvas-audit.yml @@ -27,6 +27,8 @@ jobs: env: IOS_SIMULATOR_FAMILY: ipad steps: + - name: Disable Spotlight indexing on the disposable audit runner + run: sudo mdutil -i off / - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: @@ -106,6 +108,7 @@ jobs: -only-testing:OpenNotesUITests/NotebookInteractionUITests/testDrawingOverImageSurvivesUndoAndReload \ -only-testing:OpenNotesUITests/NotebookInteractionUITests/testInvalidNativePayloadShowsRecoveryWithoutOverwritingNote \ -only-testing:OpenNotesUITests/NotebookInteractionUITests/testPreferencesAndReturnToPen \ + -only-testing:OpenNotesUITests/NotebookInteractionUITests/testLineSpacingSurvivesRelaunch \ -only-testing:OpenNotesUITests/NotebookInteractionUITests/testChoosePhotoCover \ -collect-test-diagnostics never - name: Preserve interaction test evidence diff --git a/app/folder/[id].tsx b/app/folder/[id].tsx index 8dfb6cc..14ec23e 100644 --- a/app/folder/[id].tsx +++ b/app/folder/[id].tsx @@ -28,7 +28,7 @@ import { listFolders, renameFolder, } from '../../src/services/foldersRepo'; -import type { BackgroundType, FolderMetadata, NoteMetadata } from '../../src/types/note'; +import type { BackgroundType, FolderMetadata, LineSpacing, NoteMetadata } from '../../src/types/note'; type Action = | { kind: 'createNoteBackground' } @@ -72,7 +72,7 @@ export default function FolderScreen() { }, [refresh]), ); - const handleCreateNote = useCallback(async (backgroundType: BackgroundType, title: string) => { + const handleCreateNote = useCallback(async (backgroundType: BackgroundType, title: string, lineSpacing: LineSpacing) => { if (!folder || creatingNoteRef.current) return; creatingNoteRef.current = true; setAction(null); @@ -82,6 +82,7 @@ export default function FolderScreen() { const meta = await createNote({ folderId: folder.id, backgroundType, + lineSpacing, title: title.trim() || undefined, }); router.push(`/note/${meta.id}`); @@ -185,7 +186,7 @@ export default function FolderScreen() { void handleCreateNote(type, title)} + onPick={(type, title, lineSpacing) => void handleCreateNote(type, title, lineSpacing)} onClose={() => setAction(null)} /> diff --git a/app/index.tsx b/app/index.tsx index 0def537..8d96cfa 100644 --- a/app/index.tsx +++ b/app/index.tsx @@ -46,7 +46,7 @@ import { listFolders, renameFolder, } from '../src/services/foldersRepo'; -import type { BackgroundType, FolderMetadata, NoteMetadata } from '../src/types/note'; +import type { BackgroundType, FolderMetadata, LineSpacing, NoteMetadata } from '../src/types/note'; import { t } from '../src/i18n'; type Action = @@ -154,7 +154,7 @@ export default function LibraryScreen() { [router], ); - const handleCreateNote = useCallback(async (backgroundType: BackgroundType, title: string) => { + const handleCreateNote = useCallback(async (backgroundType: BackgroundType, title: string, lineSpacing: LineSpacing) => { if (creatingNoteRef.current) return; creatingNoteRef.current = true; setAction(null); @@ -163,6 +163,7 @@ export default function LibraryScreen() { const meta = await createNote({ folderId: libraryLayout === 'columns' && selection.kind === 'folder' ? selection.id : null, backgroundType, + lineSpacing, title: title.trim() || undefined, }); openNote(meta.id); @@ -387,7 +388,7 @@ export default function LibraryScreen() { void handleCreateNote(type, title)} + onPick={(type, title, lineSpacing) => void handleCreateNote(type, title, lineSpacing)} onClose={() => setAction(null)} /> diff --git a/app/note/[id].tsx b/app/note/[id].tsx index 0a7d85d..8f72871 100644 --- a/app/note/[id].tsx +++ b/app/note/[id].tsx @@ -60,6 +60,7 @@ import { readNoteBody, renameNote, saveNoteBody, + setNoteLineSpacing, } from '../../src/services/notesRepo'; import { createEmptyNotebookData } from '../../src/services/noteBodyStorage'; import { @@ -72,11 +73,12 @@ import { recordSuccessfulNoteSave } from '../../src/services/lifecycleService'; import { duplicateAssetPosition } from '../../src/utils/continuousAssets'; import { documentVisualLayers, imageAtContentPoint } from '../../src/utils/visualLayerOrder'; import { insertImagePosition } from '../../src/utils/insertImagePosition'; +import { paperBackgroundType, resolveLineSpacing } from '../../src/utils/paperSpacing'; import { textBoxId, insertedElementId } from '../../src/utils/id'; import { spacing } from '../../src/theme/spacing'; import { t } from '../../src/i18n'; import { typography } from '../../src/theme/typography'; -import type { NoteMetadata } from '../../src/types/note'; +import type { LineSpacing, NoteMetadata } from '../../src/types/note'; import type { ToolDescriptor } from '../../src/utils/toolPalette'; const CONTENT_PADDING = 16; @@ -160,6 +162,8 @@ export default function NoteScreen() { const lastPenToolRef = useRef<'pen' | 'highlighter' | 'crayon' | 'calligraphy'>('pen'); const [metadata, setMetadata] = useState(null); + const [lineSpacingBusy, setLineSpacingBusy] = useState(false); + const lineSpacingBusyRef = useRef(false); const [enginePages, setEnginePages] = useState([]); const enginePagesRef = useRef(enginePages); const updateEnginePages = useCallback((pages: NotebookPage[]) => { @@ -788,6 +792,23 @@ export default function NoteScreen() { [id], ); + const handleLineSpacing = useCallback(async (value: LineSpacing) => { + if (!id || lineSpacingBusyRef.current) return; + lineSpacingBusyRef.current = true; + setLineSpacingBusy(true); + try { + const next = await setNoteLineSpacing(id, value); + if (!next) throw new Error('Note not found'); + if (isMountedRef.current) setMetadata(next); + } catch (error) { + if (__DEV__) console.warn('[NoteScreen] line spacing update failed', error); + Alert.alert(t.editor.statusError, t.common.pleaseTryAgain); + } finally { + lineSpacingBusyRef.current = false; + if (isMountedRef.current) setLineSpacingBusy(false); + } + }, [id]); + const handleExport = useCallback(async () => { if (!id || !canvasRef.current || isExporting) return; setIsExporting(true); @@ -810,6 +831,7 @@ export default function NoteScreen() { const result = await exportNotebookAsPdf({ data: { ...canvasData, pages: mergedPages }, pdfBackgroundUri: metadata?.pdfUri ?? null, + backgroundType: paperBackgroundType(metadata?.backgroundType ?? 'plain', metadata?.lineSpacing), filename, }); if (!result.ok) { @@ -830,6 +852,8 @@ export default function NoteScreen() { isExporting, mergeStoredPreviews, metadata?.pdfUri, + metadata?.backgroundType, + metadata?.lineSpacing, metadata?.title, rememberPagePreviews, ]); @@ -1039,7 +1063,7 @@ export default function NoteScreen() { pageHeight={PAGE_HEIGHT} toolState={toolState} holdToShapeEnabled={holdToShape} - backgroundType={metadata?.backgroundType ?? 'plain'} + backgroundType={paperBackgroundType(metadata?.backgroundType ?? 'plain', metadata?.lineSpacing)} pdfBackgroundBaseUri={metadata?.pdfUri ?? undefined} fingerDrawingEnabled={fingerDrawingEnabled} onContentTap={hasSelectableImages && !fingerDrawingEnabled && !['select', 'text', 'insert'].includes(toolState.toolType) @@ -1098,7 +1122,7 @@ export default function NoteScreen() { setToolPopover(null)} /> - setAction(null)} /> + setAction(null)} + noteLineSpacing={metadata?.backgroundType === 'lined' ? resolveLineSpacing(metadata.lineSpacing) : undefined} + onNoteLineSpacingChange={value => void handleLineSpacing(value)} lineSpacingBusy={lineSpacingBusy} /> =2.0.0", diff --git a/package.json b/package.json index 32204c0..662b5e6 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ }, "dependencies": { "@expo/vector-icons": "^15.0.3", - "@mathnotes/mobile-ink": "file:vendor/mathnotes-mobile-ink-testflight-c56a32d.tgz", + "@mathnotes/mobile-ink": "file:vendor/mathnotes-mobile-ink-0.3.13.tgz", "@react-native-async-storage/async-storage": "2.2.0", "@shopify/react-native-skia": "2.2.12", "expo": "54.0.34", diff --git a/scripts/catalogStore.test.mjs b/scripts/catalogStore.test.mjs index ea3f006..4c6f291 100644 --- a/scripts/catalogStore.test.mjs +++ b/scripts/catalogStore.test.mjs @@ -9,6 +9,22 @@ import { createCatalogStore, parseCatalog, } from '../src/services/catalogStore.ts'; +import { paperBackgroundType } from '../src/utils/paperSpacing.ts'; + +test('line spacing survives catalog and older notes retain their original paper', () => { + const input = {version: 1, folders: [], notes: [ + {id: 'old', backgroundType: 'lined'}, + {id: 'new', backgroundType: 'lined', lineSpacing: 'narrow'}, + {id: 'custom', backgroundType: 'lined', lineSpacing: 'custom-47'}, + {id: 'invalid', backgroundType: 'lined', lineSpacing: 'invalid'}, + ]}; + const notes = parseCatalog(JSON.stringify(parseCatalog(JSON.stringify(input)))).notes; + assert.equal(paperBackgroundType(notes[0].backgroundType, notes[0].lineSpacing), 'lined'); + assert.equal(paperBackgroundType(notes[1].backgroundType, notes[1].lineSpacing), 'lined-narrow'); + assert.equal(paperBackgroundType(notes[2].backgroundType, notes[2].lineSpacing), 'lined-custom-47'); + assert.equal(paperBackgroundType(notes[3].backgroundType, notes[3].lineSpacing), 'lined'); + assert.equal(paperBackgroundType('pdf', 'compact'), 'pdf'); +}); test('catalog reload preserves composed thumbnail versions and still accepts old notes', () => { const catalog = parseCatalog(JSON.stringify({ diff --git a/scripts/exportService.test.mjs b/scripts/exportService.test.mjs index 584f280..b2702ef 100644 --- a/scripts/exportService.test.mjs +++ b/scripts/exportService.test.mjs @@ -6,6 +6,7 @@ import ts from 'typescript'; import { indexAssetsByPage } from '../src/utils/continuousAssets.ts'; import { buildPdfHtml } from '../src/services/pdfExportHtml.ts'; import { overlayLayerBoundaries } from '../src/utils/visualLayerOrder.ts'; +import { pageBackgroundType } from '../src/utils/paperSpacing.ts'; const source = ts.transpileModule( readFileSync(new URL('../src/services/exportService.ts', import.meta.url), 'utf8'), @@ -90,6 +91,7 @@ function harness(files = {}, { mergePdfFiles } = {}) { if (name === '@mathnotes/mobile-ink') return mobileInk; if (name === '../utils/continuousAssets') return { indexAssetsByPage }; if (name === '../utils/visualLayerOrder') return { overlayLayerBoundaries }; + if (name === '../utils/paperSpacing') return { pageBackgroundType }; if (name === './pdfExportHtml') { return { buildPdfHtml, @@ -113,6 +115,22 @@ function harness(files = {}, { mergePdfFiles } = {}) { }; } +test('exports the note paper spacing while keeping PDF backgrounds intact', async () => { + const h = harness(); + const data = notebook([{pageType: undefined}, {pageType: 'pdf'}]); + const result = await h.exportNotebookAsPdf({ data, filename: 'paper', backgroundType: 'lined-narrow' }); + assert.equal(result.ok, true); + assert.deepEqual(Array.from(h.batchCalls[0][1]), ['lined-narrow', 'pdf']); +}); + +test('does not apply an imported PDF background to a subsequently added blank page', async () => { + const h = harness(); + const data = notebook([{pageType: 'pdf'}, {pageType: undefined}]); + const result = await h.exportNotebookAsPdf({ data, filename: 'mixed', backgroundType: 'pdf', pdfBackgroundUri: 'file:///note.pdf' }); + assert.equal(result.ok, true); + assert.deepEqual(Array.from(h.batchCalls[0][1]), ['pdf', 'plain']); +}); + test('a three-page PDF includes a photo and typed text on their original page', async () => { const photo = 'file:///notes/photo.jpg'; const h = harness({ [photo]: 'cGhvdG8=' }); diff --git a/scripts/noteThumbnails.test.mjs b/scripts/noteThumbnails.test.mjs index 7f02e94..f39edfa 100644 --- a/scripts/noteThumbnails.test.mjs +++ b/scripts/noteThumbnails.test.mjs @@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs'; import test from 'node:test'; import vm from 'node:vm'; import ts from 'typescript'; +import * as paperSpacing from '../src/utils/paperSpacing.ts'; const source = ts.transpileModule( readFileSync(new URL('../src/services/notesRepo.ts', import.meta.url), 'utf8'), @@ -39,6 +40,7 @@ function harness({ writeOk = true, renderFails = false, render = async () => com }; if (name === '../i18n') return { t: { common: { untitled: 'Untitled' } } }; if (name === '../utils/id') return {}; + if (name === '../utils/paperSpacing') return paperSpacing; if (name === './catalogStore') return {}; if (name === './pdfStorage' || name === './imageInsertStorage') return {}; throw new Error('Unexpected import: ' + name); diff --git a/scripts/thumbnailRendering.test.mjs b/scripts/thumbnailRendering.test.mjs index acfb50e..a7cc612 100644 --- a/scripts/thumbnailRendering.test.mjs +++ b/scripts/thumbnailRendering.test.mjs @@ -6,6 +6,7 @@ import vm from 'node:vm'; import ts from 'typescript'; import { createPromiseQueue } from '../src/utils/promiseQueue.ts'; import { imageLayerOrder, overlayLayerBoundaries, textLayerOrder } from '../src/utils/visualLayerOrder.ts'; +import { pageBackgroundType } from '../src/utils/paperSpacing.ts'; const require = createRequire(import.meta.url); const initCanvasKit = require('canvaskit-wasm/bin/full/canvaskit.js'); @@ -53,6 +54,7 @@ function harness({ nativeFails = false, nativeParagraphBuilder = false, nativeIm vm.runInNewContext(source, { exports, require(name) { if (name === '../utils/promiseQueue') return { createPromiseQueue }; if (name === '../utils/visualLayerOrder') return { imageLayerOrder, overlayLayerBoundaries, textLayerOrder }; + if (name === '../utils/paperSpacing') return { pageBackgroundType }; if (name === 'react-native') return { Platform: { OS: 'ios' } }; if (name === './pdfUtilsModule') return { PDFUtilsModule: nativeImage ? { readImageForThumbnail: nativeImage, @@ -111,6 +113,14 @@ test('ink-only thumbnails are rendered from the saved page even without a previe assert.equal(await h.createPageThumbnail(undefined), null); }); +test('thumbnail paper follows the note spacing even when the page is marked plain', async () => { + const h = harness(); + await h.createPageThumbnail(page([], {pageType: 'plain'}), 'lined-narrow'); + assert.equal(h.nativeCalls[0][1][0], 'lined-narrow'); + await h.createPageThumbnail(page([photo()], {pageType: 'plain'}), 'lined-compact'); + assert.equal(h.nativeCalls[1][1][0], 'lined-compact'); +}); + test('PDF-only thumbnails render the specified page and source', async () => { const h = harness(); assert.equal(await h.createPageThumbnail(page([], {previewUri: undefined, pageType: 'pdf', pdfPageNumber: 3}), diff --git a/src/components/library/CreateNoteBackgroundSheet.tsx b/src/components/library/CreateNoteBackgroundSheet.tsx index 6dee62b..e25f4bd 100644 --- a/src/components/library/CreateNoteBackgroundSheet.tsx +++ b/src/components/library/CreateNoteBackgroundSheet.tsx @@ -1,6 +1,7 @@ import React, { useEffect, useState } from 'react'; import { Pressable, + ScrollView, StyleSheet, Text, TextInput, @@ -8,16 +9,24 @@ import { useWindowDimensions, } from 'react-native'; import { Sheet } from '../ui/Sheet'; +import { LineSpacingSlider } from '../ui/LineSpacingSlider'; import { useTheme } from '../../hooks/useTheme'; import { radius, spacing } from '../../theme/spacing'; import { typography } from '../../theme/typography'; import { BACKGROUND_TYPES } from '../../types/note'; import { t } from '../../i18n'; -import type { BackgroundType } from '../../types/note'; +import type { BackgroundType, LineSpacing } from '../../types/note'; +import { customLineSpacing, lineCount } from '../../utils/paperSpacing'; + +type PresetSpacing = Exclude; +const PAPER_CHOICES = BACKGROUND_TYPES.flatMap<{ type: BackgroundType; lineSpacing: PresetSpacing }>((type) => + type === 'lined' + ? (['standard', 'narrow', 'compact'] as const).map(lineSpacing => ({ type, lineSpacing })) + : [{ type, lineSpacing: 'standard' }]); export interface CreateNoteBackgroundSheetProps { visible: boolean; - onPick: (type: BackgroundType, title: string) => void; + onPick: (type: BackgroundType, title: string, lineSpacing: LineSpacing) => void; onClose: () => void; } @@ -27,19 +36,21 @@ export function CreateNoteBackgroundSheet({ onClose, }: CreateNoteBackgroundSheetProps) { const theme = useTheme(); - const { width } = useWindowDimensions(); + const { width, height } = useWindowDimensions(); const [title, setTitle] = useState(''); + const [customCount, setCustomCount] = useState(24); const cellWidth = Math.max( 104, Math.min(148, Math.floor((width - spacing.lg * 2 - spacing.sm * 2) / 3)), ); useEffect(() => { - if (visible) setTitle(''); + if (visible) { setTitle(''); setCustomCount(24); } }, [visible]); return ( + {t.library.newNoteSheetTitle} @@ -62,10 +73,13 @@ export function CreateNoteBackgroundSheet({ /> - {BACKGROUND_TYPES.map((type) => ( + {PAPER_CHOICES.map(({ type, lineSpacing }) => ( onPick(type, title)} + key={`${type}-${lineSpacing}`} + accessibilityRole="button" + accessibilityLabel={type === 'lined' ? `${t.library.backgrounds.lined}, ${t.library.lineSpacing[lineSpacing]}` : t.library.backgrounds[type]} + testID={`paper-${type}-${lineSpacing}`} + onPress={() => onPick(type, title, lineSpacing)} style={({ pressed }) => [ styles.cell, { width: cellWidth }, @@ -77,7 +91,7 @@ export function CreateNoteBackgroundSheet({ }, ]} > - + - {t.library.backgrounds[type]} + {type === 'lined' && lineSpacing !== 'standard' + ? t.library.lineSpacing[lineSpacing] + : t.library.backgrounds[type]} ))} + + + + + + + + onPick('lined', title, customLineSpacing(customCount))} + style={[styles.customButton, {backgroundColor: theme.colors.accent}]}> + {t.library.createCustomLined} + + + ); } -function BackgroundThumbnail({ type }: { type: BackgroundType }) { +function BackgroundThumbnail({ type, lineSpacing }: { type: BackgroundType; lineSpacing: LineSpacing }) { if (type === 'pdf') { return ( @@ -109,14 +141,16 @@ function BackgroundThumbnail({ type }: { type: BackgroundType }) { ); } + const custom = type === 'lined' && lineSpacing.startsWith('custom-'); + const previewCount = custom ? Math.max(5, Math.round(lineCount(lineSpacing) * 0.42)) : 0; return ( - - {type === 'plain' ? null : Array.from({ length: type === 'dotted' ? 6 : 7 }, (_, index) => ( + + {type === 'plain' ? null : Array.from({ length: custom ? previewCount : type === 'dotted' ? 6 : type === 'lined' && lineSpacing === 'compact' ? 15 : type === 'lined' && lineSpacing === 'narrow' ? 11 : 7 }, (_, index) => ( ))} @@ -167,6 +201,11 @@ const styles = StyleSheet.create({ maxWidth: 460, alignSelf: 'center', }, + custom: {width: '100%', maxWidth: 460, alignSelf: 'center', marginTop: spacing.lg}, + customRow: {flexDirection: 'row', alignItems: 'center', gap: spacing.md}, + customSlider: {flex: 1}, + customButton: {marginTop: spacing.sm, minHeight: 44, borderRadius: radius.md, alignItems: 'center', justifyContent: 'center', paddingHorizontal: spacing.sm}, + customButtonText: {color: '#fff', fontSize: 15, fontWeight: '600', textAlign: 'center'}, cell: { height: 122, borderRadius: radius.md, @@ -192,9 +231,6 @@ const styles = StyleSheet.create({ width: '100%', backgroundColor: 'rgba(10, 132, 255, 0.42)', }, - marginLine: { - backgroundColor: 'rgba(255, 59, 48, 0.46)', - }, paperLineVertical: { position: 'absolute', top: 0, diff --git a/src/components/library/NewItemFAB.tsx b/src/components/library/NewItemFAB.tsx index 144e9ff..da0035e 100644 --- a/src/components/library/NewItemFAB.tsx +++ b/src/components/library/NewItemFAB.tsx @@ -4,6 +4,7 @@ import { Ionicons } from '@expo/vector-icons'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import { useTheme } from '../../hooks/useTheme'; import { radius, spacing } from '../../theme/spacing'; +import { t } from '../../i18n'; export interface NewItemFABProps { onPress: () => void; @@ -21,6 +22,9 @@ export function NewItemFAB({ onPress }: NewItemFABProps) { ]} > [ styles.button, diff --git a/src/components/ui/LineSpacingSlider.tsx b/src/components/ui/LineSpacingSlider.tsx new file mode 100644 index 0000000..3744b64 --- /dev/null +++ b/src/components/ui/LineSpacingSlider.tsx @@ -0,0 +1,64 @@ +import React, { useEffect, useMemo, useRef, useState } from 'react'; +import { PanResponder, StyleSheet, Text, View } from 'react-native'; + +const MIN = 12; +const MAX = 60; +const THUMB = 24; + +/** Previews while dragging and saves only when the gesture finishes. */ +export function LineSpacingSlider({ value, onCommit, onPreview, label, unit, color, muted, accent, disabled = false }: { + value: number; onCommit: (value: number) => void; onPreview?: (value: number) => void; + label: string; unit: string; color: string; muted: string; accent: string; disabled?: boolean; +}) { + const [width, setWidth] = useState(0); + const [preview, setPreview] = useState(value); + const latest = useRef({width, value, preview, onCommit, onPreview, disabled}); + latest.current = {width, value, preview, onCommit, onPreview, disabled}; + const start = useRef(0); + const initialValue = useRef(value); + useEffect(() => { setPreview(value); }, [value]); + const choose = (x: number) => { + const fraction = Math.max(0, Math.min(1, (x - THUMB / 2) / Math.max(1, latest.current.width - THUMB))); + const next = Math.round(MIN + fraction * (MAX - MIN)); + latest.current.preview = next; + setPreview(next); + latest.current.onPreview?.(next); + }; + const pan = useMemo(() => PanResponder.create({ + onStartShouldSetPanResponder: () => !latest.current.disabled, + onMoveShouldSetPanResponder: () => !latest.current.disabled, + onPanResponderGrant: event => { initialValue.current = latest.current.value; start.current = event.nativeEvent.locationX; choose(start.current); }, + onPanResponderMove: (_event, gesture) => choose(start.current + gesture.dx), + onPanResponderRelease: () => latest.current.onCommit(latest.current.preview), + onPanResponderTerminate: () => { setPreview(initialValue.current); latest.current.onPreview?.(initialValue.current); }, + }), []); + const fraction = (preview - MIN) / (MAX - MIN); + return + + {label} + {preview} {unit} + + { + if (disabled || !['increment', 'decrement'].includes(nativeEvent.actionName)) return; + const next = Math.max(MIN, Math.min(MAX, preview + (nativeEvent.actionName === 'increment' ? 1 : -1))); + setPreview(next); onPreview?.(next); onCommit(next); + }} + testID="line-spacing-slider" onLayout={event => setWidth(event.nativeEvent.layout.width)} + {...pan.panHandlers} style={styles.touch}> + + + + + ; +} + +const styles = StyleSheet.create({ + labelRow: {flexDirection: 'row', justifyContent: 'space-between', marginTop: 12}, + touch: {height: 44, justifyContent: 'center'}, + track: {position: 'absolute', left: THUMB / 2, right: THUMB / 2, height: 4, borderRadius: 2, opacity: 0.35}, + fill: {position: 'absolute', left: THUMB / 2, height: 4, borderRadius: 2}, + thumb: {position: 'absolute', width: THUMB, height: THUMB, borderRadius: THUMB / 2}, +}); diff --git a/src/components/ui/PreferencesSheet.tsx b/src/components/ui/PreferencesSheet.tsx index fbbf2b3..42e5c8b 100644 --- a/src/components/ui/PreferencesSheet.tsx +++ b/src/components/ui/PreferencesSheet.tsx @@ -5,8 +5,14 @@ import { usePreferences, type Appearance } from '../../hooks/Preferences'; import { useTheme } from '../../hooks/useTheme'; import { t } from '../../i18n'; import { radius, spacing } from '../../theme/spacing'; +import type { LineSpacing } from '../../types/note'; +import { customLineSpacing, lineCount } from '../../utils/paperSpacing'; +import { LineSpacingSlider } from './LineSpacingSlider'; -export function PreferencesSheet({ visible, onClose }: { visible: boolean; onClose: () => void }) { +export function PreferencesSheet({ visible, onClose, noteLineSpacing, onNoteLineSpacingChange, lineSpacingBusy }: { + visible: boolean; onClose: () => void; noteLineSpacing?: LineSpacing; + onNoteLineSpacingChange?: (value: LineSpacing) => void; lineSpacingBusy?: boolean; +}) { const theme = useTheme(); const { appearance, setAppearance, returnToPen, setReturnToPen, libraryLayout, setLibraryLayout, holdToShape, setHoldToShape } = usePreferences(); const choices: Array<{ value: Appearance; label: string }> = [ @@ -31,6 +37,24 @@ export function PreferencesSheet({ visible, onClose }: { visible: boolean; onClo {choice.label} )} + {noteLineSpacing && onNoteLineSpacingChange ? <> + {t.library.lineSpacingTitle} + + {(['standard', 'narrow', 'compact'] as const).map(value => onNoteLineSpacingChange(value)} + style={[styles.choice, noteLineSpacing === value && { backgroundColor: theme.colors.surfaceElevated }]}> + + {t.library.lineSpacing[value]} + + )} + + onNoteLineSpacingChange(customLineSpacing(value))} disabled={lineSpacingBusy} + label={t.library.customSpacing} unit={t.library.linesPerPage} + color={theme.colors.text} muted={theme.colors.textSecondary} accent={theme.colors.accent} /> + : null} {t.preferences.libraryView} {(['grid', 'columns'] as const).map(value => forces a compile error if BackgroundType ever // gains or loses a member without this map being updated. @@ -121,6 +122,8 @@ function normalizeNote(value: unknown): NoteMetadata | null { createdAt: isNonEmptyString(v.createdAt) ? v.createdAt : new Date(0).toISOString(), updatedAt: isNonEmptyString(v.updatedAt) ? v.updatedAt : new Date(0).toISOString(), backgroundType, + ...(isLineSpacing(v.lineSpacing) + ? { lineSpacing: v.lineSpacing } : {}), pdfUri: isNonEmptyString(v.pdfUri) ? v.pdfUri : null, thumbnailUri: isNonEmptyString(v.thumbnailUri) ? v.thumbnailUri : null, ...(isNonEmptyString(v.customCoverUri) ? { customCoverUri: v.customCoverUri } : {}), diff --git a/src/services/exportService.ts b/src/services/exportService.ts index 2dbe70f..8e9f7b4 100644 --- a/src/services/exportService.ts +++ b/src/services/exportService.ts @@ -14,6 +14,7 @@ import { import { PDFUtilsModule } from './pdfUtilsModule'; import { indexAssetsByPage } from '../utils/continuousAssets'; import { overlayLayerBoundaries } from '../utils/visualLayerOrder'; +import { pageBackgroundType } from '../utils/paperSpacing'; const EXPORT_SCALE = 1.0; const DEFAULT_NATIVE_BATCH_SIZE = 8; @@ -27,6 +28,7 @@ const PRINT_PASS_PAGES = 8; export interface ExportOptions { data: SerializedNotebookData; pdfBackgroundUri?: string | null; + backgroundType?: string; filename: string; } @@ -122,6 +124,7 @@ async function renderNativePagesInChunks(options: { exportWidth: number; exportHeight: number; pdfBackgroundUri?: string | null; + backgroundType?: string; batchSize: number; layerBoundaries: Map; }): Promise> { @@ -131,6 +134,7 @@ async function renderNativePagesInChunks(options: { exportWidth, exportHeight, pdfBackgroundUri, + backgroundType, batchSize, layerBoundaries, } = options; @@ -146,7 +150,7 @@ async function renderNativePagesInChunks(options: { ); const pngUris = await batchExportPages( inkPayloads.map((payload, offset) => layerBoundaries.has(chunkPageIndexes[offset]) ? '{"pages":{}}' : payload), - chunkPages.map((p) => p?.pageType ?? 'plain'), + chunkPages.map((p) => pageBackgroundType(backgroundType, p?.pageType)), exportWidth, exportHeight, EXPORT_SCALE, @@ -214,13 +218,14 @@ async function collectExportImages(options: { exportWidth: number; exportHeight: number; pdfBackgroundUri?: string | null; + backgroundType?: string; layerBoundaries: Map; }): Promise { - const { data, pageIndexes, exportWidth, exportHeight, pdfBackgroundUri, layerBoundaries } = options; + const { data, pageIndexes, exportWidth, exportHeight, pdfBackgroundUri, backgroundType, layerBoundaries } = options; // Saved thumbnails may omit ink owned by a neighboring page. Always render // the canonical document, in bounded batches, for the exported PDF. const rendered = await renderNativePagesInChunks({ - data, pageIndexes, exportWidth, exportHeight, pdfBackgroundUri, layerBoundaries, + data, pageIndexes, exportWidth, exportHeight, pdfBackgroundUri, backgroundType, layerBoundaries, batchSize: DEFAULT_NATIVE_BATCH_SIZE, }); return pageIndexes.map(index => { @@ -250,7 +255,7 @@ async function deleteFiles(uris: string[]): Promise { export async function exportNotebookAsPdf( options: ExportOptions, ): Promise<{ ok: boolean; uri?: string; error?: string }> { - const { data, pdfBackgroundUri, filename } = options; + const { data, pdfBackgroundUri, backgroundType, filename } = options; if (!data.pages || data.pages.length === 0) { return { ok: false, error: 'Empty notebook' }; } @@ -279,6 +284,7 @@ export async function exportNotebookAsPdf( exportWidth, exportHeight, pdfBackgroundUri, + backgroundType, layerBoundaries, }); if (rasterUris.length !== pageIndexes.length) { diff --git a/src/services/notesRepo.ts b/src/services/notesRepo.ts index 2942e42..2cac5ba 100644 --- a/src/services/notesRepo.ts +++ b/src/services/notesRepo.ts @@ -1,5 +1,6 @@ import type { SerializedNotebookData } from '@mathnotes/mobile-ink'; -import type { BackgroundType, NoteMetadata } from '../types/note'; +import type { BackgroundType, LineSpacing, NoteMetadata } from '../types/note'; +import { paperBackgroundType } from '../utils/paperSpacing'; import { noteId as makeNoteId } from '../utils/id'; import { t } from '../i18n'; import { catalogStore } from './catalogEnv'; @@ -28,6 +29,7 @@ export async function createNote(opts: { folderId?: string | null; title?: string; backgroundType?: BackgroundType; + lineSpacing?: LineSpacing; } = {}): Promise { const now = new Date().toISOString(); const meta: NoteMetadata = { @@ -37,6 +39,7 @@ export async function createNote(opts: { createdAt: now, updatedAt: now, backgroundType: opts.backgroundType ?? 'plain', + lineSpacing: opts.lineSpacing ?? 'standard', pdfUri: null, thumbnailUri: null, }; @@ -101,7 +104,7 @@ export function getNoteThumbnail(note: NoteMetadata, force = false): Promise epoch !== thumbnailEpoch); if (!uri) return note.thumbnailUri; let currentUri = note.thumbnailUri; @@ -166,6 +169,11 @@ export async function setNoteBackground( return updateMetadata(id, { backgroundType, pdfUri, thumbnailVersion: undefined }); } +export async function setNoteLineSpacing(id: string, lineSpacing: LineSpacing): Promise { + thumbnailRevisions.set(id, (thumbnailRevisions.get(id) ?? 0) + 1); + return updateMetadata(id, { lineSpacing, thumbnailVersion: undefined }); +} + async function deleteNoteFiles(id: string): Promise { await Promise.all([deleteBody(id), deletePdfForNote(id), deleteImagesForNote(id)]); } diff --git a/src/services/thumbnailService.ts b/src/services/thumbnailService.ts index df087e6..6320273 100644 --- a/src/services/thumbnailService.ts +++ b/src/services/thumbnailService.ts @@ -4,6 +4,7 @@ import { Platform } from 'react-native'; import { createPromiseQueue } from '../utils/promiseQueue'; import { PDFUtilsModule } from './pdfUtilsModule'; import { imageLayerOrder, overlayLayerBoundaries, textLayerOrder } from '../utils/visualLayerOrder'; +import { pageBackgroundType } from '../utils/paperSpacing'; export const THUMBNAIL_VERSION = 4; const PAGE_WIDTH = 820; @@ -64,7 +65,7 @@ async function composePageThumbnail( const textBoxes = (page.textBoxes ?? []).filter(box => Boolean(box.content)); if (!elements.length && !textBoxes.length) { const [rendered] = await batchExportPages( - [page.data ?? '{"pages":{}}'], [page.pageType ?? backgroundType], PAGE_WIDTH, PAGE_HEIGHT, SCALE, + [page.data ?? '{"pages":{}}'], [pageBackgroundType(backgroundType, page.pageType)], PAGE_WIDTH, PAGE_HEIGHT, SCALE, pdfUri ?? undefined, [page.pdfPageNumber ? page.pdfPageNumber - 1 : pageIndex], ); if (!rendered) throw new Error('Thumbnail page could not be rendered'); @@ -76,7 +77,7 @@ async function composePageThumbnail( let inkGroups: (string | null)[]; { [raster] = await batchExportPages( - ['{"pages":{}}'], [page.pageType ?? backgroundType], PAGE_WIDTH, PAGE_HEIGHT, SCALE, + ['{"pages":{}}'], [pageBackgroundType(backgroundType, page.pageType)], PAGE_WIDTH, PAGE_HEIGHT, SCALE, pdfUri ?? undefined, [page.pdfPageNumber ? page.pdfPageNumber - 1 : pageIndex], ); if (!raster) throw new Error('Thumbnail background could not be rendered'); diff --git a/src/types/note.ts b/src/types/note.ts index cee1abe..45f1a32 100644 --- a/src/types/note.ts +++ b/src/types/note.ts @@ -6,6 +6,8 @@ export type BackgroundType = | 'graph' | 'pdf'; +export type LineSpacing = 'standard' | 'narrow' | 'compact' | `custom-${number}`; + export const BACKGROUND_TYPES: BackgroundType[] = [ 'plain', 'lined', @@ -29,6 +31,7 @@ export interface NoteMetadata { createdAt: string; updatedAt: string; backgroundType: BackgroundType; + lineSpacing?: LineSpacing; pdfUri: string | null; thumbnailUri: string | null; thumbnailVersion?: number; diff --git a/src/utils/paperSpacing.ts b/src/utils/paperSpacing.ts new file mode 100644 index 0000000..897e660 --- /dev/null +++ b/src/utils/paperSpacing.ts @@ -0,0 +1,33 @@ +import type { BackgroundType, LineSpacing } from '../types/note'; + +export function resolveLineSpacing(value: unknown): LineSpacing { + return isLineSpacing(value) ? value : 'standard'; +} + +export function isLineSpacing(value: unknown): value is LineSpacing { + return value === 'standard' || value === 'narrow' || value === 'compact' || + (typeof value === 'string' && /^custom-(?:1[2-9]|[2-5][0-9]|60)$/.test(value)); +} + +export function lineCount(value: LineSpacing): number { + if (value === 'narrow') return 24; + if (value === 'compact') return 36; + if (value.startsWith('custom-')) return Number(value.slice(7)); + return 18; +} + +export function customLineSpacing(count: number): LineSpacing { + return `custom-${Number.isFinite(count) ? Math.max(12, Math.min(60, Math.round(count))) : 18}`; +} + +/** The stored background remains compatible with older versions of the app. */ +export function paperBackgroundType(type: BackgroundType, spacing: unknown): string { + const resolved = resolveLineSpacing(spacing); + return type === 'lined' && resolved !== 'standard' ? `lined-${resolved}` : type; +} + +/** Imported PDF pages retain their background; other pages use the note paper. */ +export function pageBackgroundType(noteType: string | undefined, pageType: string | undefined): string { + if (pageType === 'pdf') return 'pdf'; + return noteType === 'pdf' ? (pageType ?? 'plain') : (noteType ?? pageType ?? 'plain'); +} diff --git a/vendor/mathnotes-mobile-ink-0.3.13.tgz b/vendor/mathnotes-mobile-ink-0.3.13.tgz new file mode 100644 index 0000000..e14236d Binary files /dev/null and b/vendor/mathnotes-mobile-ink-0.3.13.tgz differ diff --git a/vendor/mobile-ink-source.json b/vendor/mobile-ink-source.json index 5715b6f..83b0b1b 100644 --- a/vendor/mobile-ink-source.json +++ b/vendor/mobile-ink-source.json @@ -1,8 +1,8 @@ { "package": "@mathnotes/mobile-ink", - "version": "0.3.11", + "version": "0.3.13", "source": "https://github.com/mathnotes-app/mobile-ink", - "commit": "c56a32dcd90d75fc1fef7d111e073841a5162179", - "sha256": "22e5cefb34304b75d4473790c1956629f43bbbbdf019483470a5b1db697b2b1a", - "pull_request": "https://github.com/mathnotes-app/mobile-ink/pull/65" + "commit": "02f1acd525b70c41d9bf7dc0165a1a56672a3590", + "sha256": "26cd911d028708a8436c9f2cfde52a33250122629e46b6cee82052805a283e82", + "pull_request": "https://github.com/mathnotes-app/mobile-ink/pull/68" }