A note being edited, with motion: checklist boxes fill and draw their check on a spring while a line strikes through the text and the progress bar follows, Enter adds checklist items and splits bullets, the Saved pill spins to Saving and settles back on a check after every edit, the pin turns as it toggles, a row of colour dots pops out to retint the note's edge, and a pinned toolbar applies bold, italic, heading, bullets, checklist and image to the block you are in.

Details
1import { useEffect, useRef, useState, type ComponentProps, type ComponentRef, type ReactNode } from 'react';2import {3 Image,4 KeyboardAvoidingView,5 Platform,6 Pressable,7 ScrollView,8 StyleSheet,9 Text,10 TextInput,11 View,12 useColorScheme,13 type StyleProp,14 type TextStyle,15} from 'react-native';16import Animated, {17 cancelAnimation,18 Easing,19 FadeIn,20 FadeInDown,21 FadeOut,22 useAnimatedProps,23 useAnimatedStyle,24 useSharedValue,25 withDelay,26 withRepeat,27 withSequence,28 withSpring,29 withTiming,30 ZoomIn,31} from 'react-native-reanimated';32import { LinearGradient } from 'expo-linear-gradient';33import { useSafeAreaInsets } from 'react-native-safe-area-context';34import Svg, { Path } from 'react-native-svg';35import {36 Bold,37 Check,38 ChevronLeft,39 Copy,40 Ellipsis,41 Folder,42 FolderInput,43 Hash,44 Heading,45 Image as ImageIcon,46 Italic,47 List,48 ListChecks,49 Lock,50 Pin,51 Plus,52 Share2,53 Trash2,54 X,55 type LucideIcon,56} from 'lucide-react-native';5758// ─── Brand ──────────────────────────────────────────────────────────────────59// The notes app's accent and name. Every accent colour below derives from these, so changing them rebrands the screen. The other colour tags a note can wear are per-note labels, not the brand.6061const ACCENT = '#EFA00B';62const ON_ACCENT = '#1F1503'; // text and icons on an accent fill63const APP_NAME = 'Sorrel';6465/** `hex` at `alpha` opacity, as rgba(). */66function tint(hex: string, alpha: number) {67 const n = parseInt(hex.slice(1), 16);68 return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;69}7071/** `hex` mixed toward black (amount > 0) or white (amount < 0); amount from -1 to 1. */72function shade(hex: string, amount: number) {73 const n = parseInt(hex.slice(1), 16);74 const target = amount < 0 ? 255 : 0;75 const p = Math.abs(amount);76 const c = (v: number) => Math.round(v + (target - v) * p).toString(16).padStart(2, '0');77 return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`.toUpperCase();78}7980// ─── Sample data ────────────────────────────────────────────────────────────8182const NOTE = {83 title: 'Lake weekend',84 folder: 'Trips',85 edited: 'Edited 9:41',86 photo: 'https://images.unsplash.com/photo-1482192505345-5655af888cc4?w=1000&q=80&fit=crop',87 photoAlt: 'A wooden boathouse on stilts at the edge of a mountain lake, with cloud on the cliffs behind',88 caption: 'The boathouse at 7 am, before the boats go out.',89};9091type TextKind = 'p' | 'h' | 'bullet';92type Block =93 | { id: string; kind: 'text'; as: TextKind; text: string; bold?: boolean; italic?: boolean }94 | { id: string; kind: 'image' }95 | { id: string; kind: 'checklist' };9697const BLOCKS: Block[] = [98 { id: 'intro', kind: 'text', as: 'p', text: 'Two nights at the lake with Ines and Tomas. Leave Friday straight after lunch.' },99 { id: 'photo', kind: 'image' },100 { id: 'packing', kind: 'text', as: 'h', text: 'Packing' },101 { id: 'list', kind: 'checklist' },102 { id: 'saturday', kind: 'text', as: 'h', text: 'Saturday' },103 { id: 'b1', kind: 'text', as: 'bullet', text: 'Sunrise loop around the lake, about 4 km' },104 { id: 'b2', kind: 'text', as: 'bullet', text: 'Rowing boat from the boathouse at 10:00' },105 { id: 'b3', kind: 'text', as: 'bullet', text: 'Lunch at the hut above the east shore' },106 { id: 'outro', kind: 'text', as: 'p', italic: true, text: 'Book the 18:40 bus back on Sunday. The later one skips our stop.' },107];108109type Item = { id: string; text: string; done: boolean; fresh?: boolean };110111const ITEMS: Item[] = [112 { id: 'i1', text: 'Hiking boots and wool socks', done: true },113 { id: 'i2', text: 'Rain shell', done: true },114 { id: 'i3', text: 'Headlamp, spare batteries', done: false },115 { id: 'i4', text: 'Thermos for the sunrise walk', done: false },116 { id: 'i5', text: 'Print the hut booking', done: false },117];118119const TAGS = ['trips', 'mountains', 'autumn'];120121// The colour tags a note can wear. The first is the app's accent; the rest are fixed label colours.122const COLORS = [123 { id: 'amber', name: 'Amber', color: ACCENT },124 { id: 'coral', name: 'Coral', color: '#E2574C' },125 { id: 'green', name: 'Green', color: '#2F9E6B' },126 { id: 'teal', name: 'Teal', color: '#1B97A6' },127 { id: 'blue', name: 'Blue', color: '#3E7BE0' },128 { id: 'graphite', name: 'Graphite', color: '#7F838C' },129] as const;130type ColorId = (typeof COLORS)[number]['id'];131132const MENU: { id: string; label: string; icon: LucideIcon; danger?: boolean }[] = [133 { id: 'share', label: 'Share note', icon: Share2 },134 { id: 'copy', label: 'Duplicate', icon: Copy },135 { id: 'move', label: 'Move to folder', icon: FolderInput },136 { id: 'lock', label: 'Lock note', icon: Lock },137 { id: 'delete', label: 'Delete', icon: Trash2, danger: true },138];139140// ─── Palette ────────────────────────────────────────────────────────────────141142const SUCCESS = '#2F9E6B';143const POP = { damping: 11, stiffness: 260, mass: 0.6 };144const PRESS = { damping: 16, stiffness: 320, mass: 0.6 };145const COLUMN = 520;146const CHECK_LENGTH = 16;147const SAVE_DELAY = 1100;148const NO_OUTLINE = Platform.OS === 'web' ? ({ outlineStyle: 'none', overflow: 'hidden' } as object) : null;149150function usePalette() {151 const dark = useColorScheme() === 'dark';152 return {153 dark,154 bg: dark ? '#100F0D' : '#FBFAF7',155 surface: dark ? '#1D1B18' : '#FFFFFF',156 fg: dark ? '#F5F2EC' : '#1B1915',157 body: dark ? '#D9D5CC' : '#3A372F',158 muted: dark ? '#9A958A' : '#7D786C',159 faint: dark ? '#5C584F' : '#BEB9AD',160 border: dark ? '#2C2A25' : '#E9E5DC',161 chip: dark ? '#1D1B18' : '#F2EFE8',162 pressed: dark ? '#26241F' : '#F0EDE5',163 accentText: dark ? shade(ACCENT, -0.15) : shade(ACCENT, 0.36),164 accentSoft: dark ? tint(ACCENT, 0.18) : tint(ACCENT, 0.16),165 danger: dark ? '#FF7B72' : '#D6453D',166 wash: dark ? 0.16 : 0.13,167 photoHold: dark ? '#1F3B3A' : '#CFE6E2',168 };169}170type Palette = ReturnType<typeof usePalette>;171172const countWords = (s: string) => (s.trim() ? s.trim().split(/\s+/).length : 0);173174// ─── Small controls ─────────────────────────────────────────────────────────175176type ScaleProps = { children: ReactNode; onPress?: () => void; label: string; to?: number; selected?: boolean; expanded?: boolean; style?: StyleProp<TextStyle> };177178function PressableScale({ children, onPress, label, to = 0.9, selected, expanded, style }: ScaleProps) {179 const scale = useSharedValue(1);180 const anim = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));181 return (182 <Pressable183 role="button"184 aria-label={label}185 aria-selected={selected}186 aria-expanded={expanded}187 onPress={onPress}188 onPressIn={() => (scale.value = withSpring(to, PRESS))}189 onPressOut={() => (scale.value = withSpring(1, PRESS))}190 style={style}191 >192 <Animated.View style={anim}>{children}</Animated.View>193 </Pressable>194 );195}196197function Spinner({ color, track }: { color: string; track: string }) {198 const r = useSharedValue(0);199 useEffect(() => {200 r.value = withRepeat(withTiming(360, { duration: 700, easing: Easing.linear }), -1);201 return () => cancelAnimation(r);202 }, [r]);203 const style = useAnimatedStyle(() => ({ transform: [{ rotate: `${r.value}deg` }] }));204 return <Animated.View style={[styles.spinner, { borderColor: track, borderTopColor: color }, style]} />;205}206207/** "Saving..." with a spinner while an edit is pending, then a check pops in next to "Saved". */208function SaveStatus({ saving, pal }: { saving: boolean; pal: Palette }) {209 return (210 <View role="status" aria-label={saving ? 'Saving' : 'Saved'} style={[styles.status, { backgroundColor: pal.chip }]}>211 <View style={styles.statusIcon}>212 {saving ? (213 <Animated.View key="saving" entering={FadeIn.duration(140)}>214 <Spinner color={pal.accentText} track={pal.border} />215 </Animated.View>216 ) : (217 <Animated.View key="saved" entering={ZoomIn.springify().damping(11).stiffness(240)} style={styles.statusCheck}>218 <Check size={10} color="#FFFFFF" strokeWidth={3.6} />219 </Animated.View>220 )}221 </View>222 <Animated.Text key={saving ? 'saving' : 'saved'} entering={FadeIn.duration(200)} style={[styles.statusLabel, { color: pal.muted }]}>223 {saving ? 'Saving...' : 'Saved'}224 </Animated.Text>225 </View>226 );227}228229/** The pin lies tilted while off and turns upright, with a small pop, when the note is pinned. */230function PinButton({ pinned, onPress, pal }: { pinned: boolean; onPress: () => void; pal: Palette }) {231 const turn = useSharedValue(pinned ? 1 : 0);232 const pop = useSharedValue(1);233 const booted = useRef(false);234 useEffect(() => {235 turn.value = withSpring(pinned ? 1 : 0, { damping: 10, stiffness: 200, mass: 0.7 });236 if (booted.current) pop.value = withSequence(withTiming(1.25, { duration: 110 }), withSpring(1, POP));237 booted.current = true;238 }, [pinned, turn, pop]);239 const style = useAnimatedStyle(() => ({ transform: [{ rotate: `${45 - turn.value * 45}deg` }, { scale: pop.value }] }));240 return (241 <PressableScale label={pinned ? 'Unpin note' : 'Pin note'} selected={pinned} onPress={onPress}>242 <View style={[styles.round, pinned && { backgroundColor: pal.accentSoft }]}>243 <Animated.View style={style}>244 <Pin size={19} color={pinned ? pal.accentText : pal.fg} fill={pinned ? pal.accentText : 'transparent'} strokeWidth={2} />245 </Animated.View>246 </View>247 </PressableScale>248 );249}250251// ─── The note's colour edge: one layer per colour, the chosen one fades in ───252253function Edge({ color, pal }: { color: ColorId; pal: Palette }) {254 return (255 <View pointerEvents="none" style={styles.edge}>256 {COLORS.map((item) => (257 <EdgeLayer key={item.id} hex={item.color} active={item.id === color} wash={pal.wash} />258 ))}259 </View>260 );261}262263function EdgeLayer({ hex, active, wash }: { hex: string; active: boolean; wash: number }) {264 const o = useSharedValue(active ? 1 : 0);265 useEffect(() => {266 o.value = withTiming(active ? 1 : 0, { duration: 360, easing: Easing.out(Easing.cubic) });267 }, [active, o]);268 const style = useAnimatedStyle(() => ({ opacity: o.value }));269 return (270 <Animated.View style={[StyleSheet.absoluteFill, style]}>271 <LinearGradient colors={[tint(hex, wash), tint(hex, 0)]} start={{ x: 0, y: 0.5 }} end={{ x: 1, y: 0.5 }} style={StyleSheet.absoluteFill} />272 <View style={[styles.edgeStripe, { backgroundColor: hex }]} />273 </Animated.View>274 );275}276277// ─── Popovers: the colour dots and the more menu ────────────────────────────278279function ColorPicker({ value, onPick, pal, top }: { value: ColorId; onPick: (id: ColorId) => void; pal: Palette; top: number }) {280 return (281 <Animated.View282 entering={FadeIn.duration(140)}283 exiting={FadeOut.duration(140)}284 role="radiogroup"285 aria-label="Note colour"286 style={[styles.pop, styles.colorPop, { top, backgroundColor: pal.surface, borderColor: pal.border }, pal.dark ? styles.popDark : styles.popLight]}287 >288 {COLORS.map((item, i) => {289 const on = item.id === value;290 return (291 <Animated.View key={item.id} entering={ZoomIn.delay(i * 34).springify().damping(11).stiffness(260)}>292 <Pressable293 role="radio"294 aria-label={item.name}295 aria-checked={on}296 onPress={() => onPick(item.id)}297 style={({ pressed }) => [styles.dotHit, { borderColor: on ? item.color : 'transparent', opacity: pressed ? 0.7 : 1 }]}298 >299 <View style={[styles.dot, { backgroundColor: item.color }]}>300 {on && (301 <Animated.View entering={ZoomIn.springify().damping(11)}>302 <Check size={13} color="#FFFFFF" strokeWidth={3.4} />303 </Animated.View>304 )}305 </View>306 </Pressable>307 </Animated.View>308 );309 })}310 </Animated.View>311 );312}313314function MoreMenu({ onPick, pal, top }: { onPick: () => void; pal: Palette; top: number }) {315 return (316 <Animated.View317 entering={ZoomIn.springify().damping(16).stiffness(280)}318 exiting={FadeOut.duration(140)}319 role="menu"320 aria-label="Note actions"321 style={[styles.pop, styles.menu, { top, backgroundColor: pal.surface, borderColor: pal.border }, pal.dark ? styles.popDark : styles.popLight]}322 >323 {MENU.map((item) => {324 const Icon = item.icon;325 const ink = item.danger ? pal.danger : pal.fg;326 return (327 <Pressable328 key={item.id}329 role="menuitem"330 aria-label={item.label}331 onPress={onPick}332 style={({ pressed }) => [styles.menuRow, item.danger && { borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: pal.border }, pressed && { backgroundColor: pal.pressed }]}333 >334 <Text style={[styles.menuLabel, { color: ink }]}>{item.label}</Text>335 <Icon size={18} color={ink} strokeWidth={2} />336 </Pressable>337 );338 })}339 <Text style={[styles.menuFoot, { color: pal.muted, borderTopColor: pal.border }]}>Synced to {APP_NAME} Cloud</Text>340 </Animated.View>341 );342}343344// ─── A text input that grows with its text ──────────────────────────────────345// A hidden copy of the text sets the height and the input fills it, so it sizes the same way on every platform.346347type AutoTextProps = {348 value: string;349 onChangeText: (v: string) => void;350 textStyle: StyleProp<TextStyle>;351 color: string;352 label: string;353 placeholder?: string;354 placeholderColor: string;355 autoFocus?: boolean;356 onFocus?: () => void;357 onKeyPress?: ComponentProps<typeof TextInput>['onKeyPress'];358};359360function AutoText({ value, onChangeText, textStyle, color, label, placeholder, placeholderColor, autoFocus, onFocus, onKeyPress }: AutoTextProps) {361 const input = useRef<ComponentRef<typeof TextInput>>(null);362 // A block made by pressing Enter takes the cursor once it is on screen.363 useEffect(() => {364 if (!autoFocus) return;365 const id = setTimeout(() => input.current?.focus(), 30);366 return () => clearTimeout(id);367 }, [autoFocus]);368 return (369 <View style={styles.auto}>370 <Text aria-hidden style={[textStyle, styles.autoMirror]}>371 {value ? (value.endsWith('\n') ? `${value} ` : value) : placeholder || ' '}372 </Text>373 <TextInput374 ref={input}375 multiline376 scrollEnabled={false}377 value={value}378 onChangeText={onChangeText}379 onFocus={onFocus}380 onKeyPress={onKeyPress}381 aria-label={label}382 placeholder={placeholder}383 placeholderTextColor={placeholderColor}384 selectionColor={ACCENT}385 style={[textStyle, styles.autoInput, { color }, NO_OUTLINE]}386 />387 </View>388 );389}390391// ─── Checklist ──────────────────────────────────────────────────────────────392393const AnimatedPath = Animated.createAnimatedComponent(Path);394395/** The box fills on a spring, the check draws itself, and a line runs through the text. */396function CheckRow({ item, onToggle, pal }: { item: Item; onToggle: () => void; pal: Palette }) {397 const fill = useSharedValue(item.done ? 1 : 0);398 const draw = useSharedValue(item.done ? 1 : 0);399 const strike = useSharedValue(item.done ? 1 : 0);400 useEffect(() => {401 if (item.done) {402 fill.value = withSpring(1, POP);403 draw.value = withDelay(70, withSpring(1, { damping: 14, stiffness: 210, mass: 0.6 }));404 strike.value = withDelay(90, withTiming(1, { duration: 260, easing: Easing.out(Easing.cubic) }));405 } else {406 fill.value = withTiming(0, { duration: 160 });407 draw.value = withTiming(0, { duration: 120 });408 strike.value = withTiming(0, { duration: 180 });409 }410 }, [item.done, fill, draw, strike]);411412 const fillStyle = useAnimatedStyle(() => ({ opacity: Math.min(1, fill.value * 2), transform: [{ scale: 0.4 + fill.value * 0.6 }] }));413 const mark = useAnimatedProps(() => ({ strokeDashoffset: CHECK_LENGTH * (1 - Math.min(1, Math.max(0, draw.value))) }));414 const textStyle = useAnimatedStyle(() => ({ opacity: 1 - strike.value * 0.52 }));415 const lineStyle = useAnimatedStyle(() => ({ opacity: strike.value > 0.01 ? 1 : 0, transform: [{ scaleX: strike.value }] }));416417 return (418 <Animated.View entering={item.fresh ? FadeInDown.springify().damping(15).stiffness(240) : undefined}>419 <Pressable role="checkbox" aria-checked={item.done} aria-label={item.text} onPress={onToggle} style={({ pressed }) => [styles.checkRow, pressed && { backgroundColor: pal.pressed }]}>420 <View style={[styles.box, { borderColor: pal.faint }]}>421 <Animated.View style={[styles.boxFill, fillStyle]} />422 <View>423 <Svg width={14} height={14} viewBox="0 0 14 14">424 <AnimatedPath d="M2.6 7.4l2.9 2.9 5.9-6.4" stroke={ON_ACCENT} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round" fill="none" strokeDasharray={`${CHECK_LENGTH} ${CHECK_LENGTH}`} animatedProps={mark} />425 </Svg>426 </View>427 </View>428 <View style={styles.checkTextWrap}>429 <Animated.Text numberOfLines={1} style={[styles.checkText, { color: pal.body }, textStyle]}>430 {item.text}431 </Animated.Text>432 <Animated.View pointerEvents="none" style={[styles.strike, { backgroundColor: pal.muted }, lineStyle]} />433 </View>434 </Pressable>435 </Animated.View>436 );437}438439type ChecklistProps = {440 items: Item[];441 onToggle: (id: string) => void;442 onAdd: (text: string) => void;443 inputRef: React.RefObject<ComponentRef<typeof TextInput> | null>;444 onFocusChange: (focused: boolean) => void;445 pal: Palette;446};447448function Checklist({ items, onToggle, onAdd, inputRef, onFocusChange, pal }: ChecklistProps) {449 const [draft, setDraft] = useState('');450 const done = items.filter((i) => i.done).length;451 const share = items.length ? done / items.length : 0;452 const progress = useSharedValue(share);453 useEffect(() => {454 progress.value = withSpring(share, { damping: 16, stiffness: 160, mass: 0.7 });455 }, [share, progress]);456 const barStyle = useAnimatedStyle(() => ({ width: `${Math.min(1, Math.max(0, progress.value)) * 100}%` }));457458 const submit = () => {459 const text = draft.trim();460 if (!text) return;461 onAdd(text);462 setDraft('');463 };464465 return (466 <View style={[styles.checklist, { backgroundColor: pal.surface, borderColor: pal.border }]}>467 <View style={styles.progressRow}>468 <View style={[styles.track, { backgroundColor: pal.border }]}>469 <Animated.View style={[styles.trackFill, barStyle]} />470 </View>471 <Text aria-live="polite" style={[styles.progressLabel, { color: pal.muted }]}>472 {done} of {items.length} done473 </Text>474 </View>475 {items.map((item) => (476 <CheckRow key={item.id} item={item} onToggle={() => onToggle(item.id)} pal={pal} />477 ))}478 <View style={styles.addRow}>479 <Pressable role="button" aria-label="Add item" onPress={() => (draft.trim() ? submit() : inputRef.current?.focus())} style={[styles.box, styles.addBox, { borderColor: pal.faint }]}>480 <Plus size={13} color={pal.muted} strokeWidth={2.6} />481 </Pressable>482 <TextInput483 ref={inputRef}484 value={draft}485 onChangeText={setDraft}486 onSubmitEditing={submit}487 onFocus={() => onFocusChange(true)}488 onBlur={() => onFocusChange(false)}489 submitBehavior="submit"490 returnKeyType="done"491 aria-label="New checklist item"492 placeholder="Add item"493 placeholderTextColor={pal.muted}494 selectionColor={ACCENT}495 style={[styles.addInput, { color: pal.fg }, NO_OUTLINE]}496 />497 {draft.trim() ? (498 <Animated.View entering={ZoomIn.springify().damping(13)}>499 <PressableScale label="Add to checklist" onPress={submit}>500 <View style={styles.addGo}>501 <Text style={styles.addGoLabel}>Add</Text>502 </View>503 </PressableScale>504 </Animated.View>505 ) : null}506 </View>507 </View>508 );509}510511// ─── Image block ────────────────────────────────────────────────────────────512513function ImageBlock({ onRemove, pal }: { onRemove: () => void; pal: Palette }) {514 const o = useSharedValue(0);515 const style = useAnimatedStyle(() => ({ opacity: o.value }));516 return (517 <View>518 <View style={[styles.photo, { backgroundColor: pal.photoHold }]}>519 <Animated.View style={[StyleSheet.absoluteFill, style]}>520 <Image source={{ uri: NOTE.photo }} alt={NOTE.photoAlt} resizeMode="cover" onLoad={() => (o.value = withTiming(1, { duration: 520 }))} style={styles.fill} />521 </Animated.View>522 <PressableScale label="Remove image" onPress={onRemove} style={styles.photoRemove}>523 <View style={styles.photoRemoveDisc}>524 <X size={15} color="#FFFFFF" strokeWidth={2.4} />525 </View>526 </PressableScale>527 </View>528 <Text style={[styles.caption, { color: pal.muted }]}>{NOTE.caption}</Text>529 </View>530 );531}532533// ─── Formatting toolbar ─────────────────────────────────────────────────────534535function Tool({ icon: Icon, label, active, onPress, pal }: { icon: LucideIcon; label: string; active?: boolean; onPress: () => void; pal: Palette }) {536 const t = useSharedValue(active ? 1 : 0);537 useEffect(() => {538 t.value = withSpring(active ? 1 : 0, { damping: 14, stiffness: 300, mass: 0.6 });539 }, [active, t]);540 const chip = useAnimatedStyle(() => ({ opacity: Math.min(1, t.value * 1.5), transform: [{ scale: 0.6 + t.value * 0.4 }] }));541 return (542 <PressableScale label={label} selected={!!active} onPress={onPress} to={0.84} style={styles.toolSlot}>543 <View style={styles.tool}>544 <Animated.View style={[StyleSheet.absoluteFill, styles.toolChip, { backgroundColor: pal.accentSoft }, chip]} />545 <Icon size={20} color={active ? pal.accentText : pal.fg} strokeWidth={active ? 2.6 : 2.1} />546 </View>547 </PressableScale>548 );549}550551// ─── Screen ─────────────────────────────────────────────────────────────────552553let uid = 0;554const nextId = (prefix: string) => `${prefix}-${++uid}`;555556export default function NotesEditorScreen() {557 const c = usePalette();558 const insets = useSafeAreaInsets();559 const [title, setTitle] = useState(NOTE.title);560 const [blocks, setBlocks] = useState<Block[]>(BLOCKS);561 const [items, setItems] = useState<Item[]>(ITEMS);562 const [activeId, setActiveId] = useState<string | null>('packing');563 const [focusId, setFocusId] = useState<string | null>(null);564 const [adding, setAdding] = useState(false);565 const [pinned, setPinned] = useState(true);566 const [color, setColor] = useState<ColorId>('amber');567 const [open, setOpen] = useState<'none' | 'colors' | 'menu'>('none');568 const [saving, setSaving] = useState(false);569 const [edited, setEdited] = useState(false);570 const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);571 const addInput = useRef<ComponentRef<typeof TextInput>>(null);572 const booted = useRef(false);573574 useEffect(() => {575 booted.current = true;576 return () => {577 if (saveTimer.current) clearTimeout(saveTimer.current);578 };579 }, []);580581 /** Every edit shows "Saving..." and, once the typing pauses, saves. Replace the timer with your save call. */582 const touch = () => {583 setSaving(true);584 setEdited(true);585 if (saveTimer.current) clearTimeout(saveTimer.current);586 saveTimer.current = setTimeout(() => setSaving(false), SAVE_DELAY);587 };588589 const tagColor = COLORS.find((item) => item.id === color)?.color ?? ACCENT;590 const active = blocks.find((b) => b.id === activeId);591 const activeText = active && active.kind === 'text' ? active : null;592 const hasImage = blocks.some((b) => b.kind === 'image');593 const words =594 countWords(title) +595 blocks.reduce((n, b) => n + (b.kind === 'text' ? countWords(b.text) : 0), 0) +596 items.reduce((n, i) => n + countWords(i.text), 0);597598 const patch = (id: string, change: Partial<Extract<Block, { kind: 'text' }>>) => {599 setBlocks((list) => list.map((b) => (b.id === id && b.kind === 'text' ? { ...b, ...change } : b)));600 touch();601 };602603 /** Typing in a block. Enter in a bullet starts the next bullet (or leaves the list if it is empty); Enter in a heading starts a paragraph. */604 const edit = (block: Extract<Block, { kind: 'text' }>, value: string) => {605 const at = value.indexOf('\n');606 if (block.as === 'p' || at < 0) return patch(block.id, { text: value });607 if (block.as === 'bullet' && !value.trim()) return patch(block.id, { as: 'p', text: '' });608 const next: Block = { id: nextId('block'), kind: 'text', as: block.as === 'bullet' ? 'bullet' : 'p', text: value.slice(at + 1).replace(/\n/g, ' ') };609 setBlocks((list) => list.flatMap((b) => (b.id === block.id && b.kind === 'text' ? [{ ...b, text: value.slice(0, at) }, next] : [b])));610 setFocusId(next.id);611 setActiveId(next.id);612 touch();613 };614615 /** Backspace in an empty bullet removes it. */616 const keyFor = (block: Extract<Block, { kind: 'text' }>): NonNullable<ComponentProps<typeof TextInput>['onKeyPress']> => (e) => {617 if (e.nativeEvent.key !== 'Backspace' || block.text || block.as !== 'bullet') return;618 setBlocks((list) => list.filter((b) => b.id !== block.id));619 setActiveId(null);620 touch();621 };622623 const format = (change: (b: Extract<Block, { kind: 'text' }>) => Partial<Extract<Block, { kind: 'text' }>>) => {624 if (activeText) patch(activeText.id, change(activeText));625 };626627 const toggleImage = () => {628 setBlocks((list) => {629 if (list.some((b) => b.kind === 'image')) return list.filter((b) => b.kind !== 'image');630 const at = Math.max(0, list.findIndex((b) => b.id === activeId));631 return [...list.slice(0, at + 1), { id: nextId('photo'), kind: 'image' as const }, ...list.slice(at + 1)];632 });633 touch();634 };635636 const toggleItem = (id: string) => {637 setItems((list) => list.map((i) => (i.id === id ? { ...i, done: !i.done } : i)));638 touch();639 };640 const addItem = (text: string) => {641 setItems((list) => [...list, { id: nextId('item'), text, done: false, fresh: true }]);642 touch();643 };644645 const pick = (id: ColorId) => {646 setColor(id);647 touch();648 setTimeout(() => setOpen('none'), 260);649 };650651 const enter = (i: number) => FadeInDown.delay(booted.current ? 0 : 60 + i * 45).duration(booted.current ? 220 : 420);652 const popTop = insets.top + 54;653654 return (655 <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={[styles.screen, { backgroundColor: c.bg }]}>656 <View style={styles.column}>657 {/* Opaque top bar, so the note never shows through it */}658 <View style={[styles.header, { backgroundColor: c.bg, paddingTop: insets.top, height: insets.top + 52 }]}>659 <Edge color={color} pal={c} />660 <PressableScale label={`Back to ${APP_NAME} notes`}>661 <View style={styles.round}>662 <ChevronLeft size={24} color={c.fg} strokeWidth={2.2} />663 </View>664 </PressableScale>665 <SaveStatus saving={saving} pal={c} />666 <View style={styles.fill} />667 <PinButton668 pinned={pinned}669 pal={c}670 onPress={() => {671 setPinned((v) => !v);672 touch();673 }}674 />675 <PressableScale label="Note colour" expanded={open === 'colors'} onPress={() => setOpen(open === 'colors' ? 'none' : 'colors')}>676 <View style={[styles.round, open === 'colors' && { backgroundColor: c.pressed }]}>677 <View style={[styles.swatch, { backgroundColor: tagColor, borderColor: c.bg, boxShadow: `0 0 0 1.5px ${tagColor}` }]} />678 </View>679 </PressableScale>680 <PressableScale label="More actions" expanded={open === 'menu'} onPress={() => setOpen(open === 'menu' ? 'none' : 'menu')}>681 <View style={[styles.round, open === 'menu' && { backgroundColor: c.pressed }]}>682 <Ellipsis size={22} color={c.fg} strokeWidth={2.2} />683 </View>684 </PressableScale>685 </View>686687 <View style={styles.fill}>688 <Edge color={color} pal={c} />689 <ScrollView keyboardShouldPersistTaps="handled" showsVerticalScrollIndicator={false} contentContainerStyle={styles.content}>690 <Animated.View entering={enter(0)}>691 <AutoText692 value={title}693 onChangeText={(v) => {694 setTitle(v.replace(/\n/g, ''));695 touch();696 }}697 textStyle={styles.title}698 color={c.fg}699 label="Title"700 placeholder="Title"701 placeholderColor={c.faint}702 />703 <View style={styles.meta}>704 <Folder size={13} color={tagColor} strokeWidth={2.4} />705 <Text style={[styles.metaStrong, { color: c.body }]}>{NOTE.folder}</Text>706 <View style={[styles.metaDot, { backgroundColor: c.faint }]} />707 <Text style={[styles.metaText, { color: c.muted }]}>{edited ? 'Edited just now' : NOTE.edited}</Text>708 <View style={[styles.metaDot, { backgroundColor: c.faint }]} />709 <Text aria-live="polite" style={[styles.metaText, styles.tabular, { color: c.muted }]}>710 {words} words711 </Text>712 </View>713 </Animated.View>714715 {blocks.map((block, i) => {716 if (block.kind === 'image') {717 return (718 <Animated.View key={block.id} entering={enter(i + 1)} exiting={FadeOut.duration(160)} style={styles.blockImage}>719 <ImageBlock onRemove={toggleImage} pal={c} />720 </Animated.View>721 );722 }723 if (block.kind === 'checklist') {724 return (725 <Animated.View key={block.id} entering={enter(i + 1)} style={styles.blockList}>726 <Checklist items={items} onToggle={toggleItem} onAdd={addItem} inputRef={addInput} onFocusChange={setAdding} pal={c} />727 </Animated.View>728 );729 }730 const weight = block.bold ? (block.as === 'h' ? styles.heavier : styles.bold) : null;731 const input = (732 <AutoText733 value={block.text}734 onChangeText={(v) => edit(block, v)}735 onFocus={() => setActiveId(block.id)}736 onKeyPress={keyFor(block)}737 autoFocus={block.id === focusId}738 textStyle={[block.as === 'h' ? styles.heading : styles.para, weight, block.italic && styles.italic]}739 color={block.as === 'h' ? c.fg : c.body}740 label={block.as === 'h' ? 'Heading' : block.as === 'bullet' ? 'List item' : 'Paragraph'}741 placeholder={block.as === 'h' ? 'Heading' : block.as === 'bullet' ? 'List item' : 'Write something'}742 placeholderColor={c.faint}743 />744 );745 return (746 <Animated.View key={block.id} entering={enter(i + 1)} style={block.as === 'h' ? styles.blockHeading : block.as === 'bullet' ? styles.blockBullet : styles.blockPara}>747 {block.as === 'bullet' && <View style={[styles.bullet, { backgroundColor: c.muted }]} />}748 {input}749 </Animated.View>750 );751 })}752753 <Animated.View entering={enter(blocks.length + 1)} style={styles.tags} aria-label="Tags">754 {TAGS.map((tag) => (755 <Pressable key={tag} role="button" aria-label={`Tag ${tag}`} style={({ pressed }) => [styles.tag, { backgroundColor: pressed ? c.pressed : c.chip }]}>756 <Hash size={12} color={c.muted} strokeWidth={2.6} />757 <Text style={[styles.tagLabel, { color: c.body }]}>{tag}</Text>758 </Pressable>759 ))}760 <Pressable role="button" aria-label="Add tag" style={({ pressed }) => [styles.tag, styles.tagAdd, { borderColor: c.faint, opacity: pressed ? 0.55 : 1 }]}>761 <Plus size={12} color={c.muted} strokeWidth={2.6} />762 <Text style={[styles.tagLabel, { color: c.muted }]}>Tag</Text>763 </Pressable>764 </Animated.View>765 </ScrollView>766 </View>767768 {/* Opaque toolbar above the home indicator. It formats the block the cursor was last in. */}769 <View role="toolbar" aria-label="Formatting" style={[styles.toolbar, { backgroundColor: c.bg, borderTopColor: c.border, paddingBottom: insets.bottom + 6 }]}>770 <Tool icon={Bold} label="Bold" active={!!activeText?.bold} onPress={() => format((b) => ({ bold: !b.bold }))} pal={c} />771 <Tool icon={Italic} label="Italic" active={!!activeText?.italic} onPress={() => format((b) => ({ italic: !b.italic }))} pal={c} />772 <Tool icon={Heading} label="Heading" active={activeText?.as === 'h'} onPress={() => format((b) => ({ as: b.as === 'h' ? 'p' : 'h' }))} pal={c} />773 <View style={[styles.toolDivider, { backgroundColor: c.border }]} />774 <Tool icon={List} label="Bullet list" active={activeText?.as === 'bullet'} onPress={() => format((b) => ({ as: b.as === 'bullet' ? 'p' : 'bullet' }))} pal={c} />775 <Tool icon={ListChecks} label="Checklist" active={adding} onPress={() => addInput.current?.focus()} pal={c} />776 <Tool icon={ImageIcon} label={hasImage ? 'Remove image' : 'Insert image'} onPress={toggleImage} pal={c} />777 </View>778779 {open !== 'none' && <Pressable aria-label="Close" onPress={() => setOpen('none')} style={StyleSheet.absoluteFill} />}780 {open === 'colors' && <ColorPicker value={color} onPick={pick} pal={c} top={popTop} />}781 {open === 'menu' && <MoreMenu onPick={() => setOpen('none')} pal={c} top={popTop} />}782 </View>783 </KeyboardAvoidingView>784 );785}786787// ─── Styles ─────────────────────────────────────────────────────────────────788789const styles = StyleSheet.create({790 screen: { flex: 1, overflow: 'hidden' },791 // On tablets and the web the note stays a phone-width column, centred on the screen's own background.792 column: { flex: 1, width: '100%', maxWidth: COLUMN, alignSelf: 'center' },793 fill: { flex: 1 },794 tabular: { fontVariant: ['tabular-nums'] },795 content: { paddingLeft: 24, paddingRight: 20, paddingTop: 10, paddingBottom: 28 },796797 // Top bar798 header: { flexDirection: 'row', alignItems: 'center', paddingLeft: 10, paddingRight: 10, gap: 2, overflow: 'hidden', zIndex: 1 },799 round: { width: 40, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center' },800 swatch: { width: 20, height: 20, borderRadius: 10, borderWidth: 2.5 },801 status: { height: 28, borderRadius: 14, paddingLeft: 8, paddingRight: 11, flexDirection: 'row', alignItems: 'center', gap: 6, marginLeft: 2 },802 statusIcon: { width: 16, height: 16, alignItems: 'center', justifyContent: 'center' },803 statusCheck: { width: 16, height: 16, borderRadius: 8, backgroundColor: SUCCESS, alignItems: 'center', justifyContent: 'center' },804 statusLabel: { fontSize: 13, fontWeight: '600', letterSpacing: -0.1 },805 spinner: { width: 14, height: 14, borderRadius: 7, borderWidth: 2 },806807 // Colour edge808 edge: { position: 'absolute', left: 0, top: 0, bottom: 0, width: 110 },809 edgeStripe: { position: 'absolute', left: 0, top: 0, bottom: 0, width: 5 },810811 // Popovers812 pop: { position: 'absolute', right: 12, borderRadius: 20, borderWidth: StyleSheet.hairlineWidth, zIndex: 5 },813 popLight: { shadowColor: '#3B2F12', shadowOpacity: 0.16, shadowRadius: 24, shadowOffset: { width: 0, height: 12 } },814 popDark: { shadowColor: '#000000', shadowOpacity: 0.6, shadowRadius: 24, shadowOffset: { width: 0, height: 12 } },815 colorPop: { flexDirection: 'row', alignItems: 'center', gap: 4, paddingHorizontal: 10, paddingVertical: 9, borderRadius: 26 },816 dotHit: { width: 38, height: 38, borderRadius: 19, borderWidth: 2, alignItems: 'center', justifyContent: 'center' },817 dot: { width: 28, height: 28, borderRadius: 14, alignItems: 'center', justifyContent: 'center' },818 menu: { width: 232, paddingVertical: 6, transformOrigin: 'right top', overflow: 'hidden' },819 menuRow: { height: 46, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },820 menuLabel: { fontSize: 15.5, fontWeight: '500', letterSpacing: -0.1 },821 menuFoot: { marginTop: 6, paddingTop: 10, paddingBottom: 6, paddingHorizontal: 16, fontSize: 12, borderTopWidth: StyleSheet.hairlineWidth },822823 // Title and meta line824 title: { fontSize: 32, lineHeight: 38, fontWeight: '800', letterSpacing: -1 },825 meta: { marginTop: 6, flexDirection: 'row', alignItems: 'center', gap: 6 },826 metaStrong: { fontSize: 13, fontWeight: '600' },827 metaText: { fontSize: 13 },828 metaDot: { width: 3, height: 3, borderRadius: 1.5 },829830 // Text blocks831 auto: { flex: 1, minWidth: 0 },832 autoMirror: { opacity: 0 },833 autoInput: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, padding: 0, margin: 0, textAlignVertical: 'top' },834 blockPara: { marginTop: 14, flexDirection: 'row' },835 blockHeading: { marginTop: 20, flexDirection: 'row' },836 blockBullet: { marginTop: 8, flexDirection: 'row', paddingLeft: 4, gap: 12 },837 blockImage: { marginTop: 16 },838 blockList: { marginTop: 10 },839 para: { fontSize: 16.5, lineHeight: 25, letterSpacing: -0.1 },840 heading: { fontSize: 21, lineHeight: 27, fontWeight: '700', letterSpacing: -0.5 },841 bold: { fontWeight: '700' },842 heavier: { fontWeight: '900' },843 italic: { fontStyle: 'italic' },844 bullet: { marginTop: 10, width: 5.5, height: 5.5, borderRadius: 3 },845846 // Image block847 photo: { height: 156, borderRadius: 18, overflow: 'hidden' },848 photoRemove: { position: 'absolute', top: 8, right: 8 },849 photoRemoveDisc: { width: 28, height: 28, borderRadius: 14, backgroundColor: 'rgba(12,16,16,0.52)', alignItems: 'center', justifyContent: 'center' },850 caption: { marginTop: 8, fontSize: 13, lineHeight: 18, fontStyle: 'italic' },851852 // Checklist853 checklist: { borderRadius: 18, borderWidth: StyleSheet.hairlineWidth, paddingVertical: 6, overflow: 'hidden' },854 progressRow: { height: 30, paddingHorizontal: 14, flexDirection: 'row', alignItems: 'center', gap: 12 },855 track: { flex: 1, height: 5, borderRadius: 2.5, overflow: 'hidden' },856 trackFill: { height: 5, borderRadius: 2.5, backgroundColor: ACCENT },857 progressLabel: { fontSize: 12.5, fontWeight: '600', fontVariant: ['tabular-nums'] },858 checkRow: { minHeight: 38, paddingHorizontal: 14, flexDirection: 'row', alignItems: 'center', gap: 12 },859 box: { width: 22, height: 22, borderRadius: 7, borderWidth: 1.8, alignItems: 'center', justifyContent: 'center' },860 boxFill: { position: 'absolute', top: -1.8, left: -1.8, right: -1.8, bottom: -1.8, borderRadius: 7, backgroundColor: ACCENT },861 checkTextWrap: { flexShrink: 1, justifyContent: 'center' },862 checkText: { fontSize: 16, lineHeight: 22, letterSpacing: -0.1 },863 strike: { position: 'absolute', left: -2, right: -2, height: 1.5, borderRadius: 1, transformOrigin: 'left center' },864 addRow: { height: 40, paddingLeft: 14, paddingRight: 8, flexDirection: 'row', alignItems: 'center', gap: 12 },865 addBox: { borderStyle: 'dashed' },866 addInput: { flex: 1, minWidth: 0, height: 40, fontSize: 16, padding: 0 },867 addGo: { height: 28, paddingHorizontal: 12, borderRadius: 14, backgroundColor: ACCENT, justifyContent: 'center' },868 addGoLabel: { color: ON_ACCENT, fontSize: 13, fontWeight: '700' },869870 // Tags871 tags: { marginTop: 24, flexDirection: 'row', flexWrap: 'wrap', gap: 8 },872 tag: { height: 30, paddingLeft: 9, paddingRight: 12, borderRadius: 15, flexDirection: 'row', alignItems: 'center', gap: 4 },873 tagAdd: { borderWidth: 1, borderStyle: 'dashed' },874 tagLabel: { fontSize: 13.5, fontWeight: '500' },875876 // Toolbar877 toolbar: { flexDirection: 'row', alignItems: 'center', paddingTop: 6, paddingHorizontal: 10, borderTopWidth: StyleSheet.hairlineWidth },878 toolSlot: { flex: 1, alignItems: 'center' },879 tool: { width: 46, height: 42, alignItems: 'center', justifyContent: 'center' },880 toolChip: { borderRadius: 13 },881 toolDivider: { width: StyleSheet.hairlineWidth, height: 22, marginHorizontal: 4 },882});