mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 06:37:33 +00:00
Rich formatting and colours for notes (#1889)
* Rich formatting and colours for notes Asked for in discussion #1629: notes should carry formatting, links and colour, so a warning reads differently from a recommendation. Notes have rendered Markdown for a long time. The problem was that the only way to write it was a bare textarea, so unless you already knew the syntax there was nothing to tell you it existed. Both note fields get a formatting bar - bold, italic, strikethrough, code, link, lists, quote - which edits Markdown rather than replacing it with a rich-text model, so the stored value stays plain text that the PDF, the plugin API and every existing note keep reading unchanged. Links now open in their own tab. A bare anchor navigates the planner away, which loses the open day and the map, and without rel=noopener the opened page can navigate this one - notes are content other trip members wrote. Day notes get a colour from a short shared palette. It tints the card, the border and the icon circle, and it reaches the PDF as the spine and rule rather than a fill. The dialog is two columns now, with a live preview of the card beside the picker, because a row of swatches says nothing about what a tinted note looks like next to a place. On the phone the thirty-two icon grid was most of the screen, so it is folded behind the chosen icon, which doubles as the colour preview. The detail field there got the same formatting bar and the same 2000 character ceiling as the desktop one - they write the same column. * Fix the tests that pinned the old note caps, and rework the note actions The e2e suite builds its own day_notes table by hand rather than going through schema.ts, so it never got the new column and every note insert came back 500. Three more tests wrote down the 250 character body cap and the old create() arity. While in there: the edit and delete buttons on a note card were a 10px icon in a 14px box, side by side, and they took width away from the text on every note whether you were hovering or not. They are stacked in a capsule now, 30px targets with their own hover states, floating over the right edge of the card only while the pointer is on it. The text keeps the full width the rest of the time. * Centre the day badge when there is no weather to stack under it The badge is pinned to the top of the row because with weather it is a tall stack that has to start there. Without a location there is no weather block, so all that is left is a 26px circle floating above the day title. * Render the place subtitle in the places list, and drop the form hint The row in the places sidebar printed the description raw while the same line in the day plan renders it, so a place written with the formatting bar read as _underscores_ in one list and italics in the other. Still clamped to one line - it is a list entry, not the inspector. The "Markdown supported" line under the notes field goes: the bar above it already says so.
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
import { Ban } from 'lucide-react'
|
||||
import { NOTE_COLORS } from '@trek/shared'
|
||||
import { useTranslation } from '../../i18n'
|
||||
|
||||
interface Props {
|
||||
/** The picked colour, or null for the neutral card. */
|
||||
value: string | null
|
||||
onChange: (color: string | null) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Swatch row for a note's colour (#1629).
|
||||
*
|
||||
* The palette is deliberately short and lives in @trek/shared, so the picker,
|
||||
* the card and the PDF cannot drift apart. The first cell clears the colour
|
||||
* rather than being a colour of its own — "no colour" is the default state, not
|
||||
* an eighth option.
|
||||
*/
|
||||
export default function NoteColorPicker({ value, onChange }: Props) {
|
||||
const { t } = useTranslation()
|
||||
const selected = 'outline outline-2 outline-[var(--accent)] outline-offset-2 scale-110'
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(null)}
|
||||
aria-pressed={value === null}
|
||||
aria-label={t('notes.color.none')}
|
||||
title={t('notes.color.none')}
|
||||
className={`w-7 h-7 rounded-full grid place-items-center border-2 border-dashed transition-transform duration-150 hover:scale-110 motion-reduce:hover:scale-100 motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-[var(--accent)] ${
|
||||
value === null ? `border-solid border-transparent bg-surface-hover ${selected}` : 'border-edge-secondary hover:border-edge'
|
||||
}`}
|
||||
>
|
||||
<Ban size={12} className="text-content-faint" />
|
||||
</button>
|
||||
|
||||
{NOTE_COLORS.map(color => (
|
||||
<button
|
||||
key={color}
|
||||
type="button"
|
||||
onClick={() => onChange(color)}
|
||||
aria-pressed={value === color}
|
||||
aria-label={t(`notes.color.${COLOR_NAMES[color]}`)}
|
||||
title={t(`notes.color.${COLOR_NAMES[color]}`)}
|
||||
className={`w-7 h-7 rounded-full ring-1 ring-inset ring-black/10 dark:ring-white/15 transition-transform duration-150 hover:scale-110 motion-reduce:hover:scale-100 motion-reduce:transition-none focus-visible:outline-2 focus-visible:outline-[var(--accent)] ${
|
||||
value === color ? selected : ''
|
||||
}`}
|
||||
style={{ backgroundColor: color }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Names rather than hex codes in the label, so a screen reader says something useful. */
|
||||
const COLOR_NAMES: Record<string, string> = {
|
||||
'#dc2626': 'red',
|
||||
'#ea580c': 'orange',
|
||||
'#d97706': 'amber',
|
||||
'#16a34a': 'green',
|
||||
'#0891b2': 'cyan',
|
||||
'#2563eb': 'blue',
|
||||
'#9333ea': 'purple',
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import { render } from '../../../tests/helpers/render'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useRef, useState } from 'react'
|
||||
import NoteFormatToolbar from './NoteFormatToolbar'
|
||||
|
||||
/**
|
||||
* The toolbar edits somebody else's controlled field, so every test drives it
|
||||
* through a real textarea rather than asserting on a callback in isolation —
|
||||
* the selection handling is the part that breaks, and it only exists in the DOM.
|
||||
*/
|
||||
function Harness({ initial = '', onValue }: { initial?: string; onValue?: (v: string) => void }) {
|
||||
const ref = useRef<HTMLTextAreaElement | null>(null)
|
||||
const [value, setValue] = useState(initial)
|
||||
return (
|
||||
<>
|
||||
<NoteFormatToolbar textareaRef={ref} onChange={v => { setValue(v); onValue?.(v) }} />
|
||||
<textarea ref={ref} aria-label="body" value={value} onChange={e => setValue(e.target.value)} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const field = () => screen.getByLabelText('body') as HTMLTextAreaElement
|
||||
const select = (from: number, to: number) => {
|
||||
const ta = field()
|
||||
ta.focus()
|
||||
ta.setSelectionRange(from, to)
|
||||
}
|
||||
|
||||
describe('NoteFormatToolbar', () => {
|
||||
it('FE-NOTEBAR-001: wraps the selection and leaves the selection on the text, not the markers', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial="closes at 5pm" />)
|
||||
select(0, 6)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /bold/i }))
|
||||
|
||||
expect(field().value).toBe('**closes** at 5pm')
|
||||
// "closes", not "**closes**" — a second format nests instead of wrapping syntax.
|
||||
// The selection is restored in a rAF, after the field holds the new text.
|
||||
await waitFor(() => expect(field().value.slice(field().selectionStart, field().selectionEnd)).toBe('closes'))
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-002: an empty selection inserts the markers and puts the caret between them', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial="note" />)
|
||||
select(4, 4)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /italic/i }))
|
||||
|
||||
expect(field().value).toBe('note__')
|
||||
await waitFor(() => expect(field().selectionStart).toBe(5))
|
||||
expect(field().selectionEnd).toBe(5)
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-003: a list prefix applies to the line the caret is on, not the whole field', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial={'first\nsecond'} />)
|
||||
select(8, 8) // inside "second"
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /bulleted list/i }))
|
||||
|
||||
expect(field().value).toBe('first\n- second')
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-004: pressing the same line button again removes the prefix', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial="- already a list" />)
|
||||
select(5, 5)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /bulleted list/i }))
|
||||
|
||||
expect(field().value).toBe('already a list')
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-005: the link button leaves a placeholder URL to type over', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial="opening hours" />)
|
||||
select(0, 13)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^link$/i }))
|
||||
|
||||
expect(field().value).toBe('[opening hours](https://)')
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-006: the buttons do not take focus away from the field', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<Harness initial="text" />)
|
||||
select(0, 4)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /bold/i }))
|
||||
|
||||
// If the button had taken focus, the selection would be gone and the wrap
|
||||
// would have landed at position 0 instead of around the word.
|
||||
expect(field().value).toBe('**text**')
|
||||
await waitFor(() => expect(document.activeElement).toBe(field()))
|
||||
})
|
||||
|
||||
it('FE-NOTEBAR-007: does nothing when the field is not mounted', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
function Detached() {
|
||||
const ref = useRef<HTMLTextAreaElement | null>(null)
|
||||
return <NoteFormatToolbar textareaRef={ref} onChange={onChange} />
|
||||
}
|
||||
render(<Detached />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /bold/i }))
|
||||
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useRef } from 'react'
|
||||
import { Bold, Italic, Strikethrough, List, ListOrdered, Link2, Quote, Code } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n'
|
||||
|
||||
type FormatAction =
|
||||
| { type: 'wrap'; before: string; after: string }
|
||||
| { type: 'line'; prefix: string }
|
||||
|
||||
interface Props {
|
||||
/** The field being formatted. Must be mounted before a button is pressed. */
|
||||
textareaRef: React.RefObject<HTMLTextAreaElement | null>
|
||||
/** Receives the whole new value — the field stays controlled by its owner. */
|
||||
onChange: (value: string) => void
|
||||
/** Rendered smaller, for the narrow note dialog. */
|
||||
compact?: boolean
|
||||
/** Mobile sheets run on their own token family, scoped to `.m-root`. */
|
||||
variant?: 'desktop' | 'mobile'
|
||||
}
|
||||
|
||||
const ACTIONS: Array<{ icon: typeof Bold; labelKey: string; action: FormatAction }> = [
|
||||
{ icon: Bold, labelKey: 'notes.format.bold', action: { type: 'wrap', before: '**', after: '**' } },
|
||||
{ icon: Italic, labelKey: 'notes.format.italic', action: { type: 'wrap', before: '_', after: '_' } },
|
||||
{ icon: Strikethrough, labelKey: 'notes.format.strike', action: { type: 'wrap', before: '~~', after: '~~' } },
|
||||
{ icon: Code, labelKey: 'notes.format.code', action: { type: 'wrap', before: '`', after: '`' } },
|
||||
{ icon: Link2, labelKey: 'notes.format.link', action: { type: 'wrap', before: '[', after: '](https://)' } },
|
||||
{ icon: List, labelKey: 'notes.format.list', action: { type: 'line', prefix: '- ' } },
|
||||
{ icon: ListOrdered, labelKey: 'notes.format.orderedList', action: { type: 'line', prefix: '1. ' } },
|
||||
{ icon: Quote, labelKey: 'notes.format.quote', action: { type: 'line', prefix: '> ' } },
|
||||
]
|
||||
|
||||
/**
|
||||
* Formatting bar for the note fields (#1629).
|
||||
*
|
||||
* Notes have rendered Markdown for a long time, but only ever offered a bare
|
||||
* textarea to write it in, so unless you already knew the syntax there was no
|
||||
* way to find out it existed. This is that discovery surface.
|
||||
*
|
||||
* It edits Markdown rather than being a WYSIWYG editor on purpose: the stored
|
||||
* value stays plain text that the PDF export, the plugin API and every existing
|
||||
* note keep reading unchanged.
|
||||
*
|
||||
* Split from Journey's MarkdownToolbar, which is bound to the journal's own
|
||||
* `--journal-*` variables and hardcodes English labels; this one runs on theme
|
||||
* tokens and goes through i18n, so it can sit in the planner.
|
||||
*/
|
||||
export default function NoteFormatToolbar({ textareaRef, onChange, compact, variant = 'desktop' }: Props) {
|
||||
const { t } = useTranslation()
|
||||
// Applied after the re-render, when the field holds the new text.
|
||||
const pendingSelection = useRef<[number, number] | null>(null)
|
||||
|
||||
const apply = (action: FormatAction) => {
|
||||
const ta = textareaRef.current
|
||||
if (!ta) return
|
||||
|
||||
const { selectionStart: start, selectionEnd: end, value } = ta
|
||||
const selected = value.slice(start, end)
|
||||
let next: string
|
||||
let caret: [number, number]
|
||||
|
||||
if (action.type === 'wrap') {
|
||||
next = value.slice(0, start) + action.before + selected + action.after + value.slice(end)
|
||||
caret = selected
|
||||
// Keep the selection on the text, not on the markers around it, so a
|
||||
// second click on another button nests instead of wrapping the syntax.
|
||||
? [start + action.before.length, end + action.before.length]
|
||||
: [start + action.before.length, start + action.before.length]
|
||||
} else {
|
||||
const lineStart = value.lastIndexOf('\n', start - 1) + 1
|
||||
const alreadyPrefixed = value.startsWith(action.prefix, lineStart)
|
||||
next = alreadyPrefixed
|
||||
? value.slice(0, lineStart) + value.slice(lineStart + action.prefix.length)
|
||||
: value.slice(0, lineStart) + action.prefix + value.slice(lineStart)
|
||||
const shift = alreadyPrefixed ? -action.prefix.length : action.prefix.length
|
||||
caret = [Math.max(lineStart, start + shift), Math.max(lineStart, end + shift)]
|
||||
}
|
||||
|
||||
pendingSelection.current = caret
|
||||
onChange(next)
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
const el = textareaRef.current
|
||||
const sel = pendingSelection.current
|
||||
if (!el || !sel) return
|
||||
el.focus()
|
||||
el.setSelectionRange(sel[0], sel[1])
|
||||
pendingSelection.current = null
|
||||
})
|
||||
}
|
||||
|
||||
const size = compact ? 26 : 30
|
||||
const buttonCls = variant === 'mobile'
|
||||
? 'grid place-items-center rounded-[10px] border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] text-m-muted active:bg-m-act active:text-m-actfg'
|
||||
: 'grid place-items-center rounded-lg text-content-muted hover:text-content hover:bg-surface-hover transition-colors'
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-[2px]" role="toolbar" aria-label={t('notes.format.toolbar')}>
|
||||
{ACTIONS.map(({ icon: Icon, labelKey, action }) => (
|
||||
<button
|
||||
key={labelKey}
|
||||
type="button"
|
||||
title={t(labelKey)}
|
||||
aria-label={t(labelKey)}
|
||||
// Buttons in a toolbar above a field must not steal focus, or the
|
||||
// selection they are about to format is gone before the click lands.
|
||||
onMouseDown={e => e.preventDefault()}
|
||||
onClick={() => apply(action)}
|
||||
className={buttonCls}
|
||||
style={{ width: size, height: size, cursor: 'pointer', padding: 0, ...(variant === 'mobile' ? {} : { border: 0, background: 'none' }) }}
|
||||
>
|
||||
<Icon size={compact ? 13 : 15} strokeWidth={1.9} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import Markdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import { markdownLinkComponents } from './markdownLink'
|
||||
|
||||
describe('markdownLinkComponents', () => {
|
||||
it('FE-MDLINK-001: a link in a note opens in its own tab instead of navigating the planner away', () => {
|
||||
render(
|
||||
<Markdown remarkPlugins={[remarkGfm]} components={markdownLinkComponents}>
|
||||
{'[opening hours](https://example.com/hours)'}
|
||||
</Markdown>
|
||||
)
|
||||
const link = screen.getByRole('link', { name: 'opening hours' })
|
||||
expect(link).toHaveAttribute('href', 'https://example.com/hours')
|
||||
expect(link).toHaveAttribute('target', '_blank')
|
||||
})
|
||||
|
||||
it('FE-MDLINK-002: the opened page gets no handle on the app', () => {
|
||||
render(
|
||||
<Markdown remarkPlugins={[remarkGfm]} components={markdownLinkComponents}>
|
||||
{'[booking](https://example.com)'}
|
||||
</Markdown>
|
||||
)
|
||||
// Without noopener the target can navigate this window through window.opener,
|
||||
// and a note is content other trip members wrote.
|
||||
expect(screen.getByRole('link', { name: 'booking' }).getAttribute('rel')).toContain('noopener')
|
||||
})
|
||||
|
||||
it('FE-MDLINK-003: a bare URL typed into a note becomes a link too', () => {
|
||||
render(
|
||||
<Markdown remarkPlugins={[remarkGfm]} components={markdownLinkComponents}>
|
||||
{'tickets: https://example.com/tickets'}
|
||||
</Markdown>
|
||||
)
|
||||
expect(screen.getByRole('link', { name: 'https://example.com/tickets' })).toHaveAttribute('target', '_blank')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Components } from 'react-markdown'
|
||||
|
||||
/**
|
||||
* How a link inside a note behaves (#1629).
|
||||
*
|
||||
* react-markdown renders a bare `<a href>`, which navigates the SPA away from
|
||||
* the trip: the planner state, the open day, the map viewport are all gone, and
|
||||
* the way back is the browser's back button. A note is a place to park a
|
||||
* booking confirmation or an opening-hours page, so the link opens in its own
|
||||
* tab instead.
|
||||
*
|
||||
* `rel` is not decoration. Without `noopener` the opened page gets a handle on
|
||||
* this one through `window.opener` and can navigate it somewhere else, and a
|
||||
* note is user-supplied content that other trip members read.
|
||||
*/
|
||||
export const markdownLinkComponents: Components = {
|
||||
a: ({ children, href, ...rest }) => (
|
||||
<a {...rest} href={href} target="_blank" rel="noopener noreferrer nofollow">
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}
|
||||
Reference in New Issue
Block a user