Repository navigation
fix(muya): updateParagraph data-loss on list/quote + front-matter insertion + frontmatterType lang (Phase G) - #4429
Conversation
`replaceBlockByLabel`'s frontmatter case derived `lang` with
`/\+-/.test(frontmatterType)`, a regex that tests for the literal
substring '+-' and so never matched any single-char preference value
('-','+',';','{') — `lang` was always 'json'. With the default '-' (YAML)
or '+' (TOML) preference, inserting Front Matter round-tripped to JSON
`{ ... }` braces instead of `---`/`+++` fences.
Replace the buggy regex with a `frontmatterMeta()` helper that maps
frontmatterType to lang+style exactly like legacy muyajs
`handleFrontMatter` (paragraphCtrl.js): '-' -> yaml/'-', '+' -> toml/'+',
';' -> json/';', '{' -> json/'{'. The serializer switches on `lang`, so
this is what makes YAML/TOML emit their fences. Exported for reuse by the
document-start insertion path.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…kquote The Paragraph menu item / `paragraph.paragraph` command sends the 'paragraph' label. Inside a list or blockquote the migrated engine routed it straight to `replaceBlockByLabel` on `_outmostBlockAtCursor()` (the whole container), replacing it with a single paragraph built from only the first content's leading text — every other list item / quote line was silently lost (e.g. `- one\n- two` collapsed to `one`). Legacy muyajs treated 'paragraph' inside a container as a no-op (the cursor's immediate parent is already a paragraph, so paragraphCtrl.js `case 'paragraph'` returned early). Restore that: guard the plain 'paragraph' label so it is a no-op on a list/blockquote container, preserving every item. Leaf blocks (heading, hr, ...) still convert to a paragraph, and `reset-to-paragraph` remains the explicit unwrap command. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… idempotent
The Paragraph > Front Matter menu item sends the 'front-matter' label.
`updateParagraph` had no front-matter case, so it fell through to
`replaceBlockByLabel({ block: _outmostBlockAtCursor(), label: 'frontmatter' })`,
which REPLACED the block at the cursor with a frontmatter block — destroying
that block's content and producing invalid mid-document front matter, with
no idempotency guard (repeat invocation duplicated the block).
Front matter is only valid as the first block of a document. Add a
front-matter branch that mirrors legacy muyajs `handleFrontMatter`:
no-op when the document already starts with front matter, otherwise prepend
a new frontmatter block at the very top via `_insertFrontMatter()` without
touching the cursor block. The block's lang/style follow
`frontmatterType` via the shared `frontmatterMeta` helper.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR fixes three @muyajs/core (packages/muya) regressions found during the Phase G audit, focused on preventing silent data loss in Muya.updateParagraph() and correcting front matter insertion/serialization behavior. It also adds unit tests to cover these previously untested cases.
Changes:
- Prevent
updateParagraph('paragraph')from collapsing list/blockquote containers (data-loss regression) by guarding container conversions. - Make
updateParagraph('front-matter')prepend a front matter block at document start (idempotent) rather than replacing the cursor block (data-loss regression). - Fix
frontmatterType→{ lang, style }derivation via afrontmatterMeta()helper and add new unit tests for these behaviors.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| packages/muya/src/ui/paragraphQuickInsertMenu/config.ts | Adds frontmatterMeta() and uses it when constructing frontmatter state. |
| packages/muya/src/muya.ts | Adds front matter prepend logic and guards paragraph conversion inside list/blockquote containers to prevent data loss. |
| packages/muya/src/tests/updateParagraph.spec.ts | Adds regression tests ensuring paragraph is a no-op for list/blockquote containers and still converts leaf headings. |
| packages/muya/src/tests/frontMatter.spec.ts | Adds tests for front-matter insertion behavior and frontmatterType-driven serialization. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| if ( | ||
| label === 'paragraph' | ||
| && (isAnyListState(block.getState()) || block.blockName === 'block-quote') | ||
| ) { | ||
| return; | ||
| } |
There was a problem hiding this comment.
Fixed in 1c91d9f. You're right — the broad label === 'paragraph' && (isAnyList || block-quote) container guard wrongly suppressed converting a non-paragraph leaf nested inside a container.
Replaced it with _convertLeafToParagraph(), which operates on the cursor's immediate leaf (_immediateBlockAtCursor() = the active content's parent), mirroring legacy muyajs paragraphCtrl.js case 'paragraph' (parent = getParent(block)):
- no-op only when that leaf is already a
paragraph(legacyparent.type === 'p'); - otherwise convert just that single leaf via
replaceBlockByLabel(block.replaceWithkeeps it inside its list-item / blockquote).
The enclosing container is never touched, so the original G4 data loss stays fixed while a heading inside a list item now converts correctly. New test in updateParagraph.spec.ts (b8fc75b): "'paragraph' converts a heading inside a list item, leaving the list intact" — asserts the item became a paragraph, the container is still a 2-item bullet list, both items survive, and the atx hash run is gone.
| case 'frontmatter': { | ||
| const fmState = deepClone(emptyStates.frontmatter); | ||
| fmState.meta.style = frontmatterType; | ||
| fmState.meta.lang = /\+-/.test(frontmatterType) ? 'yaml' : 'json'; | ||
| Object.assign(fmState.meta, frontmatterMeta(frontmatterType)); | ||
| state = fmState; | ||
| newBlock = ScrollPage.loadBlock(label).create(muya, state); | ||
| break; |
There was a problem hiding this comment.
Fixed in 1c91d9f. Agreed — the G5 fix only covered Muya.updateParagraph; the quick-insert path still did an in-place block.replaceWith(newBlock), so converting an empty paragraph mid-document produced invalid front matter (and the keyboard-shortcut path didn't even consult checkCanInsertFrontMatter).
I took the "align with updateParagraph" option: extracted the idempotent doc-start insertion (formerly the private Muya._insertFrontMatter) into a shared insertFrontMatterAtStart(muya) helper here in config.ts, and routed BOTH entry points through it. replaceBlockByLabel now handles label === 'frontmatter' by calling insertFrontMatterAtStart(muya) and returning before the in-place block.replaceWith — so it prepends at document start and is a no-op when front matter already exists, regardless of where the cursor is. Since replaceBlockByLabel is the sink for both the menu click and the keyboard shortcut, the shortcut path is covered too.
New tests in frontMatter.spec.ts (a7fddad): a quick-insert front matter (replaceBlockByLabel) describe block proving mid-document insert lands at doc start (both original paragraphs survive — the in-place replace would have destroyed the cursor block), is idempotent, and honors frontmatterType.
| it('frontmatterType \';\' inserts a JSON block (;;; fences)', async () => { | ||
| const muya = bootMuya('body\n', ';'); | ||
| placeCursorOn(muya, 0); | ||
| muya.updateParagraph('front-matter'); | ||
|
|
||
| await vi.waitFor(() => { | ||
| expect(muya.getState()[0].name).toBe('frontmatter'); | ||
| }); | ||
|
|
||
| // eslint-disable-next-line ts/no-explicit-any | ||
| expect((muya.getState()[0] as any).meta.lang).toBe('json'); | ||
| expect(muya.getMarkdown().startsWith(';;;\n')).toBe(true); | ||
| }); |
There was a problem hiding this comment.
Added in a7fddad. New case in frontMatter.spec.ts: "frontmatterType '{' inserts a JSON block (brace fences)" — asserts meta.lang === 'json', meta.style === '{', and that getMarkdown() serializes the JSON-braces variant (startsWith('{\n')) and explicitly NOT the ;;; fences. The -/+/;/{ matrix is now complete.
…k-insert front matter Two follow-ups from the Copilot review of the Phase G data-loss fixes. G4 (review #1): the `label === 'paragraph'` guard returned early for ANY list/blockquote container, which wrongly suppressed converting a NON-paragraph leaf nested inside the container — e.g. a heading inside a list item stayed a heading. Legacy muyajs (`paragraphCtrl.js case 'paragraph'`) operated on the cursor's immediate leaf (`parent = getParent(block)`) and was a no-op only when that leaf was already a paragraph (`parent.type === 'p'`); otherwise it converted just the leaf. Replace the broad container guard with `_convertLeafToParagraph`, which targets the immediate block at the cursor: no-op when it is already a paragraph, otherwise convert that single leaf in place via `replaceBlockByLabel`. The enclosing list/blockquote is untouched, so the original G4 data loss (collapsing every item/line into one paragraph) stays fixed while a nested heading converts correctly. G5 (review #2): `replaceBlockByLabel`'s `frontmatter` case still did an in-place `block.replaceWith(newBlock)`, so the quick-insert menu ("/Front Matter") could create a frontmatter block MID-document by converting an empty paragraph — but front matter is only valid at document start. The G5 fix had only covered `updateParagraph`. Extract the idempotent doc-start insertion (formerly `Muya._insertFrontMatter`) into a shared `insertFrontMatterAtStart(muya)` helper in config.ts and route BOTH entry points through it: `updateParagraph('front-matter')` and the `frontmatter` label in `replaceBlockByLabel` (which now prepends + returns before the in-place replace). This also closes the keyboard-shortcut quick-insert path, which never consulted `checkCanInsertFrontMatter`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Guards review #1 on PR #4429: `updateParagraph('paragraph')` with the cursor on a heading nested in a list item must convert just that item's heading to a paragraph and leave the 2-item bullet list intact — the earlier "no-op on any list/blockquote container" guard wrongly left the heading unconverted. Asserts the first item became a paragraph, the container is still a 2-item bullet list, both items survive, and the atx hash run is gone. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rType '{'
Guards reviews #2 and #3 on PR #4429.
Review #2 (G5 quick-insert): add a `replaceBlockByLabel({ label:
'frontmatter' })` describe block proving the quick-insert path inserts at
document START when triggered mid-document (both original paragraphs
survive — the old in-place replace would have destroyed the cursor block),
is idempotent when front matter already exists, and honors frontmatterType.
Review #3 (G2 '{' case): add the missing frontmatterType '{' coverage —
asserts lang 'json' + style '{' serialize the JSON-braces variant (`{ … }`)
rather than the `;;;` fences, completing the `-`/`+`/`;`/`{` matrix.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The shortcut tokens rendered as bare text. Give each <kbd> a bordered, rounded keycap style (theme-aware via --floatBgColor / --floatBorderColor / --editorColor) so the symbol shortcuts read as discrete keys, matching the pre-refactor button look. Refs #4429 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…rtcut symbols) (#4504) * fix(muya): restore the last cursor on editor focus editor.focus() unconditionally moved the caret to the first content block. The desktop command palette blurs the editor (clearing activeContentBlock) and then re-focuses it before dispatching a command, so any palette-invoked block command operated on the first block instead of the user's block. This was invisible for commands with keyboard shortcuts / native menu items (which never go through the blur+focus round-trip), but "Reset Paragraph" has no keybinding and is palette-only, so it always no-oped on the wrong block. focus() now restores the user's last caret when its block is still in the tree, falling back to the first block otherwise. Refs #4429 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(muya): unwrap a list from the front menu's active list item Clicking the already-active list type in the paragraph front menu was a no-op; legacy muyajs toggled the list off, unwrapping every item back into plain paragraphs. The front menu now mirrors that behaviour, matching the command-palette/menu "reset-to-paragraph" command. The engine unwrap (formerly the private _resetToParagraph) is promoted to a public Muya.resetToParagraph(block) so the front menu can reset the block it targets rather than the cursor block, keeping a single shared code path. Refs #4429 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * fix(desktop): render command palette shortcuts as key symbols Keybindings are stored as Electron word-form accelerators (Command, Option, Control). normalizeAccelerator only mapped the literal "cmd"/"ctrl" substrings, so the palette rendered literal "Command"/"Option" tokens that were inconsistent with the muya front menu and the native menus. Add a pure acceleratorToTokens(acc, isOsx) helper that maps modifiers to the native symbols (⌘ ⇧ ⌥ ⌃) on macOS and to readable words elsewhere, and route normalizeAccelerator through it. Refs #4429 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> * style(desktop): render command palette shortcuts as keycap buttons The shortcut tokens rendered as bare text. Give each <kbd> a bordered, rounded keycap style (theme-aware via --floatBgColor / --floatBorderColor / --editorColor) so the symbol shortcuts read as discrete keys, matching the pre-refactor button look. Refs #4429 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Fixes three
@muyajs/coreengine bugs found by the Phase G desktop↔engine audit (G2, G4, G5). Two are silent data-loss bugs. Engine-only (packages/muya); all three were untested, which is why they slipped the migration.G4 (data loss) — Paragraph menu "Paragraph" destroyed a list/blockquote
updateParagraph('paragraph')inside a list/blockquote routed straight toreplaceBlockByLabelon_outmostBlockAtCursor()(the whole container) and replaced it with a single paragraph built from only the first content's leading text — every other item/line was silently lost (- one\n- two→one). Legacy muyajs treated 'paragraph' inside a container as a no-op (the cursor's immediate parent is already a paragraph). Restored that: the plain 'paragraph' label is now a guarded no-op on a list/blockquote container, preserving every item. Leaf blocks (heading, hr, …) still convert;reset-to-paragraphremains the explicit unwrap command.G5 (data loss) — Paragraph menu "Front Matter" replaced the cursor block in place
updateParagraph('front-matter')had no special case and fell through toreplaceBlockByLabel({ block: _outmostBlockAtCursor(), label: 'frontmatter' }), replacing the cursor block in place — destroying its content, producing invalid mid-document front matter, and not idempotent (repeat invocation duplicated the block). Front matter is only valid as the first block. Added a front-matter branch mirroring legacyhandleFrontMatter: idempotent no-op when the document already starts with front matter, otherwise prepend a new frontmatter block at the very top via_insertFrontMatter()without touching the cursor block.G2 — frontmatterType produced JSON braces for YAML/TOML
The frontmatter
langwas derived with/\+-/.test(frontmatterType), a regex matching the literal substring+-that never matches any single-char preference (-,+,;,{), solangwas alwaysjson. With the default-(YAML) or+(TOML), inserting Front Matter round-tripped to{ ... }braces instead of---/+++fences. Replaced with afrontmatterMeta()helper mapping frontmatterType → lang+style exactly like legacy muyajs:-→yaml/---,+→toml/+++,;→json/;;;,{→json/{}. Reused by the G5 insertion path.Tests
All three were untested. Added muya unit tests proving:
updateParagraph.spec.ts).frontMatter.spec.ts).-/+/;produce yaml/toml/json (---/+++/;;;) fences respectively (frontMatter.spec.ts).Verification (all green)
pnpm -C packages/muya lint(0 errors, baseline 30 warnings) ·lint:types·lint:css·check-circular(no cycles) ·test(74 files / 589 pass) ·test:spec(1347 pass — no CommonMark/GFM conformance regression).Refs: Phase G audit (G2, G4, G5).
🤖 Generated with Claude Code