From 43251f74ce8e709814fceac497c6a362578f66a0 Mon Sep 17 00:00:00 2001 From: Viktor Lidholt Date: Tue, 27 Oct 2026 20:27:02 +0200 Subject: [PATCH 1/2] feat(write): Wonky Markdown flavor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Wonky Markdown, Write's second Markdown flavor matching the Serverpod blog's directives (spec: specs/wonky_write/11-wonky-markdown.md). GitHub Markdown stays the default; the flavor is a per-document setting that publications can choose. - Elements: callouts, details, cards (nestable containers), grids, buttons, arrow links, chips, numbered headings and YouTube videos (`::youtube`). - Visual editing with chrome, menus, toolbar and slash items; in-place editing of grid items like table cells. - Import/export of the directives; HTML, PDF and print render them, other formats and GitHub Markdown get fallbacks. - MCP tools and the AI assistant know the syntax. - Editing details: typing at the end of a chip or button extends it and → steps out; the caret and click targets match the pills; double and triple clicks in grid items and table cells; values set to what they are succeed without an edit; block chrome ⋯ menus without duplicates. - Sync: a copy restored from the offline cache is checked against the server once on connect. - super_editor patches SE-11 (caret height), SE-12 (caret adjustment), SE-13 (click split at the glyph middle) and SE-14 (content opting out of the editor's gestures), see third_party/super_editor/PATCHES.md. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- TODO.md | 21 + docs/blog-integration.md | 23 +- packages/wonky_app/lib/l10n/wonky_app_en.arb | 3 + .../wonky_app/lib/l10n/wonky_app_en_XA.arb | 3 + .../wonky_app/lib/src/commands/command.dart | 8 + .../lib/src/commands/command_dispatcher.dart | 7 + .../src/commands/palette/command_palette.dart | 2 +- .../lib/src/l10n/wonky_app_localizations.dart | 18 + .../src/l10n/wonky_app_localizations_en.dart | 19 + .../lib/src/menus/menu_resolver.dart | 4 +- .../publications/publications_section.dart | 7 + packages/wonky_core/lib/mcp/write_tools.dart | 37 +- .../wonky_rich_text/lib/src/attributes.dart | 114 +- .../lib/src/import_warning.dart | 4 + .../wonky_rich_text/lib/src/inline_run.dart | 64 +- .../lib/src/markdown/inline_markdown.dart | 44 +- .../lib/src/markdown/inline_reader.dart | 67 +- .../lib/src/markdown/inline_writer.dart | 100 +- .../lib/src/markdown/md_syntax.dart | 20 +- .../lib/src/markdown/wonky_syntax.dart | 454 + .../wonky_rich_text/lib/wonky_rich_text.dart | 1 + .../wonky_write_core/lib/src/delta/boxes.dart | 224 + .../lib/src/delta/embeds.dart | 300 +- .../lib/src/delta/normalizer.dart | 155 +- .../lib/src/delta/validator.dart | 111 +- .../lib/src/derived/outline.dart | 15 +- .../lib/src/derived/plain_text.dart | 10 +- .../lib/src/derived/stats.dart | 2 + .../lib/src/edit/document_edits.dart | 47 +- .../lib/src/edit/document_reader.dart | 18 +- .../lib/src/export/docx/docx_exporter.dart | 184 +- .../lib/src/export/html/html_writer.dart | 99 +- .../src/export/markdown_file_exporter.dart | 2 + .../lib/src/export/odt/odt_exporter.dart | 195 +- .../lib/src/export/office/office_support.dart | 24 + .../lib/src/export/pdf/pdf_exporter.dart | 956 +- .../lib/src/export/pdf/pdf_text.dart | 5 + .../lib/src/export/rtf/rtf_exporter.dart | 7 +- .../lib/src/export/txt_exporter.dart | 9 +- .../lib/src/export/wonky_icons.dart | 72 + .../lib/src/import/import_api.dart | 35 +- .../lib/src/import/wonky_importers.dart | 13 +- .../wonky_write_core/lib/src/ir/doc_tree.dart | 166 +- .../lib/src/ir/doc_tree_builder.dart | 243 +- .../lib/src/markdown/markdown_exporter.dart | 133 +- .../lib/src/markdown/markdown_importer.dart | 128 +- .../lib/src/markdown/wonky_to_gfm.dart | 329 + .../lib/src/testing/generators.dart | 147 +- .../lib/src/theme/mappers/css_writer.dart | 197 + .../lib/src/theme/model/catalog.dart | 71 + .../lib/src/theme/model/values.dart | 21 + .../lib/src/theme/resolve/base_theme.dart | 63 + .../lib/src/theme/resolve/resolved_theme.dart | 385 + .../lib/src/theme/resolve/theme_resolver.dart | 167 + .../lib/wonky_write_core.dart | 2 + .../test/export/wonky_export_test.dart | 156 + .../test/markdown/wonky_markdown_test.dart | 573 + specs/18-publications-and-submissions.md | 4 +- specs/wonky_write/02-document-model.md | 4 +- specs/wonky_write/03-sync-protocol.md | 4 +- specs/wonky_write/04-editor.md | 27 +- specs/wonky_write/05-screens-menus-toolbar.md | 3 + specs/wonky_write/06-themes.md | 3 +- specs/wonky_write/07-import-export-print.md | 2 + specs/wonky_write/09-mcp-and-ai.md | 1 + specs/wonky_write/11-wonky-markdown.md | 501 + specs/wonky_write/README.md | 1 + third_party/super_editor/PATCHES.md | 76 + .../document_caret_overlay.dart | 25 +- .../document_gestures_mouse.dart | 47 +- .../lib/src/default_editor/super_editor.dart | 10 + .../lib/src/default_editor/text.dart | 89 +- .../super_editor/supereditor_caret_test.dart | 4 +- .../wonky_patches/se11_caret_height_test.dart | 86 + .../wonky_patches/se12_caret_adjust_test.dart | 47 + .../wonky_patches/se13_glyph_hit_test.dart | 40 + .../se14_gesture_opt_out_test.dart | 52 + .../models/publication_input.dart | 15 + .../models/publication_settings.dart | 15 + .../publications/models/submission_view.dart | 15 + .../write/messages/doc_meta_changed.dart | 3 +- .../src/protocol/write/models/document.dart | 14 + .../write/models/document_meta_change.dart | 2 +- .../write/models/document_meta_patch.dart | 3 +- .../write/models/document_meta_view.dart | 15 + .../publications/models/publication.dart | 32 +- .../models/publication_input.dart | 15 + .../models/publication_settings.dart | 15 + .../publications/models/submission_view.dart | 15 + wonky_server/lib/src/generated/protocol.dart | 14 + .../write/messages/doc_meta_changed.dart | 3 +- .../src/generated/write/models/document.dart | 29 + .../write/models/document_meta_change.dart | 4 +- .../write/models/document_meta_patch.dart | 3 +- .../write/models/document_meta_view.dart | 15 + .../lib/src/platform/ai/assistant_target.dart | 7 +- .../src/platform/board/ai/spec_index.g.dart | 30 + .../lib/src/platform/drive/drive_copies.dart | 4 +- .../lib/src/platform/drive/drive_service.dart | 25 +- .../publications/models/publication.spy.yaml | 3 + .../models/publication_input.spy.yaml | 2 + .../models/publication_settings.spy.yaml | 2 + .../models/submission_view.spy.yaml | 2 + .../publications/publication_service.dart | 13 +- .../publications/submission_service.dart | 5 + .../lib/src/write/ai/inline_ai_service.dart | 10 +- .../src/write/ai/write_context_builder.dart | 14 +- .../lib/src/write/ai/write_prompts.dart | 27 +- .../lib/src/write/content/write_content.dart | 27 +- .../write/export/write_export_service.dart | 6 +- .../write/export/write_import_service.dart | 6 + .../lib/src/write/mcp/headless_editor.dart | 2 + .../src/write/mcp/write_tool_handlers.dart | 89 +- .../write/messages/doc_meta_changed.spy.yaml | 3 +- .../lib/src/write/models/document.spy.yaml | 2 + .../models/document_meta_change.spy.yaml | 2 +- .../write/models/document_meta_patch.spy.yaml | 3 +- .../write/models/document_meta_view.spy.yaml | 2 + .../lib/src/write/ot/document_connection.dart | 1 + .../lib/src/write/ot/document_service.dart | 17 +- .../lib/src/write/ot/document_store.dart | 2 + .../definition.json | 20276 ++++++++++++++++ .../definition.sql | 4387 ++++ .../definition_project.json | 16971 +++++++++++++ .../migration.json | 61 + .../migration.sql | 45 + .../migrations/migration_registry.txt | 1 + .../write/wonky_markdown_test.dart | 161 + wonky_write/lib/commands/command_icons.dart | 32 + wonky_write/lib/commands/editor_commands.dart | 37 +- wonky_write/lib/commands/extras_commands.dart | 1 + wonky_write/lib/commands/screen_commands.dart | 229 +- wonky_write/lib/commands/write_command.dart | 15 + wonky_write/lib/config/write_menus.dart | 151 + .../document/write_document_session.dart | 46 +- .../attributions/wonky_attributions.dart | 101 + .../commands/editor_command_catalog.dart | 14 + .../commands/wonky_command_catalog.dart | 497 + .../commands/wonky_markdown_commands.dart | 825 + .../commands/write_editor_commands.dart | 60 +- .../editor/components/box_frames.dart | 690 + .../editor/components/editor_services.dart | 66 + .../editor/components/grid_component.dart | 458 + .../editor/components/inline_pills.dart | 266 + .../editor/components/wonky_components.dart | 552 +- .../editor/components/youtube_component.dart | 285 + .../controller/write_editor_controller.dart | 42 +- .../editor/grid/inline_grid_editing.dart | 452 + .../editor/keyboard/editor_keyboard.dart | 44 + .../editor/layers/document_geometry.dart | 24 +- .../editor/mapping/attribution_mapping.dart | 16 + .../editor/mapping/delta_node_codec.dart | 52 +- .../editor/mapping/wonky_embed_node.dart | 5 +- .../features/editor/mapping/wonky_schema.dart | 55 +- .../features/editor/model/field_clicks.dart | 156 + .../editor/paste/clipboard_codec.dart | 19 +- .../editor/paste/editor_clipboard.dart | 7 +- .../features/editor/plugins/slash_items.dart | 111 +- .../reactions/block_conversion_reactions.dart | 50 +- .../editor/reactions/box_guard_reaction.dart | 108 + .../editor/reactions/pill_boundary.dart | 113 + .../reactions/typing_attributes_reaction.dart | 23 +- .../editor/reactions/wonky_shortcuts.dart | 225 + .../requests/block_editing_handlers.dart | 64 +- .../features/editor/setup/editor_factory.dart | 23 +- .../features/editor/styles/editor_theme.dart | 8 + .../features/editor/styles/style_phases.dart | 94 +- .../features/editor/styles/wonky_style.dart | 240 + .../editor/styles/write_stylesheet.dart | 36 +- .../editor/tables/inline_table_editing.dart | 206 +- .../lib/features/editor/ui/wonky_editor.dart | 175 +- .../lib/features/export/export_service.dart | 6 + .../lib/features/import/import_service.dart | 15 +- .../lib/features/links/link_editor.dart | 51 +- .../lib/features/outline/outline_panel.dart | 8 +- .../features/print/print_preview_screen.dart | 1 + .../lib/features/publish/submit_dialog.dart | 8 + .../lib/features/screen/document_menus.dart | 43 + .../features/screen/selection_toolbar.dart | 11 +- .../lib/features/screen/wonky_menus.dart | 383 + .../screen/write_document_controller.dart | 7 + .../screen/write_document_screen.dart | 65 + .../lib/features/screen/write_toolbar.dart | 62 +- .../sync/document_sync_controller.dart | 15 + .../theme_editor/theme_editor_model.dart | 21 +- .../features/theme_editor/theme_sample.dart | 44 +- .../lib/features/themes/theme_adapter.dart | 2 + .../lib/l10n/gen/write_localizations.dart | 624 + .../lib/l10n/gen/write_localizations_en.dart | 4935 ++-- wonky_write/lib/l10n/write_en.arb | 123 +- wonky_write/lib/l10n/write_en_XA.arb | 106 +- .../commands/write_commands_test.dart | 69 + .../wonky_markdown_commands_test.dart | 312 + .../editor/components/box_frames_test.dart | 75 + .../editor/components/grid_editing_test.dart | 349 + .../editor/components/step_heading_test.dart | 41 + .../mapping/delta_document_mapper_test.dart | 66 + .../editor/model/field_clicks_test.dart | 90 + .../editor/reactions/pill_boundary_test.dart | 108 + .../reactions/wonky_shortcuts_test.dart | 211 + .../styles/pill_spacing_style_phase_test.dart | 65 + .../editor/ui/editor_clicks_test.dart | 88 + .../editor/ui/editor_extras_test.dart | 57 + .../features/editor/ui/wonky_editor_test.dart | 32 + .../sync/document_sync_controller_test.dart | 27 + 206 files changed, 61916 insertions(+), 2624 deletions(-) create mode 100644 packages/wonky_rich_text/lib/src/markdown/wonky_syntax.dart create mode 100644 packages/wonky_write_core/lib/src/delta/boxes.dart create mode 100644 packages/wonky_write_core/lib/src/export/wonky_icons.dart create mode 100644 packages/wonky_write_core/lib/src/markdown/wonky_to_gfm.dart create mode 100644 packages/wonky_write_core/test/export/wonky_export_test.dart create mode 100644 packages/wonky_write_core/test/markdown/wonky_markdown_test.dart create mode 100644 specs/wonky_write/11-wonky-markdown.md create mode 100644 third_party/super_editor/test/wonky_patches/se11_caret_height_test.dart create mode 100644 third_party/super_editor/test/wonky_patches/se12_caret_adjust_test.dart create mode 100644 third_party/super_editor/test/wonky_patches/se13_glyph_hit_test.dart create mode 100644 third_party/super_editor/test/wonky_patches/se14_gesture_opt_out_test.dart create mode 100644 wonky_server/migrations/20261026171832105-wonky-markdown/definition.json create mode 100644 wonky_server/migrations/20261026171832105-wonky-markdown/definition.sql create mode 100644 wonky_server/migrations/20261026171832105-wonky-markdown/definition_project.json create mode 100644 wonky_server/migrations/20261026171832105-wonky-markdown/migration.json create mode 100644 wonky_server/migrations/20261026171832105-wonky-markdown/migration.sql create mode 100644 wonky_server/test/integration/write/wonky_markdown_test.dart create mode 100644 wonky_write/lib/features/editor/commands/wonky_command_catalog.dart create mode 100644 wonky_write/lib/features/editor/commands/wonky_markdown_commands.dart create mode 100644 wonky_write/lib/features/editor/components/box_frames.dart create mode 100644 wonky_write/lib/features/editor/components/grid_component.dart create mode 100644 wonky_write/lib/features/editor/components/inline_pills.dart create mode 100644 wonky_write/lib/features/editor/components/youtube_component.dart create mode 100644 wonky_write/lib/features/editor/grid/inline_grid_editing.dart create mode 100644 wonky_write/lib/features/editor/model/field_clicks.dart create mode 100644 wonky_write/lib/features/editor/reactions/box_guard_reaction.dart create mode 100644 wonky_write/lib/features/editor/reactions/pill_boundary.dart create mode 100644 wonky_write/lib/features/editor/reactions/wonky_shortcuts.dart create mode 100644 wonky_write/lib/features/editor/styles/wonky_style.dart create mode 100644 wonky_write/lib/features/screen/wonky_menus.dart create mode 100644 wonky_write/test/features/editor/commands/wonky_markdown_commands_test.dart create mode 100644 wonky_write/test/features/editor/components/box_frames_test.dart create mode 100644 wonky_write/test/features/editor/components/grid_editing_test.dart create mode 100644 wonky_write/test/features/editor/components/step_heading_test.dart create mode 100644 wonky_write/test/features/editor/model/field_clicks_test.dart create mode 100644 wonky_write/test/features/editor/reactions/pill_boundary_test.dart create mode 100644 wonky_write/test/features/editor/reactions/wonky_shortcuts_test.dart create mode 100644 wonky_write/test/features/editor/styles/pill_spacing_style_phase_test.dart create mode 100644 wonky_write/test/features/editor/ui/editor_clicks_test.dart diff --git a/AGENTS.md b/AGENTS.md index 1642f5d6..1b32bbb8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ ## Specs -The specs in `specs/` are the source of truth. Start with `specs/README.md` (reading order, conventions), then `specs/01-architecture.md` (layout, package rules, how the apps are served). App specs: `specs/wonky_write/`, `specs/wonky_sheets/`, `specs/wonky_drive/` and `specs/wonky_slides/` (v2 decisions: `specs/v2-review.md`). Cross-app features: `specs/16-bugs-and-improvements.md` (Bugs & improvements board, M12); the RevLog sync of Sheets and Slides: `specs/17-revlog-sync.md`. Blog submissions from Wonky Write (M14, built): `specs/18-publications-and-submissions.md`; the guide for blog owners is `docs/blog-integration.md`. First-party usage analytics for admins in Wonky Drive (`/drive/analytics`, built): `specs/19-usage-analytics.md`. When implementation reveals a better approach, update the spec in the same change. +The specs in `specs/` are the source of truth. Start with `specs/README.md` (reading order, conventions), then `specs/01-architecture.md` (layout, package rules, how the apps are served). App specs: `specs/wonky_write/`, `specs/wonky_sheets/`, `specs/wonky_drive/` and `specs/wonky_slides/` (v2 decisions: `specs/v2-review.md`). Cross-app features: `specs/16-bugs-and-improvements.md` (Bugs & improvements board, M12); the RevLog sync of Sheets and Slides: `specs/17-revlog-sync.md`. Blog submissions from Wonky Write (M14, built): `specs/18-publications-and-submissions.md`; the guide for blog owners is `docs/blog-integration.md`. Wonky Markdown, Write's second Markdown flavor (the blog's directives: callouts, details, cards, grids, buttons, chips, numbered headings; set per document, publications choose theirs): `specs/wonky_write/11-wonky-markdown.md`. First-party usage analytics for admins in Wonky Drive (`/drive/analytics`, built): `specs/19-usage-analytics.md`. When implementation reveals a better approach, update the spec in the same change. Key rules from the specs: every user-visible action is a command and every state change is undoable (`specs/08-commands-and-undo.md`); single window, never open new tabs or windows (`specs/03-app-shell-and-navigation.md`); UI is built with `shad` and custom widgets in `wonky_ui` (`specs/02-design-system.md`); everything works in light and dark. diff --git a/TODO.md b/TODO.md index 3a38842e..69b6f52f 100644 --- a/TODO.md +++ b/TODO.md @@ -147,6 +147,27 @@ Spec: `specs/18-publications-and-submissions.md` §13; guide: `docs/blog-integra - [ ] Moderators who sign up later get access only with the next submit or status change; grant at sign-up instead. +## Wonky Markdown (Write 11) — open items + +Spec: `specs/wonky_write/11-wonky-markdown.md`. + +- [ ] Chip icons (`:chip[x]{icon=…}`): kept in the Delta and in Markdown, not drawn in the + editor or the exports (out of scope by decision). +- [ ] App widget tests per §12: container frames and chrome, grid inline editing (Enter, + Backspace, arrows, Tab), link style popover, slash items, menu and toolbar visibility per + flavor; light/dark goldens of the elements in the editor, print preview, PDF and HTML. +- [ ] Submit dialog: a *Switch flavor* action next to the flavor warning (today it points to + *File › Markdown flavor*). +- [ ] AC-WM.1–7 and 9 were walked through in a release build (2026-10-26); still open: the + same with two collaborators (flavor switch seen by both), AC-WM.8 through the UI (a + Wonky publication and a submission), and pasting the blog examples as Markdown (the + agent browser pane can't write the clipboard; covered by the codec tests). +- [ ] YouTube videos: the blog's renderer for `::youtube` (`docs/blog-integration.md`; the + serverpod_website repository); thumbnails instead of a link in PDF, DOCX and ODT + exports; other video sites if needed. +- [ ] Chips inside tinted callouts have little contrast (the chip's gray `@codeBg` pill on a + light tint, editor and PDF); consider a subtle border or a tint-aware chip color. + ## RevLog sync — open items Sheets and Slides sync through RevLog (`specs/17-revlog-sync.md`); the CRDT engine, the sync diff --git a/docs/blog-integration.md b/docs/blog-integration.md index f85c9c9b..c7ec0046 100644 --- a/docs/blog-integration.md +++ b/docs/blog-integration.md @@ -229,7 +229,7 @@ Every body has these fields: | `type` | When | Other fields | |--------|------|--------------| | `publication.ping` | You choose *Send test*, or save a new webhook URL | — | -| `submission.submitted` | Every Submit, Resubmit and Submit update | `submission`, `sequence`, `revision`, `fields`, `markdown`, `assets`, `submittedBy` | +| `submission.submitted` | Every Submit, Resubmit and Submit update | `submission`, `sequence`, `revision`, `fields`, `markdown`, `markdownFlavor`, `assets`, `submittedBy` | | `submission.withdrawn` | The contributor withdraws the story, or moves the document to the trash | `submission`, `reason`: `author` or `trashed` | | `submission.disconnected` | The contributor disconnects the document from your blog. No more updates will come for this submission | `submission` | | `comment.created` | Someone replies in the document's thread of your blog's messages (§6.2) | `submission`, `comment` | @@ -260,6 +260,7 @@ Ignore types you don't know; new ones may be added. "note": "Fixed the code samples, thanks!" }, "markdown": "# How we sped up our CI three times\n\n…\n\n![Build times](https://wonky.work/api/pub/v1/assets/ast_0192a3b4-1111-7000-8000-000000000002)\n", + "markdownFlavor": "gfm", "assets": [ { "id": "ast_0192a3b4-1111-7000-8000-000000000002", @@ -287,6 +288,26 @@ Ignore types you don't know; new ones may be added. - Images uploaded to Wonky are WebP (`image/webp`), at most 2048 px on their longest side, with their metadata (EXIF, including GPS) removed. Older images can keep the type they were uploaded with, so read the `type` of each asset. +- `markdownFlavor` is `gfm` or `wonky`. A publication set to **Wonky Markdown** (in its settings) + starts new stories as Wonky documents, and their `markdown` can use the Serverpod blog + directives: callouts (`:::warning[Title]` … `:::`), `:::details`, `:::card`, + `:::grid{columns=3 bullets=check}`, `:button[…](…)`, `:link[…](…)`, `:chip[…]` and numbered + headings (`## (1) Title`); see `specs/wonky_write/11-wonky-markdown.md` §4. A `gfm` story + never contains them. +- Wonky stories can also hold **YouTube videos**, a Wonky extension your renderer has to add: + a line `::youtube[Title]{id=AGAQ_N56wCs start=90}` (the title and `start`, in seconds, are + optional; the id is always the 11-character video id). Render it like this, escaping the + title: + + ```html + + ``` + + The pattern is `^::youtube(?:\[([^\]]*)\])?(?:\s*\{([^}]*)\})?\s*$`, with the options read like + the other directives' (`{key=value key=value}`). - `markdown` is CommonMark with GitHub tables and task lists. Open suggestions in the document are sent as the original text; comments are never included. There is no front matter: the title and the other fields are in `fields` (the Markdown usually starts with the title as a heading, diff --git a/packages/wonky_app/lib/l10n/wonky_app_en.arb b/packages/wonky_app/lib/l10n/wonky_app_en.arb index 0ddda7d8..33d289e3 100644 --- a/packages/wonky_app/lib/l10n/wonky_app_en.arb +++ b/packages/wonky_app/lib/l10n/wonky_app_en.arb @@ -3093,6 +3093,9 @@ "pubTemplate": "Template document (optional)", "pubTemplateHint": "Paste a link to one of your Wonky Write documents", "pubTemplateInvalid": "Paste the link of a Wonky Write document.", + "pubMarkdownFlavor": "Markdown flavor of new stories", + "pubMarkdownGfm": "GitHub Markdown", + "pubMarkdownWonky": "Wonky Markdown (Serverpod blog directives)", "pubRequired": "Required.", "pubHttpsOnly": "Use an https:// address.", "pubFieldSummary": "Summary", diff --git a/packages/wonky_app/lib/l10n/wonky_app_en_XA.arb b/packages/wonky_app/lib/l10n/wonky_app_en_XA.arb index ba3cdf22..28ed712d 100644 --- a/packages/wonky_app/lib/l10n/wonky_app_en_XA.arb +++ b/packages/wonky_app/lib/l10n/wonky_app_en_XA.arb @@ -1332,6 +1332,9 @@ "pubTemplate": "[Ţéɱþļåţé ðöçûɱéñţ (öþţîöñåļ) one two th]", "pubTemplateHint": "[Þåšţé å ļîñķ ţö öñé öƒ ýöûŕ Ŵöñķý Ŵŕîţé ðöçûɱéñţš one two three]", "pubTemplateInvalid": "[Þåšţé ţĥé ļîñķ öƒ å Ŵöñķý Ŵŕîţé ðöçûɱéñţ. one two thre]", + "pubMarkdownFlavor": "[Ṁåŕķðöŵñ ƒļåṽöŕ öƒ ñéŵ šţöŕîéš one two th]", + "pubMarkdownGfm": "[ĜîţĤûƀ Ṁåŕķðöŵñ one t]", + "pubMarkdownWonky": "[Ŵöñķý Ṁåŕķðöŵñ (Šéŕṽéŕþöð ƀļöĝ ðîŕéçţîṽéš) one two three]", "pubRequired": "[Ŕéǫûîŕéð. one]", "pubHttpsOnly": "[Ûšé åñ ĥţţþš:// åððŕéšš. one two]", "pubFieldSummary": "[Šûɱɱåŕý one]", diff --git a/packages/wonky_app/lib/src/commands/command.dart b/packages/wonky_app/lib/src/commands/command.dart index f01a9d88..461ab4da 100644 --- a/packages/wonky_app/lib/src/commands/command.dart +++ b/packages/wonky_app/lib/src/commands/command.dart @@ -32,6 +32,10 @@ abstract class Command { IconData? get icon => null; + /// The icon of a menu item that invokes the command with [args] (a + /// command with a choice argument can show one icon per choice). + IconData? iconFor(Map args) => icon; + /// Extra search terms for the palette. List aliases(BuildContext context) => const []; @@ -71,6 +75,10 @@ abstract class Command { /// Whether the command can run now (drives disabled state everywhere). bool isEnabled(CommandContext ctx, A args) => true; + /// Whether menus, the palette and toolbars show the command at all (Write + /// hides its Wonky Markdown commands in GitHub Markdown documents). + bool isVisible(CommandContext ctx, A args) => true; + /// Tooltip for the disabled state ("You have view access"). String? disabledReason(CommandContext ctx, A args) => null; diff --git a/packages/wonky_app/lib/src/commands/command_dispatcher.dart b/packages/wonky_app/lib/src/commands/command_dispatcher.dart index 00f77004..5c44d488 100644 --- a/packages/wonky_app/lib/src/commands/command_dispatcher.dart +++ b/packages/wonky_app/lib/src/commands/command_dispatcher.dart @@ -34,8 +34,12 @@ class CommandState { required this.enabled, required this.checked, required this.disabledReason, + this.visible = true, }); + /// Whether the command is shown ([Command.isVisible]). + final bool visible; + final bool enabled; final bool? checked; final String? disabledReason; @@ -92,12 +96,14 @@ class CommandDispatcher { final ctx = _context(InvocationSource.menu, null); try { final a = command.parseArgs(args); + final visible = command.isVisible(ctx, a); final role = roleProblem(command, ctx); if (role != null) { return CommandState( enabled: false, checked: command.isChecked(ctx, a), disabledReason: role, + visible: visible, ); } final enabled = command.isEnabled(ctx, a); @@ -105,6 +111,7 @@ class CommandDispatcher { enabled: enabled, checked: command.isChecked(ctx, a), disabledReason: enabled ? null : command.disabledReason(ctx, a), + visible: visible, ); } catch (_) { return const CommandState( diff --git a/packages/wonky_app/lib/src/commands/palette/command_palette.dart b/packages/wonky_app/lib/src/commands/palette/command_palette.dart index e870e415..46ac8bed 100644 --- a/packages/wonky_app/lib/src/commands/palette/command_palette.dart +++ b/packages/wonky_app/lib/src/commands/palette/command_palette.dart @@ -103,7 +103,7 @@ class _CommandPaletteBodyState extends State<_CommandPaletteBody> { final l = WonkyAppLocalizations.of(context); final commands = [ for (final c in s.registry.all) - if (c.showInPalette) c, + if (c.showInPalette && s.dispatcher.stateOf(c.id.value).visible) c, ]; PaletteRow rowOf( Command c, { diff --git a/packages/wonky_app/lib/src/l10n/wonky_app_localizations.dart b/packages/wonky_app/lib/src/l10n/wonky_app_localizations.dart index 926ce2b9..8187b498 100644 --- a/packages/wonky_app/lib/src/l10n/wonky_app_localizations.dart +++ b/packages/wonky_app/lib/src/l10n/wonky_app_localizations.dart @@ -8086,6 +8086,24 @@ abstract class WonkyAppLocalizations { /// **'Paste the link of a Wonky Write document.'** String get pubTemplateInvalid; + /// No description provided for @pubMarkdownFlavor. + /// + /// In en, this message translates to: + /// **'Markdown flavor of new stories'** + String get pubMarkdownFlavor; + + /// No description provided for @pubMarkdownGfm. + /// + /// In en, this message translates to: + /// **'GitHub Markdown'** + String get pubMarkdownGfm; + + /// No description provided for @pubMarkdownWonky. + /// + /// In en, this message translates to: + /// **'Wonky Markdown (Serverpod blog directives)'** + String get pubMarkdownWonky; + /// No description provided for @pubRequired. /// /// In en, this message translates to: diff --git a/packages/wonky_app/lib/src/l10n/wonky_app_localizations_en.dart b/packages/wonky_app/lib/src/l10n/wonky_app_localizations_en.dart index a2eafaf3..d6aab668 100644 --- a/packages/wonky_app/lib/src/l10n/wonky_app_localizations_en.dart +++ b/packages/wonky_app/lib/src/l10n/wonky_app_localizations_en.dart @@ -4659,6 +4659,15 @@ class WonkyAppLocalizationsEn extends WonkyAppLocalizations { @override String get pubTemplateInvalid => 'Paste the link of a Wonky Write document.'; + @override + String get pubMarkdownFlavor => 'Markdown flavor of new stories'; + + @override + String get pubMarkdownGfm => 'GitHub Markdown'; + + @override + String get pubMarkdownWonky => 'Wonky Markdown (Serverpod blog directives)'; + @override String get pubRequired => 'Required.'; @@ -9756,6 +9765,16 @@ class WonkyAppLocalizationsEnXa extends WonkyAppLocalizationsEn { String get pubTemplateInvalid => '[Þåšţé ţĥé ļîñķ öƒ å Ŵöñķý Ŵŕîţé ðöçûɱéñţ. one two thre]'; + @override + String get pubMarkdownFlavor => '[Ṁåŕķðöŵñ ƒļåṽöŕ öƒ ñéŵ šţöŕîéš one two th]'; + + @override + String get pubMarkdownGfm => '[ĜîţĤûƀ Ṁåŕķðöŵñ one t]'; + + @override + String get pubMarkdownWonky => + '[Ŵöñķý Ṁåŕķðöŵñ (Šéŕṽéŕþöð ƀļöĝ ðîŕéçţîṽéš) one two three]'; + @override String get pubRequired => '[Ŕéǫûîŕéð. one]'; diff --git a/packages/wonky_app/lib/src/menus/menu_resolver.dart b/packages/wonky_app/lib/src/menus/menu_resolver.dart index da235d77..4883cfad 100644 --- a/packages/wonky_app/lib/src/menus/menu_resolver.dart +++ b/packages/wonky_app/lib/src/menus/menu_resolver.dart @@ -84,6 +84,7 @@ class MenuResolver { return null; } final state = services.dispatcher.stateOf(commandId, args); + if (!state.visible) return null; final title = label ?? command.title(context); // Drive-scope shortcuts (F2, Del, S…) only apply on the home screen. final driveOnly = @@ -133,7 +134,7 @@ class MenuResolver { return WonkyMenuItem( key: k, label: title, - icon: command.icon, + icon: command.iconFor(args), shortcut: shortcut, enabled: state.enabled, disabledReason: state.disabledReason, @@ -165,6 +166,7 @@ class MenuResolver { return { 'title': c.label ?? command?.title(context) ?? c.commandId, 'enabled': state.enabled, + if (!state.visible) 'hidden': true, if (state.checked != null) 'checked': state.checked, if (services.keymap.shortcutTextOf(c.commandId) != null) 'shortcut': services.keymap.shortcutTextOf(c.commandId), diff --git a/packages/wonky_app/lib/src/publications/publications_section.dart b/packages/wonky_app/lib/src/publications/publications_section.dart index 005fcda9..7842d3bd 100644 --- a/packages/wonky_app/lib/src/publications/publications_section.dart +++ b/packages/wonky_app/lib/src/publications/publications_section.dart @@ -150,6 +150,12 @@ class _PublicationsSectionState extends State { ? null : l.pubTemplateInvalid, ), + SelectFieldSpec( + id: 'markdownFlavor', + label: l.pubMarkdownFlavor, + options: {'gfm': l.pubMarkdownGfm, 'wonky': l.pubMarkdownWonky}, + initial: p?.markdownFlavor == 'wonky' ? 'wonky' : 'gfm', + ), SelectFieldSpec( id: 'summary', label: l.pubFieldSummary, @@ -218,6 +224,7 @@ class _PublicationsSectionState extends State { ? null : r.text('termsUrl').trim(), templateItemUuid: _uuidIn(r.text('template')), + markdownFlavor: r.text('markdownFlavor'), fields: PublicationFields( summary: mode('summary'), tags: mode('tags'), diff --git a/packages/wonky_core/lib/mcp/write_tools.dart b/packages/wonky_core/lib/mcp/write_tools.dart index e88c124e..0d019f57 100644 --- a/packages/wonky_core/lib/mcp/write_tools.dart +++ b/packages/wonky_core/lib/mcp/write_tools.dart @@ -186,6 +186,15 @@ abstract final class WriteSchemas { ); } +/// The Wonky Markdown syntax, for tool descriptions (Write 11 §4, §10). +const _wonkySyntax = + '; in Wonky documents also :::info|tip|note|warning|caution|danger[Title] ' + '… :::, :::details (first ### is the summary) … :::, :::card … :::, ' + ':::grid{columns=3 bullets=check} with "- item" lines … :::, ' + ':button[Label](url){variant=secondary}, :link[Label](url), ' + ':chip[Label], "## (1) Title" numbered headings and ' + '::youtube[Title]{id=VIDEO_ID start=SECONDS} videos on their own line'; + const _addressing = ' Addressing: prefer quote ranges ({"type":"quote","quote":"…"}); ' 'offsets are 0-based Delta offsets (UTF-16 code units, embeds count 1, ' @@ -304,8 +313,10 @@ abstract final class WriteTools { name: 'write.insert_markdown', title: 'Insert Markdown', description: - 'Inserts GitHub-flavored Markdown at a position (headings, lists, ' - 'quotes, code, tables, links, images by URL). as: "auto" (default; a ' + 'Inserts Markdown at a position (headings, lists, quotes, code, ' + 'tables, links, images by URL) in the document\'s flavor ' + '(markdown_flavor of write.get_document)$_wonkySyntax. as: "auto" ' + '(default; a ' 'single paragraph inserted mid-line is merged inline, otherwise ' 'blocks), "inline" or "blocks". Use it to add new content; use ' 'write.replace_range to rewrite existing text.$_addressing', @@ -597,6 +608,27 @@ abstract final class WriteTools { scopes: _edit, ); + static final setMarkdownFlavor = McpToolDefinition( + name: 'write.set_markdown_flavor', + title: 'Set the Markdown flavor', + description: + 'Sets the document\'s Markdown flavor: "gfm" (GitHub-flavored, the ' + 'default) or "wonky" (GFM plus the Serverpod blog directives: ' + 'callouts, details, cards, grids, buttons, arrow links, chips, ' + 'numbered headings). Switching to "gfm" converts Wonky elements to ' + 'their closest GFM form (one change); with convert: false it fails ' + 'with validation_failed when there is something to convert. Revert ' + 'with changes.revert.', + inputSchema: WriteSchemas.doc( + { + 'flavor': const JsonSchema.string(enumValues: ['gfm', 'wonky']), + 'convert': const JsonSchema.boolean(defaultValue: true), + }, + required: ['flavor'], + ), + scopes: _edit, + ); + static final updatePageSetup = McpToolDefinition( name: 'write.update_page_setup', title: 'Update the page setup', @@ -742,6 +774,7 @@ abstract final class WriteTools { insertTable, updateTable, updatePageSetup, + setMarkdownFlavor, listSuggestions, acceptSuggestion, rejectSuggestion, diff --git a/packages/wonky_rich_text/lib/src/attributes.dart b/packages/wonky_rich_text/lib/src/attributes.dart index 753e7008..82debb42 100644 --- a/packages/wonky_rich_text/lib/src/attributes.dart +++ b/packages/wonky_rich_text/lib/src/attributes.dart @@ -30,6 +30,15 @@ abstract final class WonkyAttr { /// `String` — user UUID of a mention; always paired with a `mailto:` [link]. static const mention = 'mention'; + /// `String` — Wonky Markdown look of a [link]: `arrow`, `button` or + /// `buttonSecondary` (Write 11 §2.1). Excludes [bold], [italic], [strike], + /// [code] and [mention]. + static const linkStyle = 'linkStyle'; + + /// `true` or a `String` icon name — a Wonky Markdown chip (Write 11 §2.1). + /// Excludes every other inline attribute. + static const chip = 'chip'; + // Block. /// `int` 1–6 — heading level. @@ -47,6 +56,15 @@ abstract final class WonkyAttr { /// `int` 1–8 — list nesting level; only valid together with [list]. static const indent = 'indent'; + /// `int` 0–9999 — the number of a Wonky Markdown numbered heading + /// (`## (n) Title`); only valid with [header] 2 or 3 (Write 11 §2.2). + static const step = 'step'; + + /// `List` of container frames, outermost first — the Wonky Markdown + /// containers (callout, details, card) a line is in (Write 11 §2.2). + /// Valid next to every other block attribute and on embed lines. + static const box = 'box'; + // Overlays. /// Prefix of comment anchor keys: `cmt_: true`. @@ -56,13 +74,62 @@ abstract final class WonkyAttr { static const suggestionPrefix = 'sug_'; /// All inline attribute keys. - static const inlineKeys = {bold, italic, strike, code, link, mention}; + static const inlineKeys = { + bold, + italic, + strike, + code, + link, + mention, + linkStyle, + chip, + }; /// Inline keys that `code` excludes. static const codeExcludedKeys = {bold, italic, strike}; + /// Inline keys that [linkStyle] excludes (its label is plain text). + static const linkStyleExcludedKeys = {bold, italic, strike, code, mention}; + + /// Inline keys that [chip] excludes (its label is plain text). + static const chipExcludedKeys = { + bold, + italic, + strike, + code, + link, + mention, + linkStyle, + }; + /// All block attribute keys. - static const blockKeys = {header, blockquote, codeBlock, list, indent}; + static const blockKeys = { + header, + blockquote, + codeBlock, + list, + indent, + step, + box, + }; + + /// The block keys a [BlockFormat] describes (a block type change rewrites + /// them all); [box] is not one of them, so containers survive block type + /// changes. + static const blockFormatKeys = { + header, + blockquote, + codeBlock, + list, + indent, + step, + }; + + /// Values of [linkStyle]. + static const linkStyles = {'arrow', 'button', 'buttonSecondary'}; + + /// Maximum [step] number. + static const maxStep = 9999; /// Mutually exclusive block-type keys (in normalization priority order); /// only [blockquote] may sit next to [list] (a list item in a quote). @@ -165,13 +232,16 @@ final class BlockFormat { this.checked = false, this.language = '', this.quoted = false, + this.step, }); /// A plain paragraph. static const paragraph = BlockFormat(BlockType.paragraph); - /// Heading of [level] 1–6. - const BlockFormat.heading(int level) : this(BlockType.heading, level: level); + /// Heading of [level] 1–6, a numbered heading when [step] is set (levels + /// 2–3 only, Write 11 §2.2). + const BlockFormat.heading(int level, {int? step}) + : this(BlockType.heading, level: level, step: step); /// The block type. final BlockType type; @@ -193,6 +263,10 @@ final class BlockFormat { /// line is [BlockType.quote]. final bool quoted; + /// The number of a numbered heading (`## (n) Title`, Wonky Markdown); + /// `null` otherwise. Only set for headings of level 2 or 3. + final int? step; + /// Whether the line is part of a blockquote (a quote line or a quoted /// list item). bool get inQuote => type == BlockType.quote || quoted; @@ -219,7 +293,18 @@ final class BlockFormat { if (code is String) return BlockFormat(BlockType.code, language: code); final header = attributes[WonkyAttr.header]; if (header is int && header >= 1 && header <= 6) { - return BlockFormat(BlockType.heading, level: header); + final step = attributes[WonkyAttr.step]; + return BlockFormat( + BlockType.heading, + level: header, + step: + (header == 2 || header == 3) && + step is int && + step >= 0 && + step <= WonkyAttr.maxStep + ? step + : null, + ); } final list = ListKind.tryParse(attributes[WonkyAttr.list]); if (list != null) { @@ -261,7 +346,10 @@ final class BlockFormat { /// The block attributes for this format (`null` for a paragraph). Map? toAttributes() => switch (type) { BlockType.paragraph => null, - BlockType.heading => {WonkyAttr.header: level}, + BlockType.heading => { + WonkyAttr.header: level, + if (step != null && (level == 2 || level == 3)) WonkyAttr.step: step, + }, BlockType.quote => {WonkyAttr.blockquote: true}, BlockType.code => {WonkyAttr.codeBlock: language}, BlockType.bullet || BlockType.ordered || BlockType.task => { @@ -272,12 +360,13 @@ final class BlockFormat { }; /// An attribute patch (for a `retain` on the `"\n"`) that changes - /// [current] block attributes into this format: every block key not in this - /// format is set to `null`. + /// [current] block attributes into this format: every block format key + /// ([WonkyAttr.blockFormatKeys]) not in this format is set to `null`; + /// [WonkyAttr.box] is kept. Map patchFrom(Map? current) { final target = toAttributes() ?? const {}; final patch = {}; - for (final key in WonkyAttr.blockKeys) { + for (final key in WonkyAttr.blockFormatKeys) { final has = current?.containsKey(key) ?? false; if (target.containsKey(key)) { if (!has || current![key] != target[key]) patch[key] = target[key]; @@ -296,17 +385,18 @@ final class BlockFormat { other.indent == indent && other.checked == checked && other.language == language && - other.quoted == quoted; + other.quoted == quoted && + other.step == step; @override int get hashCode => - Object.hash(type, level, indent, checked, language, quoted); + Object.hash(type, level, indent, checked, language, quoted, step); @override String toString() => 'BlockFormat($type, level: $level, indent: $indent, ' 'checked: $checked, language: "$language"' - '${quoted ? ', quoted' : ''})'; + '${quoted ? ', quoted' : ''}${step != null ? ', step: $step' : ''})'; } /// Kind of a suggestion part. diff --git a/packages/wonky_rich_text/lib/src/import_warning.dart b/packages/wonky_rich_text/lib/src/import_warning.dart index 95d37f1e..7e9095b4 100644 --- a/packages/wonky_rich_text/lib/src/import_warning.dart +++ b/packages/wonky_rich_text/lib/src/import_warning.dart @@ -7,6 +7,10 @@ enum ImportWarningKind { /// Nested blockquotes flattened to one level. nestedQuoteFlattened, + /// A Wonky Markdown directive was not closed, held lines it cannot keep + /// (a grid's non-item lines) or nested too deep (Write 11 §4). + directiveFlattened, + /// A list inside a blockquote was flattened to quote lines. listInQuoteFlattened, diff --git a/packages/wonky_rich_text/lib/src/inline_run.dart b/packages/wonky_rich_text/lib/src/inline_run.dart index ba6230d2..63a7fcbb 100644 --- a/packages/wonky_rich_text/lib/src/inline_run.dart +++ b/packages/wonky_rich_text/lib/src/inline_run.dart @@ -13,6 +13,9 @@ final class InlineRun { this.code = false, this.link, this.mentionUserUuid, + this.linkStyle, + this.chip = false, + this.chipIcon, }); /// Text; may contain U+2028 (soft break), never `"\n"`. @@ -36,6 +39,16 @@ final class InlineRun { /// Mentioned user UUID (with a `mailto:` [link]). final String? mentionUserUuid; + /// Wonky Markdown look of the [link]: `arrow`, `button` or + /// `buttonSecondary` (Write 11 §2.1). + final String? linkStyle; + + /// Whether the run is a Wonky Markdown chip. + final bool chip; + + /// The chip's icon name (kept, not shown; Write 11 WM10). + final String? chipIcon; + /// Whether formatting equals [other]'s. bool sameFormat(InlineRun other) => bold == other.bold && @@ -43,7 +56,10 @@ final class InlineRun { strike == other.strike && code == other.code && link == other.link && - mentionUserUuid == other.mentionUserUuid; + mentionUserUuid == other.mentionUserUuid && + linkStyle == other.linkStyle && + chip == other.chip && + chipIcon == other.chipIcon; /// Whether the run has no formatting. bool get isPlain => @@ -52,7 +68,9 @@ final class InlineRun { !strike && !code && link == null && - mentionUserUuid == null; + mentionUserUuid == null && + linkStyle == null && + !chip; /// Copy with changed fields. InlineRun copyWith({ @@ -65,6 +83,10 @@ final class InlineRun { bool clearLink = false, String? mentionUserUuid, bool clearMention = false, + String? linkStyle, + bool clearLinkStyle = false, + bool? chip, + String? chipIcon, }) => InlineRun( text ?? this.text, bold: bold ?? this.bold, @@ -75,17 +97,24 @@ final class InlineRun { mentionUserUuid: clearMention ? null : (mentionUserUuid ?? this.mentionUserUuid), + linkStyle: clearLinkStyle ? null : (linkStyle ?? this.linkStyle), + chip: chip ?? this.chip, + chipIcon: chip == false ? null : (chipIcon ?? this.chipIcon), ); - /// Delta attributes of this run (`null` when plain). + /// Delta attributes of this run (`null` when plain). A chip or a styled + /// link drops what it excludes (Write 11 §2.1). Map? toAttributes() { + if (chip) return {'chip': chipIcon ?? true}; + final styled = linkStyle != null && link != null; final a = { - if (bold && !code) 'bold': true, - if (italic && !code) 'italic': true, - if (strike && !code) 'strike': true, - if (code) 'code': true, + if (bold && !code && !styled) 'bold': true, + if (italic && !code && !styled) 'italic': true, + if (strike && !code && !styled) 'strike': true, + if (code && !styled) 'code': true, 'link': ?link, - 'mention': ?mentionUserUuid, + if (!styled) 'mention': ?mentionUserUuid, + if (styled) 'linkStyle': linkStyle, }; return a.isEmpty ? null : a; } @@ -100,6 +129,9 @@ final class InlineRun { code: a?['code'] == true, link: a?['link'] as String?, mentionUserUuid: a?['mention'] as String?, + linkStyle: a?['linkStyle'] as String?, + chip: a?['chip'] == true || a?['chip'] is String, + chipIcon: a?['chip'] is String ? a!['chip'] as String : null, ); @override @@ -107,8 +139,18 @@ final class InlineRun { other is InlineRun && other.text == text && sameFormat(other); @override - int get hashCode => - Object.hash(text, bold, italic, strike, code, link, mentionUserUuid); + int get hashCode => Object.hash( + text, + bold, + italic, + strike, + code, + link, + mentionUserUuid, + linkStyle, + chip, + chipIcon, + ); @override String toString() { @@ -119,6 +161,8 @@ final class InlineRun { if (code) 'c', if (link != null) 'link=$link', if (mentionUserUuid != null) '@$mentionUserUuid', + if (linkStyle != null) 'style=$linkStyle', + if (chip) 'chip${chipIcon == null ? '' : '=$chipIcon'}', ]; return 'Run("$text"${f.isEmpty ? '' : ' ${f.join(',')}'})'; } diff --git a/packages/wonky_rich_text/lib/src/markdown/inline_markdown.dart b/packages/wonky_rich_text/lib/src/markdown/inline_markdown.dart index 68404303..7320d113 100644 --- a/packages/wonky_rich_text/lib/src/markdown/inline_markdown.dart +++ b/packages/wonky_rich_text/lib/src/markdown/inline_markdown.dart @@ -8,13 +8,23 @@ import '../inline_run.dart'; import 'inline_reader.dart'; import 'inline_writer.dart'; import 'md_syntax.dart'; +import 'wonky_syntax.dart'; /// Parsing and canonicalization of inline Markdown strings. abstract final class InlineMarkdown { - /// Parses inline Markdown (e.g. a table cell) into runs. Block structure is - /// ignored: the text is read as one paragraph. - static List parse(String source, {List? warnings}) { - final nodes = parseMarkdownAst(source.replaceAll('\n', ' ')); + /// Parses inline Markdown into runs. Block structure is ignored: the text + /// is read as one paragraph. The [MarkdownFlavor.wonky] flavor reads chips + /// and styled links (Write 11 §4). + static List parse( + String source, { + List? warnings, + MarkdownFlavor flavor = MarkdownFlavor.gfm, + }) { + final nodes = parseMarkdownAst( + source.replaceAll('\n', ' '), + flavor: flavor, + blocks: false, + ); final reader = InlineReader(warnings ?? []); final runs = []; for (final n in nodes) { @@ -28,10 +38,26 @@ abstract final class InlineMarkdown { } /// Plain text of inline Markdown (formatting removed). - static String toPlainText(String source) => - InlineRun.plainText(parse(source)); + static String toPlainText( + String source, { + MarkdownFlavor flavor = MarkdownFlavor.gfm, + }) => InlineRun.plainText(parse(source, flavor: flavor)); - /// Canonical inline Markdown for a table cell: `write(parse(cell))`. - static String canonicalCell(String cell) => - InlineMarkdownWriter.write(parse(cell), context: InlineContext.tableCell); + /// Parses a stored cell: a Write table cell or grid item. Stored cells are + /// written in the Wonky inline syntax whatever the document's flavor, so + /// chips and styled links in cells survive (Write 11 §2.3). + static List parseCell( + String cell, { + List? warnings, + }) => parse(cell, warnings: warnings, flavor: MarkdownFlavor.wonky); + + /// Plain text of a stored cell. + static String cellPlainText(String cell) => + InlineRun.plainText(parseCell(cell)); + + /// Canonical inline Markdown for a stored cell: `write(parseCell(cell))`. + static String canonicalCell(String cell) => InlineMarkdownWriter.write( + parseCell(cell), + context: InlineContext.tableCell, + ); } diff --git a/packages/wonky_rich_text/lib/src/markdown/inline_reader.dart b/packages/wonky_rich_text/lib/src/markdown/inline_reader.dart index d502d72e..75f0049a 100644 --- a/packages/wonky_rich_text/lib/src/markdown/inline_reader.dart +++ b/packages/wonky_rich_text/lib/src/markdown/inline_reader.dart @@ -8,6 +8,7 @@ import '../links.dart'; import '../import_warning.dart'; import '../inline_run.dart'; import 'md_syntax.dart'; +import 'wonky_syntax.dart'; /// Title prefix that marks a mailto link as a mention: /// `[@Anna](mailto:anna@x.com "wonky-mention:")`. @@ -60,6 +61,9 @@ final class InlineReader { var _code = 0; String? _link; String? _mention; + String? _linkStyle; + var _chip = false; + String? _chipIcon; var _warnedHtml = false; var _warnedLink = false; @@ -118,16 +122,22 @@ final class InlineReader { void _emit(String text) { if (text.isEmpty) return; final code = _code > 0; + if (_chip) { + _pieces.add(RunPiece(InlineRun(text, chip: true, chipIcon: _chipIcon))); + return; + } + final styled = _linkStyle != null && _link != null; _pieces.add( RunPiece( InlineRun( text, - bold: _bold > 0 && !code, - italic: _italic > 0 && !code, - strike: _strike > 0 && !code, - code: code, + bold: _bold > 0 && !code && !styled, + italic: _italic > 0 && !code && !styled, + strike: _strike > 0 && !code && !styled, + code: code && !styled, link: _link, - mentionUserUuid: _link != null ? _mention : null, + mentionUserUuid: _link != null && !styled ? _mention : null, + linkStyle: styled ? _linkStyle : null, ), ), ); @@ -178,6 +188,17 @@ final class InlineReader { case 'input': // Task checkbox; handled by the block importer. break; + case WonkyMdTags.button || WonkyMdTags.arrowLink: + _styledLink(node); + case WonkyMdTags.chip: + final prevChip = _chip; + final prevIcon = _chipIcon; + _chip = true; + final icon = node.attributes[WonkyMdTags.icon]; + _chipIcon = icon != null && _iconName.hasMatch(icon) ? icon : null; + _children(node); + _chip = prevChip; + _chipIcon = prevIcon; default: _children(node); } @@ -189,6 +210,42 @@ final class InlineReader { } } + static final _iconName = RegExp(r'^[a-z0-9-]{1,32}$'); + + /// `:button[…](…)` / `:link[…](…)` (Write 11 §4): a link with a + /// `linkStyle`; an unsupported URL keeps the label as text. + void _styledLink(md.Element node) { + final href = node.attributes[WonkyMdTags.href] ?? ''; + final normalized = LinkPolicy.normalizeLink(href); + if (normalized == null) { + if (!_warnedLink) { + warnings.add( + ImportWarning( + ImportWarningKind.unsupportedLink, + 'Link "$href" is not supported; text kept', + ), + ); + _warnedLink = true; + } + _children(node); + return; + } + final prevLink = _link; + final prevMention = _mention; + final prevStyle = _linkStyle; + _link = normalized; + _mention = null; + _linkStyle = node.tag == WonkyMdTags.arrowLink + ? 'arrow' + : node.attributes[WonkyMdTags.variant] == 'secondary' + ? 'buttonSecondary' + : 'button'; + _children(node); + _link = prevLink; + _mention = prevMention; + _linkStyle = prevStyle; + } + void _anchor(md.Element node) { final href = decodeMdEntities(node.attributes['href'] ?? ''); final title = node.attributes['title'] == null diff --git a/packages/wonky_rich_text/lib/src/markdown/inline_writer.dart b/packages/wonky_rich_text/lib/src/markdown/inline_writer.dart index 0feb2dd8..5bce29ab 100644 --- a/packages/wonky_rich_text/lib/src/markdown/inline_writer.dart +++ b/packages/wonky_rich_text/lib/src/markdown/inline_writer.dart @@ -4,6 +4,7 @@ library; import '../delta_utils.dart'; import '../inline_run.dart'; import 'inline_reader.dart'; +import 'wonky_syntax.dart'; /// How emphasis is written. enum EmphasisStyle { @@ -57,23 +58,48 @@ final class _Break extends _Tok { abstract final class InlineMarkdownWriter { /// Writes [runs] in [context] using [style]. Visual lines (after hard /// breaks) are separated by `"\n"`; callers add container prefixes. + /// + /// Chips and styled links are written as Wonky directives (Write 11 §4) + /// in the [MarkdownFlavor.wonky] flavor (the default: table cells and grid + /// items store them so) and as plain text and plain links in + /// [MarkdownFlavor.gfm]. static String write( List runs, { InlineContext context = InlineContext.block, EmphasisStyle style = EmphasisStyle.asterisk, + MarkdownFlavor flavor = MarkdownFlavor.wonky, }) { - final merged = InlineRun.merge(runs); + final wonky = flavor == MarkdownFlavor.wonky; + final merged = InlineRun.merge([ + for (final r in runs) + wonky || (!r.chip && r.linkStyle == null) + ? r + : r.copyWith(clearLinkStyle: true, chip: false), + ]); final toks = <_Tok>[]; _writeSequence(merged, toks, style, context); _markTrailingBreaks(toks, context); - return _render(toks, context); + return _render(toks, context, wonky: wonky); } /// Escapes plain [text] (no formatting) for [context]. static String escapePlain( String text, { InlineContext context = InlineContext.plain, - }) => write([InlineRun(text)], context: context); + MarkdownFlavor flavor = MarkdownFlavor.wonky, + }) => write([InlineRun(text)], context: context, flavor: flavor); + + /// A chip or styled link label as the blog reads it: plain text without + /// `]` (written as `)`) and without line breaks (Write 11 §2.1). + static String directiveLabel(String text) => text + .replaceAll(']', ')') + .replaceAll(softBreak, ' ') + .replaceAll('\n', ' '); + + /// A styled link URL as the blog reads it (`\(([^)]*)\)`): no `(`, `)` + /// or whitespace. + static String directiveUrl(String url) => + url.replaceAll('(', '%28').replaceAll(')', '%29').replaceAll(' ', '%20'); // --------------------------------------------------------------------- // Structure @@ -94,11 +120,43 @@ abstract final class InlineMarkdownWriter { var i = 0; while (i < runs.length) { final r = runs[i]; + if (r.chip) { + _closeUntil(active, out, style, (_) => false); + final icon = r.chipIcon == null ? '' : '{icon=${r.chipIcon}}'; + out.add(_Markup(':chip[${directiveLabel(r.text)}]$icon')); + i++; + continue; + } + if (r.link != null && r.linkStyle != null) { + _closeUntil(active, out, style, (_) => false); + final label = StringBuffer(); + var j = i; + while (j < runs.length && + runs[j].link == r.link && + runs[j].linkStyle == r.linkStyle && + !runs[j].chip) { + label.write(runs[j].text); + j++; + } + final text = directiveLabel(label.toString()); + final url = directiveUrl(r.link!); + out.add( + _Markup(switch (r.linkStyle) { + 'arrow' => ':link[$text]($url)', + 'buttonSecondary' => ':button[$text]($url){variant=secondary}', + _ => ':button[$text]($url)', + }), + ); + i = j; + continue; + } if (r.link != null) { // Link group: consecutive runs with the same link + mention. var j = i; while (j < runs.length && runs[j].link == r.link && + runs[j].linkStyle == null && + !runs[j].chip && runs[j].mentionUserUuid == r.mentionUserUuid) { j++; } @@ -262,7 +320,8 @@ abstract final class InlineMarkdownWriter { trailing: !textAfter || context != InlineContext.block, ); } else if (t is _Char || - (t is _Markup && (t.s.startsWith('`') || t.s == '['))) { + (t is _Markup && + (t.s.startsWith('`') || t.s == '[' || t.s.startsWith(':')))) { textAfter = true; } } @@ -276,7 +335,11 @@ abstract final class InlineMarkdownWriter { static final _asciiAlnum = RegExp('[A-Za-z0-9]'); static final _alnum = RegExp(r'[\p{L}\p{N}]', unicode: true); - static String _render(List<_Tok> toks, InlineContext context) { + static String _render( + List<_Tok> toks, + InlineContext context, { + required bool wonky, + }) { final b = StringBuffer(); // Split into visual lines at hard breaks. var lineStart = 0; @@ -284,7 +347,7 @@ abstract final class InlineMarkdownWriter { final isEnd = i == toks.length; final t = isEnd ? null : toks[i]; if (!isEnd && !(t is _Break && !t.trailing)) continue; - _renderLine(toks, lineStart, i, b, context); + _renderLine(toks, lineStart, i, b, context, wonky: wonky); if (!isEnd) b.write('\\\n'); lineStart = i + 1; } @@ -302,8 +365,9 @@ abstract final class InlineMarkdownWriter { int from, int to, StringBuffer b, - InlineContext context, - ) { + InlineContext context, { + required bool wonky, + }) { // Digit-list rule: a line starting with 1–9 digits then "." or ")". var escapeIndex = -1; if (from < to && toks[from] is _Char) { @@ -354,6 +418,7 @@ abstract final class InlineMarkdownWriter { rest: i + 1 < to ? _restText(toks, i + 1, to) : '', recent: recent, context: context, + wonky: wonky, ); // package:markdown does not decode a character reference right // after a backtick; an empty HTML comment separates them. @@ -394,6 +459,7 @@ abstract final class InlineMarkdownWriter { required String rest, required String recent, required InlineContext context, + required bool wonky, }) { if ((atLineStart || atLineEnd) && _ws.hasMatch(ch)) return _entity(ch); if (forceEscape) return '\\$ch'; @@ -426,7 +492,21 @@ abstract final class InlineMarkdownWriter { case '&': return _entityLike.hasMatch('&$rest') ? '&' : '&'; case ':': - return rest.startsWith('//') ? r'\:' : ch; + // `://` would become an autolink, a line starting with `::` a + // Wonky directive (`:::type`, `::youtube`; escaped in both flavors, + // Write 11 §5.3; `[` is always escaped, so `:chip[` in text never + // reads as a chip). + return rest.startsWith('//') || (atLineStart && rest.startsWith(':')) + ? r'\:' + : ch; + case '(': + // `## (1) Title` is a numbered heading in Wonky Markdown. + return wonky && + atLineStart && + context == InlineContext.heading && + _stepPrefix.hasMatch(rest) + ? r'\(' + : ch; case '@': final emailish = prev != null && @@ -445,6 +525,8 @@ abstract final class InlineMarkdownWriter { return ch; } + static final _stepPrefix = RegExp(r'^\d+\)\s'); + static bool _alnumOrDot(String c) => _alnum.hasMatch(c) || c == '.' || c == '_' || c == '-' || c == '+'; } diff --git a/packages/wonky_rich_text/lib/src/markdown/md_syntax.dart b/packages/wonky_rich_text/lib/src/markdown/md_syntax.dart index de1fa87b..eb51cb48 100644 --- a/packages/wonky_rich_text/lib/src/markdown/md_syntax.dart +++ b/packages/wonky_rich_text/lib/src/markdown/md_syntax.dart @@ -3,6 +3,8 @@ library; import 'package:markdown/markdown.dart' as md; +import 'wonky_syntax.dart'; + /// GFM block/inline syntaxes without footnotes (kept as literal text, 02 §2.1). final md.ExtensionSet wonkyGfm = md.ExtensionSet( const [ @@ -19,9 +21,21 @@ final md.ExtensionSet wonkyGfm = md.ExtensionSet( ); /// Parses [source] into an AST with HTML encoding on, so literal `<`/`&` -/// arrive as entities and raw inline HTML stays raw. -List parseMarkdownAst(String source) { - final doc = md.Document(extensionSet: wonkyGfm, encodeHtml: true); +/// arrive as entities and raw inline HTML stays raw. The [MarkdownFlavor.wonky] +/// flavor adds the Wonky directives (Write 11 §4, [WonkyMdTags]); without +/// [blocks] only the inline ones. +List parseMarkdownAst( + String source, { + MarkdownFlavor flavor = MarkdownFlavor.gfm, + bool blocks = true, +}) { + final wonky = flavor == MarkdownFlavor.wonky; + final doc = md.Document( + extensionSet: wonkyGfm, + encodeHtml: true, + blockSyntaxes: wonky && blocks ? wonkyBlockSyntaxes : const [], + inlineSyntaxes: wonky ? wonkyInlineSyntaxes : const [], + ); return doc.parseLines(source.split('\n')); } diff --git a/packages/wonky_rich_text/lib/src/markdown/wonky_syntax.dart b/packages/wonky_rich_text/lib/src/markdown/wonky_syntax.dart new file mode 100644 index 00000000..a8cb3f0a --- /dev/null +++ b/packages/wonky_rich_text/lib/src/markdown/wonky_syntax.dart @@ -0,0 +1,454 @@ +/// The Wonky Markdown directives (Write 11 §4) as `package:markdown` +/// syntaxes: the grammar of the Serverpod blog's renderer +/// (`serverpod_website_server/lib/src/markdown/markdown_renderer.dart`), +/// producing AST elements the Write importer maps to Delta attributes. +library; + +import 'package:markdown/markdown.dart' as md; + +/// The Markdown flavor of a document (Write 11 §1 WM1). +enum MarkdownFlavor { + /// GitHub-Flavored Markdown (the default). + gfm('gfm'), + + /// GFM plus the Wonky Markdown directives. + wonky('wonky'); + + const MarkdownFlavor(this.value); + + /// The stored value. + final String value; + + /// Parses a stored value; unknown values and `null` are [gfm]. + static MarkdownFlavor parse(Object? value) => + value == wonky.value ? wonky : gfm; +} + +/// AST tags and attribute names of the Wonky directive elements. +abstract final class WonkyMdTags { + /// `:button[label](url){variant=secondary}` — attributes [href], + /// [variant]; one text child (the label, HTML-encoded). + static const button = 'wonky-button'; + + /// `:link[label](url)` — attribute [href]; one text child. + static const arrowLink = 'wonky-link'; + + /// `:chip[label]{icon=name}` — attribute [icon]; one text child. + static const chip = 'wonky-chip'; + + /// A container (`:::callout`, `:::details`, `:::card`) — attributes + /// [type], [variant], [title]; block children. A details element's + /// summary heading comes first and has the [summary] attribute. + static const box = 'wonky-box'; + + /// `:::grid{columns=n bullets=b}` — attributes [columns], [bullets], + /// [dropped] (lines that were not items); [gridItem] children. + static const grid = 'wonky-grid'; + + /// One grid item; inline children. + static const gridItem = 'wonky-grid-item'; + + /// Attribute: link destination (raw, not normalized). + static const href = 'href'; + + /// Attribute: button variant (`primary` or `secondary`). + static const variant = 'variant'; + + /// Attribute: chip icon name. + static const icon = 'icon'; + + /// Attribute: container type (`callout`, `details`, `card`). + static const type = 'type'; + + /// Attribute: callout title. + static const title = 'title'; + + /// Attribute on the summary heading of a details container. + static const summary = 'wonky-summary'; + + /// Attribute: grid columns (raw option value). + static const columns = 'columns'; + + /// Attribute: grid bullets (raw option value). + static const bullets = 'bullets'; + + /// Attribute: number of lines a grid dropped (not items). + static const dropped = 'dropped'; + + /// Attribute on a container or grid that ran to the end of its parent + /// without a closing `:::`. + static const unterminated = 'unterminated'; + + /// Attribute on an `h2`/`h3` element: the step number of a numbered + /// heading. + static const step = 'wonky-step'; + + /// `::youtube[title]{id=… start=…}` — attributes [videoId], [start], + /// [title] (raw), [raw] (the whole line, kept when the id is invalid). + static const youtube = 'wonky-youtube'; + + /// Attribute: the YouTube video id (raw `id` option). + static const videoId = 'videoId'; + + /// Attribute: the start time (raw `start` option). + static const start = 'start'; + + /// Attribute: the source line of a leaf directive. + static const raw = 'raw'; +} + +/// The callout types of `:::` (Write 11 §2.2). +const wonkyCalloutVariants = [ + 'info', + 'tip', + 'note', + 'warning', + 'caution', + 'danger', +]; + +/// The block syntaxes of the Wonky flavor. +const List wonkyBlockSyntaxes = [ + _YouTubeSyntax(), + _NumberedHeadingSyntax(), + _CalloutSyntax(), + _DetailsSyntax(), + _GridSyntax(), + _CardSyntax(), +]; + +/// The inline syntaxes of the Wonky flavor. +final List wonkyInlineSyntaxes = [ + _ButtonSyntax(), + _ArrowLinkSyntax(), + _ChipSyntax(), +]; + +/// Parses `{key=value key2=value2}` options (the blog's `_parseOptions`). +Map parseWonkyOptions(String? raw) { + if (raw == null || raw.trim().isEmpty) return const {}; + final options = {}; + for (final token in raw.trim().split(RegExp(r'\s+'))) { + final eq = token.indexOf('='); + if (eq > 0) options[token.substring(0, eq)] = token.substring(eq + 1); + } + return options; +} + +/// HTML-encodes a label like `package:markdown` does with `encodeHtml`, so +/// the reader's entity decoding gives it back exactly. +String _encode(String s) => s + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"') + .replaceAll("'", '''); + +// --------------------------------------------------------------------------- +// Inline directives. + +class _ButtonSyntax extends md.InlineSyntax { + _ButtonSyntax() + : super( + r':button\[([^\]]*)\]\(([^)]*)\)(?:\{([^}]*)\})?', + startCharacter: 0x3A, + ); + + @override + bool onMatch(md.InlineParser parser, Match match) { + final variant = parseWonkyOptions(match[3])['variant'] == 'secondary' + ? 'secondary' + : 'primary'; + parser.addNode( + md.Element(WonkyMdTags.button, [md.Text(_encode(match[1]!))]) + ..attributes[WonkyMdTags.href] = match[2]! + ..attributes[WonkyMdTags.variant] = variant, + ); + return true; + } +} + +class _ArrowLinkSyntax extends md.InlineSyntax { + _ArrowLinkSyntax() + : super(r':link\[([^\]]*)\]\(([^)]*)\)', startCharacter: 0x3A); + + @override + bool onMatch(md.InlineParser parser, Match match) { + parser.addNode( + md.Element(WonkyMdTags.arrowLink, [md.Text(_encode(match[1]!))]) + ..attributes[WonkyMdTags.href] = match[2]!, + ); + return true; + } +} + +class _ChipSyntax extends md.InlineSyntax { + _ChipSyntax() + : super(r':chip\[([^\]]*)\](?:\{([^}]*)\})?', startCharacter: 0x3A); + + @override + bool onMatch(md.InlineParser parser, Match match) { + final icon = parseWonkyOptions(match[2])['icon']; + final element = md.Element(WonkyMdTags.chip, [md.Text(_encode(match[1]!))]); + if (icon != null && icon.isNotEmpty) { + element.attributes[WonkyMdTags.icon] = icon; + } + parser.addNode(element); + return true; + } +} + +// --------------------------------------------------------------------------- +// Block directives. + +/// A `::youtube[title]{id=… start=…}` leaf directive on its own line +/// (Write 11 §4). The title is plain text. +class _YouTubeSyntax extends md.BlockSyntax { + const _YouTubeSyntax(); + + @override + RegExp get pattern => + RegExp(r'^::youtube(?:\[([^\]]*)\])?(?:\s*\{([^}]*)\})?\s*$'); + + @override + md.Node parse(md.BlockParser parser) { + final line = parser.current.content.trim(); + final match = pattern.firstMatch(parser.current.content)!; + final options = parseWonkyOptions(match[2]); + parser.advance(); + final element = md.Element.empty(WonkyMdTags.youtube) + ..attributes[WonkyMdTags.videoId] = options['id'] ?? '' + ..attributes[WonkyMdTags.raw] = line; + final start = options['start']; + if (start != null) element.attributes[WonkyMdTags.start] = start; + final title = match[1]?.trim(); + if (title != null && title.isNotEmpty) { + element.attributes[WonkyMdTags.title] = title; + } + return element; + } +} + +/// A `##` or `###` heading with a leading `(n)`. +class _NumberedHeadingSyntax extends md.BlockSyntax { + const _NumberedHeadingSyntax(); + + @override + RegExp get pattern => RegExp(r'^(#{2,3})\s+\((\d+)\)\s+(.*)$'); + + @override + md.Node parse(md.BlockParser parser) { + final match = pattern.firstMatch(parser.current.content)!; + final level = match[1]!.length; + parser.advance(); + return md.Element('h$level', [md.UnparsedContent(match[3]!.trim())]) + ..attributes[WonkyMdTags.step] = match[2]!; + } +} + +class _CalloutSyntax extends md.BlockSyntax { + const _CalloutSyntax(); + + @override + RegExp get pattern => RegExp( + r'^:::(info|tip|note|warning|caution|danger)\b(?:\[([^\]]*)\])?\s*$', + ); + + @override + md.Node parse(md.BlockParser parser) { + final match = pattern.firstMatch(parser.current.content)!; + final title = match[2]?.trim(); + parser.advance(); + final body = _collectLines(parser); + final element = + md.Element( + WonkyMdTags.box, + md.BlockParser(body.lines, parser.document).parseLines(), + ) + ..attributes[WonkyMdTags.type] = 'callout' + ..attributes[WonkyMdTags.variant] = match[1]!.toLowerCase(); + if (title != null && title.isNotEmpty) { + element.attributes[WonkyMdTags.title] = title; + } + if (!body.terminated) element.attributes[WonkyMdTags.unterminated] = '1'; + return element; + } +} + +final _summaryHeading = RegExp(r'^###\s+(.*)$'); + +/// A `:::details` disclosure: its first own `###` is the summary. +class _DetailsSyntax extends md.BlockSyntax { + const _DetailsSyntax(); + + @override + RegExp get pattern => RegExp(r'^:::details\s*$'); + + @override + md.Node parse(md.BlockParser parser) { + parser.advance(); + final body = _collectLines(parser); + final lines = body.lines; + final index = _ownLines(lines).firstWhere( + (i) => _summaryHeading.hasMatch(lines[i].content.trim()), + orElse: () => -1, + ); + final children = []; + var rest = lines; + if (index != -1) { + final summary = _summaryHeading + .firstMatch(lines[index].content.trim())![1]! + .trim(); + children.add( + md.Element('h3', [md.UnparsedContent(summary)]) + ..attributes[WonkyMdTags.summary] = '1', + ); + rest = [...lines.take(index), ...lines.skip(index + 1)]; + } + children.addAll(md.BlockParser(rest, parser.document).parseLines()); + final element = md.Element(WonkyMdTags.box, children) + ..attributes[WonkyMdTags.type] = 'details'; + if (!body.terminated) element.attributes[WonkyMdTags.unterminated] = '1'; + return element; + } +} + +final _gridItem = RegExp(r'^[-*]\s+(.*)$'); + +/// A `:::grid{columns=n bullets=b}` of bullet items. +class _GridSyntax extends md.BlockSyntax { + const _GridSyntax(); + + @override + RegExp get pattern => RegExp(r'^:::grid(?:\s*\{([^}]*)\})?\s*$'); + + @override + md.Node parse(md.BlockParser parser) { + final options = parseWonkyOptions( + pattern.firstMatch(parser.current.content)![1], + ); + parser.advance(); + final body = _collectLines(parser); + final lines = body.lines; + final items = []; + final own = _ownLines(lines).toSet(); + var dropped = 0; + for (var i = 0; i < lines.length; i++) { + if (lines[i].isBlankLine) continue; + final item = own.contains(i) + ? _gridItem.firstMatch(lines[i].content.trim()) + : null; + if (item == null) { + // Not an item, or inside a code fence or a nested directive. + dropped++; + continue; + } + items.add( + md.Element(WonkyMdTags.gridItem, [md.UnparsedContent(item[1]!.trim())]), + ); + } + final element = md.Element(WonkyMdTags.grid, items) + ..attributes[WonkyMdTags.columns] = options['columns'] ?? '' + ..attributes[WonkyMdTags.bullets] = options['bullets'] ?? ''; + if (dropped > 0) element.attributes[WonkyMdTags.dropped] = '$dropped'; + if (!body.terminated) element.attributes[WonkyMdTags.unterminated] = '1'; + return element; + } +} + +/// A `:::card` container. +class _CardSyntax extends md.BlockSyntax { + const _CardSyntax(); + + @override + RegExp get pattern => RegExp(r'^:::card\s*$'); + + @override + md.Node parse(md.BlockParser parser) { + parser.advance(); + final body = _collectLines(parser); + final element = md.Element( + WonkyMdTags.box, + md.BlockParser(body.lines, parser.document).parseLines(), + )..attributes[WonkyMdTags.type] = 'card'; + if (!body.terminated) element.attributes[WonkyMdTags.unterminated] = '1'; + return element; + } +} + +final _directiveOpen = RegExp(r'^:::[a-zA-Z]'); + +/// Consumes the lines up to the matching closing `:::` (nested directives +/// are tracked, fenced code is skipped). +({List lines, bool terminated}) _collectLines(md.BlockParser parser) { + final lines = []; + var depth = 1; + var inFence = false; + while (!parser.isDone) { + final trimmed = parser.current.content.trim(); + if (trimmed.startsWith('```')) inFence = !inFence; + if (!inFence) { + if (trimmed == ':::') { + if (--depth == 0) { + parser.advance(); + return (lines: lines, terminated: true); + } + } else if (_directiveOpen.hasMatch(trimmed)) { + depth++; + } + } + lines.add(parser.current); + parser.advance(); + } + return (lines: lines, terminated: false); +} + +/// The indices of the lines a directive owns (not inside a code fence or a +/// nested directive). +Iterable _ownLines(List lines) sync* { + var depth = 0; + var inFence = false; + for (var i = 0; i < lines.length; i++) { + final content = lines[i].content.trim(); + if (content.startsWith('```')) { + inFence = !inFence; + continue; + } + if (inFence) continue; + if (_directiveOpen.hasMatch(content)) { + depth++; + } else if (content == ':::') { + if (depth > 0) depth--; + } else if (depth == 0) { + yield i; + } + } +} + +final _directiveLine = RegExp( + // A container line (`:::type`) or a YouTube video (`::youtube`). + r'^(?::::(?:info|tip|note|warning|caution|danger|details|card|grid)' + r'|::youtube)\b', +); +final _inlineDirective = RegExp( + r':(?:button|link)\[[^\]]*\]\([^)]*\)|:chip\[[^\]]*\]', +); + +/// Whether [markdown] uses Wonky directives (a directive line or an inline +/// button, link or chip outside code), so a new document imported from it +/// should be Wonky Markdown (Write 11 §5.1). +bool looksLikeWonkyMarkdown(String markdown) { + var inFence = false; + for (final raw in markdown.split('\n')) { + final line = raw.trim(); + if (line.startsWith('```') || line.startsWith('~~~')) { + inFence = !inFence; + continue; + } + if (inFence) continue; + if (_directiveLine.hasMatch(line)) return true; + final withoutCode = line.replaceAll(RegExp(r'`[^`]*`'), ''); + if (_inlineDirective.hasMatch(withoutCode)) return true; + } + return false; +} diff --git a/packages/wonky_rich_text/lib/wonky_rich_text.dart b/packages/wonky_rich_text/lib/wonky_rich_text.dart index e3569004..793d06e5 100644 --- a/packages/wonky_rich_text/lib/wonky_rich_text.dart +++ b/packages/wonky_rich_text/lib/wonky_rich_text.dart @@ -27,5 +27,6 @@ export 'src/markdown/inline_markdown.dart'; export 'src/markdown/inline_reader.dart'; export 'src/markdown/inline_writer.dart'; export 'src/markdown/md_syntax.dart'; +export 'src/markdown/wonky_syntax.dart'; export 'src/rich_text_normalizer.dart'; export 'src/text_rules.dart'; diff --git a/packages/wonky_write_core/lib/src/delta/boxes.dart b/packages/wonky_write_core/lib/src/delta/boxes.dart new file mode 100644 index 00000000..8709c931 --- /dev/null +++ b/packages/wonky_write_core/lib/src/delta/boxes.dart @@ -0,0 +1,224 @@ +/// Wonky Markdown containers: the `box` block attribute +/// (specs/wonky_write/11-wonky-markdown.md §2.2). +library; + +import 'package:collection/collection.dart'; + +import 'attributes.dart'; + +/// The type of a container. +enum BoxType { + /// `:::info` … `:::danger` — a tinted note box. + callout('callout'), + + /// `:::details` — an expandable item; its first H3 is the summary. + details('details'), + + /// `:::card` — a promo box. + card('card'); + + const BoxType(this.value); + + /// The stored value. + final String value; + + /// Parses a stored value; `null` if unknown. + static BoxType? tryParse(Object? value) => + BoxType.values.firstWhereOrNull((t) => t.value == value); +} + +/// The type of a callout. +enum CalloutVariant { + /// Info. + info('info', 'Info'), + + /// Tip. + tip('tip', 'Tip'), + + /// Note. + note('note', 'Note'), + + /// Warning. + warning('warning', 'Warning'), + + /// Caution (the blog styles it as a warning with its own label). + caution('caution', 'Caution'), + + /// Danger. + danger('danger', 'Danger'); + + const CalloutVariant(this.value, this.label); + + /// The stored value (and the directive name, `:::warning`). + final String value; + + /// The English label shown when the callout has no title (the blog's). + final String label; + + /// Parses a stored value; `null` if unknown. + static CalloutVariant? tryParse(Object? value) => + CalloutVariant.values.firstWhereOrNull((v) => v.value == value); +} + +/// One container a line is in: an entry of the `box` attribute. +final class BoxFrame { + /// Creates a frame. + const BoxFrame({ + required this.id, + required this.type, + this.variant, + this.title, + }); + + /// A callout frame. + const BoxFrame.callout({ + required String id, + CalloutVariant variant = CalloutVariant.info, + String? title, + }) : this(id: id, type: BoxType.callout, variant: variant, title: title); + + /// Identity of the container (UUIDv7). + final String id; + + /// The container type. + final BoxType type; + + /// The callout type (callouts only, never null for them). + final CalloutVariant? variant; + + /// The callout title (callouts only; plain text, single line). + final String? title; + + /// Maximum nesting depth of containers. + static const maxDepth = 3; + + /// Maximum title length. + static const maxTitleLength = 200; + + /// Parses a frame; `null` when invalid. A callout without a valid variant + /// is invalid; [variant] and [title] of other types are ignored. + static BoxFrame? tryParse(Object? json) { + if (json is! Map) return null; + final id = json['id']; + final type = BoxType.tryParse(json['type']); + if (id is! String || id.isEmpty || type == null) return null; + if (type != BoxType.callout) return BoxFrame(id: id, type: type); + final variant = CalloutVariant.tryParse(json['variant']); + if (variant == null) return null; + final title = json['title']; + return BoxFrame( + id: id, + type: type, + variant: variant, + title: title is String && title.isNotEmpty ? title : null, + ); + } + + /// The canonical form of a title: one line, trimmed, at most + /// [maxTitleLength] characters, `]` written as `)` (the blog's grammar + /// cannot hold it); `null` when empty. + static String? canonicalTitle(String? title) { + if (title == null) return null; + var t = title + .replaceAll(RegExp('[\n\r\t

]'), ' ') + .replaceAll(']', ')') + .trim(); + if (t.length > maxTitleLength) t = t.substring(0, maxTitleLength).trim(); + return t.isEmpty ? null : t; + } + + /// The JSON value. + Map toJson() => { + 'id': id, + 'type': type.value, + if (type == BoxType.callout) + 'variant': (variant ?? CalloutVariant.info).value, + if (type == BoxType.callout && title != null) 'title': title, + }; + + /// Copy with changed fields. + BoxFrame copyWith({ + String? id, + BoxType? type, + CalloutVariant? variant, + String? title, + bool clearTitle = false, + }) { + final t = type ?? this.type; + return BoxFrame( + id: id ?? this.id, + type: t, + variant: t == BoxType.callout + ? (variant ?? this.variant ?? CalloutVariant.info) + : null, + title: t != BoxType.callout || clearTitle ? null : (title ?? this.title), + ); + } + + /// The label a callout shows: its title, else the variant's label. + String get calloutLabel => title ?? (variant ?? CalloutVariant.info).label; + + /// Whether [other] has the same properties (ignoring [id]). + bool sameProperties(BoxFrame other) => + other.type == type && other.variant == variant && other.title == title; + + @override + bool operator ==(Object other) => + other is BoxFrame && + other.id == id && + other.type == type && + other.variant == variant && + other.title == title; + + @override + int get hashCode => Object.hash(id, type, variant, title); + + @override + String toString() => 'BoxFrame(${toJson()})'; +} + +/// Helpers for the `box` attribute value (a list of [BoxFrame] JSON maps). +abstract final class Boxes { + /// The frames of a line's attributes, outermost first; invalid frames are + /// skipped (use the validator to detect them). + static List of(Map? attributes) => + parse(attributes?[WonkyAttr.box]); + + /// Parses a `box` value. + static List parse(Object? value) { + if (value is! List) return const []; + final out = []; + for (final v in value) { + final f = BoxFrame.tryParse(v); + if (f != null) out.add(f); + } + return out; + } + + /// The `box` value of [frames] (`null` when empty). + static List>? toValue(List frames) => + frames.isEmpty ? null : [for (final f in frames) f.toJson()]; + + /// Whether lines with frame paths [a] and [b] are in the same container + /// at [depth] (the same frame ids at depths 0…[depth]). + static bool sameAt(List a, List b, int depth) { + if (a.length <= depth || b.length <= depth) return false; + for (var k = 0; k <= depth; k++) { + if (a[k].id != b[k].id) return false; + } + return true; + } + + /// The number of leading containers [a] and [b] share. + static int commonDepth(List a, List b) { + var k = 0; + while (k < a.length && k < b.length && a[k].id == b[k].id) { + k++; + } + return k; + } + + /// Whether two frame paths are the same containers (ids only). + static bool samePath(List a, List b) => + a.length == b.length && commonDepth(a, b) == a.length; +} diff --git a/packages/wonky_write_core/lib/src/delta/embeds.dart b/packages/wonky_write_core/lib/src/delta/embeds.dart index 466513f6..c5328172 100644 --- a/packages/wonky_write_core/lib/src/delta/embeds.dart +++ b/packages/wonky_write_core/lib/src/delta/embeds.dart @@ -32,7 +32,7 @@ enum CellAlign { sealed class WonkyEmbed { const WonkyEmbed(); - /// Embed type key (`image`, `divider`, `table`). + /// Embed type key (`image`, `divider`, `table`, `grid`, `youtube`). String get type; /// Stable embed id. @@ -49,6 +49,8 @@ sealed class WonkyEmbed { ImageEmbed.typeKey, DividerEmbed.typeKey, TableEmbed.typeKey, + GridEmbed.typeKey, + YouTubeEmbed.typeKey, }; /// Parses an `insert` value. Returns `null` when [insert] is not a valid @@ -62,6 +64,8 @@ sealed class WonkyEmbed { ImageEmbed.typeKey => ImageEmbed.tryParse(data), DividerEmbed.typeKey => DividerEmbed.tryParse(data), TableEmbed.typeKey => TableEmbed.tryParse(data), + GridEmbed.typeKey => GridEmbed.tryParse(data), + YouTubeEmbed.typeKey => YouTubeEmbed.tryParse(data), _ => null, }; } @@ -304,3 +308,297 @@ final class TableEmbed extends WonkyEmbed { @override String toString() => 'TableEmbed(${toData()})'; } + +/// The bullet of the items of a [GridEmbed]. +enum GridBullets { + /// A check mark. + check('check'), + + /// A circle. + circle('circle'), + + /// No bullet. + none('none'); + + const GridBullets(this.value); + + /// JSON value (and the directive option, `bullets=check`). + final String value; + + /// Parses a value; unknown values and `null` are [none] (the blog's + /// default). + static GridBullets parse(Object? value) => + GridBullets.values.firstWhereOrNull((b) => b.value == value) ?? none; +} + +/// A Wonky Markdown grid (Write 11 §2.3): +/// `{"grid": {"id", "columns": 1–4, "bullets", "items": [cellMarkdown]}}`. +/// +/// Items are stored inline Markdown (like table cells), single line. +final class GridEmbed extends WonkyEmbed { + /// Creates a grid embed. + const GridEmbed({ + required this.id, + this.columns = defaultColumns, + this.bullets = GridBullets.check, + required this.items, + }); + + /// Type key. + static const typeKey = 'grid'; + + /// The blog's default column count. + static const defaultColumns = 3; + + /// Maximum number of items. + static const maxItems = 100; + + @override + String get type => typeKey; + + @override + final String id; + + /// Number of columns, 1–4. + final int columns; + + /// Item bullets. + final GridBullets bullets; + + /// Inline-Markdown items (at least one in canonical form). + final List items; + + /// The canonical column count of a raw value: 1, 2 or 4 as given, 3 + /// otherwise (the blog's rule). + static int canonicalColumns(Object? value) { + final n = value is int ? value : int.tryParse('${value ?? ''}'); + return switch (n) { + 1 || 2 || 4 => n!, + _ => defaultColumns, + }; + } + + /// Parses the embed payload; `null` when invalid. + static GridEmbed? tryParse(Map data) { + final id = data['id']; + final rawItems = data['items']; + final columns = data['columns'] ?? defaultColumns; + final bullets = data['bullets'] ?? GridBullets.none.value; + if (id is! String || id.isEmpty || rawItems is! List) return null; + if (columns is! int || bullets is! String) return null; + final items = []; + for (final item in rawItems) { + if (item is! String) return null; + items.add(item); + } + return GridEmbed( + id: id, + columns: columns, + bullets: GridBullets.parse(bullets), + items: items, + ); + } + + @override + Map toData() => { + 'id': id, + 'columns': columns, + 'bullets': bullets.value, + 'items': [...items], + }; + + /// Copy with changed fields. + GridEmbed copyWith({ + String? id, + int? columns, + GridBullets? bullets, + List? items, + }) => GridEmbed( + id: id ?? this.id, + columns: columns ?? this.columns, + bullets: bullets ?? this.bullets, + items: items ?? this.items, + ); + + @override + bool operator ==(Object other) => + other is GridEmbed && + other.id == id && + other.columns == columns && + other.bullets == bullets && + const ListEquality().equals(other.items, items); + + @override + int get hashCode => Object.hash( + id, + columns, + bullets, + const ListEquality().hash(items), + ); + + @override + String toString() => 'GridEmbed(${toData()})'; +} + +/// A YouTube video (Wonky Markdown, Write 11 §2.3): +/// `{"youtube": {"id", "videoId", "start"?, "title"?}}`. +/// +/// [videoId] is the 11-character YouTube id, [start] the start time in +/// seconds, [title] a single-line title (the label of +/// `::youtube[title]{id=… start=…}`). +final class YouTubeEmbed extends WonkyEmbed { + /// Creates a YouTube embed. + const YouTubeEmbed({ + required this.id, + required this.videoId, + this.start, + this.title, + }); + + /// Type key. + static const typeKey = 'youtube'; + + /// Longest start time (100 hours). + static const maxStart = 360000; + + static final _videoId = RegExp(r'^[A-Za-z0-9_-]{11}$'); + + @override + String get type => typeKey; + + @override + final String id; + + /// The YouTube video id. + final String videoId; + + /// Start time in seconds. + final int? start; + + /// Title (single line, no `]`). + final String? title; + + /// Whether [value] is a YouTube video id. + static bool isVideoId(String value) => _videoId.hasMatch(value); + + /// Parses the embed payload; `null` when invalid. + static YouTubeEmbed? tryParse(Map data) { + final id = data['id']; + final videoId = data['videoId']; + final start = data['start']; + final title = data['title']; + if (id is! String || id.isEmpty || videoId is! String) return null; + if (!isVideoId(videoId)) return null; + if (start != null && (start is! int || start < 0 || start > maxStart)) { + return null; + } + if (title != null && title is! String) return null; + return YouTubeEmbed( + id: id, + videoId: videoId, + start: start as int?, + title: title as String?, + ); + } + + /// The video id and start time of a YouTube URL (`watch?v=`, `youtu.be/`, + /// `/embed/`, `/shorts/`, `/live/`, with `t=`/`start=`) or of a bare video + /// id; `null` when [input] is neither. + static ({String videoId, int? start})? parseUrl(String input) { + final text = input.trim(); + if (isVideoId(text)) return (videoId: text, start: null); + final uri = Uri.tryParse(text.contains('://') ? text : 'https://$text'); + if (uri == null) return null; + final host = uri.host.toLowerCase().replaceFirst(RegExp(r'^(www|m)\.'), ''); + String? videoId; + if (host == 'youtu.be') { + videoId = uri.pathSegments.firstOrNull; + } else if (host == 'youtube.com' || + host == 'music.youtube.com' || + host == 'youtube-nocookie.com') { + final segments = uri.pathSegments; + if (segments.length == 1 && segments.first == 'watch') { + videoId = uri.queryParameters['v']; + } else if (segments.length >= 2 && + const {'embed', 'shorts', 'live', 'v'}.contains(segments.first)) { + videoId = segments[1]; + } + } + if (videoId == null || !isVideoId(videoId)) return null; + final time = uri.queryParameters['t'] ?? uri.queryParameters['start']; + return (videoId: videoId, start: parseTime(time)); + } + + /// Seconds of a YouTube time (`90`, `90s`, `1m30s`, `1h2m3s`), or `null`. + static int? parseTime(String? value) { + if (value == null || value.isEmpty) return null; + final plain = int.tryParse(value); + if (plain != null) return plain >= 0 && plain <= maxStart ? plain : null; + final m = RegExp(r'^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$').firstMatch(value); + if (m == null || m.group(0)!.isEmpty) return null; + final seconds = + int.parse(m.group(1) ?? '0') * 3600 + + int.parse(m.group(2) ?? '0') * 60 + + int.parse(m.group(3) ?? '0'); + return seconds <= maxStart ? seconds : null; + } + + /// The canonical title of a raw one: single line, `]` as `)` (the + /// directive label can't hold it), at most 300 characters; empty → `null`. + static String? canonicalTitle(String? title) { + if (title == null) return null; + var t = title + .replaceAll(RegExp('[\n\r\t\u2028\u2029]'), ' ') + .replaceAll(']', ')') + .trim(); + if (t.length > 300) t = t.substring(0, 300).trim(); + return t.isEmpty ? null : t; + } + + /// The watch page (links, GitHub-style fallback). + String get watchUrl => + 'https://www.youtube.com/watch?v=$videoId' + '${start == null || start == 0 ? '' : '&t=${start}s'}'; + + /// The player (HTML export, the blog). + String get embedUrl => + 'https://www.youtube.com/embed/$videoId' + '${start == null || start == 0 ? '' : '?start=$start'}'; + + /// The video's thumbnail (16:9 with letterbox bars at `hqdefault`). + String get thumbnailUrl => 'https://i.ytimg.com/vi/$videoId/hqdefault.jpg'; + + @override + Map toData() => { + 'id': id, + 'videoId': videoId, + 'start': ?start, + 'title': ?title, + }; + + /// Copy with changed fields ([clearStart]/[clearTitle] remove them). + YouTubeEmbed copyWith({ + String? id, + String? videoId, + int? start, + String? title, + bool clearStart = false, + bool clearTitle = false, + }) => YouTubeEmbed( + id: id ?? this.id, + videoId: videoId ?? this.videoId, + start: clearStart ? null : start ?? this.start, + title: clearTitle ? null : title ?? this.title, + ); + + @override + bool operator ==(Object other) => + other is YouTubeEmbed && + other.id == id && + other.videoId == videoId && + other.start == start && + other.title == title; + + @override + int get hashCode => Object.hash(id, videoId, start, title); +} diff --git a/packages/wonky_write_core/lib/src/delta/normalizer.dart b/packages/wonky_write_core/lib/src/delta/normalizer.dart index 61002ed3..4a3c5e98 100644 --- a/packages/wonky_write_core/lib/src/delta/normalizer.dart +++ b/packages/wonky_write_core/lib/src/delta/normalizer.dart @@ -4,6 +4,7 @@ library; import 'package:dart_quill_delta/dart_quill_delta.dart'; import 'attributes.dart'; +import 'boxes.dart'; import 'delta_utils.dart'; import 'document.dart'; import 'embeds.dart'; @@ -53,6 +54,13 @@ enum NormalizationFix { /// Suggestion timestamps stamped with server time. stampedSuggestion, + + /// Chip or link style exclusions applied (Write 11 §2.4 rule 10). + styledTextExclusion, + + /// Invalid container frames removed or canonicalized (Write 11 §2.4 + /// rule 11). + normalizedBox, } /// Result of [WonkyDeltaNormalizer.normalize]. @@ -265,6 +273,7 @@ final class WonkyDeltaNormalizer { endsDocument: end == docLength, prevListIndent: listIndent(before), prevListQuoted: BlockFormat.fromAttributes(before).quoted, + prevListBox: Boxes.of(before), ); // The change within the window. @@ -299,8 +308,13 @@ final class WonkyDeltaNormalizer { ); // A list indent clamped differently from here on (the change removed or // re-indented a list item) cascades to the next lines. + // So does a change of the last line's list kind or containers. + final lastOut = r.document.operations.last.attributes; if (!window.endsDocument && - listIndent(r.document.operations.last.attributes) != listIndent(last)) { + (listIndent(lastOut) != listIndent(last) || + BlockFormat.fromAttributes(lastOut).quoted != + BlockFormat.fromAttributes(last).quoted || + !Boxes.samePath(Boxes.of(lastOut), Boxes.of(last)))) { return whole(); } final fixup = Delta()..retain(start); @@ -344,6 +358,7 @@ final class WonkyDeltaNormalizer { int? prevListIndent = window.prevListIndent; var prevListQuoted = window.prevListQuoted; + var prevListBox = window.prevListBox; for (final line in doc.lines) { final isLast = window.endsDocument && line.index == doc.lines.length - 1; final blockIn = line.attributes; @@ -389,14 +404,27 @@ final class WonkyDeltaNormalizer { if (hasEmbed && live.length > 1) fixes.add(NormalizationFix.movedEmbed); // Indent clamping uses the output state at each emitted line end. - Map clamped() => - _clampIndent(blockOut, prevListIndent, prevListQuoted, fixes); + Map clamped() => _clampIndent( + blockOut, + prevListIndent, + prevListQuoted, + prevListBox, + fixes, + ); void track(Map attrs) { final f = BlockFormat.fromAttributes(attrs); prevListIndent = f.isList ? f.indent : null; prevListQuoted = f.quoted; + prevListBox = Boxes.of(attrs); } + // The attributes an embed's line end keeps: overlays and the box. + Map embedLineAttrs(Map overlaysOf) => { + ...Attributes.overlays(overlaysOf), + if (blockOut.containsKey(WonkyAttr.box)) + WonkyAttr.box: blockOut[WonkyAttr.box], + }; + for (var gi = 0; gi < groups.length; gi++) { final g = groups[gi]; if (g.isRemoved) { @@ -422,7 +450,7 @@ final class WonkyDeltaNormalizer { b.keep(s.data, s.attributes, attrsOut); } if (!isFinal) { - b.insert('\n', null); + b.insert('\n', Attributes.orNull(embedLineAttrs(const {}))); } prevListIndent = null; } else { @@ -454,10 +482,9 @@ final class WonkyDeltaNormalizer { continue; } final endsWithEmbed = live.isNotEmpty && live.last.isEmbed; - var finalAttrs = endsWithEmbed - ? Attributes.overlays(blockOut) - : clamped(); - if (endsWithEmbed && Attributes.block(blockIn).isNotEmpty) { + var finalAttrs = endsWithEmbed ? embedLineAttrs(blockOut) : clamped(); + if (endsWithEmbed && + Attributes.block(blockIn).keys.any((k) => k != WonkyAttr.box)) { fixes.add(NormalizationFix.movedEmbed); } if (live.isEmpty && line.segments.isNotEmpty) { @@ -628,10 +655,42 @@ final class WonkyDeltaNormalizer { } else { fixes.add(NormalizationFix.removedAttributes); } + case WonkyAttr.linkStyle: + if (WonkyAttr.linkStyles.contains(v)) { + out[key] = v; + } else { + fixes.add(NormalizationFix.removedAttributes); + } + case WonkyAttr.chip: + if (v == true || + (v is String && WonkyDeltaValidator.chipIcon.hasMatch(v))) { + out[key] = v; + } else { + fixes.add(NormalizationFix.removedAttributes); + } default: fixes.add(NormalizationFix.removedAttributes); } } + // A chip and a styled link are plain-text labels (Write 11 §2.1). + if (out.containsKey(WonkyAttr.chip)) { + for (final k in WonkyAttr.chipExcludedKeys) { + if (out.remove(k) != null) { + fixes.add(NormalizationFix.styledTextExclusion); + } + } + } else if (out.containsKey(WonkyAttr.linkStyle)) { + if (!out.containsKey(WonkyAttr.link)) { + out.remove(WonkyAttr.linkStyle); + fixes.add(NormalizationFix.styledTextExclusion); + } else { + for (final k in WonkyAttr.linkStyleExcludedKeys) { + if (out.remove(k) != null) { + fixes.add(NormalizationFix.styledTextExclusion); + } + } + } + } if (out.containsKey(WonkyAttr.code)) { for (final k in WonkyAttr.codeExcludedKeys) { if (out.remove(k) != null) fixes.add(NormalizationFix.codeExclusion); @@ -702,6 +761,29 @@ final class WonkyDeltaNormalizer { type = key; out[key] = value; } + if (attrs.containsKey(WonkyAttr.step)) { + final v = attrs[WonkyAttr.step]; + final level = out[WonkyAttr.header]; + if (v is int && + v >= 0 && + v <= WonkyAttr.maxStep && + (level == 2 || level == 3)) { + out[WonkyAttr.step] = v; + } else { + fixes.add(NormalizationFix.removedAttributes); + } + } + if (attrs.containsKey(WonkyAttr.box)) { + final box = _normalizeBox(attrs[WonkyAttr.box]); + if (box == null) { + fixes.add(NormalizationFix.normalizedBox); + } else { + if (!_deepEquals(box, attrs[WonkyAttr.box])) { + fixes.add(NormalizationFix.normalizedBox); + } + out[WonkyAttr.box] = box; + } + } if (attrs.containsKey(WonkyAttr.indent)) { final v = attrs[WonkyAttr.indent]; final n = v is int ? v : (v is num ? v.round() : null); @@ -729,18 +811,45 @@ final class WonkyDeltaNormalizer { return out; } + /// The canonical `box` value of [value]: valid frames only (Write 11 + /// §2.4 rule 11), distinct ids, at most [BoxFrame.maxDepth] (the + /// outermost), canonical titles; `null` when none is left. + static List>? _normalizeBox(Object? value) { + if (value is! List) return null; + final frames = []; + final ids = {}; + for (final v in value) { + final f = BoxFrame.tryParse(v); + if (f == null || !ids.add(f.id)) continue; + frames.add( + f.title == null + ? f + : (BoxFrame.canonicalTitle(f.title) == null + ? f.copyWith(clearTitle: true) + : f.copyWith(title: BoxFrame.canonicalTitle(f.title))), + ); + if (frames.length == BoxFrame.maxDepth) break; + } + return Boxes.toValue(frames); + } + /// Clamps a list line's indent to one deeper than the previous list line - /// of the same run; a quoted and an unquoted list are two runs. + /// of the same run; a quoted and an unquoted list, and lists in different + /// containers, are two runs. Map _clampIndent( Map block, int? prevListIndent, bool prevListQuoted, + List prevListBox, Set fixes, ) { if (!block.containsKey(WonkyAttr.list)) return block; final indent = (block[WonkyAttr.indent] as int?) ?? 0; final quoted = block[WonkyAttr.blockquote] == true; - final maxAllowed = prevListIndent == null || prevListQuoted != quoted + final maxAllowed = + prevListIndent == null || + prevListQuoted != quoted || + !Boxes.samePath(prevListBox, Boxes.of(block)) ? 0 : prevListIndent + 1; if (indent <= maxAllowed) return block; @@ -840,6 +949,25 @@ final class WonkyDeltaNormalizer { ); case DividerEmbed(): return embed; + case YouTubeEmbed(:final title): + final canonical = YouTubeEmbed.canonicalTitle(title); + return canonical == title + ? embed + : embed.copyWith(title: canonical, clearTitle: canonical == null); + case GridEmbed(): + final normalizeCell = tableCellNormalizer; + final items = [ + for (final c in embed.items.take(GridEmbed.maxItems)) + normalizeCell == null + ? _singleLine(c) + : normalizeCell(_singleLine(c)), + ]; + return GridEmbed( + id: embed.id, + columns: GridEmbed.canonicalColumns(embed.columns), + bullets: embed.bullets, + items: items.isEmpty ? const [''] : items, + ); case TableEmbed(): final padded = embed.padded(); final normalizeCell = tableCellNormalizer; @@ -969,13 +1097,15 @@ final class _Window { required this.endsDocument, required this.prevListIndent, required this.prevListQuoted, + required this.prevListBox, }); const _Window.whole() : startsDocument = true, endsDocument = true, prevListIndent = null, - prevListQuoted = false; + prevListQuoted = false, + prevListBox = const []; /// Whether the first line is the document's first. final bool startsDocument; @@ -988,4 +1118,7 @@ final class _Window { /// Whether the line before the first is a quoted list item. final bool prevListQuoted; + + /// The containers of the line before the first. + final List prevListBox; } diff --git a/packages/wonky_write_core/lib/src/delta/validator.dart b/packages/wonky_write_core/lib/src/delta/validator.dart index 159114d1..a9d677cf 100644 --- a/packages/wonky_write_core/lib/src/delta/validator.dart +++ b/packages/wonky_write_core/lib/src/delta/validator.dart @@ -5,6 +5,7 @@ import 'package:dart_quill_delta/dart_quill_delta.dart'; import 'package:wonky_rich_text/wonky_rich_text.dart' show TextRules; import 'attributes.dart'; +import 'boxes.dart'; import 'embeds.dart'; import 'links.dart'; @@ -45,6 +46,17 @@ enum ValidationCode { /// `mention` without a `mailto:` link. mentionWithoutMailto, + /// `linkStyle` without a plain link, `chip` with a link, or either with + /// formatting their plain-text label excludes (Write 11 §2.4 rule 10). + styledTextFormatting, + + /// An invalid `box` value (Write 11 §2.4 rule 11). + invalidBox, + + /// `step` on a line that is not a level 2–3 heading (Write 11 §2.4 + /// rule 12). + invalidStep, + /// An embed that is not on its own line, or followed by a `"\n"` with block /// attributes. embedPlacement, @@ -173,6 +185,7 @@ final class WonkyDeltaValidator { // (A quoted and an unquoted list next to each other are two runs.) int? prevListIndent; var prevListQuoted = false; + var prevListBox = const []; Operation? prev; var prevWasEmbed = false; @@ -247,7 +260,7 @@ final class WonkyDeltaValidator { final nlOffset = offset + j; final format = _checkBlockAttributes(attrs, nlOffset, add); if (lineHasEmbed) { - if (Attributes.block(attrs).isNotEmpty) { + if (Attributes.block(attrs).keys.any((k) => k != WonkyAttr.box)) { add( ValidationCode.embedPlacement, nlOffset, @@ -284,8 +297,11 @@ final class WonkyDeltaValidator { pendingInline.clear(); // Indent rules. if (format != null && format.isList) { + final box = Boxes.of(attrs); final maxAllowed = - prevListIndent == null || prevListQuoted != format.quoted + prevListIndent == null || + prevListQuoted != format.quoted || + !Boxes.samePath(prevListBox, box) ? 0 : prevListIndent + 1; if (format.indent > maxAllowed) { @@ -297,6 +313,7 @@ final class WonkyDeltaValidator { } prevListIndent = format.indent; prevListQuoted = format.quoted; + prevListBox = box; } else { prevListIndent = null; } @@ -418,8 +435,41 @@ final class WonkyDeltaValidator { 'Invalid mention', ); } + case WonkyAttr.linkStyle: + if (!WonkyAttr.linkStyles.contains(v)) { + add( + ValidationCode.invalidAttributeValue, + offset, + 'Invalid link style "$v"', + ); + } + case WonkyAttr.chip: + if (v != true && (v is! String || !chipIcon.hasMatch(v))) { + add( + ValidationCode.invalidAttributeValue, + offset, + 'Invalid chip "$v"', + ); + } } } + if (attrs.containsKey(WonkyAttr.linkStyle) && + (attrs[WonkyAttr.link] is! String || + WonkyAttr.linkStyleExcludedKeys.any(attrs.containsKey))) { + add( + ValidationCode.styledTextFormatting, + offset, + '"linkStyle" needs a plain link and excludes formatting', + ); + } + if (attrs.containsKey(WonkyAttr.chip) && + WonkyAttr.chipExcludedKeys.any(attrs.containsKey)) { + add( + ValidationCode.styledTextFormatting, + offset, + '"chip" excludes other formatting and links', + ); + } if (attrs[WonkyAttr.code] == true && WonkyAttr.codeExcludedKeys.any(attrs.containsKey)) { add( @@ -441,6 +491,27 @@ final class WonkyDeltaValidator { _checkOverlays(attrs, offset, add, block: false); } + /// Valid chip icon names (Write 11 §2.1). + static final chipIcon = RegExp(r'^[a-z0-9-]{1,32}$'); + + /// Whether [value] is a valid `box` value (Write 11 §2.4 rule 11). + static bool isValidBox(Object? value) { + if (value is! List || value.isEmpty || value.length > BoxFrame.maxDepth) { + return false; + } + final ids = {}; + for (final v in value) { + final frame = BoxFrame.tryParse(v); + if (frame == null || !ids.add(frame.id)) return false; + if (frame.toJson().length != (v as Map).length) return false; + if (frame.title != null && + BoxFrame.canonicalTitle(frame.title) != frame.title) { + return false; + } + } + return true; + } + /// Returns the line's format if its block attributes are valid enough to /// interpret (used for contextual checks). static BlockFormat? _checkBlockAttributes( @@ -514,6 +585,22 @@ final class WonkyDeltaValidator { '"indent" without "list"', ); } + case WonkyAttr.step: + final header = attrs[WonkyAttr.header]; + if (v is! int || + v < 0 || + v > WonkyAttr.maxStep || + (header != 2 && header != 3)) { + add( + ValidationCode.invalidStep, + offset, + '"step" must be 0–${WonkyAttr.maxStep} on a level 2–3 heading', + ); + } + case WonkyAttr.box: + if (!isValidBox(v)) { + add(ValidationCode.invalidBox, offset, 'Invalid "box" value'); + } } } if (types > 1) { @@ -597,6 +684,26 @@ final class WonkyDeltaValidator { } case DividerEmbed(): break; + case YouTubeEmbed(:final title): + if (title != null && title != YouTubeEmbed.canonicalTitle(title)) { + add( + ValidationCode.invalidEmbed, + offset, + 'YouTube title must be trimmed single-line text without "]"', + ); + } + case GridEmbed(:final columns, :final items): + if (columns != GridEmbed.canonicalColumns(columns) || + items.isEmpty || + items.length > GridEmbed.maxItems || + items.any((c) => !_isSingleLineText(c))) { + add( + ValidationCode.invalidEmbed, + offset, + 'Grid must have 1–4 columns and 1–${GridEmbed.maxItems} ' + 'single-line items', + ); + } case TableEmbed(:final rows, :final align): final cols = rows.first.length; if (cols == 0 || diff --git a/packages/wonky_write_core/lib/src/derived/outline.dart b/packages/wonky_write_core/lib/src/derived/outline.dart index ebe672d9..d1655b24 100644 --- a/packages/wonky_write_core/lib/src/derived/outline.dart +++ b/packages/wonky_write_core/lib/src/derived/outline.dart @@ -20,6 +20,7 @@ final class OutlineEntry { required this.sectionStart, required this.sectionLength, required this.anchorId, + this.step, }); /// 0-based index among headings. @@ -47,6 +48,12 @@ final class OutlineEntry { /// Unique anchor id (`h--`). final String anchorId; + /// The number of a numbered heading (Wonky Markdown, Write 11 §2.3). + final int? step; + + /// [text] as shown in outlines: `(n) ` before a numbered heading. + String get label => step == null ? text : '($step) $text'; + /// JSON form (snake_case, as used by MCP). Map toJson() => { 'index': index, @@ -56,6 +63,7 @@ final class OutlineEntry { 'section_start': sectionStart, 'section_length': sectionLength, 'anchor_id': anchorId, + 'step': ?step, }; @override @@ -74,15 +82,15 @@ final class OutlineExtractor { /// Headings of a parsed document. List outlineOf(WonkyDocument doc) { final anchors = AnchorIdGenerator(); - final raw = <(DocumentLine, int, String)>[]; + final raw = <(DocumentLine, int, String, int?)>[]; for (final line in doc.lines) { final f = line.format; if (f.type != BlockType.heading) continue; - raw.add((line, f.level, headingText(line.text))); + raw.add((line, f.level, headingText(line.text), f.step)); } final result = []; for (var i = 0; i < raw.length; i++) { - final (line, level, text) = raw[i]; + final (line, level, text, step) = raw[i]; var end = doc.length; for (var j = i + 1; j < raw.length; j++) { if (raw[j].$2 <= level) { @@ -100,6 +108,7 @@ final class OutlineExtractor { sectionStart: line.start, sectionLength: end - line.start, anchorId: anchors.next(text), + step: step, ), ); } diff --git a/packages/wonky_write_core/lib/src/derived/plain_text.dart b/packages/wonky_write_core/lib/src/derived/plain_text.dart index f17aea3a..6c75f044 100644 --- a/packages/wonky_write_core/lib/src/derived/plain_text.dart +++ b/packages/wonky_write_core/lib/src/derived/plain_text.dart @@ -13,7 +13,7 @@ import '../markdown/inline_markdown.dart'; abstract final class PlainTextRenderer { /// Plain text of [document]: one line per line, soft breaks as `"\n"`, /// images as `[image: alt]`, dividers as `---`, tables as TSV (cells as - /// plain text). Suggestions rendered per [view]. + /// plain text), grid items one per line. Suggestions rendered per [view]. static String render( Delta document, { SuggestionViewMode view = SuggestionViewMode.accepted, @@ -37,11 +37,17 @@ abstract final class PlainTextRenderer { row .map( (c) => - InlineMarkdown.toPlainText(c).replaceAll('\t', ' '), + InlineMarkdown.cellPlainText(c).replaceAll('\t', ' '), ) .join('\t'), ); } + case GridEmbed(:final items): + for (final item in items) { + out.add(InlineMarkdown.cellPlainText(item)); + } + case YouTubeEmbed(:final title): + out.add(title == null ? '[video]' : '[video: $title]'); case null: break; } diff --git a/packages/wonky_write_core/lib/src/derived/stats.dart b/packages/wonky_write_core/lib/src/derived/stats.dart index 0e98f981..8e6da875 100644 --- a/packages/wonky_write_core/lib/src/derived/stats.dart +++ b/packages/wonky_write_core/lib/src/derived/stats.dart @@ -143,6 +143,8 @@ final class DocumentStatsCalculator { tables++; case DividerEmbed(): dividers++; + case GridEmbed() || YouTubeEmbed(): + break; case null: break; } diff --git a/packages/wonky_write_core/lib/src/edit/document_edits.dart b/packages/wonky_write_core/lib/src/edit/document_edits.dart index a8c37148..18b78632 100644 --- a/packages/wonky_write_core/lib/src/edit/document_edits.dart +++ b/packages/wonky_write_core/lib/src/edit/document_edits.dart @@ -6,6 +6,7 @@ import 'package:dart_quill_delta/dart_quill_delta.dart'; import 'package:uuid/uuid.dart'; import '../delta/attributes.dart'; +import '../delta/boxes.dart'; import '../delta/delta_diff.dart'; import '../delta/delta_utils.dart'; import '../delta/document.dart'; @@ -343,12 +344,17 @@ final class EditResult { /// Builds change Deltas for document edits. All builders are pure: they take /// the current document and return a normalized change. final class DocumentEdits { - /// Creates the builders. [idGenerator] creates embed ids (UUIDv7). + /// Creates the builders. [idGenerator] creates embed ids (UUIDv7); + /// Markdown input is read in [flavor] (the document's, Write 11 §5.1). DocumentEdits({ String Function()? idGenerator, this.maxDocumentChars = WonkyDeltaValidator.defaultMaxDocumentChars, + this.flavor = MarkdownFlavor.gfm, }) : idGenerator = idGenerator ?? (() => const Uuid().v7()); + /// The Markdown flavor input is read in. + final MarkdownFlavor flavor; + /// Embed id generator. final String Function() idGenerator; @@ -373,14 +379,15 @@ final class DocumentEdits { } return const MarkdownCodec().importMarkdown( markdown, - options: ImportOptions(idGenerator: idGenerator), + options: ImportOptions(idGenerator: idGenerator, flavor: flavor), ); } static bool _isSingleParagraph(WonkyDocument f) => f.lines.length == 1 && !f.lines.first.isEmbedLine && - f.lines.first.format.type == BlockType.paragraph; + f.lines.first.format.type == BlockType.paragraph && + Boxes.of(f.lines.first.attributes).isEmpty; // --------------------------------------------------------------------- // Insertion @@ -421,6 +428,29 @@ final class DocumentEdits { ); } + /// [fragment] with the containers [host] put around every line (the + /// fragment's own containers nest inside, up to [BoxFrame.maxDepth]). + static Delta _nestIn(Delta fragment, List host) { + if (host.isEmpty) return fragment; + final out = Delta(); + for (final line in WonkyDocument(fragment).lines) { + for (final s in line.segments) { + out.insert(s.data, s.attributes); + } + if (!line.hasNewline) continue; + final path = [...host, ...Boxes.of(line.attributes)]; + out.insert('\n', { + ...line.attributes, + WonkyAttr.box: Boxes.toValue( + path.length > BoxFrame.maxDepth + ? path.sublist(0, BoxFrame.maxDepth) + : path, + ), + }); + } + return DeltaUtils.canonical(out); + } + /// Returns (change, start of inserted content). (Delta, int) _insertChange( WonkyDocument doc, @@ -429,11 +459,13 @@ final class DocumentEdits { required InsertAs as, }) { AddressResolver.of(doc).checkOffset(at); - final frag = WonkyDocument(DeltaUtils.canonical(fragment)); final line = doc.lineAt(at); + final canonical = DeltaUtils.canonical(fragment); + final single = _isSingleParagraph(WonkyDocument(canonical)); + // Blocks inserted in a container go into it (Write 11 §7.4). + final frag = WonkyDocument(_nestIn(canonical, Boxes.of(line.attributes))); final fragLen = frag.length; final withoutLastNewline = frag.delta.slice(0, fragLen - 1); - final single = _isSingleParagraph(frag); final inline = !line.isEmbedLine && single && @@ -448,7 +480,8 @@ final class DocumentEdits { } final lastNewline = frag.lines.last.attributes; final lineBlock = Attributes.block(line.attributes); - final isEmptyPlain = line.isEmpty && lineBlock.isEmpty; + final isEmptyPlain = + line.isEmpty && lineBlock.keys.every((k) => k == WonkyAttr.box); if (isEmptyPlain) { // Fill the empty paragraph. for (final op in withoutLastNewline.operations) { @@ -808,7 +841,7 @@ final class DocumentEdits { }; final runs = format == ReplaceFormat.markdownInline ? [ - for (final r in InlineMarkdown.parse(text)) + for (final r in InlineMarkdown.parse(text, flavor: flavor)) ( r.text, {...Attributes.overlays(firstAttrs), ...?r.toAttributes()}, diff --git a/packages/wonky_write_core/lib/src/edit/document_reader.dart b/packages/wonky_write_core/lib/src/edit/document_reader.dart index 292cf9b9..a7abd860 100644 --- a/packages/wonky_write_core/lib/src/edit/document_reader.dart +++ b/packages/wonky_write_core/lib/src/edit/document_reader.dart @@ -9,6 +9,7 @@ import '../delta/delta_utils.dart'; import '../delta/document.dart'; import '../derived/outline.dart'; import '../derived/plain_text.dart'; +import '../import/import_api.dart' show MarkdownFlavor; import '../ir/doc_tree.dart'; import '../ir/doc_tree_builder.dart'; import '../markdown/markdown_exporter.dart'; @@ -72,8 +73,11 @@ final class ReadResult { /// Reads documents in agent-friendly formats. final class DocumentReader { - /// Creates a reader. - const DocumentReader(); + /// Creates a reader writing Markdown in [flavor] (Write 11 §5.2). + const DocumentReader({this.flavor = MarkdownFlavor.gfm}); + + /// The flavor of Markdown content. + final MarkdownFlavor flavor; /// Reads [document] (head, raw with overlays). /// @@ -151,6 +155,7 @@ final class DocumentReader { slice, mode, frontMatter: range == null ? frontMatter : null, + flavor: flavor, ); return _page(md, format, doc.length, maxChars, cursor, blocks); } @@ -161,6 +166,7 @@ final class DocumentReader { Delta document, SuggestionViewMode mode, { String? frontMatter, + MarkdownFlavor flavor = MarkdownFlavor.gfm, }) { final source = mode == SuggestionViewMode.raw ? _criticMarkup(document) @@ -170,7 +176,9 @@ final class DocumentReader { view: mode == SuggestionViewMode.raw ? SuggestionViewMode.raw : mode, meta: DocMeta(frontMatter: frontMatter), ); - return const MarkdownExporter().export(tree); + return MarkdownExporter( + options: MarkdownExportOptions(flavor: flavor), + ).export(tree); } /// Wraps `ins`/`del` suggestion text in CriticMarkup markers. @@ -247,7 +255,9 @@ final class DocumentReader { doc.delta, view: SuggestionViewMode.raw, ); - final export = const MarkdownExporter().exportWithPositions(tree); + final export = MarkdownExporter( + options: MarkdownExportOptions(flavor: flavor), + ).exportWithPositions(tree); if (export.blocks.length == infos.length) mdPositions = export.blocks; } final result = >[]; diff --git a/packages/wonky_write_core/lib/src/export/docx/docx_exporter.dart b/packages/wonky_write_core/lib/src/export/docx/docx_exporter.dart index fb6ef225..1e37da9c 100644 --- a/packages/wonky_write_core/lib/src/export/docx/docx_exporter.dart +++ b/packages/wonky_write_core/lib/src/export/docx/docx_exporter.dart @@ -9,6 +9,7 @@ library; import 'dart:math' as math; import 'dart:typed_data'; +import '../../delta/boxes.dart'; import '../../delta/embeds.dart'; import '../../ir/doc_tree.dart'; import '../../layout/page_setup.dart'; @@ -71,7 +72,15 @@ final class _DocxJob { input.theme, input.variant, ); - late final DocTree tree = exportTree(input, options); + late final DocTree tree = exportTree(input, options).withVideosAsLinks; + + /// The blocks in document order with Wonky containers flattened + /// (Write 11 §9): a callout's title and a details summary become bold + /// paragraphs, and every block in a container gets the container's look + /// ([_boxes]). + late final List _blocks = _flatten(tree.blocks, null); + final _boxes = Map.identity(); + final _titleColors = Map.identity(); late final double contentWidth = contentWidthPt(input, theme); late final double contentHeight = contentHeightPt(input, theme); Map _images = const {}; @@ -464,7 +473,7 @@ final class _DocxJob { /// Natural (style) spacing of each block before collapsing. List<(double, double)> _naturalSpacing() { - final blocks = tree.blocks; + final blocks = _blocks; final out = <(double, double)>[]; for (var i = 0; i < blocks.length; i++) { final b = blocks[i]; @@ -472,6 +481,15 @@ final class _DocxJob { final next = i + 1 < blocks.length ? blocks[i + 1] : null; bool isListLike(DocBlock? x) => x is ListItemBlock || x is TaskBlock; switch (b) { + case ContainerBlock(): + // Flattened ([_blocks]). + out.add((0, 0)); + case YouTubeBlock(): + // Links ([DocTree.withVideosAsLinks]). + out.add((0, 0)); + case GridBlock(): + final g = theme.wonky.grid; + out.add((g.spaceBefore, g.spaceAfter)); case ParagraphBlock(): var before = theme.body.box.spaceBefore; var after = theme.body.box.spaceAfter; @@ -533,7 +551,7 @@ final class _DocxJob { String _body() { final b = StringBuffer(); - final blocks = tree.blocks; + final blocks = _blocks; final natural = _naturalSpacing(); // Collapsed: Word adds after(prev) + before(next); emit // before = max(0, before - after(prev)) so the gap is the max (06 §7.3). @@ -559,6 +577,22 @@ final class _DocxJob { final (before, after) = spacing[i]; final (natBefore, natAfter) = natural[i]; switch (block) { + case ContainerBlock(): + // Flattened ([_blocks]). + break; + case YouTubeBlock(): + // Links ([DocTree.withVideosAsLinks]). + break; + case GridBlock(): + if (i > 0 && before > 0.5) b.write(_spacer(before)); + b.write(_grid(block)); + b.write(_spacer(natAfter)); + if (i + 1 < blocks.length) { + spacing[i + 1] = ( + math.max(0, spacing[i + 1].$1 - natAfter).toDouble(), + spacing[i + 1].$2, + ); + } case ParagraphBlock(:final runs): final p = ParaProps(); final styleBefore = theme.body.box.spaceBefore; @@ -568,13 +602,31 @@ final class _DocxJob { if (theme.body.firstLineIndent > 0 && runs.isNotEmpty) { p.firstLine = theme.body.firstLineIndent; } - b.write(_paragraph(p, runs)); + _boxed(block, p); + final titleColor = _titleColors[block]; + if (titleColor != null) { + // A callout title. + p.keepNext = true; + final props = RunProps() + ..bold = true + ..color = titleColor; + b.write( + '${p.xml()}${_textRun(InlineRun.plainText(runs), props)}', + ); + } else { + b.write(_paragraph(p, runs)); + } case HeadingBlock(:final level, :final runs, :final anchorId): final box = theme.heading(level).box; final p = ParaProps()..style = DocxStyleIds.heading(level); if (before != box.spaceBefore) p.spaceBefore = before; + _boxed(block, p); final bookmark = _bookmarks[anchorId]; final content = StringBuffer(); + if (block.step != null) { + // A numbered heading (Write 11 §9). + content.write(_textRun('${block.step}. ', null)); + } if (bookmark != null) { content.write( '', @@ -617,6 +669,7 @@ final class _DocxJob { if (before != 0) p.spaceBefore = before; if (after != theme.list.itemSpacing) p.spaceAfter = after; if (block.inQuote) _quoted(p, indent); + _boxed(block, p); b.write(_paragraph(p, runs)); case TaskBlock(:final checked, :final indent, :final runs): orderedNum.remove(indent); @@ -626,6 +679,7 @@ final class _DocxJob { if (before != 0) p.spaceBefore = before; if (after != theme.list.itemSpacing) p.spaceAfter = after; if (block.inQuote) _quoted(p, indent); + _boxed(block, p); final glyph = RunProps() ..font = 'Segoe UI Symbol' ..color = theme.task.checkbox.borderColor; @@ -653,6 +707,7 @@ final class _DocxJob { final la = last ? after : theme.body.box.spaceAfter; if (lb != 0) p.spaceBefore = lb; if (la != 0) p.spaceAfter = la; + _boxed(block, p); b.write(_paragraph(p, lines[l])); } case CodeBlock(:final language, :final text): @@ -697,6 +752,109 @@ final class _DocxJob { return b.toString(); } + /// Flattens Wonky containers ([_blocks]). + List _flatten(List blocks, _Box? box) { + final out = []; + for (final b in blocks) { + if (b is! ContainerBlock) { + if (box != null) _boxes[b] = box; + out.add(b); + continue; + } + final w = theme.wonky; + final depth = (box?.depth ?? 0) + 1; + final frame = b.frame; + final _Box inner; + switch (frame.type) { + case BoxType.callout: + final cc = w.callout.colorsFor( + (frame.variant ?? CalloutVariant.info).value, + ); + inner = _Box( + cc.background, + BorderPt( + width: math.max(w.callout.borderWidth, 1.5) * 2, + style: LineStyle.solid, + color: cc.border, + ), + depth, + ); + final title = ParagraphBlock([ + InlineRun(frame.calloutLabel, bold: true), + ]); + _titleColors[title] = cc.title; + _boxes[title] = inner; + out.add(title); + case BoxType.details: + inner = _Box(w.details.background, w.details.border, depth); + final summary = ParagraphBlock([ + for (final r in b.summary?.runs ?? const []) + r.code ? r : r.copyWith(bold: true), + ]); + _boxes[summary] = inner; + out.add(summary); + case BoxType.card: + inner = _Box(w.card.background, null, depth); + } + out.addAll(_flatten(b.body, inner)); + } + return out; + } + + /// Gives a paragraph in a Wonky container the container's shading, left + /// border and nesting indent. + void _boxed(DocBlock block, ParaProps p) { + final box = _boxes[block]; + if (box == null) return; + p.shading ??= box.shading; + final border = box.border; + if (p.left == null && border != null && border.isVisible) { + p.left = docxBorder('left', border, space: 6); + } + if (p.indentLeft == null && box.depth > 1) { + p.indentLeft = 12.0 * (box.depth - 1); + } + } + + /// A Wonky grid as a borderless table (Write 11 §9). + String _grid(GridBlock g) { + final cols = g.columns.clamp(1, 4); + final width = contentWidth / cols; + final b = StringBuffer( + '' + '', + ); + for (var c = 0; c < cols; c++) { + b.write(''); + } + b.write(''); + final glyph = switch (g.bullets) { + GridBullets.check => '✓ ', + GridBullets.circle => '• ', + GridBullets.none => '', + }; + final bullet = RunProps() + ..color = theme.wonky.grid.bulletColor + ..bold = true; + for (var r = 0; r * cols < g.items.length; r++) { + b.write(''); + for (var c = 0; c < cols; c++) { + final k = r * cols + c; + final p = ParaProps()..spaceAfter = theme.wonky.grid.rowGap; + final content = k < g.items.length + ? '${_textRun(glyph, bullet)}${_runs(g.items[k])}' + : ''; + b.write( + '${p.xml()}$content', + ); + } + b.write(''); + } + b.write(''); + return b.toString(); + } + String _toc() { final depth = 3; return '' @@ -755,11 +913,19 @@ final class _DocxJob { p.style = DocxStyleIds.codeChar; return p; } + if (r.chip) { + // A chip: shaded text (Write 11 §9). + p + ..shading = theme.wonky.chip.background + ..color = theme.wonky.chip.color; + return p; + } if (r.mentionUserUuid != null) { p.style = DocxStyleIds.mention; } else if (r.link != null) { p.style = DocxStyleIds.hyperlink; } + if (r.linkStyle != null) p.bold = true; if (r.bold) { p.bold = true; if (theme.bold.color != null) p.color = theme.bold.color; @@ -997,3 +1163,13 @@ final class _DocxJob { return b.toString(); } } + +/// The look of a Wonky container in DOCX: paragraph shading, left border, +/// nesting depth. +final class _Box { + const _Box(this.shading, this.border, this.depth); + + final int? shading; + final BorderPt? border; + final int depth; +} diff --git a/packages/wonky_write_core/lib/src/export/html/html_writer.dart b/packages/wonky_write_core/lib/src/export/html/html_writer.dart index 06226a16..87da128f 100644 --- a/packages/wonky_write_core/lib/src/export/html/html_writer.dart +++ b/packages/wonky_write_core/lib/src/export/html/html_writer.dart @@ -2,11 +2,14 @@ /// (07 §5.3, §5.8). library; +import '../../delta/boxes.dart'; import '../../delta/delta_utils.dart'; +import '../../delta/embeds.dart'; import '../../highlight/syntax_highlighter.dart'; import '../../ir/doc_tree.dart'; import '../../markdown/inline_reader.dart' show mentionTitlePrefix; import '../export_api.dart'; +import '../wonky_icons.dart'; /// Options of [HtmlBodyWriter]. final class HtmlBodyOptions { @@ -198,8 +201,17 @@ final class HtmlBodyWriter { switch (block) { case ParagraphBlock(:final runs): return runs.isEmpty ? '

$_br

' : '

${inline(runs)}

'; - case HeadingBlock(:final level, :final runs, :final anchorId): - return '${runs.isEmpty ? _br : inline(runs)}'; + case HeadingBlock( + :final level, + :final runs, + :final anchorId, + :final step, + ): + final badge = step == null + ? '' + : '$step'; + final cls = step == null ? '' : ' class="wonky-step"'; + return '$badge${runs.isEmpty ? _br : inline(runs)}'; case QuoteBlock(:final lines): return '
${_quoteLines(lines)}
'; case CodeBlock(:final language, :final text): @@ -252,6 +264,57 @@ final class HtmlBodyWriter { return b.toString(); case ListItemBlock() || TaskBlock(): return blocks([block]); + case ContainerBlock(): + return _container(block); + case YouTubeBlock(:final embed): + // EPUB readers can't play it: a link (Write 11 §9). + if (options.xhtml) return this.block(block.asLink); + final title = escape(embed.title ?? 'YouTube video'); + return '
'; + case GridBlock(:final columns, :final bullets, :final items): + final bullet = switch (bullets) { + GridBullets.check => WonkyIcons.check(cls: 'wonky-grid-bullet'), + GridBullets.circle => WonkyIcons.circle(cls: 'wonky-grid-bullet'), + GridBullets.none => '', + }; + final b = StringBuffer('
'); + for (final item in items) { + b.write( + '
$bullet' + '${inline(item)}
', + ); + } + b.write('
'); + return b.toString(); + } + } + + /// A Wonky Markdown container (Write 11 §9). + String _container(ContainerBlock block) { + final frame = block.frame; + switch (frame.type) { + case BoxType.callout: + final variant = (frame.variant ?? CalloutVariant.info).value; + return '
' + '
' + '${WonkyIcons.callout(variant, cls: 'wonky-callout-icon')}' + '${escape(frame.calloutLabel)}
' + '${blocks(block.children)}
'; + case BoxType.details: + final summary = block.summary; + return '
' + '' + '${summary == null || summary.runs.isEmpty ? '' : inline(summary.runs)}' + '${WonkyIcons.chevron(cls: 'wonky-details-chevron')}' + '
${blocks(block.body)}
' + '
'; + case BoxType.card: + return '
${blocks(block.children)}
'; } } @@ -278,10 +341,42 @@ final class HtmlBodyWriter { var i = 0; while (i < runs.length) { final r = runs[i]; + if (r.chip) { + b.write('${escape(r.text)}'); + i++; + continue; + } + if (r.link != null && r.linkStyle != null) { + var j = i; + final label = StringBuffer(); + while (j < runs.length && + runs[j].link == r.link && + runs[j].linkStyle == r.linkStyle) { + label.write(runs[j].text); + j++; + } + final href = attr(options.links.resolve(r.link!)); + final text = escape(label.toString().replaceAll(softBreak, ' ')); + b.write(switch (r.linkStyle) { + 'arrow' => + '
' + '$text${WonkyIcons.arrow(cls: 'wonky-link-arrow')}', + 'buttonSecondary' => + '$text', + _ => + '' + '$text', + }); + i = j; + continue; + } if (r.link != null) { var j = i; while (j < runs.length && runs[j].link == r.link && + runs[j].linkStyle == null && + !runs[j].chip && runs[j].mentionUserUuid == r.mentionUserUuid) { j++; } diff --git a/packages/wonky_write_core/lib/src/export/markdown_file_exporter.dart b/packages/wonky_write_core/lib/src/export/markdown_file_exporter.dart index 3fda166a..bf02fc55 100644 --- a/packages/wonky_write_core/lib/src/export/markdown_file_exporter.dart +++ b/packages/wonky_write_core/lib/src/export/markdown_file_exporter.dart @@ -62,6 +62,7 @@ final class MarkdownFileExporter _ => img.src, }, linkRewriter: input.links.resolve, + flavor: input.meta.markdownFlavor, ), ).export(tree); return ExportArtifact( @@ -121,6 +122,7 @@ final class MarkdownZipExporter frontMatter: options.frontMatter, imageSource: (img) => paths[img.src] ?? img.src, linkRewriter: input.links.resolve, + flavor: input.meta.markdownFlavor, ), ).export(tree); entries.add(ZipEntry.text('document.md', md)); diff --git a/packages/wonky_write_core/lib/src/export/odt/odt_exporter.dart b/packages/wonky_write_core/lib/src/export/odt/odt_exporter.dart index 8ed99a91..ff2d3768 100644 --- a/packages/wonky_write_core/lib/src/export/odt/odt_exporter.dart +++ b/packages/wonky_write_core/lib/src/export/odt/odt_exporter.dart @@ -3,6 +3,7 @@ library; import 'dart:math' as math; +import '../../delta/boxes.dart'; import '../../delta/embeds.dart'; import 'package:wonky_fonts/wonky_fonts.dart'; import '../../ir/doc_tree.dart'; @@ -43,7 +44,7 @@ final class OdtExporter implements DocumentExporter { ) async { input.cancel?.throwIfCancelled(); input.progress?.call(ExportPhase.loading, 0); - final tree = exportTree(input, options); + final tree = exportTree(input, options).withVideosAsLinks; final theme = ThemeResolver.instance.resolve(input.theme, input.variant); final warnings = []; final images = await resolveOfficeImages(input, tree, warnings); @@ -308,7 +309,23 @@ final class _OdtWriter { String contentXml() { if (options.includeToc) _toc(); - final blocks = tree.blocks; + _blocks(tree.blocks); + if (tree.blocks.isEmpty && !options.includeToc) { + _body.write(''); + } + input.progress?.call(ExportPhase.layout, 1); + return '$_xmlDecl' + '${fontFaceDecls()}' + '${_auto.out}' + '$_body' + ''; + } + + /// Paragraph properties of the Wonky container being written (Write 11 + /// §9): shading, left border and nesting indent; empty outside one. + var _boxProps = const {}; + + void _blocks(List blocks) { var i = 0; while (i < blocks.length) { if (i % 64 == 0) { @@ -329,6 +346,13 @@ final class _OdtWriter { continue; } switch (b) { + case ContainerBlock(): + _container(b); + case YouTubeBlock(): + // Links ([DocTree.withVideosAsLinks]). + break; + case GridBlock(): + _grid(b); case ParagraphBlock(:final runs): _paragraph(_p('Standard'), runs); case HeadingBlock(): @@ -348,15 +372,128 @@ final class _OdtWriter { } i++; } - if (blocks.isEmpty && !options.includeToc) { - _body.write(''); + } + + /// A Wonky container: a callout's title or a details summary as a bold + /// paragraph, then the content, all with the container's shading. + void _container(ContainerBlock c) { + final w = t.wonky; + final frame = c.frame; + final saved = _boxProps; + final depth = + (saved['wonky-depth'] == null ? 0 : int.parse(saved['wonky-depth']!)) + + 1; + int? background; + BorderPt? border; + switch (frame.type) { + case BoxType.callout: + final cc = w.callout.colorsFor( + (frame.variant ?? CalloutVariant.info).value, + ); + background = cc.background; + border = BorderPt( + width: math.max(w.callout.borderWidth, 1.5) * 2, + style: LineStyle.solid, + color: cc.border, + ); + case BoxType.details: + background = w.details.background; + border = w.details.border; + case BoxType.card: + background = w.card.background; } - input.progress?.call(ExportPhase.layout, 1); - return '$_xmlDecl' - '${fontFaceDecls()}' - '${_auto.out}' - '$_body' - ''; + _boxProps = { + 'wonky-depth': '$depth', + if (background != null) 'fo:background-color': _color(background), + if (border != null && border.isVisible) ...{ + 'fo:border-left': '${_pt(border.width)} solid ${_color(border.color)}', + 'fo:padding-left': _pt(6), + }, + if (depth > 1) 'fo:margin-left': _pt(12.0 * (depth - 1)), + }; + switch (frame.type) { + case BoxType.callout: + final cc = w.callout.colorsFor( + (frame.variant ?? CalloutVariant.info).value, + ); + final span = _textStyle({ + 'fo:font-weight': 'bold', + 'fo:color': _color(cc.title), + }); + _body + ..write( + '', + ) + ..write('') + ..write(xmlText(frame.calloutLabel)) + ..write(''); + case BoxType.details: + _paragraph(_p('Standard', {'fo:keep-with-next': 'always'}), [ + for (final r in c.summary?.runs ?? const []) + r.code ? r : r.copyWith(bold: true), + ]); + case BoxType.card: + break; + } + _blocks(c.body); + _boxProps = saved; + } + + /// A Wonky grid as a borderless table (Write 11 §9). + void _grid(GridBlock g) { + _tables++; + final cols = g.columns.clamp(1, 4); + final tableStyle = _auto.add( + 'Ta', + 'table', + null, + '', + ); + final colStyle = _auto.add( + 'Co', + 'table-column', + null, + '', + ); + final glyph = switch (g.bullets) { + GridBullets.check => '✓ ', + GridBullets.circle => '• ', + GridBullets.none => '', + }; + final bullet = _textStyle({ + 'fo:font-weight': 'bold', + 'fo:color': _color(t.wonky.grid.bulletColor), + }); + final para = _p('Standard', {'fo:margin-bottom': _pt(t.wonky.grid.rowGap)}); + _body + ..write( + '', + ) + ..write( + ' 1 ? ' table:number-columns-repeated="$cols"' : ''}/>', + ); + for (var r = 0; r * cols < g.items.length; r++) { + _body.write(''); + for (var c = 0; c < cols; c++) { + final k = r * cols + c; + _body.write(''); + if (k < g.items.length) { + _paragraph( + para, + g.items[k], + lead: glyph.isEmpty + ? '' + : '$glyph', + ); + } else { + _body.write(''); + } + _body.write(''); + } + _body.write(''); + } + _body.write(''); } String metaXml() { @@ -439,7 +576,13 @@ final class _OdtWriter { /// the page number start. String _p(String parent, [Map para = const {}]) { var attrs = const {}; - var props = para; + var props = _boxProps.isEmpty + ? para + : { + for (final e in _boxProps.entries) + if (e.key != 'wonky-depth') e.key: e.value, + ...para, + }; if (_firstPending) { _firstPending = false; attrs = const {'style:master-page-name': 'Standard'}; @@ -531,6 +674,15 @@ final class _OdtWriter { String? _runStyle(InlineRun r) { if (r.code) return 'Source_20_Text'; + if (r.chip) { + return _textStyle({ + 'fo:background-color': _color(t.wonky.chip.background), + 'fo:color': _color(t.wonky.chip.color), + }); + } + if (r.linkStyle != null) { + return _textStyle({'fo:font-weight': 'bold'}); + } final parent = r.mentionUserUuid != null ? _mentionStyle : null; if (!r.bold && !r.italic && !r.strike) return parent; final props = { @@ -560,9 +712,11 @@ final class _OdtWriter { void _heading(HeadingBlock h) { final level = h.level.clamp(1, 6); final style = _p('Heading_20_$level'); - final bookmark = h.anchorId.isEmpty - ? '' - : ''; + final bookmark = + (h.anchorId.isEmpty + ? '' + : '') + + (h.step == null ? '' : xmlText('${h.step}. ')); _paragraph( style, h.runs, @@ -905,7 +1059,7 @@ final class _OdtWriter { // Table of contents void _toc() { - final labels = headingLabels(tree, t); + final labels = allHeadingLabels(tree, t); const title = 'Contents'; _body ..write( @@ -934,10 +1088,13 @@ final class _OdtWriter { ..write(''); _paragraph(_p('Contents_20_Heading'), const [InlineRun(title)]); _body.write(''); - for (var i = 0; i < tree.blocks.length; i++) { - final b = tree.blocks[i]; - if (b is! HeadingBlock || b.level > _tocDepth) continue; - final text = '${labels[i] ?? ''}${runsPlainText(b.runs)}'; + // Details summaries are bold paragraphs, not headings. + final summaries = { + for (final c in tree.allBlocks.whereType()) ?c.summary, + }; + for (final b in tree.allBlocks.whereType()) { + if (b.level > _tocDepth || summaries.contains(b)) continue; + final text = '${labels[b] ?? ''}${runsPlainText(b.runs)}'; if (text.trim().isEmpty) continue; _body.write(''); final o = _TextOut(_body); diff --git a/packages/wonky_write_core/lib/src/export/office/office_support.dart b/packages/wonky_write_core/lib/src/export/office/office_support.dart index 5a4c663e..683f1152 100644 --- a/packages/wonky_write_core/lib/src/export/office/office_support.dart +++ b/packages/wonky_write_core/lib/src/export/office/office_support.dart @@ -414,6 +414,30 @@ Map headingLabels(DocTree tree, ResolvedWriteTheme theme) { return out; } +/// Heading number labels of every heading of [tree], containers included +/// (details summaries are not numbered, Write 11 §9), by heading. +Map allHeadingLabels( + DocTree tree, + ResolvedWriteTheme theme, +) { + final out = Map.identity(); + if (!theme.headingNumbering.enabled) return out; + final numberer = HeadingNumberer(theme.headingNumbering); + void walk(List blocks, {HeadingBlock? summary}) { + for (final b in blocks) { + if (b is HeadingBlock && !identical(b, summary)) { + final label = numberer.next(b.level); + if (label != null) out[b] = label; + } else if (b is ContainerBlock) { + walk(b.children, summary: b.summary); + } + } + } + + walk(tree.blocks); + return out; +} + /// Applies a theme case transform to [text] for formats without a native /// equivalent. String applyCase(String text, CaseTransform transform) => switch (transform) { diff --git a/packages/wonky_write_core/lib/src/export/pdf/pdf_exporter.dart b/packages/wonky_write_core/lib/src/export/pdf/pdf_exporter.dart index 2246be0f..a30d5e9a 100644 --- a/packages/wonky_write_core/lib/src/export/pdf/pdf_exporter.dart +++ b/packages/wonky_write_core/lib/src/export/pdf/pdf_exporter.dart @@ -13,7 +13,9 @@ import 'package:pdf/pdf.dart'; // ignore: implementation_imports import 'package:pdf/src/pdf/format/string.dart' show PdfString; +import '../../delta/boxes.dart'; import '../../delta/delta_utils.dart'; +import '../../delta/embeds.dart'; import '../../highlight/syntax_highlighter.dart'; import '../../ir/doc_tree.dart'; import '../../layout/header_footer_tokens.dart'; @@ -41,7 +43,42 @@ final class _DeterministicDocument extends PdfDocument { Uint8List get documentID => _id; } -enum _Kind { text, image, rule, table } +enum _Kind { text, image, rule, table, grid, spacer } + +/// One Wonky Markdown container a block is in (Write 11 §9): the frame the +/// block's slices draw behind their content. +final class _Frame { + _Frame({ + required this.x, + required this.width, + required this.background, + required this.border, + required this.radius, + this.top = false, + this.bottom = false, + }); + + /// Left offset from the content left (pt) and width of the container. + final double x; + final double width; + final int? background; + final BorderPt border; + final double radius; + + /// Whether the block is the container's first (header) / last block. + final bool top; + final bool bottom; + + _Frame copyWith({bool? top, bool? bottom}) => _Frame( + x: x, + width: width, + background: background, + border: border, + radius: radius, + top: top ?? this.top, + bottom: bottom ?? this.bottom, + ); +} /// One cell of a laid-out table. final class _Cell { @@ -83,11 +120,42 @@ final class _Block { final int? background; final BordersPt? borders; final double radius; - final double spaceBefore; - final double spaceAfter; + double spaceBefore; + double spaceAfter; final bool keepWithNext; final bool pageBreakBefore; + /// Left offset from the content left and available width (pt): narrower + /// inside Wonky containers. + double x = 0; + double width = 0; + + /// The containers the block is in, outermost first. + List<_Frame> frames = const []; + + /// Height of a spacer block (a container's top or bottom padding). + double spacerHeight = 0; + + // Wonky decorations (Write 11 §9). + int? stepNumber; + double stepSize = 0; + int stepBackground = 0; + PdfRunStyle? stepStyle; + String? calloutIcon; + int iconColor = 0; + double iconSize = 0; + int? chevronColor; + double chevronSize = 0; + + // Grid: rows → cells → lines. + List>> gridRows = const []; + double gridColumnWidth = 0; + double gridColumnGap = 0; + double gridTextLeft = 0; + GridBullets gridBullets = GridBullets.none; + int gridBulletColor = 0; + double gridBulletSize = 0; + // Decorations. BorderPt? leftBar; BorderPt? bottomBorder; @@ -187,7 +255,7 @@ final class _PdfJob { input.theme, input.variant, ); - late final DocTree tree = exportTree(input, options); + late final DocTree tree = exportTree(input, options).withVideosAsLinks; late final PdfDocument doc = _DeterministicDocument( Uint8List.fromList( sha256 @@ -224,6 +292,15 @@ final class _PdfJob { ); }(); late final double contentWidth = pageWidth - margins.left - margins.right; + + /// Left offset and width of the area blocks are laid out in (narrower + /// inside Wonky containers), and the containers around it. + double _x = 0; + late double _avail = contentWidth; + final _frameStack = <_Frame>[]; + + /// Heading numbering labels (details summaries are not numbered). + final _headingLabels = {}; final _images = {}; List<_Block> blocks = []; List headingPages = []; @@ -259,9 +336,29 @@ final class _PdfJob { _images[im.src] = await _loadImage(im); } input.cancel?.throwIfCancelled(); + _labelHeadings(); blocks = await _buildBlocks(tree.blocks); } + void _labelHeadings() { + final headings = []; + void walk(List list) { + for (final b in list) { + if (b is HeadingBlock) headings.add(b); + if (b is ContainerBlock) walk(b.body); + } + } + + walk(tree.blocks); + final labels = HeadingNumberer.labelsFor( + theme.headingNumbering, + headings.map((h) => h.level), + ); + for (var i = 0; i < headings.length; i++) { + _headingLabels[headings[i]] = labels[i]; + } + } + /// A turn for the event loop when the export runs on the UI isolate (web, /// 07 §4.3), then the cancellation check: without the turn, *Cancel* /// (and the progress) could only be handled after the whole export. @@ -273,7 +370,7 @@ final class _PdfJob { String _allText() { final b = StringBuffer(); - for (final block in tree.blocks) { + for (final block in tree.allBlocks) { switch (block) { case ParagraphBlock(:final runs) || HeadingBlock(:final runs) || @@ -294,10 +391,21 @@ final class _PdfJob { } case ImageBlock(:final alt, :final title): b.write('$alt${title ?? ''}'); + case GridBlock(:final items): + for (final i in items) { + b.write(InlineRun.plainText(i)); + } + case YouTubeBlock(:final asLink): + b.write(InlineRun.plainText(asLink.runs)); + case ContainerBlock(:final frame): + b.write(frame.calloutLabel.toUpperCase()); + b.write(frame.calloutLabel); case RuleBlock(): break; } } + // Arrow link glyphs, step numbers. + b.write('\u2197\u21920123456789'); return b.toString(); } @@ -354,11 +462,25 @@ final class _PdfJob { int? color, bool strikeAll = false, CaseTransform caseTransform = CaseTransform.none, + int? weight, }) { final t = theme; final out = <(String, PdfRunStyle)>[]; - for (final r in runs) { + for (var k = 0; k < runs.length; k++) { + final r = runs[k]; final text = applyCase(r.text, caseTransform); + final styled = _styledRun(r, text, base, strikeAll: strikeAll); + if (styled != null) { + // A plain space on each side keeps pills apart from their + // neighbours (the pill reaches into it). + final pill = styled.first.$2.background != null; + final space = _base(base); + final gap = r.chip ? ' ' : ' '; + if (pill && k > 0) out.add((gap, space)); + out.addAll(styled); + if (pill && k < runs.length - 1) out.add((gap, space)); + continue; + } if (r.code) { final ic = t.inlineCode; out.add(( @@ -381,7 +503,9 @@ final class _PdfJob { )); continue; } - final weight = r.bold ? (t.bold.fontWeight ?? 700) : base.fontWeight; + final runWeight = r.bold + ? (t.bold.fontWeight ?? 700) + : (weight ?? base.fontWeight); final italic = r.italic ? true : base.italic; var c = color ?? base.color; if (r.bold && t.bold.color != null) c = t.bold.color!; @@ -394,7 +518,7 @@ final class _PdfJob { PdfRunStyle( font: fonts.font( base.fontFamily, - isMention ? t.mention.fontWeight : weight, + isMention ? t.mention.fontWeight : runWeight, italic, ), size: base.fontSize, @@ -419,6 +543,73 @@ final class _PdfJob { return out; } + /// A chip, button or arrow link (Write 11 §9): pills behind the label, + /// links kept; `null` for other runs. + List<(String, PdfRunStyle)>? _styledRun( + InlineRun r, + String text, + ResolvedTextStyle base, { + bool strikeAll = false, + }) { + final w = theme.wonky; + final size = base.fontSize; + if (r.chip) { + final ch = w.chip; + return [ + ( + text, + PdfRunStyle( + font: fonts.font(base.fontFamily, ch.fontWeight, false), + size: size, + color: ch.color, + background: ch.background, + backgroundPadX: size * 0.3, + backgroundRadius: math.min(ch.borderRadius, size * 0.6), + strike: strikeAll, + ), + ), + ]; + } + final link = r.link; + final style = r.linkStyle; + if (link == null || style == null) return null; + final target = input.links.resolve(link); + final bt = w.button; + if (style == 'arrow') { + final s = PdfRunStyle( + font: fonts.font(base.fontFamily, bt.arrowWeight, false), + size: size, + color: bt.arrowColor, + link: target, + strike: strikeAll, + ); + return [(text, s), ('\u00a0${_arrowGlyph(s.font)}', s)]; + } + final secondary = style == 'buttonSecondary'; + return [ + ( + text, + PdfRunStyle( + font: fonts.font(base.fontFamily, bt.fontWeight, false), + size: size, + color: secondary ? bt.secondaryColor : bt.color, + background: secondary ? bt.secondaryBackground : bt.background, + backgroundPadX: size * 0.3, + backgroundRadius: math.min(bt.borderRadius, size * 0.6), + link: target, + strike: strikeAll, + ), + ), + ]; + } + + /// `↗`, or a fallback the fonts can draw. + String _arrowGlyph(PdfFont font) { + if (fonts.supports(0x2197, font)) return '\u2197'; + if (fonts.supports(0x2192, font)) return '\u2192'; + return '>'; + } + PdfRunStyle _base(ResolvedTextStyle s, {bool mono = false}) => styler.text(s, mono: mono); @@ -427,11 +618,6 @@ final class _PdfJob { Future> _buildBlocks(List source) async { final t = theme; - final labels = HeadingNumberer.labelsFor( - t.headingNumbering, - source.whereType().map((h) => h.level), - ); - var headingIndex = 0; final out = <_Block>[]; DocBlock? prev; for (var i = 0; i < source.length; i++) { @@ -440,12 +626,13 @@ final class _PdfJob { final b = source[i]; final afterHeading = prev is HeadingBlock; final next = i + 1 < source.length ? source[i + 1] : null; + final mark = out.length; switch (b) { case ParagraphBlock(:final runs): final box = t.body.box; final lines = breaker.layout( _runs(runs, t.body.style), - contentWidth, + _avail, lineHeight: t.body.style.lineHeight, baseStyle: _base(t.body.style), align: box.align, @@ -467,9 +654,14 @@ final class _PdfJob { ); case HeadingBlock(:final level, :final runs, :final anchorId): final h = t.headings[level - 1]; - final label = labels[headingIndex++]; + final label = _headingLabels[b]; final all = [if (label != null) InlineRun(label), ...runs]; - final width = contentWidth - h.box.padding.horizontal; + final step = b.step; + final badge = step == null + ? 0.0 + : h.style.fontSize * t.wonky.stepBadge.sizeRatio; + final badgeGap = step == null ? 0.0 : h.style.fontSize * 0.45; + final width = _avail - h.box.padding.horizontal - badge - badgeGap; final lines = breaker.layout( _runs(all, h.style, caseTransform: h.style.caseTransform), width, @@ -486,6 +678,7 @@ final class _PdfJob { index: i, kind: _Kind.text, lines: lines, + textLeft: badge + badgeGap, paddingTop: h.box.padding.top, paddingBottom: h.box.padding.bottom + borderH, paddingLeft: h.box.padding.left, @@ -500,9 +693,20 @@ final class _PdfJob { ..bottomBorderGap = h.borderBottomGap ..anchorId = anchorId ..headingLevel = level - ..headingTitle = InlineRun.plainText( - all, - ).replaceAll(softBreak, ' ').trim(), + ..headingTitle = InlineRun.plainText([ + if (step != null) InlineRun('($step) '), + ...all, + ]).replaceAll(softBreak, ' ').trim() + ..stepNumber = step + ..stepSize = badge + ..stepBackground = t.wonky.stepBadge.background + ..stepStyle = step == null + ? null + : PdfRunStyle( + font: fonts.font(h.style.fontFamily, 700, false), + size: badge * 0.6, + color: t.wonky.stepBadge.color, + ), ); case ListItemBlock( :final kind, @@ -539,7 +743,7 @@ final class _PdfJob { final q = t.blockquote; final bar = q.bar.isVisible ? q.bar.width : 0.0; final left = q.box.padding.left + bar; - final width = contentWidth - left - q.box.padding.right; + final width = _avail - left - q.box.padding.right; final laid = []; for (var li = 0; li < lines.length; li++) { laid.addAll( @@ -592,12 +796,265 @@ final class _PdfJob { ); case TableBlock(): out.add(_table(b, i)); + case GridBlock(): + out.add(_grid(b, i)); + case YouTubeBlock(): + // Links ([DocTree.withVideosAsLinks]). + break; + case ContainerBlock(): + out.addAll(await _container(b, i)); + } + if (b is! ContainerBlock) { + for (var k = mark; k < out.length; k++) { + out[k] + ..x = _x + ..width = _avail + ..frames = List.of(_frameStack); + } } prev = b; } return out; } + /// A Wonky container (Write 11 §9): a header block (callout title, + /// details summary or top padding), the children laid out in the + /// container's inner area, and a bottom padding block; every block + /// carries the container's frame. + Future> _container(ContainerBlock c, int index) async { + final t = theme; + final w = t.wonky; + final frame = c.frame; + final ( + background, + border, + radius, + pad, + spaceBefore, + spaceAfter, + ) = switch (frame.type) { + BoxType.callout => () { + final cc = w.callout.colorsFor( + (frame.variant ?? CalloutVariant.info).value, + ); + return ( + cc.background as int?, + BorderPt( + width: w.callout.borderWidth, + style: LineStyle.solid, + color: cc.border, + ), + w.callout.borderRadius, + w.callout.padding, + w.callout.spaceBefore, + w.callout.spaceAfter, + ); + }(), + BoxType.details => ( + w.details.background, + w.details.border, + w.details.borderRadius, + w.details.padding, + w.details.spaceBefore, + w.details.spaceAfter, + ), + BoxType.card => ( + w.card.background, + BorderPt.none, + w.card.borderRadius, + w.card.padding, + w.card.spaceBefore, + w.card.spaceAfter, + ), + }; + final bw = border.isVisible ? border.width : 0.0; + final outerX = _x; + final outerW = _avail; + final f = _Frame( + x: outerX, + width: outerW, + background: background, + border: border, + radius: radius, + ); + final innerX = outerX + bw + pad.left; + final innerW = math.max(1.0, outerW - 2 * bw - pad.horizontal); + final saved = List.of(_frameStack); + final out = <_Block>[]; + void place(_Block b, _Frame frame) => out.add( + b + ..x = innerX + ..width = innerW + ..frames = [...saved, frame], + ); + + // Header. + final topPad = bw + pad.top; + final body = t.body.style; + switch (frame.type) { + case BoxType.callout: + final co = w.callout; + final cc = co.colorsFor((frame.variant ?? CalloutVariant.info).value); + final size = body.fontSize * co.titleSizeRatio; + final style = PdfRunStyle( + font: fonts.font(body.fontFamily, co.titleWeight, false), + size: size, + color: cc.title, + letterSpacing: size * 0.025, + ); + final icon = size * 1.4; + final gap = size * 0.5; + final lines = breaker.layout( + [(applyCase(frame.calloutLabel, co.titleCase), style)], + innerW - icon - gap, + lineHeight: 1.6, + baseStyle: style, + ); + place( + _Block( + source: c, + index: index, + kind: _Kind.text, + lines: lines, + textLeft: icon + gap, + paddingTop: topPad, + paddingBottom: body.fontSize * 0.4, + spaceBefore: spaceBefore, + keepWithNext: true, + ) + ..calloutIcon = (frame.variant ?? CalloutVariant.info).value + ..iconColor = cc.title + ..iconSize = icon, + f.copyWith(top: true), + ); + case BoxType.details: + final summary = c.summary; + final style = _base(body); + final chevron = body.fontSize * 1.25; + final lines = breaker.layout( + _runs( + summary?.runs ?? const [], + body, + weight: w.details.summaryWeight, + ), + innerW - chevron - body.fontSize, + lineHeight: body.lineHeight, + baseStyle: style, + ); + place( + _Block( + source: c, + index: index, + kind: _Kind.text, + lines: lines, + paddingTop: topPad, + paddingBottom: c.body.isEmpty ? 0 : body.fontSize * 0.75, + spaceBefore: spaceBefore, + keepWithNext: true, + ) + ..chevronColor = w.details.chevronColor + ..chevronSize = chevron, + f.copyWith(top: true), + ); + case BoxType.card: + place( + _Block( + source: c, + index: index, + kind: _Kind.spacer, + spaceBefore: spaceBefore, + keepWithNext: true, + )..spacerHeight = topPad, + f.copyWith(top: true), + ); + } + + // Children. + final prevX = _x; + final prevW = _avail; + _x = innerX; + _avail = innerW; + _frameStack.add(f); + final children = await _buildBlocks(c.body); + _frameStack.removeLast(); + _x = prevX; + _avail = prevW; + if (children.isNotEmpty) { + // The container's padding replaces the children's outer spacing. + children.first.spaceBefore = 0; + children.last.spaceAfter = 0; + } + out.addAll(children); + + // Bottom padding. + place( + _Block( + source: c, + index: index, + kind: _Kind.spacer, + spaceAfter: spaceAfter, + )..spacerHeight = bw + pad.bottom, + f.copyWith(bottom: true), + ); + return out; + } + + /// A Wonky grid (Write 11 §9): items in columns, rows paginate. + _Block _grid(GridBlock g, int index) { + final t = theme; + final st = t.wonky.grid; + final body = t.body.style; + var cols = g.columns; + if (_avail < 360) cols = math.min(cols, 2); + if (_avail < 240) cols = 1; + final colW = (_avail - st.columnGap * (cols - 1)) / cols; + final bullet = g.bullets == GridBullets.none ? 0.0 : body.fontSize * 1.1; + final textLeft = bullet == 0 ? 0.0 : bullet + body.fontSize * 0.5; + final rows = >>[]; + final metrics = []; + for (var r = 0; r * cols < g.items.length; r++) { + final cells = >[]; + var h = 0.0; + for (var c = 0; c < cols && r * cols + c < g.items.length; c++) { + final lines = breaker.layout( + _runs(g.items[r * cols + c], body), + math.max(1, colW - textLeft), + lineHeight: body.lineHeight, + baseStyle: _base(body), + ); + cells.add(lines); + h = math.max(h, lines.fold(0.0, (s, l) => s + l.height)); + } + final last = (r + 1) * cols >= g.items.length; + final gap = last ? 0.0 : st.rowGap; + rows.add(cells); + metrics.add( + RowMetrics( + h + gap, + cellLineHeights: [ + for (final c in cells) [for (final l in c) l.height], + ], + cellPadding: gap, + ), + ); + } + return _Block( + source: g, + index: index, + kind: _Kind.grid, + spaceBefore: st.spaceBefore, + spaceAfter: st.spaceAfter, + ) + ..gridRows = rows + ..gridColumnWidth = colW + ..gridColumnGap = st.columnGap + ..gridTextLeft = textLeft + ..gridBullets = g.bullets + ..gridBulletColor = st.bulletColor + ..gridBulletSize = bullet + .._rowMetrics.addAll(metrics); + } + _Block _listItem( DocBlock b, int index, @@ -621,7 +1078,7 @@ final class _PdfJob { ? q.box.padding.left + (q.bar.isVisible ? q.bar.width : 0.0) : 0.0; final left = quoteLeft + l.indentPerLevel * (indent + 1); - final width = contentWidth - left - (quoted ? q.box.padding.right : 0); + final width = _avail - left - (quoted ? q.box.padding.right : 0); final lines = breaker.layout( _runs( runs, @@ -688,7 +1145,7 @@ final class _PdfJob { final cb = t.codeBlock; final base = _base(cb.style, mono: true); final spans = SyntaxHighlighter.instance.tokenize(text, language); - final width = contentWidth - cb.box.padding.horizontal; + final width = _avail - cb.box.padding.horizontal; final lines = []; var lineStart = 0; for (final raw in text.split('\n')) { @@ -766,12 +1223,12 @@ final class _PdfJob { ); final pdfImage = _images[b.src]; final maxW = st.maxWidth.fraction != null - ? contentWidth * st.maxWidth.fraction! - : math.min(contentWidth, st.maxWidth.points ?? contentWidth); + ? _avail * st.maxWidth.fraction! + : math.min(_avail, st.maxWidth.points ?? _avail); if (pdfImage == null) { block ..placeholder = '[Image: ${b.alt}]' - ..imageWidth = math.min(maxW, contentWidth) + ..imageWidth = math.min(maxW, _avail) ..imageHeight = t.body.style.fontSize * 3; } else { final w = math.min(maxW, pdfImage.width * 0.75); @@ -783,13 +1240,13 @@ final class _PdfJob { ..imageBorder = st.border; } block.imageLeft = st.align == ImageAlign.center - ? (contentWidth - block.imageWidth) / 2 + ? (_avail - block.imageWidth) / 2 : 0; if (st.caption.show && b.title != null && b.title!.isNotEmpty) { block ..caption = breaker.layout( [(b.title!, _base(st.caption.style))], - contentWidth, + _avail, lineHeight: st.caption.style.lineHeight, baseStyle: _base(st.caption.style), align: st.caption.align, @@ -824,8 +1281,8 @@ final class _PdfJob { } } final sum = natural.fold(0.0, (s, w) => s + w); - final widths = ts.width == TableWidth.full || sum > contentWidth - ? [for (final w in natural) w / sum * contentWidth] + final widths = ts.width == TableWidth.full || sum > _avail + ? [for (final w in natural) w / sum * _avail] : natural; final rows = >[]; final heights = []; @@ -950,6 +1407,25 @@ final class _PdfJob { rows: b._rowMetrics, headerRows: b.rows.isEmpty ? 0 : 1, ); + case _Kind.grid: + return BlockMetrics( + blockIndex: i, + kind: BlockMetricsKind.table, + spaceBefore: b.spaceBefore, + spaceAfter: b.spaceAfter, + rows: b._rowMetrics, + headerRows: 0, + ); + case _Kind.spacer: + // Never split; moves to the next page with what follows. + return BlockMetrics( + blockIndex: i, + kind: BlockMetricsKind.image, + spaceBefore: b.spaceBefore, + spaceAfter: b.spaceAfter, + fixedHeight: b.spacerHeight, + keepWithNext: b.keepWithNext, + ); } } @@ -1054,7 +1530,7 @@ final class _PdfJob { lines: lines, textLeft: indent, spaceAfter: 2, - ); + )..width = contentWidth; } PdfRunStyle _withLink(PdfRunStyle s, String link) => PdfRunStyle( @@ -1110,9 +1586,20 @@ final class _PdfJob { } final geo = _geometry(page.index); if (options.headerFooter) _headerFooter(g, page.index, count, geo); + double? prevBottom; for (final slice in page.slices) { final b = blocks[slice.blockIndex]; final top = geo.contentTop + slice.y; + if (b.frames.isNotEmpty) { + _paintFrames( + g, + b, + slice, + top, + prevBottom == null ? null : top - prevBottom, + ); + } + prevBottom = top + slice.height; switch (b.kind) { case _Kind.text: _paintText(pdfPage, g, b, slice, top); @@ -1122,6 +1609,10 @@ final class _PdfJob { if (slice.height > 0) _paintRule(g, b, top); case _Kind.table: _paintTable(pdfPage, g, b, slice, top); + case _Kind.grid: + _paintGrid(pdfPage, g, b, slice, top); + case _Kind.spacer: + break; } // Anchors and bookmarks at the first slice of a heading. if (b.anchorId != null && !slice.isContinuation) { @@ -1232,24 +1723,35 @@ final class _PdfJob { double top, ) { final baseline = pageHeight - (top + line.ascent); + // Backgrounds first, one per run of pieces in the same style (a chip or + // button label of several words is one pill), so no pill covers text. + final pieces = line.pieces; + for (var i = 0; i < pieces.length; i++) { + final s = pieces[i].style; + if (s.background == null || pieces[i].text.isEmpty) continue; + var j = i; + while (j + 1 < pieces.length && identical(pieces[j + 1].style, s)) { + j++; + } + final x0 = left + pieces[i].x - s.backgroundPadX; + final x1 = left + pieces[j].x + pieces[j].width + s.backgroundPadX; + g + ..setFillColor(_color(s.background!)) + ..drawRRect( + x0, + baseline - s.size * 0.25, + x1 - x0, + s.size * 1.2, + s.backgroundRadius, + s.backgroundRadius, + ) + ..fillPath(); + i = j; + } for (final p in line.pieces) { if (p.text.isEmpty) continue; final s = p.style; final x = left + p.x; - if (s.background != null) { - final bh = s.size * 1.2; - g - ..setFillColor(_color(s.background!)) - ..drawRRect( - x - s.backgroundPadX, - baseline - s.size * 0.25, - p.width + 2 * s.backgroundPadX, - bh, - s.backgroundRadius, - s.backgroundRadius, - ) - ..fillPath(); - } g ..setFillColor(_color(s.color)) ..drawString( @@ -1304,31 +1806,24 @@ final class _PdfJob { ) { final from = slice.lineFrom ?? 0; final to = math.min(slice.lineTo ?? b.lines.length, b.lines.length); - final left = margins.left; + final left = margins.left + b.x; final bottomY = pageHeight - (top + slice.height); // Box background / borders. if (b.background != null) { final r = slice.isContinuation || slice.continues ? 0.0 : b.radius; g ..setFillColor(_color(b.background!)) - ..drawRRect(left, bottomY, contentWidth, slice.height, r, r) + ..drawRRect(left, bottomY, b.width, slice.height, r, r) ..fillPath(); } final borders = b.borders; if (borders != null && borders.hasAny) { final yTop = pageHeight - top; if (borders.top.isVisible && !slice.isContinuation) { - _strokeLine(g, left, yTop, left + contentWidth, yTop, borders.top); + _strokeLine(g, left, yTop, left + b.width, yTop, borders.top); } if (borders.bottom.isVisible && !slice.continues) { - _strokeLine( - g, - left, - bottomY, - left + contentWidth, - bottomY, - borders.bottom, - ); + _strokeLine(g, left, bottomY, left + b.width, bottomY, borders.bottom); } if (borders.left.isVisible) { _strokeLine(g, left, bottomY, left, yTop, borders.left); @@ -1336,9 +1831,9 @@ final class _PdfJob { if (borders.right.isVisible) { _strokeLine( g, - left + contentWidth, + left + b.width, bottomY, - left + contentWidth, + left + b.width, yTop, borders.right, ); @@ -1356,6 +1851,7 @@ final class _PdfJob { final textLeft = left + b.textLeft + b.paddingLeft; if (i == 0 && !slice.isContinuation) { _paintMarker(g, b, line, textLeft, y); + _paintWonkyMarks(g, b, line, left + b.paddingLeft, y); } _drawLine(page, g, line, textLeft, y); y += line.height; @@ -1363,7 +1859,327 @@ final class _PdfJob { if (b.bottomBorder != null && !slice.continues) { final by = pageHeight - (y + b.bottomBorderGap + b.bottomBorder!.width / 2); - _strokeLine(g, left, by, left + contentWidth, by, b.bottomBorder!); + _strokeLine(g, left, by, left + b.width, by, b.bottomBorder!); + } + } + + /// A callout icon, details chevron or step badge on a block's first line. + void _paintWonkyMarks( + PdfGraphics g, + _Block b, + PdfLine line, + double left, + double top, + ) { + final cy = pageHeight - (top + line.height / 2); + if (b.calloutIcon != null) { + _drawIcon(g, b.calloutIcon!, left, cy, b.iconSize, b.iconColor); + } + if (b.chevronColor != null) { + _drawIcon( + g, + 'chevron', + left + b.width - b.chevronSize, + cy, + b.chevronSize, + b.chevronColor!, + ); + } + final step = b.stepNumber; + final style = b.stepStyle; + if (step != null && style != null) { + final r = b.stepSize / 2; + g + ..setFillColor(_color(b.stepBackground)) + ..drawEllipse(left + r, cy, r, r) + ..fillPath(); + final text = '$step'; + final w = breaker.measure(text, style); + g + ..setFillColor(_color(style.color)) + ..drawString( + style.font, + style.size, + text, + left + r - w / 2, + cy - style.size * 0.35, + ); + } + } + + /// Draws a Lucide icon of the Wonky elements (the 24-unit icons of + /// `WonkyIcons`, as strokes) with its left edge at [x], vertically centered + /// on [cy] (PDF coordinates), [size] pt wide. + void _drawIcon( + PdfGraphics g, + String name, + double x, + double cy, + double size, + int color, + ) { + final s = size / 24; + final top = cy + size / 2; + double px(double v) => x + v * s; + double py(double v) => top - v * s; + void poly(List<(double, double)> pts, {bool close = false}) { + g.moveTo(px(pts.first.$1), py(pts.first.$2)); + for (final p in pts.skip(1)) { + g.lineTo(px(p.$1), py(p.$2)); + } + if (close) g.closePath(); + g.strokePath(); + } + + void curve( + double x1, + double y1, + double x2, + double y2, + double x3, + double y3, + ) => g.curveTo(px(x1), py(y1), px(x2), py(y2), px(x3), py(y3)); + void dot(double cxv, double cyv) { + g + ..drawEllipse(px(cxv), py(cyv), s * 1.15, s * 1.15) + ..fillPath(); + } + + g + ..saveContext() + ..setStrokeColor(_color(color)) + ..setFillColor(_color(color)) + ..setLineWidth(2 * s) + ..setLineCap(PdfLineCap.round) + ..setLineJoin(PdfLineJoin.round); + switch (name) { + case 'info': + g + ..drawEllipse(px(12), py(12), 10 * s, 10 * s) + ..strokePath(); + poly([(12, 16), (12, 12)]); + dot(12, 8); + case 'tip': + const k = 6 * 0.5523; + g.moveTo(px(15), py(14)); + curve(15.2, 13, 15.7, 12.3, 16.5, 11.5); + curve(17.5, 10.6, 18, 9.3, 18, 8); + curve(18, 8 - k, 12 + k, 2, 12, 2); + curve(12 - k, 2, 6, 8 - k, 6, 8); + curve(6, 9, 6.2, 10.2, 7.5, 11.5); + curve(8.2, 12.2, 8.8, 13, 9, 14); + g.strokePath(); + poly([(9, 18), (15, 18)]); + poly([(10, 22), (14, 22)]); + case 'note': + const k = 2 * 0.5523; + g.moveTo(px(22), py(17)); + curve(22, 17 + k, 20 + k, 19, 20, 19); + g + ..lineTo(px(6.8), py(19)) + ..lineTo(px(2), py(21.3)) + ..lineTo(px(2), py(5)); + curve(2, 5 - k, 4 - k, 3, 4, 3); + g.lineTo(px(20), py(3)); + curve(20 + k, 3, 22, 5 - k, 22, 5); + g + ..closePath() + ..strokePath(); + dot(8, 11); + dot(12, 11); + dot(16, 11); + case 'warning' || 'caution': + poly([(12, 3.2), (21.9, 20), (2.1, 20)], close: true); + poly([(12, 9), (12, 13)]); + dot(12, 17); + case 'danger': + poly(const [ + (8.69, 2), + (15.31, 2), + (22, 8.69), + (22, 15.31), + (15.31, 22), + (8.69, 22), + (2, 15.31), + (2, 8.69), + ], close: true); + poly([(12, 8), (12, 12)]); + dot(12, 16); + case 'chevron': + poly([(19, 9), (12, 16), (5, 9)]); + case 'check': + poly([(5, 13), (9, 17), (19, 7)]); + case 'circle': + g + ..drawEllipse(px(12), py(12), 4 * s, 4 * s) + ..fillPath(); + } + g.restoreContext(); + } + + /// The frames of the containers around [b] behind one of its slices + /// (Write 11 §9): background, side borders, and the top/bottom edges with + /// rounded corners on the container's first and last slice. A frame + /// reaches up over the gap to the slice above it on the page, so a + /// container is one continuous box. + void _paintFrames( + PdfGraphics g, + _Block b, + PlacedSlice slice, + double top, + double? gapAbove, + ) { + for (final f in b.frames) { + final roundTop = f.top && !slice.isContinuation; + final roundBottom = f.bottom && !slice.continues; + // A hair of overlap with the slice above hides the seam between fills. + final yTop = top - (roundTop || gapAbove == null ? 0 : gapAbove + 0.5); + final h = top + slice.height - yTop; + if (h <= 0) continue; + final x = margins.left + f.x; + final yb = pageHeight - (top + slice.height); + final maxR = math.min(f.width / 2, roundTop && roundBottom ? h / 2 : h); + final rt = roundTop ? math.min(f.radius, maxR) : 0.0; + final rb = roundBottom ? math.min(f.radius, maxR) : 0.0; + if (f.background != null) { + g.setFillColor(_color(f.background!)); + _framePath(g, x, yb, f.width, h, rt, rb); + g.fillPath(); + } + final border = f.border; + if (!border.isVisible) continue; + final inset = border.width / 2; + final bx = x + inset; + final bw = f.width - border.width; + final byb = yb + (roundBottom ? inset : 0); + final bt = yb + h - (roundTop ? inset : 0); + g + ..saveContext() + ..setStrokeColor(_color(border.color)) + ..setLineWidth(border.width); + const k = 0.5523; + if (roundTop && roundBottom) { + _framePath(g, bx, byb, bw, bt - byb, rt, rb); + } else if (roundTop) { + g + ..moveTo(bx, byb) + ..lineTo(bx, bt - rt) + ..curveTo(bx, bt - rt + rt * k, bx + rt - rt * k, bt, bx + rt, bt) + ..lineTo(bx + bw - rt, bt) + ..curveTo( + bx + bw - rt + rt * k, + bt, + bx + bw, + bt - rt + rt * k, + bx + bw, + bt - rt, + ) + ..lineTo(bx + bw, byb); + } else if (roundBottom) { + g + ..moveTo(bx, bt) + ..lineTo(bx, byb + rb) + ..curveTo(bx, byb + rb - rb * k, bx + rb - rb * k, byb, bx + rb, byb) + ..lineTo(bx + bw - rb, byb) + ..curveTo( + bx + bw - rb + rb * k, + byb, + bx + bw, + byb + rb - rb * k, + bx + bw, + byb + rb, + ) + ..lineTo(bx + bw, bt); + } else { + g + ..moveTo(bx, byb) + ..lineTo(bx, bt) + ..moveTo(bx + bw, byb) + ..lineTo(bx + bw, bt); + } + g + ..strokePath() + ..restoreContext(); + } + } + + /// A rectangle with corner radius [rt] at the top and [rb] at the bottom + /// (PDF coordinates: [yb] is the bottom edge). + static void _framePath( + PdfGraphics g, + double x, + double yb, + double w, + double h, + double rt, + double rb, + ) { + const k = 0.5523; + final t = yb + h; + g + ..moveTo(x + rb, yb) + ..lineTo(x + w - rb, yb); + if (rb > 0) { + g.curveTo( + x + w - rb + rb * k, + yb, + x + w, + yb + rb - rb * k, + x + w, + yb + rb, + ); + } + g.lineTo(x + w, t - rt); + if (rt > 0) { + g.curveTo(x + w, t - rt + rt * k, x + w - rt + rt * k, t, x + w - rt, t); + } + g.lineTo(x + rt, t); + if (rt > 0) g.curveTo(x + rt - rt * k, t, x, t - rt + rt * k, x, t - rt); + g.lineTo(x, yb + rb); + if (rb > 0) g.curveTo(x, yb + rb - rb * k, x + rb - rb * k, yb, x + rb, yb); + g.closePath(); + } + + /// A Wonky grid slice: its rows, each item with its bullet. + void _paintGrid( + PdfPage page, + PdfGraphics g, + _Block b, + PlacedSlice slice, + double top, + ) { + var y = top; + final from = slice.rowFrom ?? 0; + final to = math.min(slice.rowTo ?? b.gridRows.length, b.gridRows.length); + for (var r = from; r < to; r++) { + final split = r == from && slice.rowSplit != null ? slice.rowSplit : null; + final cells = b.gridRows[r]; + var rowH = 0.0; + for (var c = 0; c < cells.length; c++) { + final x = + margins.left + b.x + c * (b.gridColumnWidth + b.gridColumnGap); + final (f, t) = split != null && c < split.length + ? split[c] + : (0, cells[c].length); + var ly = y; + for (var li = f; li < math.min(t, cells[c].length); li++) { + final line = cells[c][li]; + if (li == 0 && b.gridBullets != GridBullets.none) { + _drawIcon( + g, + b.gridBullets == GridBullets.check ? 'check' : 'circle', + x, + pageHeight - (ly + line.height / 2), + b.gridBulletSize, + b.gridBulletColor, + ); + } + _drawLine(page, g, line, x + b.gridTextLeft, ly); + ly += line.height; + } + rowH = math.max(rowH, ly - y); + } + y += split != null ? rowH : b._rowMetrics[r].height; } } @@ -1449,7 +2265,7 @@ final class _PdfJob { final scale = slice.scale; final w = b.imageWidth * scale; final h = b.imageHeight * scale; - final x = margins.left + (b.imageLeft + (b.imageWidth - w) / 2); + final x = margins.left + b.x + (b.imageLeft + (b.imageWidth - w) / 2); final y = pageHeight - (top + h); final image = b.image; if (image == null) { @@ -1498,7 +2314,7 @@ final class _PdfJob { } var cy = top + h + b.captionGap; for (final line in b.caption) { - _drawLine(null, g, line, margins.left, cy); + _drawLine(null, g, line, margins.left + b.x, cy); cy += line.height; } } @@ -1506,19 +2322,21 @@ final class _PdfJob { void _paintRule(PdfGraphics g, _Block b, double top) { final r = b.rule!; final width = r.width.fraction != null - ? contentWidth * r.width.fraction! - : math.min(contentWidth, r.width.points ?? contentWidth); - final x = margins.left + (contentWidth - width) / 2; + ? b.width * r.width.fraction! + : math.min(b.width, r.width.points ?? b.width); + final x = margins.left + b.x + (b.width - width) / 2; if (r.style == RuleStyle.ornament) { final style = _base(r.ornamentStyle); final lines = breaker.layout( [(r.ornament, style)], - contentWidth, + b.width, lineHeight: r.ornamentStyle.lineHeight, baseStyle: style, align: ThemeAlign.center, ); - if (lines.isNotEmpty) _drawLine(null, g, lines.first, margins.left, top); + if (lines.isNotEmpty) { + _drawLine(null, g, lines.first, margins.left + b.x, top); + } return; } final y = pageHeight - (top + b.ruleHeight / 2); @@ -1579,7 +2397,7 @@ final class _PdfJob { } rowH = maxH + pad.vertical; } - var x = margins.left; + var x = margins.left + b.x; for (var c = 0; c < b.rows[r].length; c++) { final cell = b.rows[r][c]; final w = b.columnWidths[c]; @@ -1611,9 +2429,9 @@ final class _PdfJob { if (drawBottom) { _strokeLine( g, - margins.left, + margins.left + b.x, bottom, - margins.left + tableWidth, + margins.left + b.x + tableWidth, bottom, border, ); @@ -1624,7 +2442,7 @@ final class _PdfJob { g ..setStrokeColor(_color(ts.borderColor)) ..setLineWidth(ts.borderWidth) - ..drawRect(margins.left, pageHeight - y, tableWidth, y - tableTop) + ..drawRect(margins.left + b.x, pageHeight - y, tableWidth, y - tableTop) ..strokePath(); } } diff --git a/packages/wonky_write_core/lib/src/export/pdf/pdf_text.dart b/packages/wonky_write_core/lib/src/export/pdf/pdf_text.dart index 1bae0315..b8268be6 100644 --- a/packages/wonky_write_core/lib/src/export/pdf/pdf_text.dart +++ b/packages/wonky_write_core/lib/src/export/pdf/pdf_text.dart @@ -108,6 +108,11 @@ final class PdfFontBook { }); } + /// Whether [rune] can be drawn with [primary] or a fallback face. + bool supports(int rune, PdfFont primary) => + primary.isRuneSupported(rune) || + _fallbacks.any((f) => f.isRuneSupported(rune)); + /// Splits [text] into segments renderable with [primary] or a fallback; /// unsupported characters become `?` (with a warning). List<(String, PdfFont)> segments(String text, PdfFont primary) { diff --git a/packages/wonky_write_core/lib/src/export/rtf/rtf_exporter.dart b/packages/wonky_write_core/lib/src/export/rtf/rtf_exporter.dart index 709b2961..a0559615 100644 --- a/packages/wonky_write_core/lib/src/export/rtf/rtf_exporter.dart +++ b/packages/wonky_write_core/lib/src/export/rtf/rtf_exporter.dart @@ -9,6 +9,7 @@ import '../../delta/embeds.dart'; import 'package:wonky_fonts/wonky_fonts.dart'; import '../../import/import_support.dart' show MonospaceFonts; import '../../ir/doc_tree.dart'; +import '../../markdown/wonky_to_gfm.dart'; import '../../layout/page_setup.dart'; import '../../markdown/inline_reader.dart' show mentionTitlePrefix; import '../../theme/model/style_enums.dart'; @@ -50,7 +51,8 @@ final class RtfExporter implements DocumentExporter { RtfExportOptions options, ) async { input.cancel?.throwIfCancelled(); - final tree = exportTree(input, options); + // Wonky elements in their GFM form (Write 11 §9). + final tree = WonkyToGfm.tree(exportTree(input, options)); final warnings = []; if (input.variant == ThemeVariant.dark) { warnings.add( @@ -530,6 +532,9 @@ final class _RtfWriter { if (b is! ListItemBlock && b is! TaskBlock) orderedLs.clear(); } switch (b) { + case ContainerBlock() || GridBlock() || YouTubeBlock(): + // Converted to their GFM form above. + break; case ParagraphBlock(:final runs): final box = theme.body.box; final after = prev is HeadingBlock; diff --git a/packages/wonky_write_core/lib/src/export/txt_exporter.dart b/packages/wonky_write_core/lib/src/export/txt_exporter.dart index fb5b74d5..425c8291 100644 --- a/packages/wonky_write_core/lib/src/export/txt_exporter.dart +++ b/packages/wonky_write_core/lib/src/export/txt_exporter.dart @@ -7,6 +7,7 @@ import 'dart:typed_data'; import '../delta/delta_utils.dart'; import '../ir/doc_tree.dart'; import '../markdown/inline_markdown.dart'; +import '../markdown/wonky_to_gfm.dart'; import 'export_api.dart'; import 'markdown_file_exporter.dart'; @@ -44,6 +45,9 @@ final class TxtExporter implements DocumentExporter { TxtExportOptions options, { LinkResolver links = const IdentityLinkResolver(), }) { + // Wonky elements as text: a callout's label line, grid items as lines, + // `(n) ` before numbered headings (Write 11 §9). + tree = WonkyToGfm.tree(tree); final blocks = <(String text, bool listLike, bool code)>[]; String runs(List rs) => runsText(rs, links); @@ -109,9 +113,12 @@ final class TxtExporter implements DocumentExporter { case TableBlock(:final cellMarkdown): final cells = [ for (final r in cellMarkdown) - [for (final c in r) InlineMarkdown.toPlainText(c)], + [for (final c in r) InlineMarkdown.cellPlainText(c)], ]; blocks.add((_table(cells, options.tables), false, true)); + case ContainerBlock() || GridBlock() || YouTubeBlock(): + // Converted above. + blocks.add(('', false, false)); } } // A list inside a quote (Write 02 §1.2): the items behind `> `, joined to diff --git a/packages/wonky_write_core/lib/src/export/wonky_icons.dart b/packages/wonky_write_core/lib/src/export/wonky_icons.dart new file mode 100644 index 00000000..969cef44 --- /dev/null +++ b/packages/wonky_write_core/lib/src/export/wonky_icons.dart @@ -0,0 +1,72 @@ +/// The SVG icons of the Wonky Markdown elements in exports (Write 11 §9): +/// the Lucide icons the Serverpod blog and docs use, colored with +/// `currentColor` (HTML) or a given color (PDF). +library; + +const _stroke = + 'fill="none" stroke="currentColor" stroke-width="2" ' + 'stroke-linecap="round" stroke-linejoin="round"'; + +String _svg(String body, {String? cls, String attrs = _stroke}) => + ''; + +const _calloutBodies = { + 'info': + '' + '', + 'tip': + '' + '', + 'note': + '' + '', + 'warning': + '', + 'danger': + '', +}; + +/// The SVG icons of Wonky Markdown elements. +abstract final class WonkyIcons { + /// The icon of callout type [variant] (`caution` uses `warning`'s). + static String callout(String variant, {String? cls}) => _svg( + _calloutBodies[variant == 'caution' ? 'warning' : variant] ?? + _calloutBodies['note']!, + cls: cls, + ); + + /// The `bullets=check` marker. + static String check({String? cls}) => + _svg('', cls: cls); + + /// The `bullets=circle` marker. + static String circle({String? cls}) => _svg( + '', + cls: cls, + attrs: 'fill="currentColor"', + ); + + /// The disclosure chevron of a details summary. + static String chevron({String? cls}) => + _svg('', cls: cls); + + /// The trailing arrow of an arrow link. + static String arrow({String? cls}) => _svg( + '', + cls: cls, + attrs: _stroke.replaceFirst('stroke-width="2"', 'stroke-width="2.25"'), + ); + + /// [svg] with `currentColor` replaced by [hex] (`#rrggbb`), for renderers + /// without CSS (PDF). + static String colored(String svg, String hex) => + svg.replaceAll('currentColor', hex); +} diff --git a/packages/wonky_write_core/lib/src/import/import_api.dart b/packages/wonky_write_core/lib/src/import/import_api.dart index 4e5caf43..09fb83f9 100644 --- a/packages/wonky_write_core/lib/src/import/import_api.dart +++ b/packages/wonky_write_core/lib/src/import/import_api.dart @@ -5,10 +5,15 @@ import 'dart:typed_data'; import 'package:dart_quill_delta/dart_quill_delta.dart'; import 'package:uuid/uuid.dart'; -import 'package:wonky_rich_text/wonky_rich_text.dart' show ImportWarning; +import 'package:wonky_rich_text/wonky_rich_text.dart' + show ImportWarning, MarkdownFlavor; export 'package:wonky_rich_text/wonky_rich_text.dart' - show ImportWarning, ImportWarningKind; + show + ImportWarning, + ImportWarningKind, + MarkdownFlavor, + looksLikeWonkyMarkdown; /// Import source formats. enum ImportFormat { @@ -99,6 +104,7 @@ final class ImportResult { this.language, this.images = const [], this.pageSetup, + this.markdownFlavor = MarkdownFlavor.gfm, }); /// The imported, normalized and valid document delta. @@ -121,6 +127,10 @@ final class ImportResult { /// Page geometry from the source, when present. final ImportedPageSetup? pageSetup; + + /// The flavor Markdown was read in (Write 11 §5.1); `wonky` when the + /// source had Wonky directives and [ImportOptions.detectFlavor] was set. + final MarkdownFlavor markdownFlavor; } /// Options shared by importers. @@ -131,13 +141,32 @@ final class ImportOptions { this.txtLineBreaks = TxtLineBreaks.paragraph, this.baseUrl, this.fileName, + this.flavor = MarkdownFlavor.gfm, + this.detectFlavor = false, }) : idGenerator = idGenerator ?? _uuidV7; static String _uuidV7() => const Uuid().v7(); - /// Generates embed ids (UUIDv7 by default; inject for determinism). + /// Generates embed and container ids (UUIDv7 by default; inject for + /// determinism). final String Function() idGenerator; + /// The Markdown flavor Markdown sources are read in (Write 11 §5.1). + final MarkdownFlavor flavor; + + /// Read Markdown that contains Wonky directives as Wonky Markdown (new + /// documents from a file, Write 11 §5.1). + final bool detectFlavor; + + /// Copy with [flavor] changed. + ImportOptions withFlavor(MarkdownFlavor flavor) => ImportOptions( + idGenerator: idGenerator, + txtLineBreaks: txtLineBreaks, + baseUrl: baseUrl, + fileName: fileName, + flavor: flavor, + ); + /// Plain-text line break handling. final TxtLineBreaks txtLineBreaks; diff --git a/packages/wonky_write_core/lib/src/import/wonky_importers.dart b/packages/wonky_write_core/lib/src/import/wonky_importers.dart index 002c17cc..1a92a539 100644 --- a/packages/wonky_write_core/lib/src/import/wonky_importers.dart +++ b/packages/wonky_write_core/lib/src/import/wonky_importers.dart @@ -138,7 +138,7 @@ final class WonkyImporters { final decoded = ImportTextDecoder.decode(bytes); final r = const MarkdownCodec().importMarkdown( decoded.text, - options: options, + options: _flavored(decoded.text, options), ); final w = decoded.warning; return w == null ? r : _withWarnings(r, [w]); @@ -201,7 +201,7 @@ final class WonkyImporters { final text = ImportTextDecoder.decode(main.content).text; return const MarkdownCodec().importMarkdown( text, - options: options, + options: _flavored(text, options), resolveImage: resolve, ); } @@ -219,6 +219,13 @@ final class WonkyImporters { return out.join('/'); } + /// [options] reading [markdown] as Wonky Markdown when it has directives + /// and detection is on. + static ImportOptions _flavored(String markdown, ImportOptions options) => + options.detectFlavor && looksLikeWonkyMarkdown(markdown) + ? options.withFlavor(MarkdownFlavor.wonky) + : options; + static ImportResult _withWarnings( ImportResult r, List extra, @@ -230,6 +237,7 @@ final class WonkyImporters { language: r.language, images: r.images, pageSetup: r.pageSetup, + markdownFlavor: r.markdownFlavor, ); } @@ -285,6 +293,7 @@ abstract final class ImportPostProcessor { frontMatter: result.frontMatter, language: result.language, pageSetup: result.pageSetup, + markdownFlavor: result.markdownFlavor, ); } } diff --git a/packages/wonky_write_core/lib/src/ir/doc_tree.dart b/packages/wonky_write_core/lib/src/ir/doc_tree.dart index 7233cb42..00d0d675 100644 --- a/packages/wonky_write_core/lib/src/ir/doc_tree.dart +++ b/packages/wonky_write_core/lib/src/ir/doc_tree.dart @@ -2,8 +2,10 @@ library; import 'package:collection/collection.dart'; -import 'package:wonky_rich_text/wonky_rich_text.dart' show InlineRun; +import 'package:wonky_rich_text/wonky_rich_text.dart' + show InlineRun, MarkdownFlavor; +import '../delta/boxes.dart'; import '../delta/embeds.dart'; export 'package:wonky_rich_text/wonky_rich_text.dart' show InlineRun; @@ -29,6 +31,7 @@ final class DocMeta { this.description, this.createdAt, this.modifiedAt, + this.markdownFlavor = MarkdownFlavor.gfm, }); /// Document UUID. @@ -55,6 +58,9 @@ final class DocMeta { /// Last modification time (used for deterministic timestamps). final DateTime? modifiedAt; + /// The document's Markdown flavor (Markdown exports, Write 11 §5.2). + final MarkdownFlavor markdownFlavor; + /// Copy with changed fields. DocMeta copyWith({ String? documentUuid, @@ -65,6 +71,7 @@ final class DocMeta { String? description, DateTime? createdAt, DateTime? modifiedAt, + MarkdownFlavor? markdownFlavor, }) => DocMeta( documentUuid: documentUuid ?? this.documentUuid, title: title ?? this.title, @@ -74,6 +81,7 @@ final class DocMeta { description: description ?? this.description, createdAt: createdAt ?? this.createdAt, modifiedAt: modifiedAt ?? this.modifiedAt, + markdownFlavor: markdownFlavor ?? this.markdownFlavor, ); } @@ -105,6 +113,7 @@ final class HeadingBlock extends DocBlock { this.level, this.runs, { this.anchorId = '', + this.step, super.deltaStart, super.deltaLength, }); @@ -112,6 +121,10 @@ final class HeadingBlock extends DocBlock { /// Level 1–6. final int level; + /// The number of a numbered heading (Wonky Markdown `## (n) Title`, Write + /// 11 §2.2); levels 2–3 only. + final int? step; + /// Inline content. final List runs; @@ -279,6 +292,120 @@ final class TableBlock extends DocBlock { TableEmbed toEmbed() => TableEmbed(id: id, align: align, rows: cellMarkdown); } +/// A Wonky Markdown container (callout, details, card; Write 11 §6) and the +/// blocks in it. +final class ContainerBlock extends DocBlock { + /// Creates a container. + const ContainerBlock( + this.frame, + this.children, { + super.deltaStart, + super.deltaLength, + }); + + /// The container's properties (from its first line). + final BoxFrame frame; + + /// The blocks in the container (containers nest). + final List children; + + /// The container type. + BoxType get type => frame.type; + + /// A details container's summary: its first child when that is a level-3 + /// heading (Write 11 §2.2); `null` otherwise and for other types. + HeadingBlock? get summary { + if (type != BoxType.details) return null; + final first = children.firstOrNull; + return first is HeadingBlock && first.level == 3 ? first : null; + } + + /// The children without the [summary]. + List get body => summary == null ? children : children.sublist(1); +} + +/// A Wonky Markdown grid (Write 11 §2.3). +final class GridBlock extends DocBlock { + /// Creates a grid block. + const GridBlock( + this.id, + this.columns, + this.bullets, + this.items, { + required this.itemMarkdown, + super.deltaStart, + super.deltaLength, + }); + + /// Embed id. + final String id; + + /// Number of columns, 1–4. + final int columns; + + /// Item bullets. + final GridBullets bullets; + + /// Parsed items. + final List> items; + + /// The stored inline-Markdown items (same shape as [items]). + final List itemMarkdown; + + /// As an embed. + GridEmbed toEmbed() => GridEmbed( + id: id, + columns: columns, + bullets: bullets, + items: itemMarkdown, + ); +} + +/// A Wonky Markdown YouTube video (Write 11 §2.3). +final class YouTubeBlock extends DocBlock { + /// Creates a YouTube block. + const YouTubeBlock(this.embed, {super.deltaStart, super.deltaLength}); + + /// The embed (id, video id, start, title). + final YouTubeEmbed embed; + + /// The video as a paragraph linking to it (its title, else the watch + /// URL): the exports that can't play it (PDF, DOCX, ODT; Write 11 §9). + ParagraphBlock get asLink => ParagraphBlock( + [InlineRun(embed.title ?? embed.watchUrl, link: embed.watchUrl)], + deltaStart: deltaStart, + deltaLength: deltaLength, + ); +} + +/// [blocks] with every YouTube video as a link paragraph +/// ([YouTubeBlock.asLink]), containers' contents included. +List videosAsLinks(List blocks) { + if (!walkDocBlocks(blocks).any((b) => b is YouTubeBlock)) return blocks; + return [ + for (final b in blocks) + switch (b) { + YouTubeBlock() => b.asLink, + ContainerBlock(:final frame, :final children) => ContainerBlock( + frame, + videosAsLinks(children), + deltaStart: b.deltaStart, + deltaLength: b.deltaLength, + ), + _ => b, + }, + ]; +} + +/// All blocks of [blocks] in document order, the contents of containers +/// after the container itself. +Iterable walkDocBlocks(Iterable blocks) sync* { + for (final b in blocks) { + yield b; + if (b is ContainerBlock) yield* walkDocBlocks(b.children); + } +} + /// The document IR: blocks plus metadata. final class DocTree { /// Creates a tree. @@ -290,11 +417,40 @@ final class DocTree { /// Metadata. final DocMeta meta; - /// Headings in order. - Iterable get headings => blocks.whereType(); + /// Every block in document order, containers' contents included. + Iterable get allBlocks => walkDocBlocks(blocks); + + /// This tree with every YouTube video as a link paragraph. + DocTree get withVideosAsLinks { + final linked = videosAsLinks(blocks); + return identical(linked, blocks) ? this : DocTree(linked, meta: meta); + } + + /// Headings in order (in containers too). + Iterable get headings => allBlocks.whereType(); + + /// Images in order (in containers too). + Iterable get images => allBlocks.whereType(); + + /// Whether the tree holds Wonky Markdown elements (containers, grids, + /// numbered headings, chips, styled links). + bool get hasWonkyElements => allBlocks.any( + (b) => switch (b) { + ContainerBlock() || GridBlock() || YouTubeBlock() => true, + HeadingBlock(:final step, :final runs) => + step != null || runs.any(_isWonkyRun), + ParagraphBlock(:final runs) || + ListItemBlock(:final runs) || + TaskBlock(:final runs) => runs.any(_isWonkyRun), + QuoteBlock(:final lines) => lines.any((l) => l.any(_isWonkyRun)), + TableBlock(:final rows) => rows.any( + (r) => r.any((c) => c.any(_isWonkyRun)), + ), + _ => false, + }, + ); - /// Images in order. - Iterable get images => blocks.whereType(); + static bool _isWonkyRun(InlineRun r) => r.chip || r.linkStyle != null; /// The first block if it is a level-1 heading. HeadingBlock? get titleHeading { diff --git a/packages/wonky_write_core/lib/src/ir/doc_tree_builder.dart b/packages/wonky_write_core/lib/src/ir/doc_tree_builder.dart index fdb8d197..9356c16e 100644 --- a/packages/wonky_write_core/lib/src/ir/doc_tree_builder.dart +++ b/packages/wonky_write_core/lib/src/ir/doc_tree_builder.dart @@ -5,6 +5,7 @@ import 'package:dart_quill_delta/dart_quill_delta.dart'; import '../collab/suggestion_view.dart'; import '../delta/attributes.dart'; +import '../delta/boxes.dart'; import '../delta/document.dart'; import '../delta/embeds.dart'; import '../delta/normalizer.dart'; @@ -20,7 +21,10 @@ final class DocTreeBuilder { /// Builds a [DocTree] from [document]: applies the suggestion [view], /// strips `cmt_*`, groups quote and code lines, computes list ordinals /// (per list run and indent level, restarting after a non-list block, a - /// shallower item or a change of list kind) and unique heading anchors. + /// shallower item, a change of list kind or of containers) and unique + /// heading anchors, and nests the blocks of Wonky Markdown containers into + /// [ContainerBlock]s (Write 11 §2.2: consecutive lines with the same frame + /// id at a depth are one container). DocTree fromDelta( Delta document, { SuggestionViewMode view = SuggestionViewMode.accepted, @@ -31,19 +35,31 @@ final class DocTreeBuilder { : SuggestionView.render(document, view, stripComments: true); final doc = WonkyDocument(viewed); final blocks = []; + // The containers of each block in [blocks]. + final paths = >[]; final anchors = AnchorIdGenerator(); // Ordinal state per indent level: (kind, count). final ordinals = {}; // Whether the list run so far is inside a quote (a quoted and an // unquoted list next to each other are two lists). var quotedRun = false; + var runPath = const []; var i = 0; final lines = doc.lines; while (i < lines.length) { final line = lines[i]; final f = line.format; - if (!f.isList || f.quoted != quotedRun) ordinals.clear(); + final path = Boxes.of(line.attributes); + bool samePath(DocumentLine l) => + Boxes.samePath(Boxes.of(l.attributes), path); + if (!f.isList || + f.quoted != quotedRun || + !Boxes.samePath(path, runPath)) { + ordinals.clear(); + } quotedRun = f.isList && f.quoted; + runPath = path; + final blockCount = blocks.length; if (line.isEmbedLine) { final embed = line.embed; switch (embed) { @@ -74,16 +90,40 @@ final class DocTreeBuilder { t.align, [ for (final r in t.rows) - [for (final c in r) InlineMarkdown.parse(c)], + [for (final c in r) InlineMarkdown.parseCell(c)], ], cellMarkdown: t.rows, deltaStart: line.start, deltaLength: line.length, ), ); + case GridEmbed(): + blocks.add( + GridBlock( + embed.id, + embed.columns, + embed.bullets, + [ + for (final item in embed.items) + InlineMarkdown.parseCell(item), + ], + itemMarkdown: embed.items, + deltaStart: line.start, + deltaLength: line.length, + ), + ); + case YouTubeEmbed(): + blocks.add( + YouTubeBlock( + embed, + deltaStart: line.start, + deltaLength: line.length, + ), + ); case null: break; } + if (blocks.length > blockCount) paths.add(path); ordinals.clear(); i++; continue; @@ -107,6 +147,7 @@ final class DocTreeBuilder { anchorId: anchors.next( InlineRun.plainText(runs).replaceAll('\u2028', ' ').trim(), ), + step: f.step, deltaStart: line.start, deltaLength: line.length, ), @@ -118,7 +159,8 @@ final class DocTreeBuilder { var end = start; while (i < lines.length && lines[i].format.type == BlockType.quote && - !lines[i].isEmbedLine) { + !lines[i].isEmbedLine && + samePath(lines[i])) { quoteLines.add(_runs(lines[i])); end = lines[i].end; i++; @@ -133,7 +175,9 @@ final class DocTreeBuilder { var end = start; while (i < lines.length && lines[i].format.type == BlockType.code && - lines[i].format.language == language) { + lines[i].format.language == language && + !lines[i].isEmbedLine && + samePath(lines[i])) { codeLines.add(lines[i].text); end = lines[i].end; i++; @@ -182,8 +226,49 @@ final class DocTreeBuilder { } i++; } + if (blocks.length > blockCount) paths.add(path); + } + return DocTree(_nest(blocks, paths, 0, blocks.length, 0), meta: meta); + } + + /// Nests `blocks[from..to)` at container [depth]: runs of blocks whose + /// frame at [depth] has the same id become one [ContainerBlock]. + static List _nest( + List blocks, + List> paths, + int from, + int to, + int depth, + ) { + final out = []; + var i = from; + while (i < to) { + final path = paths[i]; + if (path.length <= depth) { + out.add(blocks[i]); + i++; + continue; + } + final frame = path[depth]; + var j = i + 1; + while (j < to && + paths[j].length > depth && + paths[j][depth].id == frame.id) { + j++; + } + final start = blocks[i].deltaStart; + final last = blocks[j - 1]; + out.add( + ContainerBlock( + frame, + _nest(blocks, paths, i, j, depth + 1), + deltaStart: start, + deltaLength: last.deltaStart + last.deltaLength - start, + ), + ); + i = j; } - return DocTree(blocks, meta: meta); + return out; } static List _runs(DocumentLine line) => InlineRun.merge([ @@ -198,6 +283,7 @@ final class DocTreeToDelta { const DocTreeToDelta(); /// Converts [tree]; the result is normalized (and therefore valid). + /// Blocks in [ContainerBlock]s get the containers' frames as `box`. Delta convert(DocTree tree) { final d = Delta(); void runs(List rs) { @@ -207,65 +293,96 @@ final class DocTreeToDelta { } } - for (final b in tree.blocks) { - switch (b) { - case ParagraphBlock(runs: final rs): - runs(rs); - d.insert('\n'); - case HeadingBlock(:final level, runs: final rs): - runs(rs); - d.insert('\n', {WonkyAttr.header: level.clamp(1, 6)}); - case ListItemBlock( - :final kind, - :final indent, - :final inQuote, - runs: final rs, - ): - runs(rs); - d.insert('\n', { - WonkyAttr.list: kind == ListKindIr.ordered - ? ListKind.ordered.value - : ListKind.bullet.value, - if (indent > 0) - WonkyAttr.indent: indent.clamp(1, WonkyAttr.maxIndent), - if (inQuote) WonkyAttr.blockquote: true, - }); - case TaskBlock( - :final checked, - :final indent, - :final inQuote, - runs: final rs, - ): - runs(rs); - d.insert('\n', { - WonkyAttr.list: checked - ? ListKind.checked.value - : ListKind.unchecked.value, - if (indent > 0) - WonkyAttr.indent: indent.clamp(1, WonkyAttr.maxIndent), - if (inQuote) WonkyAttr.blockquote: true, - }); - case QuoteBlock(:final lines): - for (final l in lines) { - runs(l); - d.insert('\n', {WonkyAttr.blockquote: true}); - } - case CodeBlock(:final language, :final text): - for (final l in text.split('\n')) { - if (l.isNotEmpty) d.insert(l); - d.insert('\n', {WonkyAttr.codeBlock: language}); - } - case ImageBlock(): - d.insert(b.toEmbed().toInsert()); - d.insert('\n'); - case RuleBlock(:final id): - d.insert(DividerEmbed(id: id).toInsert()); - d.insert('\n'); - case TableBlock(): - d.insert(b.toEmbed().toInsert()); - d.insert('\n'); + void line(List path, [Map? block]) { + final attrs = { + ...?block, + if (path.isNotEmpty) WonkyAttr.box: Boxes.toValue(path), + }; + d.insert('\n', attrs.isEmpty ? null : attrs); + } + + void blocks(List list, List path) { + for (final b in list) { + switch (b) { + case ParagraphBlock(runs: final rs): + runs(rs); + line(path); + case HeadingBlock(:final level, :final step, runs: final rs): + runs(rs); + line(path, { + WonkyAttr.header: level.clamp(1, 6), + WonkyAttr.step: ?step, + }); + case ListItemBlock( + :final kind, + :final indent, + :final inQuote, + runs: final rs, + ): + runs(rs); + line(path, { + WonkyAttr.list: kind == ListKindIr.ordered + ? ListKind.ordered.value + : ListKind.bullet.value, + if (indent > 0) + WonkyAttr.indent: indent.clamp(1, WonkyAttr.maxIndent), + if (inQuote) WonkyAttr.blockquote: true, + }); + case TaskBlock( + :final checked, + :final indent, + :final inQuote, + runs: final rs, + ): + runs(rs); + line(path, { + WonkyAttr.list: checked + ? ListKind.checked.value + : ListKind.unchecked.value, + if (indent > 0) + WonkyAttr.indent: indent.clamp(1, WonkyAttr.maxIndent), + if (inQuote) WonkyAttr.blockquote: true, + }); + case QuoteBlock(:final lines): + for (final l in lines) { + runs(l); + line(path, {WonkyAttr.blockquote: true}); + } + case CodeBlock(:final language, :final text): + for (final l in text.split('\n')) { + if (l.isNotEmpty) d.insert(l); + line(path, {WonkyAttr.codeBlock: language}); + } + case ImageBlock(): + d.insert(b.toEmbed().toInsert()); + line(path); + case RuleBlock(:final id): + d.insert(DividerEmbed(id: id).toInsert()); + line(path); + case TableBlock(): + d.insert(b.toEmbed().toInsert()); + line(path); + case GridBlock(): + d.insert(b.toEmbed().toInsert()); + line(path); + case YouTubeBlock(:final embed): + d.insert(embed.toInsert()); + line(path); + case ContainerBlock(:final frame, :final children): + if (path.length >= BoxFrame.maxDepth) { + // Too deep: the content joins the enclosing container. + blocks(children, path); + } else if (children.isEmpty) { + // A container holds at least one line. + line([...path, frame]); + } else { + blocks(children, [...path, frame]); + } + } } } + + blocks(tree.blocks, const []); return const WonkyDeltaNormalizer().normalize(d).document; } } diff --git a/packages/wonky_write_core/lib/src/markdown/markdown_exporter.dart b/packages/wonky_write_core/lib/src/markdown/markdown_exporter.dart index 90ff9c8c..13c44295 100644 --- a/packages/wonky_write_core/lib/src/markdown/markdown_exporter.dart +++ b/packages/wonky_write_core/lib/src/markdown/markdown_exporter.dart @@ -1,12 +1,15 @@ /// [DocTree] → Markdown (02 §2.2, 07 §5.1). library; +import '../delta/boxes.dart'; import '../delta/delta_utils.dart'; import '../import/import_api.dart'; +import '../delta/embeds.dart'; import '../ir/doc_tree.dart'; import 'front_matter.dart'; import 'inline_writer.dart'; import 'markdown_importer.dart'; +import 'wonky_to_gfm.dart'; /// Options of [MarkdownExporter]. final class MarkdownExportOptions { @@ -16,6 +19,7 @@ final class MarkdownExportOptions { this.imageSource, this.omitImages = false, this.linkRewriter, + this.flavor = MarkdownFlavor.gfm, }); /// Emit [DocMeta.frontMatter] when present. @@ -30,9 +34,13 @@ final class MarkdownExportOptions { /// Rewrites link targets (internal `wonky://` links → https / `#slug`). final String Function(String link)? linkRewriter; + + /// The flavor to write (Write 11 §5.2). GFM export writes Wonky elements + /// in their GFM form ([WonkyToGfm]). + final MarkdownFlavor flavor; } -/// Serializes the IR to GFM with context-aware escaping. +/// Serializes the IR to GFM (or Wonky Markdown) with context-aware escaping. /// /// Every paragraph-like block is verified by parsing it back; when delimiter /// flanking rules cannot express the formatting, `_`-delimiters and finally @@ -57,23 +65,37 @@ final class MarkdownExporter { b.write(FrontMatter.wrap(fm)); } final positions = <({int start, int length})>[]; + final blocks = _wonky ? tree.blocks : WonkyToGfm.blocks(tree.blocks); + _writeBlocks(blocks, b, positions: positions, top: true); + b.write('\n'); + return (markdown: b.toString(), blocks: positions); + } + + bool get _wonky => options.flavor == MarkdownFlavor.wonky; + + /// Writes [blocks] separated per [_separator]; [positions] gets the range + /// of each block. + void _writeBlocks( + List blocks, + StringBuffer b, { + List<({int start, int length})>? positions, + required bool top, + }) { DocBlock? prev; var first = true; final cols = _ListColumns(); - for (final block in tree.blocks) { + for (final block in blocks) { if (block is ImageBlock && options.omitImages) { - positions.add((start: b.length, length: 0)); + positions?.add((start: b.length, length: 0)); continue; } - final text = _block(block, isFirst: first, cols: cols); + final text = _block(block, isFirst: first && top, cols: cols); if (!first) b.write(_separator(prev, block)); - positions.add((start: b.length, length: text.length)); + positions?.add((start: b.length, length: text.length)); b.write(text); prev = block; first = false; } - b.write('\n'); - return (markdown: b.toString(), blocks: positions); } static bool _isListLike(DocBlock? b) => b is ListItemBlock || b is TaskBlock; @@ -99,10 +121,12 @@ final class MarkdownExporter { switch (block) { case ParagraphBlock(:final runs): return _verified(runs, marker: '', cont: '', kind: _Kind.paragraph); - case HeadingBlock(:final level, :final runs): + case HeadingBlock(:final level, :final runs, :final step): return _verified( runs, - marker: '${'#' * level} ', + marker: + '${'#' * level} ' + '${step != null && _wonky && (level == 2 || level == 3) ? '($step) ' : ''}', cont: '', kind: _Kind.heading, level: level, @@ -134,9 +158,67 @@ final class MarkdownExporter { return isFirst ? '***' : '---'; case TableBlock(): return _table(block); + case GridBlock(): + return _grid(block); + case YouTubeBlock(:final embed): + return _youtube(embed); + case ContainerBlock(): + return _container(block); } } + /// `::youtube[title]{id=… start=…}` (Write 11 §5.2). + String _youtube(YouTubeEmbed video) => + '::youtube${video.title == null ? '' : '[${video.title}]'}' + '{id=${video.videoId}' + '${video.start == null ? '' : ' start=${video.start}'}}'; + + /// `:::type` … `:::` around the container's blocks (Write 11 §5.2). + String _container(ContainerBlock block) { + final frame = block.frame; + final open = switch (frame.type) { + BoxType.callout => + ':::${(frame.variant ?? CalloutVariant.info).value}' + '${frame.title == null ? '' : '[${frame.title}]'}', + BoxType.details => ':::details', + BoxType.card => ':::card', + }; + final b = StringBuffer('$open\n\n'); + _writeBlocks(block.children, b, top: false); + b.write('\n\n:::'); + return b.toString(); + } + + /// `:::grid{…}` with one `- item` line per item (Write 11 §5.2). + String _grid(GridBlock grid) { + final lines = [ + ':::grid{columns=${grid.columns} bullets=${grid.bullets.value}}', + '', + for (final item in grid.items) + switch (InlineMarkdownWriter.write( + _rewriteLinks(item), + context: InlineContext.tableCell, + flavor: options.flavor, + )) { + '' => '- ', + final text => '- $text', + }, + '', + ':::', + ]; + return lines.join('\n'); + } + + List _rewriteLinks(List runs) => + options.linkRewriter == null + ? runs + : [ + for (final r in runs) + r.link == null + ? r + : r.copyWith(link: options.linkRewriter!(r.link!)), + ]; + String _listItem(DocBlock block, _ListColumns cols) { final (indent, runs, marker) = switch (block) { ListItemBlock(:final indent, :final runs, :final kind, :final ordinal) => @@ -173,15 +255,7 @@ final class MarkdownExporter { int level = 1, bool nested = false, }) { - final rewritten = options.linkRewriter == null - ? runs - : [ - for (final r in runs) - r.link == null - ? r - : r.copyWith(link: options.linkRewriter!(r.link!)), - ]; - final merged = InlineRun.merge(rewritten); + final merged = InlineRun.merge(_rewriteLinks(runs)); if (merged.isEmpty && (kind == _Kind.list || kind == _Kind.task)) { // Top level: a bare marker. Nested: an empty item cannot interrupt the // parent's paragraph, and a `
` HTML block would swallow the next @@ -205,6 +279,7 @@ final class MarkdownExporter { merged, context: context, style: style, + flavor: options.flavor, ); final lines = inline.split('\n'); final text = [ @@ -212,8 +287,8 @@ final class MarkdownExporter { for (final l in lines.skip(1)) cont + l, ].join('\n'); fallback ??= text; - if (_readBack(text, kind, level) case final back? - when _sameRuns(back, merged)) { + if (_readBack(text, kind, level, options.flavor) case final back? + when _sameRuns(back, _written(merged))) { return text; } if (style == EmphasisStyle.html) return text; @@ -221,6 +296,13 @@ final class MarkdownExporter { return fallback!; } + /// [runs] as the flavor writes them (GFM drops chips and link styles). + List _written(List runs) => _wonky + ? runs + : InlineRun.merge([ + for (final r in runs) r.copyWith(clearLinkStyle: true, chip: false), + ]); + static bool _sameRuns(List a, List b) { if (a.length != b.length) return false; for (var i = 0; i < a.length; i++) { @@ -231,8 +313,15 @@ final class MarkdownExporter { /// Parses a single written block back to runs; `null` when the structure is /// not the expected single block. - static List? _readBack(String markdown, _Kind kind, int level) { - final importer = MarkdownImporter(ImportOptions(idGenerator: () => 'x')); + static List? _readBack( + String markdown, + _Kind kind, + int level, + MarkdownFlavor flavor, + ) { + final importer = MarkdownImporter( + ImportOptions(idGenerator: () => 'x', flavor: flavor), + ); final tree = importer.parseTree(markdown); if (tree.blocks.length != 1) return null; final b = tree.blocks.single; diff --git a/packages/wonky_write_core/lib/src/markdown/markdown_importer.dart b/packages/wonky_write_core/lib/src/markdown/markdown_importer.dart index 6ef349f5..66b77ba1 100644 --- a/packages/wonky_write_core/lib/src/markdown/markdown_importer.dart +++ b/packages/wonky_write_core/lib/src/markdown/markdown_importer.dart @@ -6,6 +6,8 @@ import 'dart:typed_data'; import 'package:markdown/markdown.dart' as md; +import '../delta/attributes.dart'; +import '../delta/boxes.dart'; import '../delta/delta_utils.dart'; import '../delta/embeds.dart'; import '../delta/links.dart'; @@ -16,6 +18,7 @@ import 'front_matter.dart'; import 'inline_reader.dart'; import 'inline_writer.dart'; import 'md_syntax.dart'; +import 'package:wonky_rich_text/wonky_rich_text.dart' show WonkyMdTags; /// Resolves an image source that is not an absolute URL (relative path, /// `data:` URI). Returns the imported image, or `null` when unavailable. @@ -39,6 +42,7 @@ final class MarkdownImporter { var _warnedQuote = false; var _warnedStart = false; var _warnedFlatten = false; + var _warnedDirective = false; var _imageCounter = 0; /// Imports [markdown]. @@ -64,13 +68,17 @@ final class MarkdownImporter { FrontMatter.field(split.frontMatter, 'lang') ?? FrontMatter.field(split.frontMatter, 'language'), images: List.unmodifiable(_images), + markdownFlavor: options.flavor, ); } /// Parses [body] (no front matter) into the IR. DocTree parseTree(String body) { _blocks.clear(); - for (final node in parseMarkdownAst(_protectFootnotes(body))) { + for (final node in parseMarkdownAst( + _protectFootnotes(body), + flavor: options.flavor, + )) { _topBlock(node); } return DocTree(List.of(_blocks)); @@ -151,10 +159,21 @@ final class MarkdownImporter { _inlineBlock(node.children ?? const [], (runs) => ParagraphBlock(runs)); case 'h1' || 'h2' || 'h3' || 'h4' || 'h5' || 'h6': final level = int.parse(node.tag.substring(1)); + final step = int.tryParse(node.attributes[WonkyMdTags.step] ?? ''); _inlineBlock( node.children ?? const [], - (runs) => HeadingBlock(level, runs), + (runs) => HeadingBlock( + level, + runs, + step: step != null && step <= WonkyAttr.maxStep ? step : null, + ), ); + case WonkyMdTags.box: + _box(node); + case WonkyMdTags.grid: + _grid(node); + case WonkyMdTags.youtube: + _youtube(node); case 'blockquote': _quote(node, depth: 0); case 'ul' || 'ol': @@ -435,6 +454,9 @@ final class MarkdownImporter { 'blockquote', 'table', 'hr', + WonkyMdTags.box, + WonkyMdTags.grid, + WonkyMdTags.youtube, 'h1', 'h2', 'h3', @@ -505,6 +527,108 @@ final class MarkdownImporter { } } + void _directiveWarn() { + if (_warnedDirective) return; + _warnedDirective = true; + _warn( + ImportWarningKind.directiveFlattened, + 'A Wonky Markdown block was not closed or held lines it cannot keep', + ); + } + + /// A Wonky Markdown container (Write 11 §5.1): its blocks become the + /// children of a [ContainerBlock]. + void _box(md.Element node) { + if (node.attributes.containsKey(WonkyMdTags.unterminated)) { + _directiveWarn(); + } + final type = BoxType.tryParse(node.attributes[WonkyMdTags.type]); + if (type == null) return; + final id = options.idGenerator(); + final frame = type == BoxType.callout + ? BoxFrame.callout( + id: id, + variant: + CalloutVariant.tryParse(node.attributes[WonkyMdTags.variant]) ?? + CalloutVariant.info, + title: BoxFrame.canonicalTitle(node.attributes[WonkyMdTags.title]), + ) + : BoxFrame(id: id, type: type); + final outer = List.of(_blocks); + _blocks.clear(); + for (final c in node.children ?? const []) { + _topBlock(c); + } + final children = List.of(_blocks); + _blocks + ..clear() + ..addAll(outer) + ..add(ContainerBlock(frame, children)); + } + + /// A Wonky Markdown grid (Write 11 §5.1). + void _grid(md.Element node) { + if (node.attributes.containsKey(WonkyMdTags.unterminated) || + node.attributes.containsKey(WonkyMdTags.dropped)) { + _directiveWarn(); + } + final items = >[]; + for (final item + in (node.children ?? const []).whereType()) { + if (item.tag != WonkyMdTags.gridItem) continue; + items.add([ + for (final run in _reader.readRuns(item.children ?? const [])) + run.copyWith(text: run.text.replaceAll(softBreak, ' ')), + ]); + } + if (items.isEmpty) items.add(const []); + if (items.length > GridEmbed.maxItems) { + _directiveWarn(); + items.removeRange(GridEmbed.maxItems, items.length); + } + _blocks.add( + GridBlock( + options.idGenerator(), + GridEmbed.canonicalColumns(node.attributes[WonkyMdTags.columns]), + GridBullets.parse(node.attributes[WonkyMdTags.bullets]), + items, + itemMarkdown: [ + for (final runs in items) + InlineMarkdownWriter.write(runs, context: InlineContext.tableCell), + ], + ), + ); + } + + /// `::youtube[title]{id=… start=…}` (Write 11 §5.1); the id may also be + /// a YouTube URL. Without a valid id the line stays as text. + void _youtube(md.Element node) { + final parsed = YouTubeEmbed.parseUrl( + node.attributes[WonkyMdTags.videoId] ?? '', + ); + if (parsed == null) { + _directiveWarn(); + _blocks.add( + ParagraphBlock([InlineRun(node.attributes[WonkyMdTags.raw] ?? '')]), + ); + return; + } + _blocks.add( + YouTubeBlock( + YouTubeEmbed( + id: options.idGenerator(), + videoId: parsed.videoId, + start: + YouTubeEmbed.parseTime(node.attributes[WonkyMdTags.start]) ?? + parsed.start, + title: YouTubeEmbed.canonicalTitle( + node.attributes[WonkyMdTags.title], + ), + ), + ), + ); + } + void _table(md.Element table) { final rows = >>[]; final align = []; diff --git a/packages/wonky_write_core/lib/src/markdown/wonky_to_gfm.dart b/packages/wonky_write_core/lib/src/markdown/wonky_to_gfm.dart new file mode 100644 index 00000000..95fb03a3 --- /dev/null +++ b/packages/wonky_write_core/lib/src/markdown/wonky_to_gfm.dart @@ -0,0 +1,329 @@ +/// Wonky Markdown elements → their closest GitHub-Flavored Markdown form +/// (specs/wonky_write/11-wonky-markdown.md §3.2). +library; + +import 'package:dart_quill_delta/dart_quill_delta.dart'; + +import '../delta/attributes.dart'; +import '../delta/boxes.dart'; +import '../delta/document.dart'; +import '../delta/embeds.dart'; +import '../delta/normalizer.dart'; +import '../ir/doc_tree.dart'; +import '../import/import_api.dart' show MarkdownFlavor; +import 'inline_markdown.dart'; +import 'inline_writer.dart'; + +/// The Wonky elements of a document, counted for the conversion dialog. +final class WonkyInventory { + /// Creates an inventory. + const WonkyInventory({ + this.callouts = 0, + this.details = 0, + this.cards = 0, + this.grids = 0, + this.buttons = 0, + this.arrowLinks = 0, + this.chips = 0, + this.steps = 0, + this.videos = 0, + }); + + /// Callouts. + final int callouts; + + /// Details. + final int details; + + /// Cards. + final int cards; + + /// Grids. + final int grids; + + /// Buttons (primary and secondary). + final int buttons; + + /// Arrow links. + final int arrowLinks; + + /// Chips. + final int chips; + + /// Numbered headings. + final int steps; + + /// YouTube videos. + final int videos; + + /// Whether there is nothing to convert. + bool get isEmpty => + callouts + + details + + cards + + grids + + buttons + + arrowLinks + + chips + + steps + + videos == + 0; + + /// JSON form (MCP). + Map toJson() => { + 'callouts': callouts, + 'details': details, + 'cards': cards, + 'grids': grids, + 'buttons': buttons, + 'arrowLinks': arrowLinks, + 'chips': chips, + 'steps': steps, + 'videos': videos, + }; +} + +/// Converts Wonky Markdown elements to GFM (Write 11 §3.2). +abstract final class WonkyToGfm { + /// Counts the Wonky elements of [document]. + static WonkyInventory inventory(Delta document) { + final counts = {}; + void add(String key) => counts[key] = (counts[key] ?? 0) + 1; + var prevPath = const []; + String? prevStyleRun; + for (final line in WonkyDocument(document).lines) { + final path = Boxes.of(line.attributes); + final common = Boxes.commonDepth(prevPath, path); + for (var k = common; k < path.length; k++) { + add(path[k].type.value); + } + prevPath = path; + if (line.format.step != null) add('step'); + for (final s in line.segments) { + if (s.isEmbed) { + switch (WonkyEmbed.tryParse(s.data)) { + case GridEmbed(): + add('grid'); + case YouTubeEmbed(): + add('video'); + default: + break; + } + prevStyleRun = null; + continue; + } + final a = s.attributes; + final style = a?[WonkyAttr.linkStyle]; + final key = a?[WonkyAttr.chip] != null + ? 'chip' + : style == 'arrow' + ? 'arrowLink' + : style != null + ? 'button' + : null; + final run = key == null ? null : '$key|${a?[WonkyAttr.link]}'; + if (key != null && run != prevStyleRun) add(key); + prevStyleRun = run; + } + prevStyleRun = null; + } + return WonkyInventory( + callouts: counts['callout'] ?? 0, + details: counts['details'] ?? 0, + cards: counts['card'] ?? 0, + grids: counts['grid'] ?? 0, + buttons: counts['button'] ?? 0, + arrowLinks: counts['arrowLink'] ?? 0, + chips: counts['chip'] ?? 0, + steps: counts['step'] ?? 0, + videos: counts['video'] ?? 0, + ); + } + + /// The change that converts every Wonky element of [document] to GFM, + /// normalized (`document.compose(change)` is valid). Comments and + /// suggestions on converted text stay; a grid's are dropped with it. + static Delta change(Delta document) { + final doc = WonkyDocument(document); + final d = Delta(); + for (final line in doc.lines) { + final path = Boxes.of(line.attributes); + final inCallout = path.any((f) => f.type == BoxType.callout); + final prevPath = line.index == 0 + ? const [] + : Boxes.of(doc.lines[line.index - 1].attributes); + // A label line before each callout that starts here. + final common = Boxes.commonDepth(prevPath, path); + for (var k = common; k < path.length; k++) { + final f = path[k]; + if (f.type != BoxType.callout) continue; + d + ..insert(f.calloutLabel, {WonkyAttr.bold: true}) + ..insert('\n', {WonkyAttr.blockquote: true}); + } + final format = line.format; + final video = line.embed; + if (video is YouTubeEmbed) { + // A link to the video on its own line. + d + ..delete(1) + ..insert(video.title ?? video.watchUrl, { + WonkyAttr.link: video.watchUrl, + }) + ..retain(1, { + if (path.isNotEmpty) WonkyAttr.box: null, + if (inCallout) WonkyAttr.blockquote: true, + }); + continue; + } + final grid = line.embed; + if (grid is GridEmbed) { + d.delete(1); + for (var i = 0; i < grid.items.length; i++) { + for (final r in InlineMarkdown.parseCell(grid.items[i])) { + if (r.text.isEmpty) continue; + d.insert( + r.text, + r.copyWith(clearLinkStyle: true, chip: false).toAttributes(), + ); + } + final item = { + WonkyAttr.list: ListKind.bullet.value, + if (inCallout) WonkyAttr.blockquote: true, + }; + if (i < grid.items.length - 1) { + d.insert('\n', item); + } else { + d.retain(1, {...item, WonkyAttr.box: null}); + } + } + continue; + } + if (format.step != null) d.insert('(${format.step}) '); + for (final s in line.segments) { + final a = s.attributes; + final styled = + a != null && + (a.containsKey(WonkyAttr.chip) || + a.containsKey(WonkyAttr.linkStyle)); + d.retain( + s.length, + styled ? {WonkyAttr.chip: null, WonkyAttr.linkStyle: null} : null, + ); + } + final patch = { + if (path.isNotEmpty) WonkyAttr.box: null, + if (format.step != null) WonkyAttr.step: null, + if (inCallout && + !line.isEmbedLine && + (format.type == BlockType.paragraph || format.isList) && + !format.inQuote) + WonkyAttr.blockquote: true, + }; + d.retain(1, patch.isEmpty ? null : patch); + } + d.trim(); + return const WonkyDeltaNormalizer().normalizeChange(document, d).change; + } + + /// [tree] with every Wonky element in its GFM form (the GFM export, and + /// the exporters that approximate Wonky elements: TXT, RTF). + static DocTree tree(DocTree tree) => tree.hasWonkyElements + ? DocTree(blocks(tree.blocks), meta: tree.meta) + : tree; + + /// [blocks] with every Wonky element in its GFM form (the GFM Markdown + /// export of a document with Wonky elements). + static List blocks(List blocks) { + final out = []; + _convert(blocks, out, inCallout: false); + return out; + } + + static void _convert( + List blocks, + List out, { + required bool inCallout, + }) { + for (final b in blocks) { + switch (b) { + case ContainerBlock(:final frame, :final children): + if (frame.type == BoxType.callout) { + out.add( + QuoteBlock([ + [InlineRun(frame.calloutLabel, bold: true)], + ]), + ); + } + _convert( + children, + out, + inCallout: inCallout || frame.type == BoxType.callout, + ); + case YouTubeBlock(:final embed): + final link = [ + InlineRun(embed.title ?? embed.watchUrl, link: embed.watchUrl), + ]; + out.add(inCallout ? QuoteBlock([link]) : ParagraphBlock(link)); + case GridBlock(:final items): + for (final item in items) { + out.add( + ListItemBlock(ListKindIr.bullet, 0, item, inQuote: inCallout), + ); + } + case HeadingBlock(:final step, :final level, :final runs) + when step != null: + out.add( + HeadingBlock( + level, + [InlineRun('($step) '), ...runs], + anchorId: b.anchorId, + deltaStart: b.deltaStart, + deltaLength: b.deltaLength, + ), + ); + case ParagraphBlock(:final runs) when inCallout: + out.add(QuoteBlock([runs])); + case ListItemBlock( + :final kind, + :final indent, + :final runs, + :final ordinal, + ) + when inCallout: + out.add( + ListItemBlock(kind, indent, runs, ordinal: ordinal, inQuote: true), + ); + case TaskBlock(:final checked, :final indent, :final runs) + when inCallout: + out.add(TaskBlock(checked, indent, runs, inQuote: true)); + case TableBlock(:final rows) + when rows.any( + (r) => r.any((c) => c.any((x) => x.chip || x.linkStyle != null)), + ): + out.add( + TableBlock( + b.id, + b.align, + rows, + cellMarkdown: [ + for (final r in rows) + [ + for (final c in r) + InlineMarkdownWriter.write( + c, + context: InlineContext.tableCell, + flavor: MarkdownFlavor.gfm, + ), + ], + ], + deltaStart: b.deltaStart, + deltaLength: b.deltaLength, + ), + ); + default: + out.add(b); + } + } + } +} diff --git a/packages/wonky_write_core/lib/src/testing/generators.dart b/packages/wonky_write_core/lib/src/testing/generators.dart index ca864b42..00a685b3 100644 --- a/packages/wonky_write_core/lib/src/testing/generators.dart +++ b/packages/wonky_write_core/lib/src/testing/generators.dart @@ -6,6 +6,7 @@ import 'dart:math'; import 'package:dart_quill_delta/dart_quill_delta.dart'; import '../delta/attributes.dart'; +import '../delta/boxes.dart'; import '../delta/delta_utils.dart'; import '../delta/document.dart'; import '../delta/embeds.dart'; @@ -26,6 +27,7 @@ final class DeltaGenOptions { this.unicode = true, this.markdownSpecials = true, this.emptyLines = true, + this.wonky = false, }); /// Maximum number of lines. @@ -60,6 +62,13 @@ final class DeltaGenOptions { /// Generate empty lines. final bool emptyLines; + + /// Generate Wonky Markdown elements (Write 11 §2): containers (nested), + /// grids, numbered headings, styled links and chips, within the limits + /// of the round-trip guarantee (§5.4): labels without `]`, line breaks or + /// edge whitespace, styled link URLs without parentheses, details that + /// start with their summary, no code line starting with a fence. + final bool wonky; } /// Generates random, valid (normalized) Wonky documents from a seed. @@ -101,6 +110,23 @@ final class DeltaGen { 'https://ex.com/%C3%A9t%C3%A9', ]; static const _languages = ['', 'dart', 'js', 'python', 'c++', 'objective-c']; + static const _styledLinks = [ + 'https://example.com', + 'https://example.com/a_b/c?x=1&y=2#frag', + 'mailto:someone@example.com', + 'wonky://doc/0192f1a2-0000-7000-8000-000000000001#h-intro-1', + ]; + + /// A chip or styled link label: plain text without `]`, line breaks or + /// edge whitespace. + String _label() { + final t = text(options.maxRunLength) + .replaceAll(']', ')') + .replaceAll(softBreak, ' ') + .replaceAll('\u00A0', ' ') + .trim(); + return t.isEmpty ? 'x' : t; + } /// A fresh deterministic id. String nextId() { @@ -132,6 +158,19 @@ final class DeltaGen { Map? _inlineAttributes() { final attrs = {}; + if (options.wonky && random.nextInt(8) == 0) { + // A styled run; its text comes from [_label]. + if (random.nextBool()) { + attrs[WonkyAttr.chip] = random.nextInt(3) == 0 ? 'google' : true; + } else { + attrs[WonkyAttr.link] = + _styledLinks[random.nextInt(_styledLinks.length)]; + attrs[WonkyAttr.linkStyle] = WonkyAttr.linkStyles.elementAt( + random.nextInt(WonkyAttr.linkStyles.length), + ); + } + return attrs; + } if (random.nextInt(4) == 0) { attrs[WonkyAttr.code] = true; } else { @@ -194,8 +233,34 @@ final class DeltaGen { /// A random embed. WonkyEmbed embed() { - final p = random.nextInt(options.tables ? 3 : 2); + final p = random.nextInt(options.tables ? (options.wonky ? 5 : 3) : 2); switch (p) { + case 4: + const ids = ['AGAQ_N56wCs', 'dQw4w9WgXcQ', 'o3kP3dT2C5k']; + return YouTubeEmbed( + id: nextId(), + videoId: ids[random.nextInt(ids.length)], + start: random.nextBool() ? null : random.nextInt(4000), + title: random.nextBool() + ? null + : YouTubeEmbed.canonicalTitle(_singleLine(text(5))), + ); + case 3: + return GridEmbed( + id: nextId(), + columns: 1 + random.nextInt(4), + bullets: + GridBullets.values[random.nextInt(GridBullets.values.length)], + items: [ + for (var i = 0, n = 1 + random.nextInt(4); i < n; i++) + switch (random.nextInt(5)) { + 0 => '', + 1 => ':chip[${_plainWord()}]', + 2 => '**${_plainWord()}** ${_plainWord()}', + _ => 'item ${_plainWord()}', + }, + ], + ); case 0: return ImageEmbed( id: nextId(), @@ -245,30 +310,80 @@ final class DeltaGen { int? prevListIndent; var prevInQuote = false; var prevListQuoted = false; + var boxes = []; for (var l = 0; l < lines; l++) { - if (options.embeds && random.nextInt(8) == 0) { + // Containers: pop some, maybe push one (Write 11 §2.2). + var opensDetails = false; + if (options.wonky) { + final previous = boxes; + if (boxes.isNotEmpty && random.nextInt(4) == 0) { + boxes = boxes.sublist(0, random.nextInt(boxes.length)); + } + if (boxes.length < BoxFrame.maxDepth && random.nextInt(5) == 0) { + final frame = _frame(); + opensDetails = frame.type == BoxType.details; + boxes = [...boxes, frame]; + } + if (!Boxes.samePath(previous, boxes)) { + prevListIndent = null; + prevInQuote = false; + } + } + Map? withBox(Map? attrs) => + boxes.isEmpty + ? attrs + : {...?attrs, WonkyAttr.box: Boxes.toValue(boxes)}; + if (!opensDetails && options.embeds && random.nextInt(8) == 0) { final e = embed(); final attrs = options.overlays && random.nextInt(4) == 0 ? {WonkyAttr.commentKey('t${random.nextInt(3)}'): true} : null; d.insert(e.toInsert(), attrs); - d.insert('\n'); + d.insert('\n', withBox(null)); prevListIndent = null; prevInQuote = false; continue; } - final block = _blockAttributes( - prevListIndent, - prevInQuote: prevInQuote, - prevListQuoted: prevListQuoted, - ); + var block = opensDetails + ? {WonkyAttr.header: 3} + : _blockAttributes( + prevListIndent, + prevInQuote: prevInQuote, + prevListQuoted: prevListQuoted, + ); + final level = block?[WonkyAttr.header]; + // A details summary is never numbered (the blog reads `(n)` in it as + // text). + if (options.wonky && + !opensDetails && + (level == 2 || level == 3) && + random.nextInt(3) == 0) { + block = {...block!, WonkyAttr.step: random.nextInt(20)}; + } + final isCode = block?.containsKey(WonkyAttr.codeBlock) ?? false; final runs = options.emptyLines && random.nextInt(8) == 0 ? 0 : 1 + random.nextInt(options.maxRunsPerLine); for (var r = 0; r < runs; r++) { - d.insert(text(options.maxRunLength), _inlineAttributes()); + final attrs = _inlineAttributes(); + final styled = + attrs != null && + (attrs.containsKey(WonkyAttr.chip) || + attrs.containsKey(WonkyAttr.linkStyle)); + var t = styled ? _label() : text(options.maxRunLength); + if (options.wonky && attrs?[WonkyAttr.code] == true) { + // An inline code span opening a line with three backticks reads + // as a fence to the blog's directive parser (a known limit). + t = t.replaceAll('`', "'"); + } + if (options.wonky && isCode && r == 0) { + // A code line starting with a fence ends the blog's fence + // tracking (a known limit of the syntax). + t = t.replaceAll('`', "'"); + } + d.insert(t, attrs); } - d.insert('\n', block); + d.insert('\n', withBox(block)); final f = BlockFormat.fromAttributes(block); prevListIndent = f.isList ? f.indent : null; prevInQuote = f.inQuote; @@ -277,6 +392,18 @@ final class DeltaGen { return d; } + /// A random container frame. + BoxFrame _frame() { + final type = BoxType.values[random.nextInt(BoxType.values.length)]; + if (type != BoxType.callout) return BoxFrame(id: nextId(), type: type); + return BoxFrame.callout( + id: nextId(), + variant: + CalloutVariant.values[random.nextInt(CalloutVariant.values.length)], + title: random.nextBool() ? null : BoxFrame.canonicalTitle(_label()), + ); + } + /// A random valid, normalized document. Delta document() => const WonkyDeltaNormalizer().normalize(rawDocument()).document; diff --git a/packages/wonky_write_core/lib/src/theme/mappers/css_writer.dart b/packages/wonky_write_core/lib/src/theme/mappers/css_writer.dart index f5e67049..1e33a985 100644 --- a/packages/wonky_write_core/lib/src/theme/mappers/css_writer.dart +++ b/packages/wonky_write_core/lib/src/theme/mappers/css_writer.dart @@ -515,9 +515,206 @@ final class ThemeCssWriter { if (colors) 'color': c(t.body.style.color), if (layout) 'font-style': 'italic', }); + _wonkyRules(t.wonky, rule, len: len, c: c, colors: colors, layout: layout); return b.toString(); } + /// The Wonky Markdown elements (Write 11 §8–9): the classes the HTML + /// writer emits, modeled on the Serverpod blog's `markdown.css`. + void _wonkyRules( + ResolvedWonkyElements w, + void Function(String, Map) rule, { + required String Function(double) len, + required String Function(int) c, + required bool colors, + required bool layout, + }) { + const s = '.wonky-doc'; + String edges(EdgesPt e) => + '${len(e.top)} ${len(e.right)} ${len(e.bottom)} ${len(e.left)}'; + // Callouts. + final co = w.callout; + rule('$s .wonky-callout', { + if (layout) 'margin': '${len(co.spaceBefore)} 0 ${len(co.spaceAfter)}', + if (layout) 'padding': edges(co.padding), + if (layout) 'border': '${_n(co.borderWidth)}pt solid', + if (layout) 'border-radius': len(co.borderRadius), + }); + rule('$s .wonky-callout > :last-child', {if (layout) 'margin-bottom': '0'}); + rule('$s .wonky-callout-title', { + if (layout) 'display': 'flex', + if (layout) 'align-items': 'center', + if (layout) 'gap': '0.375em', + if (layout) 'margin-bottom': '0.5em', + if (layout) 'font-size': '${_n(co.titleSizeRatio)}em', + if (layout) 'font-weight': '${co.titleWeight}', + if (layout && co.titleCase != CaseTransform.none) + co.titleCase == CaseTransform.smallCaps + ? 'font-variant' + : 'text-transform': co.titleCase == CaseTransform.smallCaps + ? 'small-caps' + : co.titleCase.name, + if (layout) 'letter-spacing': '0.025em', + }); + rule('$s .wonky-callout-icon', { + if (layout) 'width': '1.4em', + if (layout) 'height': '1.4em', + if (layout) 'flex-shrink': '0', + }); + for (final v in const [ + 'info', + 'tip', + 'note', + 'warning', + 'caution', + 'danger', + ]) { + final cc = co.colorsFor(v); + rule('$s .wonky-callout-$v', { + if (colors) 'background-color': c(cc.background), + if (colors) 'border-color': c(cc.border), + }); + rule('$s .wonky-callout-$v .wonky-callout-title', { + if (colors) 'color': c(cc.title), + }); + } + // Details. + final de = w.details; + rule('$s .wonky-details', { + if (layout) 'margin': '${len(de.spaceBefore)} 0 ${len(de.spaceAfter)}', + if (layout) 'padding': edges(de.padding), + if (colors && de.background != null) + 'background-color': c(de.background!), + if (de.border.isVisible) + 'border': + '${_n(de.border.width)}pt solid ${colors ? c(de.border.color) : 'currentColor'}', + if (layout) 'border-radius': len(de.borderRadius), + }); + rule('$s .wonky-details-summary', { + if (layout) 'display': 'flex', + if (layout) 'align-items': 'center', + if (layout) 'justify-content': 'space-between', + if (layout) 'cursor': 'pointer', + if (layout) 'list-style': 'none', + if (layout) 'font-weight': '${de.summaryWeight}', + }); + rule('$s .wonky-details-summary::-webkit-details-marker', { + if (layout) 'display': 'none', + }); + rule('$s .wonky-details-chevron', { + if (layout) 'width': '1.25em', + if (layout) 'height': '1.25em', + if (layout) 'margin-left': '1em', + if (layout) 'flex-shrink': '0', + if (colors) 'color': c(de.chevronColor), + if (layout) 'transition': 'transform 150ms ease', + }); + rule('$s .wonky-details:not([open]) .wonky-details-chevron', { + if (layout) 'transform': 'rotate(-90deg)', + }); + rule('$s .wonky-details-body', {if (layout) 'margin-top': '0.75em'}); + rule('$s .wonky-details-body > :last-child', { + if (layout) 'margin-bottom': '0', + }); + // Cards. + final ca = w.card; + rule('$s .wonky-card', { + if (layout) 'margin': '${len(ca.spaceBefore)} 0 ${len(ca.spaceAfter)}', + if (layout) 'padding': edges(ca.padding), + if (colors && ca.background != null) + 'background-color': c(ca.background!), + if (layout) 'border-radius': len(ca.borderRadius), + if (layout && ca.shadow) 'box-shadow': '0 1px 2px 0 rgb(0 0 0 / 0.05)', + }); + rule('$s .wonky-card > :first-child', {if (layout) 'margin-top': '0'}); + rule('$s .wonky-card > :last-child', {if (layout) 'margin-bottom': '0'}); + // Grids. + final g = w.grid; + rule('$s .wonky-grid', { + if (layout) 'display': 'grid', + if (layout) 'margin': '${len(g.spaceBefore)} 0 ${len(g.spaceAfter)}', + if (layout) 'column-gap': len(g.columnGap), + if (layout) 'row-gap': len(g.rowGap), + if (layout) 'grid-template-columns': 'minmax(0, 1fr)', + }); + for (final n in const [2, 3, 4]) { + rule('$s .wonky-grid-$n', { + if (layout) 'grid-template-columns': 'repeat($n, minmax(0, 1fr))', + }); + } + rule('$s .wonky-grid-item', { + if (layout) 'display': 'flex', + if (layout) 'align-items': 'flex-start', + if (layout) 'gap': '0.6em', + }); + rule('$s .wonky-grid-bullet', { + if (layout) 'width': '1.25em', + if (layout) 'height': '1.25em', + if (layout) 'margin-top': '0.1em', + if (layout) 'flex-shrink': '0', + if (colors) 'color': c(g.bulletColor), + }); + // Buttons, arrow links and chips. + final bt = w.button; + rule('$s a.wonky-button', { + if (layout) 'display': 'inline-flex', + if (layout) 'align-items': 'center', + if (layout) 'padding': '0.6em 1.2em', + if (layout) 'margin': '0.15em 0', + if (layout) 'border-radius': len(bt.borderRadius), + if (layout) 'font-weight': '${bt.fontWeight}', + if (layout) 'text-decoration': 'none', + if (colors) 'color': c(bt.color), + if (colors) 'background-color': c(bt.background), + }); + rule('$s a.wonky-button-secondary', { + if (colors) 'color': c(bt.secondaryColor), + if (colors) 'background-color': c(bt.secondaryBackground), + }); + rule('$s a.wonky-link', { + if (layout) 'display': 'inline-flex', + if (layout) 'align-items': 'center', + if (layout) 'font-weight': '${bt.arrowWeight}', + if (layout) 'text-decoration': 'none', + if (colors) 'color': c(bt.arrowColor), + }); + rule('$s .wonky-link-arrow', { + if (layout) 'width': '1em', + if (layout) 'height': '1em', + if (layout) 'margin-left': '0.25em', + }); + final ch = w.chip; + rule('$s .wonky-chip', { + if (layout) 'display': 'inline-flex', + if (layout) 'align-items': 'center', + if (layout) 'padding': '0.2em 0.8em', + if (layout) 'margin': '0.1em 0', + if (layout) 'border-radius': len(ch.borderRadius), + if (layout) 'font-weight': '${ch.fontWeight}', + if (colors) 'color': c(ch.color), + if (colors) 'background-color': c(ch.background), + }); + // Numbered headings. + final sb = w.stepBadge; + rule('$s .wonky-step', { + if (layout) 'display': 'flex', + if (layout) 'align-items': 'center', + if (layout) 'gap': '0.45em', + }); + rule('$s .wonky-step-number', { + if (layout) 'display': 'inline-flex', + if (layout) 'align-items': 'center', + if (layout) 'justify-content': 'center', + if (layout) 'flex-shrink': '0', + if (layout) 'width': '${_n(sb.sizeRatio / 0.66)}em', + if (layout) 'height': '${_n(sb.sizeRatio / 0.66)}em', + if (layout) 'border-radius': '50%', + if (layout) 'font-size': '0.66em', + if (colors) 'color': c(sb.color), + if (colors) 'background-color': c(sb.background), + }); + } + void _numbering( StringBuffer b, ResolvedHeadingNumbering n, diff --git a/packages/wonky_write_core/lib/src/theme/model/catalog.dart b/packages/wonky_write_core/lib/src/theme/model/catalog.dart index 3025aa2c..3779d898 100644 --- a/packages/wonky_write_core/lib/src/theme/model/catalog.dart +++ b/packages/wonky_write_core/lib/src/theme/model/catalog.dart @@ -13,6 +13,15 @@ const _stroke = LengthProp(LengthKind.stroke); const _color = ColorProp(); const _bool = BoolProp(); +/// The colors of one callout type (Write 11 §8): [color] is the type's +/// hue; the other colors are derived from it unless set. +const _calloutVariant = ObjectProp({ + 'color': _color, + 'background': _color, + 'border': _color, + 'titleColor': _color, +}); + /// Allowed `align` values. const alignValues = ['left', 'center', 'right', 'justify']; @@ -234,6 +243,68 @@ abstract final class ThemeCatalog { 'cellPadding': EdgesProp.lengths(LengthKind.spacing), 'fontSizeRatio': NumberProp(0.5, 2), }), + // Wonky Markdown elements (Write 11 §8). + ThemeElement.callout: ObjectProp({ + 'spaceBefore': _spacing, + 'spaceAfter': _spacing, + 'padding': EdgesProp.lengths(LengthKind.spacing), + 'borderRadius': _spacing, + 'borderWidth': _stroke, + 'titleCaseTransform': EnumProp(caseTransformValues), + 'titleSizeRatio': NumberProp(0.5, 2), + 'titleWeight': WeightProp(), + 'info': _calloutVariant, + 'tip': _calloutVariant, + 'note': _calloutVariant, + 'warning': _calloutVariant, + 'danger': _calloutVariant, + }), + ThemeElement.details: ObjectProp({ + 'spaceBefore': _spacing, + 'spaceAfter': _spacing, + 'padding': EdgesProp.lengths(LengthKind.spacing), + 'background': _color, + 'border': BorderProp(), + 'borderRadius': _spacing, + 'summaryWeight': WeightProp(), + 'chevronColor': _color, + }), + ThemeElement.card: ObjectProp({ + 'spaceBefore': _spacing, + 'spaceAfter': _spacing, + 'padding': EdgesProp.lengths(LengthKind.spacing), + 'background': _color, + 'borderRadius': _spacing, + 'shadow': EnumProp(['none', 'soft']), + }), + ThemeElement.grid: ObjectProp({ + 'spaceBefore': _spacing, + 'spaceAfter': _spacing, + 'bulletColor': _color, + 'columnGap': _spacing, + 'rowGap': _spacing, + }), + ThemeElement.button: ObjectProp({ + 'background': _color, + 'color': _color, + 'secondaryBackground': _color, + 'secondaryColor': _color, + 'borderRadius': _spacing, + 'fontWeight': WeightProp(), + 'arrowColor': _color, + 'arrowWeight': WeightProp(), + }), + ThemeElement.chip: ObjectProp({ + 'background': _color, + 'color': _color, + 'borderRadius': _spacing, + 'fontWeight': WeightProp(), + }), + ThemeElement.stepBadge: ObjectProp({ + 'background': _color, + 'color': _color, + 'sizeRatio': NumberProp(0.6, 2), + }), ThemeElement.header: ObjectProp(headerFooterProps), ThemeElement.footer: ObjectProp(headerFooterProps), }; diff --git a/packages/wonky_write_core/lib/src/theme/model/values.dart b/packages/wonky_write_core/lib/src/theme/model/values.dart index d4e79adb..70a224dd 100644 --- a/packages/wonky_write_core/lib/src/theme/model/values.dart +++ b/packages/wonky_write_core/lib/src/theme/model/values.dart @@ -338,6 +338,27 @@ enum ThemeElement implements JsonEnum { /// Tables. table, + /// Wonky Markdown callouts (Write 11 §8). + callout, + + /// Wonky Markdown details. + details, + + /// Wonky Markdown cards. + card, + + /// Wonky Markdown grids. + grid, + + /// Wonky Markdown buttons and arrow links (inline). + button, + + /// Wonky Markdown chips (inline). + chip, + + /// Wonky Markdown numbered heading badges. + stepBadge, + /// Page header (overrides `page.headerFooter`). header, diff --git a/packages/wonky_write_core/lib/src/theme/resolve/base_theme.dart b/packages/wonky_write_core/lib/src/theme/resolve/base_theme.dart index 40d788bf..c6d2c182 100644 --- a/packages/wonky_write_core/lib/src/theme/resolve/base_theme.dart +++ b/packages/wonky_write_core/lib/src/theme/resolve/base_theme.dart @@ -193,6 +193,69 @@ const Map wonkyDefaultElementsJson = { 'fontWeight': 600, 'prefix': '@', }, + // Wonky Markdown elements (Write 11 §8), close to the Serverpod blog. + 'callout': { + 'spaceBefore': '6pt', + 'spaceAfter': '10pt', + 'padding': '12pt', + 'borderRadius': '6pt', + 'borderWidth': '1px', + 'titleCaseTransform': 'uppercase', + 'titleSizeRatio': 0.75, + 'titleWeight': 600, + 'info': {'color': '#0284c7'}, + 'tip': {'color': '#059669'}, + 'note': {'color': '#6b7280'}, + 'warning': {'color': '#d97706'}, + 'danger': {'color': '#dc2626'}, + }, + 'details': { + 'spaceBefore': '0pt', + 'spaceAfter': '8pt', + 'padding': '14pt', + 'background': '@page', + 'border': {'width': '1px', 'style': 'solid', 'color': '@border'}, + 'borderRadius': '9pt', + 'summaryWeight': 600, + 'chevronColor': '@muted', + }, + 'card': { + 'spaceBefore': '10pt', + 'spaceAfter': '14pt', + 'padding': { + 'top': '14pt', + 'right': '18pt', + 'bottom': '14pt', + 'left': '18pt', + }, + 'background': '@codeBg', + 'borderRadius': '9pt', + 'shadow': 'soft', + }, + 'grid': { + 'spaceBefore': '10pt', + 'spaceAfter': '14pt', + 'bulletColor': '@accent', + 'columnGap': '24pt', + 'rowGap': '9pt', + }, + 'button': { + 'background': '@accent', + 'color': '@page', + 'secondaryBackground': '@muted', + 'secondaryColor': '@page', + 'borderRadius': '6pt', + 'fontWeight': 600, + 'arrowColor': '@accent', + 'arrowWeight': 600, + }, + 'chip': { + 'background': '@codeBg', + 'color': '@text', + 'borderRadius': '200pt', + 'fontWeight': 500, + }, + 'stepBadge': {'background': '@accent', 'color': '@page', 'sizeRatio': 1.1}, 'blockquote': { 'color': '@quoteText', 'background': '@quoteBg', diff --git a/packages/wonky_write_core/lib/src/theme/resolve/resolved_theme.dart b/packages/wonky_write_core/lib/src/theme/resolve/resolved_theme.dart index 87669557..721f81e2 100644 --- a/packages/wonky_write_core/lib/src/theme/resolve/resolved_theme.dart +++ b/packages/wonky_write_core/lib/src/theme/resolve/resolved_theme.dart @@ -1286,6 +1286,7 @@ final class ResolvedWriteTheme with ResolvedValue { required this.rule, required this.image, required this.table, + required this.wonky, required this.header, required this.footer, required this.syntax, @@ -1360,6 +1361,9 @@ final class ResolvedWriteTheme with ResolvedValue { /// Tables. final ResolvedTable table; + /// Wonky Markdown elements (Write 11 §8). + final ResolvedWonkyElements wonky; + /// Page header. final ResolvedHeaderFooter header; @@ -1427,6 +1431,10 @@ final class ResolvedWriteTheme with ResolvedValue { ), ); faces.add(FontFaceKey(body.style.fontFamily, mention.fontWeight)); + faces.add(FontFaceKey(body.style.fontFamily, wonky.button.fontWeight)); + faces.add(FontFaceKey(body.style.fontFamily, wonky.button.arrowWeight)); + faces.add(FontFaceKey(body.style.fontFamily, wonky.chip.fontWeight)); + faces.add(FontFaceKey(body.style.fontFamily, wonky.details.summaryWeight)); add(table.style); faces.add(table.headerStyle.faceKey); faces.add(image.caption.style.faceKey); @@ -1459,6 +1467,7 @@ final class ResolvedWriteTheme with ResolvedValue { 'rule': rule.toJson(), 'image': image.toJson(), 'table': table.toJson(), + 'wonky': wonky.toJson(), 'header': header.toJson(), 'footer': footer.toJson(), 'syntax': {for (final e in syntax.entries) e.key.name: e.value.toJson()}, @@ -1474,3 +1483,379 @@ final class ResolvedWriteTheme with ResolvedValue { @override int get hashCode => contentHash.hashCode; } + +// --------------------------------------------------------------------------- +// Wonky Markdown elements (Write 11 §8). + +/// The colors of one callout type. +final class ResolvedCalloutColors with ResolvedValue { + /// Creates callout colors. + const ResolvedCalloutColors({ + required this.color, + required this.background, + required this.border, + required this.title, + }); + + /// The type's hue (icon). + final int color; + + /// ARGB box fill. + final int background; + + /// ARGB border. + final int border; + + /// ARGB title (label and icon) color. + final int title; + + @override + JsonMap toJson() => { + 'color': _hex(color), + 'background': _hex(background), + 'border': _hex(border), + 'titleColor': _hex(title), + }; +} + +/// Callouts. +final class ResolvedCallout with ResolvedValue { + /// Creates a callout style. + const ResolvedCallout({ + required this.spaceBefore, + required this.spaceAfter, + required this.padding, + required this.borderRadius, + required this.borderWidth, + required this.titleCase, + required this.titleSizeRatio, + required this.titleWeight, + required this.variants, + }); + + /// Space before in pt. + final double spaceBefore; + + /// Space after in pt. + final double spaceAfter; + + /// Inner padding in pt. + final EdgesPt padding; + + /// Corner radius in pt. + final double borderRadius; + + /// Border width in pt. + final double borderWidth; + + /// Case transform of the title. + final CaseTransform titleCase; + + /// Title size relative to the body size. + final double titleSizeRatio; + + /// Title weight. + final int titleWeight; + + /// Colors per type (`info`, `tip`, `note`, `warning`, `danger`). + final Map variants; + + /// The colors of callout type [variant] (`caution` uses `warning`). + ResolvedCalloutColors colorsFor(String variant) => + variants[variant == 'caution' ? 'warning' : variant] ?? variants['note']!; + + @override + JsonMap toJson() => { + 'spaceBefore': _n(spaceBefore), + 'spaceAfter': _n(spaceAfter), + 'padding': padding.toJson(), + 'borderRadius': _n(borderRadius), + 'borderWidth': _n(borderWidth), + 'titleCaseTransform': titleCase.json, + 'titleSizeRatio': _n(titleSizeRatio), + 'titleWeight': titleWeight, + for (final e in variants.entries) e.key: e.value.toJson(), + }; +} + +/// Details. +final class ResolvedDetails with ResolvedValue { + /// Creates a details style. + const ResolvedDetails({ + required this.spaceBefore, + required this.spaceAfter, + required this.padding, + required this.background, + required this.border, + required this.borderRadius, + required this.summaryWeight, + required this.chevronColor, + }); + + /// Space before in pt. + final double spaceBefore; + + /// Space after in pt. + final double spaceAfter; + + /// Inner padding in pt. + final EdgesPt padding; + + /// ARGB fill, or `null`. + final int? background; + + /// Border. + final BorderPt border; + + /// Corner radius in pt. + final double borderRadius; + + /// Summary weight. + final int summaryWeight; + + /// ARGB chevron color. + final int chevronColor; + + @override + JsonMap toJson() => { + 'spaceBefore': _n(spaceBefore), + 'spaceAfter': _n(spaceAfter), + 'padding': padding.toJson(), + 'background': _hex(background), + 'border': border.toJson(), + 'borderRadius': _n(borderRadius), + 'summaryWeight': summaryWeight, + 'chevronColor': _hex(chevronColor), + }; +} + +/// Cards. +final class ResolvedCard with ResolvedValue { + /// Creates a card style. + const ResolvedCard({ + required this.spaceBefore, + required this.spaceAfter, + required this.padding, + required this.background, + required this.borderRadius, + required this.shadow, + }); + + /// Space before in pt. + final double spaceBefore; + + /// Space after in pt. + final double spaceAfter; + + /// Inner padding in pt. + final EdgesPt padding; + + /// ARGB fill, or `null`. + final int? background; + + /// Corner radius in pt. + final double borderRadius; + + /// Whether the card casts a soft shadow. + final bool shadow; + + @override + JsonMap toJson() => { + 'spaceBefore': _n(spaceBefore), + 'spaceAfter': _n(spaceAfter), + 'padding': padding.toJson(), + 'background': _hex(background), + 'borderRadius': _n(borderRadius), + 'shadow': shadow ? 'soft' : 'none', + }; +} + +/// Grids. +final class ResolvedGrid with ResolvedValue { + /// Creates a grid style. + const ResolvedGrid({ + required this.spaceBefore, + required this.spaceAfter, + required this.bulletColor, + required this.columnGap, + required this.rowGap, + }); + + /// Space before in pt. + final double spaceBefore; + + /// Space after in pt. + final double spaceAfter; + + /// ARGB bullet color. + final int bulletColor; + + /// Gap between columns in pt. + final double columnGap; + + /// Gap between rows in pt. + final double rowGap; + + @override + JsonMap toJson() => { + 'spaceBefore': _n(spaceBefore), + 'spaceAfter': _n(spaceAfter), + 'bulletColor': _hex(bulletColor), + 'columnGap': _n(columnGap), + 'rowGap': _n(rowGap), + }; +} + +/// Buttons and arrow links. +final class ResolvedButton with ResolvedValue { + /// Creates a button style. + const ResolvedButton({ + required this.background, + required this.color, + required this.secondaryBackground, + required this.secondaryColor, + required this.borderRadius, + required this.fontWeight, + required this.arrowColor, + required this.arrowWeight, + }); + + /// ARGB primary fill. + final int background; + + /// ARGB primary label color. + final int color; + + /// ARGB secondary fill. + final int secondaryBackground; + + /// ARGB secondary label color. + final int secondaryColor; + + /// Corner radius in pt. + final double borderRadius; + + /// Label weight (snapped for the body family). + final int fontWeight; + + /// ARGB arrow link color. + final int arrowColor; + + /// Arrow link weight (snapped for the body family). + final int arrowWeight; + + @override + JsonMap toJson() => { + 'background': _hex(background), + 'color': _hex(color), + 'secondaryBackground': _hex(secondaryBackground), + 'secondaryColor': _hex(secondaryColor), + 'borderRadius': _n(borderRadius), + 'fontWeight': fontWeight, + 'arrowColor': _hex(arrowColor), + 'arrowWeight': arrowWeight, + }; +} + +/// Chips. +final class ResolvedChip with ResolvedValue { + /// Creates a chip style. + const ResolvedChip({ + required this.background, + required this.color, + required this.borderRadius, + required this.fontWeight, + }); + + /// ARGB fill. + final int background; + + /// ARGB label color. + final int color; + + /// Corner radius in pt. + final double borderRadius; + + /// Label weight (snapped for the body family). + final int fontWeight; + + @override + JsonMap toJson() => { + 'background': _hex(background), + 'color': _hex(color), + 'borderRadius': _n(borderRadius), + 'fontWeight': fontWeight, + }; +} + +/// Numbered heading badges. +final class ResolvedStepBadge with ResolvedValue { + /// Creates a badge style. + const ResolvedStepBadge({ + required this.background, + required this.color, + required this.sizeRatio, + }); + + /// ARGB fill. + final int background; + + /// ARGB number color. + final int color; + + /// Badge diameter relative to the heading's font size. + final double sizeRatio; + + @override + JsonMap toJson() => { + 'background': _hex(background), + 'color': _hex(color), + 'sizeRatio': _n(sizeRatio), + }; +} + +/// The Wonky Markdown element styles of a theme (Write 11 §8). +final class ResolvedWonkyElements with ResolvedValue { + /// Creates the styles. + const ResolvedWonkyElements({ + required this.callout, + required this.details, + required this.card, + required this.grid, + required this.button, + required this.chip, + required this.stepBadge, + }); + + /// Callouts. + final ResolvedCallout callout; + + /// Details. + final ResolvedDetails details; + + /// Cards. + final ResolvedCard card; + + /// Grids. + final ResolvedGrid grid; + + /// Buttons and arrow links. + final ResolvedButton button; + + /// Chips. + final ResolvedChip chip; + + /// Numbered heading badges. + final ResolvedStepBadge stepBadge; + + @override + JsonMap toJson() => { + 'callout': callout.toJson(), + 'details': details.toJson(), + 'card': card.toJson(), + 'grid': grid.toJson(), + 'button': button.toJson(), + 'chip': chip.toJson(), + 'stepBadge': stepBadge.toJson(), + }; +} diff --git a/packages/wonky_write_core/lib/src/theme/resolve/theme_resolver.dart b/packages/wonky_write_core/lib/src/theme/resolve/theme_resolver.dart index 92f4e124..309239a3 100644 --- a/packages/wonky_write_core/lib/src/theme/resolve/theme_resolver.dart +++ b/packages/wonky_write_core/lib/src/theme/resolve/theme_resolver.dart @@ -310,6 +310,7 @@ final class _Resolution { rule: _rule(), image: _image(), table: _table(), + wonky: _wonky(), header: _headerFooter(ThemeElement.header), footer: _headerFooter(ThemeElement.footer), syntax: Map.unmodifiable(_syntax()), @@ -321,6 +322,172 @@ final class _Resolution { ); } + // Wonky Markdown elements (Write 11 §8). + + ResolvedWonkyElements _wonky() => ResolvedWonkyElements( + callout: _callout(), + details: _details(), + card: _card(), + grid: _grid(), + button: _button(), + chip: _chip(), + stepBadge: _stepBadge(), + ); + + int get _pageColor => + colors[PaletteKey.page] ?? (_dark ? 0xff111111 : 0xffffffff); + + /// [a] mixed into [b] by [t] (0 = [b], 1 = [a]) in Oklab. + static int _mix(int a, int b, double t) { + final x = Oklab.fromArgb(a); + final y = Oklab.fromArgb(b); + return Oklab( + y.l + (x.l - y.l) * t, + y.a + (x.a - y.a) * t, + y.b + (x.b - y.b) * t, + ).toArgb(); + } + + ResolvedCallout _callout() { + final bag = layered(ThemeElement.callout); + final page = _pageColor; + final variants = {}; + for (final v in const ['info', 'tip', 'note', 'warning', 'danger']) { + final vb = bag.bag(v) ?? PropertyBag.empty; + final hue = color(vb.color('color')) ?? colors[PaletteKey.accent] ?? 0; + final title = Oklch.fromArgb(hue); + variants[v] = ResolvedCalloutColors( + color: hue, + background: + fill(vb.color('background')) ?? + _mix(hue, page, _dark ? 0.16 : 0.07), + border: + color(vb.color('border')) ?? _mix(hue, page, _dark ? 0.45 : 0.32), + title: + color(vb.color('titleColor')) ?? + title + .copyWith(l: _dark ? 0.85 : 0.42, c: title.c.clamp(0, 0.16)) + .toArgb(), + ); + } + return ResolvedCallout( + spaceBefore: pt(bag.length('spaceBefore'), bodySize), + spaceAfter: pt(bag.length('spaceAfter'), bodySize), + padding: edges(bag.lengthEdges('padding'), bodySize), + borderRadius: pt(bag.length('borderRadius'), bodySize), + borderWidth: pt(bag.length('borderWidth'), bodySize, 0.75), + titleCase: enumValue( + CaseTransform.values, + bag.string('titleCaseTransform'), + CaseTransform.uppercase, + ), + titleSizeRatio: bag.number('titleSizeRatio') ?? 0.75, + titleWeight: FontRegistry.snapWeight( + bodyStyle.fontFamily, + bag.integer('titleWeight') ?? 600, + ), + variants: Map.unmodifiable(variants), + ); + } + + ResolvedDetails _details() { + final bag = layered(ThemeElement.details); + return ResolvedDetails( + spaceBefore: pt(bag.length('spaceBefore'), bodySize), + spaceAfter: pt(bag.length('spaceAfter'), bodySize), + padding: edges(bag.lengthEdges('padding'), bodySize), + background: fill(bag.color('background')), + border: border(bag.border('border'), bodySize) ?? BorderPt.none, + borderRadius: pt(bag.length('borderRadius'), bodySize), + summaryWeight: FontRegistry.snapWeight( + bodyStyle.fontFamily, + bag.integer('summaryWeight') ?? 600, + ), + chevronColor: + color(bag.color('chevronColor')) ?? + colors[PaletteKey.muted] ?? + bodyStyle.color, + ); + } + + ResolvedCard _card() { + final bag = layered(ThemeElement.card); + return ResolvedCard( + spaceBefore: pt(bag.length('spaceBefore'), bodySize), + spaceAfter: pt(bag.length('spaceAfter'), bodySize), + padding: edges(bag.lengthEdges('padding'), bodySize), + background: fill(bag.color('background')), + borderRadius: pt(bag.length('borderRadius'), bodySize), + shadow: bag.string('shadow') != 'none', + ); + } + + ResolvedGrid _grid() { + final bag = layered(ThemeElement.grid); + return ResolvedGrid( + spaceBefore: pt(bag.length('spaceBefore'), bodySize), + spaceAfter: pt(bag.length('spaceAfter'), bodySize), + bulletColor: + color(bag.color('bulletColor')) ?? + colors[PaletteKey.accent] ?? + bodyStyle.color, + columnGap: pt(bag.length('columnGap'), bodySize, 24), + rowGap: pt(bag.length('rowGap'), bodySize, 9), + ); + } + + ResolvedButton _button() { + final bag = layered(ThemeElement.button); + final accent = colors[PaletteKey.accent] ?? bodyStyle.color; + return ResolvedButton( + background: color(bag.color('background')) ?? accent, + color: color(bag.color('color')) ?? _pageColor, + secondaryBackground: + color(bag.color('secondaryBackground')) ?? + colors[PaletteKey.muted] ?? + bodyStyle.color, + secondaryColor: color(bag.color('secondaryColor')) ?? _pageColor, + borderRadius: pt(bag.length('borderRadius'), bodySize), + fontWeight: FontRegistry.snapWeight( + bodyStyle.fontFamily, + bag.integer('fontWeight') ?? 600, + ), + arrowColor: color(bag.color('arrowColor')) ?? accent, + arrowWeight: FontRegistry.snapWeight( + bodyStyle.fontFamily, + bag.integer('arrowWeight') ?? 600, + ), + ); + } + + ResolvedChip _chip() { + final bag = layered(ThemeElement.chip); + return ResolvedChip( + background: + color(bag.color('background')) ?? + colors[PaletteKey.codeBg] ?? + _pageColor, + color: color(bag.color('color')) ?? bodyStyle.color, + borderRadius: pt(bag.length('borderRadius'), bodySize, 200), + fontWeight: FontRegistry.snapWeight( + bodyStyle.fontFamily, + bag.integer('fontWeight') ?? 500, + ), + ); + } + + ResolvedStepBadge _stepBadge() { + final bag = layered(ThemeElement.stepBadge); + return ResolvedStepBadge( + background: + color(bag.color('background')) ?? + colors[PaletteKey.accent] ?? + bodyStyle.color, + color: color(bag.color('color')) ?? _pageColor, + sizeRatio: bag.number('sizeRatio') ?? 1.1, + ); + } + ResolvedPage _page() { final bag = base.page.merge(theme.page); return ResolvedPage( diff --git a/packages/wonky_write_core/lib/wonky_write_core.dart b/packages/wonky_write_core/lib/wonky_write_core.dart index c56703c2..00c694b1 100644 --- a/packages/wonky_write_core/lib/wonky_write_core.dart +++ b/packages/wonky_write_core/lib/wonky_write_core.dart @@ -9,6 +9,7 @@ export 'package:dart_quill_delta/dart_quill_delta.dart' show Delta, Operation; export 'src/delta/attributes.dart'; export 'src/delta/delta_utils.dart'; export 'src/delta/document.dart'; +export 'src/delta/boxes.dart'; export 'src/delta/embeds.dart'; export 'src/delta/hash.dart'; export 'src/delta/links.dart'; @@ -28,6 +29,7 @@ export 'src/markdown/inline_reader.dart' show mentionTitlePrefix; export 'src/markdown/inline_writer.dart'; export 'src/markdown/markdown_codec.dart'; export 'src/markdown/markdown_exporter.dart'; +export 'src/markdown/wonky_to_gfm.dart'; export 'src/markdown/markdown_importer.dart' show MarkdownImporter, RelativeImageResolver; export 'src/delta/delta_diff.dart'; diff --git a/packages/wonky_write_core/test/export/wonky_export_test.dart b/packages/wonky_write_core/test/export/wonky_export_test.dart new file mode 100644 index 00000000..3f736c75 --- /dev/null +++ b/packages/wonky_write_core/test/export/wonky_export_test.dart @@ -0,0 +1,156 @@ +import 'dart:convert'; + +import 'package:test/test.dart'; +import 'package:wonky_write_core/wonky_write_core.dart'; + +import 'export_support.dart'; + +/// Exports of Wonky Markdown elements (Write 11 §9). +void main() { + Delta wonky(String markdown) { + var n = 0; + return const MarkdownCodec() + .importMarkdown( + markdown, + options: ImportOptions( + flavor: MarkdownFlavor.wonky, + idGenerator: () => 'e${n++}', + ), + ) + .delta; + } + + const source = + '## (1) Define your model\n\n' + ':::card\n\nCard intro\n\n' + ':::warning[Heads up]\n\nCannot be undone.\n\n- one\n- two\n\n:::\n\n' + ':::details\n\n### How does it work?\n\nIt detects changes.\n\n:::\n\n' + ':::\n\n' + ':::grid{columns=3 bullets=check}\n\n- Migrations\n- Hot reload\n' + '- AI tooling\n- Fourth item\n\n:::\n\n' + ':button[Get started](https://example.com) ' + ':button[More](https://example.com/more){variant=secondary} ' + ':link[Docs](https://docs.example.com) :chip[Dart] :chip[Flutter]\n'; + + group('Given a document with nested containers, a grid, a numbered ' + 'heading, buttons and chips', () { + test('when exporting PDF then every text is drawn and the links are ' + 'kept', () async { + final a = await const PdfExporter( + compress: false, + ).export(input(wonky(source)), const PdfExportOptions()); + final text = latin1.decode(a.bytes); + + expect(text, startsWith('%PDF-1.4')); + expect(a.pageCount, 1); + // Standard fonts draw each word as its own string. + for (final word in [ + 'HEADS', + 'UP', + 'Cannot', + 'does', + 'detects', + 'Card', + 'Migrations', + 'Fourth', + 'started', + 'Dart', + 'Flutter', + 'Define', + ]) { + expect(text, contains('($word'), reason: word); + } + expect(text, contains('/URI(https://example.com)')); + expect(text, contains('/URI(https://example.com/more)')); + expect(text, contains('/URI(https://docs.example.com)')); + }); + + test('when exporting PDF with every built-in theme in light and dark ' + 'then it succeeds', () async { + for (final b in BuiltinThemes.all) { + for (final v in ThemeVariant.values) { + final a = await const PdfExporter().export( + input(wonky(source), theme: b.key, variant: v), + const PdfExportOptions(), + ); + expect(a.pageCount, greaterThan(0), reason: '${b.key} $v'); + } + } + }); + + test('when a container spans pages then the PDF paginates it', () async { + final long = StringBuffer(':::tip\n\n'); + for (var i = 0; i < 120; i++) { + long.write('Paragraph number $i in a long tip.\n\n'); + } + long.write(':::\n'); + final a = await const PdfExporter().export( + input(wonky(long.toString())), + const PdfExportOptions(), + ); + + expect(a.pageCount, greaterThan(1)); + }); + + test('when exporting DOCX then containers are shaded, the grid is a ' + 'table and the step number leads the heading', () async { + final a = await const DocxExporter().export( + input(wonky(source)), + const OfficeExportOptions(), + ); + final xml = utf8.decode( + DeterministicZip.decode(a.bytes)['word/document.xml']!, + ); + + expect(xml, contains('>1. <')); + expect(xml, contains('Heads up')); + expect(xml, contains('')); + expect(xml, contains('Fourth item')); + expect(xml, contains('Get started')); + expect(xml, contains('Dart')); + }); + + test('when exporting ODT then containers are shaded, the grid is a ' + 'table and the step number leads the heading', () async { + final a = await const OdtExporter().export( + input(wonky(source)), + const OfficeExportOptions(), + ); + final xml = utf8.decode(DeterministicZip.decode(a.bytes)['content.xml']!); + + expect(xml, contains('1. ')); + expect(xml, contains('Heads up')); + expect(xml, contains('fo:background-color')); + expect(xml, contains('? ids}) { + var n = 0; + return codec.importMarkdown( + md, + options: ImportOptions( + flavor: MarkdownFlavor.wonky, + idGenerator: () => + ids != null && n < ids.length ? ids[n++] : 'id-${n++}', + ), + ); + } + + String exportWonky(Delta d) => codec.exportMarkdown( + d, + options: const MarkdownExportOptions(flavor: MarkdownFlavor.wonky), + ); + + List> lines(Delta d) => [ + for (final l in WonkyDocument(d).lines) {'text': l.text, ...l.attributes}, + ]; + + group('Given the blog spec examples', () { + test('when importing inline directives then buttons, arrow links and ' + 'chips become styled text', () { + final d = importWonky( + ':button[Get started](https://example.com) ' + ':button[Read more](https://example.com){variant=secondary} ' + ':link[Docs](https://docs.serverpod.dev/) ' + ':chip[Facebook] :chip[Google]{icon=google}\n', + ).delta; + + expect(d.toJson(), [ + { + 'insert': 'Get started', + 'attributes': {'link': 'https://example.com', 'linkStyle': 'button'}, + }, + {'insert': ' '}, + { + 'insert': 'Read more', + 'attributes': { + 'link': 'https://example.com', + 'linkStyle': 'buttonSecondary', + }, + }, + {'insert': ' '}, + { + 'insert': 'Docs', + 'attributes': { + 'link': 'https://docs.serverpod.dev/', + 'linkStyle': 'arrow', + }, + }, + {'insert': ' '}, + { + 'insert': 'Facebook', + 'attributes': {'chip': true}, + }, + {'insert': ' '}, + { + 'insert': 'Google', + 'attributes': {'chip': 'google'}, + }, + {'insert': '\n'}, + ]); + }); + + test('when importing a callout with a title then its lines carry the ' + 'callout frame', () { + final d = importWonky( + ':::warning[Heads up]\nThis action cannot be undone.\n:::\n', + ).delta; + + expect(lines(d), [ + { + 'text': 'This action cannot be undone.', + 'box': [ + { + 'id': 'id-0', + 'type': 'callout', + 'variant': 'warning', + 'title': 'Heads up', + }, + ], + }, + ]); + }); + + test('when importing details then the summary is the first line, a ' + 'level-3 heading', () { + final d = importWonky( + ':::details\n### How does hot reload work?\n\n' + 'Serverpod detects changes.\n:::\n', + ).delta; + const box = [ + {'id': 'id-0', 'type': 'details'}, + ]; + + expect(lines(d), [ + {'text': 'How does hot reload work?', 'header': 3, 'box': box}, + {'text': 'Serverpod detects changes.', 'box': box}, + ]); + }); + + test('when importing a grid then it becomes a grid embed', () { + final d = importWonky( + ':::grid{columns=3 bullets=check}\n- Automatic migrations\n' + '- Stateful hot reload\n- Integrated **AI** tooling\n:::\n', + ).delta; + + expect(WonkyDocument(d).lines.single.embed, isA()); + final grid = WonkyDocument(d).lines.single.embed! as GridEmbed; + expect(grid.columns, 3); + expect(grid.bullets, GridBullets.check); + expect(grid.items, [ + 'Automatic migrations', + 'Stateful hot reload', + 'Integrated **AI** tooling', + ]); + }); + + test('when importing a card with an arrow link then both survive', () { + final d = importWonky( + ':::card\nServerpod is an open-source backend framework.\n\n' + ':link[Get started](https://docs.serverpod.dev/)\n:::\n', + ).delta; + + final ls = WonkyDocument(d).lines; + expect(ls, hasLength(2)); + expect(Boxes.of(ls[0].attributes).single.type, BoxType.card); + expect(ls[1].segments.single.attributes, { + 'link': 'https://docs.serverpod.dev/', + 'linkStyle': 'arrow', + }); + }); + + test('when importing numbered headings then the numbers are steps', () { + final d = importWonky( + '## How it works\n\n### (1) Define your model\n\n' + '### (2) Run serverpod generate\n', + ).delta; + + expect(lines(d), [ + {'text': 'How it works', 'header': 2}, + {'text': 'Define your model', 'header': 3, 'step': 1}, + {'text': 'Run serverpod generate', 'header': 3, 'step': 2}, + ]); + }); + + test('when exporting them then the Markdown is the blog syntax', () { + const md = + ':::warning[Heads up]\n\nThis action cannot be undone.\n\n:::\n\n' + ':::details\n\n### How does hot reload work?\n\nIt detects changes.' + '\n\n:::\n\n' + ':::grid{columns=3 bullets=check}\n\n- Automatic migrations\n' + '- Stateful hot reload\n\n:::\n\n' + ':::card\n\nServerpod.\n\n:link[Get started](https://docs.serverpod.dev/)' + '\n\n:::\n\n' + '### (1) Define your model\n\n' + ':button[Go](https://example.com){variant=secondary} :chip[Dart]\n'; + + expect(exportWonky(importWonky(md).delta), md); + }); + }); + + group('Given nested containers', () { + const md = + ':::card\n\nIntro\n\n:::tip\n\n- One\n- Two\n\n:::\n\nOutro\n\n:::\n'; + + test('when importing then the inner lines carry both frames', () { + final d = importWonky(md).delta; + final paths = [ + for (final l in WonkyDocument(d).lines) + [for (final f in Boxes.of(l.attributes)) f.type.value], + ]; + + expect(paths, [ + ['card'], + ['card', 'callout'], + ['card', 'callout'], + ['card'], + ]); + expect(validator.validate(d).isValid, isTrue); + }); + + test('when exporting then the directives nest', () { + expect(exportWonky(importWonky(md).delta), md); + }); + + test('when building the IR then containers nest', () { + final tree = const DocTreeBuilder().fromDelta(importWonky(md).delta); + final card = tree.blocks.single as ContainerBlock; + + expect(card.type, BoxType.card); + expect(card.children, hasLength(3)); + expect((card.children[1] as ContainerBlock).children, hasLength(2)); + }); + }); + + group('Given GitHub-flavored import', () { + test('when the source has directives then they stay text', () { + final d = codec.importMarkdown(':::card\n:chip[x]\n:::\n').delta; + + expect( + InlineRun.plainText([ + for (final l in WonkyDocument(d).lines) InlineRun(l.text), + ]), + contains(':chip[x]'), + ); + expect( + WonkyDocument(d).lines.every((l) => Boxes.of(l.attributes).isEmpty), + isTrue, + ); + }); + }); + + group('Given text that looks like a directive', () { + final d = Delta() + ..insert(':::card') + ..insert('\n') + ..insert('see :chip[x] here') + ..insert('\n') + ..insert('(1) Not a step') + ..insert('\n', {'header': 2}); + + test( + 'when exporting Wonky Markdown then it is escaped and round-trips', + () { + final md = exportWonky(d); + + expect(md, contains(r'\:::card')); + expect(md, contains(r':chip\[x\]')); + expect(md, contains(r'## \(1) Not a step')); + expect(importWonky(md).delta, normalizer.normalize(d).document); + }, + ); + + test('when exporting GitHub Markdown then the directive text is escaped ' + 'too and the heading is not', () { + final md = codec.exportMarkdown(d); + + expect(md, contains(r'\:::card')); + expect(md, contains('## (1) Not a step')); + }); + }); + + group('Given a Wonky document exported as GitHub Markdown', () { + final d = importWonky( + ':::warning[Heads up]\n\nCareful.\n\n- a\n\n:::\n\n' + ':::grid{columns=2}\n\n- x\n- y\n\n:::\n\n' + '## (3) Step\n\n:button[Go](https://example.com) :chip[Tag]\n', + ).delta; + + test('then each element has its GFM form', () { + expect( + codec.exportMarkdown(d), + '> **Heads up**\n>\n> Careful.\n>\n> - a\n\n' + '- x\n- y\n\n' + '## (3) Step\n\n[Go](https://example.com) Tag\n', + ); + }); + + test('when converting the document then the change gives the same ' + 'GFM content and a valid document', () { + final change = WonkyToGfm.change(d); + final converted = d.compose(change); + + expect(validator.validate(converted).isValid, isTrue); + expect( + const DocTreeBuilder().fromDelta(converted).hasWonkyElements, + isFalse, + ); + expect(codec.exportMarkdown(converted), codec.exportMarkdown(d)); + }); + + test('then the inventory counts the elements', () { + final inv = WonkyToGfm.inventory(d); + + expect(inv.callouts, 1); + expect(inv.grids, 1); + expect(inv.steps, 1); + expect(inv.buttons, 1); + expect(inv.chips, 1); + expect(inv.details + inv.cards + inv.arrowLinks, 0); + }); + }); + + group('Given invalid Wonky attributes', () { + test('when normalizing then exclusions and limits are applied', () { + final d = Delta() + ..insert('a', {'chip': true, 'bold': true, 'link': 'https://x.com'}) + ..insert('b', {'linkStyle': 'button', 'italic': true}) + ..insert('c', { + 'linkStyle': 'arrow', + 'link': 'https://x.com', + 'code': true, + }) + ..insert('\n', {'header': 4, 'step': 2}) + ..insert('t') + ..insert('\n', { + 'box': [ + {'id': 'a', 'type': 'callout', 'variant': 'nope'}, + {'id': 'b', 'type': 'card', 'variant': 'info'}, + {'id': 'b', 'type': 'details'}, + {'id': 'c', 'type': 'callout', 'variant': 'tip', 'title': ' x]y '}, + ], + }); + + final r = normalizer.normalize(d); + + expect(r.document.toJson(), [ + { + 'insert': 'a', + 'attributes': {'chip': true}, + }, + { + 'insert': 'b', + 'attributes': {'italic': true}, + }, + { + 'insert': 'c', + 'attributes': {'link': 'https://x.com', 'linkStyle': 'arrow'}, + }, + { + 'insert': '\n', + 'attributes': {'header': 4}, + }, + {'insert': 't'}, + { + 'insert': '\n', + 'attributes': { + 'box': [ + {'id': 'b', 'type': 'card'}, + {'id': 'c', 'type': 'callout', 'variant': 'tip', 'title': 'x)y'}, + ], + }, + }, + ]); + expect(validator.validate(r.document).isValid, isTrue); + expect(validator.validate(d).isValid, isFalse); + }); + + test('when an embed line carries a box then it is kept', () { + final d = Delta() + ..insert({ + 'divider': {'id': 'd1'}, + }) + ..insert('\n', { + 'box': [ + {'id': 'k', 'type': 'card'}, + ], + }); + + expect(normalizer.normalize(d).document, d); + expect(validator.validate(d).isValid, isTrue); + }); + + test('when a list continues into another container then its indent ' + 'restarts', () { + final d = Delta() + ..insert('a') + ..insert('\n', {'list': 'bullet'}) + ..insert('b') + ..insert('\n', { + 'list': 'bullet', + 'indent': 1, + 'box': [ + {'id': 'k', 'type': 'card'}, + ], + }); + + final out = normalizer.normalize(d).document; + + expect(Attributes.block(WonkyDocument(out).lines[1].attributes), { + 'list': 'bullet', + 'box': [ + {'id': 'k', 'type': 'card'}, + ], + }); + }); + }); + + group('Given a callout in a document', () { + final doc = importWonky(':::tip\n\nFirst\n\n:::\n').delta; + + test('when inserting Markdown blocks at its end then they go into it', () { + final edits = DocumentEdits(flavor: MarkdownFlavor.wonky); + final at = WonkyDocument(doc).lines.first.newlineOffset; + + final r = edits.insertMarkdown(doc, at, '- a\n- b\n'); + + final ls = WonkyDocument(r.document).lines; + expect(ls, hasLength(3)); + expect(ls.map((l) => Boxes.of(l.attributes).single.id).toSet(), {'id-0'}); + expect(ls[1].format.type, BlockType.bullet); + }); + + test('when inserting inline Markdown mid-line then it stays inline', () { + final edits = DocumentEdits(flavor: MarkdownFlavor.wonky); + + final r = edits.insertMarkdown(doc, 2, '**x**'); + + expect(WonkyDocument(r.document).lines.single.text, 'Fixrst'); + }); + }); + + group('Given YouTube videos (Write 11 §2.3)', () { + test('when parsing YouTube URLs then the id and start time are found', () { + for (final (url, start) in [ + ('https://www.youtube.com/watch?v=AGAQ_N56wCs', null), + ('https://youtu.be/AGAQ_N56wCs?t=90', 90), + ('youtube.com/watch?v=AGAQ_N56wCs&t=1m30s', 90), + ('https://www.youtube.com/embed/AGAQ_N56wCs?start=5', 5), + ('https://m.youtube.com/shorts/AGAQ_N56wCs', null), + ('https://www.youtube-nocookie.com/embed/AGAQ_N56wCs', null), + ('AGAQ_N56wCs', null), + ]) { + expect(YouTubeEmbed.parseUrl(url), ( + videoId: 'AGAQ_N56wCs', + start: start, + ), reason: url); + } + expect(YouTubeEmbed.parseUrl('https://vimeo.com/123'), isNull); + expect(YouTubeEmbed.parseUrl('https://youtu.be/short'), isNull); + }); + + test('when importing ::youtube then it becomes an embed that exports ' + 'the same way', () { + const md = '::youtube[Launch talk]{id=AGAQ_N56wCs start=90}\n'; + final d = importWonky(md, ids: ['v1']).delta; + expect(d.operations.first.data, { + 'youtube': { + 'id': 'v1', + 'videoId': 'AGAQ_N56wCs', + 'start': 90, + 'title': 'Launch talk', + }, + }); + expect(exportWonky(d), md); + expect(validator.validate(d).isValid, isTrue); + }); + + test('when the id is invalid then the line stays as text with a ' + 'warning', () { + final r = importWonky('::youtube{id=nope}\n'); + expect(r.delta, Delta()..insert('::youtube{id=nope}\n')); + expect(r.warnings, isNotEmpty); + }); + + test('when text starts with "::youtube" then it is escaped', () { + final d = Delta()..insert('::youtube{id=AGAQ_N56wCs}\n'); + final md = exportWonky(d); + expect(md, startsWith(r'\:')); + expect(importWonky(md).delta, d); + }); + + test( + 'when converting to GitHub Markdown then it is a link to the video', + () { + final d = importWonky( + '::youtube{id=AGAQ_N56wCs start=90}\n', + ids: ['v1'], + ).delta; + expect(WonkyToGfm.inventory(d).videos, 1); + expect( + d.compose(WonkyToGfm.change(d)), + Delta() + ..insert('https://www.youtube.com/watch?v=AGAQ_N56wCs&t=90s', { + 'link': 'https://www.youtube.com/watch?v=AGAQ_N56wCs&t=90s', + }) + ..insert('\n'), + ); + }, + ); + }); + + group('Given random Wonky documents', () { + propertyTest('when exporting and importing Wonky Markdown then the delta ' + 'round-trips', (random, _) { + checkWonkyRoundTrip( + DeltaGen( + random, + options: const DeltaGenOptions(wonky: true), + ).document(), + ); + }, runs: 300); + + propertyTest('when normalizing a change on its lines then it equals ' + 'normalizing it on the whole document', (random, _) { + final gen = DeltaGen(random, options: const DeltaGenOptions(wonky: true)); + final doc = gen.document(); + final change = EditGen(random, deltaGen: gen).change(doc); + + expect( + normalizer.normalizedChange(doc, change), + normalizer.normalizeChange(doc, change).change, + reason: 'doc: ${doc.toJson()}\nchange: ${change.toJson()}', + ); + }, runs: 200); + + propertyTest('when converting to GitHub Markdown then the document is ' + 'valid and has no Wonky elements', (random, _) { + final doc = DeltaGen( + random, + options: const DeltaGenOptions(wonky: true, overlays: true), + ).document(); + final converted = doc.compose(WonkyToGfm.change(doc)); + + expect(validator.validate(converted).issues, isEmpty); + expect(WonkyToGfm.inventory(converted).isEmpty, isTrue); + }, runs: 200); + + propertyTest('when normalizing then the result is valid and normalizing ' + 'again changes nothing', (random, _) { + final raw = DeltaGen( + random, + options: const DeltaGenOptions(wonky: true, overlays: true), + ).rawDocument(); + final once = normalizer.normalize(raw).document; + + expect(validator.validate(once).issues, isEmpty); + expect(normalizer.normalize(once).document, once); + }, runs: 200); + }); +} + +/// `import(export(D, wonky), wonky) == normalize(D)` (Write 11 §5.4), with +/// container and embed ids replayed in import order. +void checkWonkyRoundTrip(Delta d) { + const codec = MarkdownCodec(); + final normalized = const WonkyDeltaNormalizer().normalize(d).document; + final ids = []; + var prevPath = const []; + for (final line in WonkyDocument(normalized).lines) { + final path = Boxes.of(line.attributes); + for (var k = Boxes.commonDepth(prevPath, path); k < path.length; k++) { + ids.add(path[k].id); + } + prevPath = path; + if (line.embed case final e?) ids.add(e.id); + } + var next = 0; + + final markdown = codec.exportMarkdown( + normalized, + options: const MarkdownExportOptions(flavor: MarkdownFlavor.wonky), + ); + final back = codec.importMarkdown( + markdown, + options: ImportOptions( + flavor: MarkdownFlavor.wonky, + idGenerator: () => next < ids.length ? ids[next++] : 'extra-${next++}', + ), + ); + + expect( + back.delta.toJson(), + equals(normalized.toJson()), + reason: 'Markdown:\n$markdown', + ); +} diff --git a/specs/18-publications-and-submissions.md b/specs/18-publications-and-submissions.md index ff7eec76..e016d4ad 100644 --- a/specs/18-publications-and-submissions.md +++ b/specs/18-publications-and-submissions.md @@ -269,13 +269,15 @@ check the signature, reject timestamps more than 5 minutes off and drop repeated "coverImage": "ast_0192…" }, "note": "Fixed the code samples, thanks!", "markdown": "# How we sped up our CI ×3\n\n…![Build graph](https://wonky.work/api/pub/v1/assets/ast_0192…)…", + "markdownFlavor": "gfm", "assets": [{ "id": "ast_0192…", "name": "build-graph.webp", "type": "image/webp", "bytes": 48213, "url": "https://wonky.work/api/pub/v1/assets/ast_0192…" }], "submittedBy": { "name": "Anna Berg", "wonkyUserId": "0191…" } } ``` -- `markdown` is the Write Markdown export (Write 07 §4) with suggestions as original, no front +- `markdown` is the Write Markdown export (Write 07 §4) in the document's flavor + (`markdownFlavor`: `gfm` or `wonky`, Write 11 §3.3) with suggestions as original, no front matter and no comments; `wonky-file://` images become asset URLs, `https://` images stay. - `fields.coverImage` is the asset id of the cover, which is always in `assets` (and a `submission_asset`, so the API key may download it). The cover is accepted when it is an diff --git a/specs/wonky_write/02-document-model.md b/specs/wonky_write/02-document-model.md index 3596a943..28b53bbb 100644 --- a/specs/wonky_write/02-document-model.md +++ b/specs/wonky_write/02-document-model.md @@ -4,7 +4,9 @@ The **canonical representation** of a Wonky Write document is a **Quill Delta** inserts only) that conforms to the **Wonky Delta Schema v1** below. Every attribute in the schema maps 1:1 to GitHub-Flavored Markdown (GFM) or to a non-printing collaboration overlay (comments, suggestions). The editor (`super_editor`) is a *view* of this Delta; Markdown is the -import/export format. +import/export format. A document in the second flavor, **Wonky Markdown** (the Serverpod blog's +directives), adds the attributes and the `grid` embed of +[11-wonky-markdown.md](11-wonky-markdown.md) §2, which map 1:1 to that flavor. Three representations, two converters each, all round-trip tested: diff --git a/specs/wonky_write/03-sync-protocol.md b/specs/wonky_write/03-sync-protocol.md index 2c3ad5ff..6a659481 100644 --- a/specs/wonky_write/03-sync-protocol.md +++ b/specs/wonky_write/03-sync-protocol.md @@ -164,7 +164,9 @@ or `getOps`). If the server is behind the stored revision (another history), the and offers the local state as a copy. ### 3.2 Integrity check -Every 200 revisions (and on demand in debug), client and server compare a SHA-256 of the +Every 200 revisions, once when a copy restored from the offline cache connects (it can have +drifted, e.g. after an op an older or newer server normalized differently than the client +predicted), and on demand in debug, client and server compare a SHA-256 of the canonical document JSON at a given revision (`Hash` message variant). Mismatch → client discards local document state (keeping the outbox as a recovery file), re-inits from a snapshot, and logs an error with the op range for diagnosis. diff --git a/specs/wonky_write/04-editor.md b/specs/wonky_write/04-editor.md index 6e363179..3e357093 100644 --- a/specs/wonky_write/04-editor.md +++ b/specs/wonky_write/04-editor.md @@ -8,6 +8,8 @@ shortcuts, undo behaviour, MCP exposure and acceptance criteria. The chrome arou [02-document-model.md](02-document-model.md) and sync and undo internals from [03-sync-protocol.md](03-sync-protocol.md). Both are authoritative; this spec never contradicts them. Where this spec needs something they do not define, it says so in §44 *Open points*. +The editing of Wonky Markdown elements (containers, grids, steps, buttons, chips, their +shortcuts and chrome) is in [11-wonky-markdown.md](11-wonky-markdown.md) §7. ## 1. Conventions @@ -362,6 +364,15 @@ undo step. ## 5. Caret navigation +The caret is as tall as the text beside it (1.2 em of the character before it, else after it, +on its baseline), not the whole line box with its leading or a taller run's line height +(super_editor patch SE-11): the same in plain text, in chips and buttons and at the end of a +line; remote carets match. At the end of a Wonky Markdown chip, button or arrow link → and ← +move the caret out of and back into the element without moving it; inside one it is drawn +right after the last glyph, before the pill's padding or the arrow (Write 11 §7.4). No caret is +drawn with an expanded selection (like desktop editors): a block selected while a grid or table +is edited in place showed a block-high caret beside it. + | Action | macOS | Win/Linux | |--------|-------|-----------| | Character left/right | ← / → | ← / → | @@ -1088,7 +1099,21 @@ selectable only as a whole. **In-place editing** (patch **SE-4**, `features/editor/tables/inline_table_editing.dart`, `write.table.editCell {nodeId?, row?, col?}`): clicking a cell (or Enter / F2 on a selected table) turns it into a text field holding the cell's **inline Markdown source**; other cells keep -their rendering. While a cell is edited the local selection (presence) is the table embed. +their rendering. While a cell is edited the local selection (presence) is the table embed, set +once the field has the focus: set while the document editor still had it (the field is built a +frame later), the editor took the text input back, so typing went to the editor, which moved its +caret before or after the table. Cells (rendered and edited) opt out of the editor's own +gestures (`DocumentGestureOptOut`, super_editor SE-14): its interactor wraps the document, so +without that a click in a cell also took the editor's focus and put its caret before or after +the table. +The cells share the field's tap region group, so pressing another cell is not a tap outside the +field (which would end editing and show the editor's selection for a moment): editing moves +straight to it. The click puts the field's caret where it was (the rendered offset mapped to the +source, skipping markup: `FieldClicks`), a double click selects the word there and a triple +click the text, counted from raw pointer events on the rendered cell and the field alike (the +field misses the click that created it, and on the web its own double click doesn't fire), the +selection kept against the field's late single click; the field uses the editor's selection +color. - Tab / Shift+Tab: next / previous cell (Tab selects the cell's text; Tab in the last cell appends a row). Enter: cell below; in the last row it appends a row. Shift+Enter: cell above. ↑ ↓: row above / below; ← → at the text edges: previous / next cell. Leaving the first or last cell (or diff --git a/specs/wonky_write/05-screens-menus-toolbar.md b/specs/wonky_write/05-screens-menus-toolbar.md index b927d9fa..06ace67a 100644 --- a/specs/wonky_write/05-screens-menus-toolbar.md +++ b/specs/wonky_write/05-screens-menus-toolbar.md @@ -10,6 +10,9 @@ defined there, §40). Shared shell structure is in [suite 03](../03-app-shell-and-navigation.md); components in [suite 02](../02-design-system.md). **No widget may call business logic directly** — every control is a `CommandButton`/`CommandMenuItem` bound to a command id (suite 08 §1.1). +The Wonky Markdown items (*File › Markdown flavor*, the Insert/Format groups, the *Insert +element* toolbar dropdown and the slash group, shown only in Wonky documents) are in +[11-wonky-markdown.md](11-wonky-markdown.md) §7.5. ## 1. Conventions diff --git a/specs/wonky_write/06-themes.md b/specs/wonky_write/06-themes.md index 879faa3a..b1dfaf22 100644 --- a/specs/wonky_write/06-themes.md +++ b/specs/wonky_write/06-themes.md @@ -10,7 +10,8 @@ HTML, DOCX, ODT, RTF, EPUB), so a document looks the same everywhere. Related specs: suite design system [../02-design-system.md](../02-design-system.md) (app tokens, `WonkyColorPicker`, `FontPicker`, `WonkyNumberStepper`), commands & undo [../08-commands-and-undo.md](../08-commands-and-undo.md) (domain `write.theme`), -MCP [../09-mcp.md](../09-mcp.md), editor [04-editor.md](04-editor.md), screens +MCP [../09-mcp.md](../09-mcp.md), editor [04-editor.md](04-editor.md), Wonky Markdown elements +[11-wonky-markdown.md](11-wonky-markdown.md) §8, screens & menus [05-screens-menus-toolbar.md](05-screens-menus-toolbar.md), exports [07-import-export-print.md](07-import-export-print.md). diff --git a/specs/wonky_write/07-import-export-print.md b/specs/wonky_write/07-import-export-print.md index af004916..c489b17d 100644 --- a/specs/wonky_write/07-import-export-print.md +++ b/specs/wonky_write/07-import-export-print.md @@ -6,6 +6,8 @@ setup** model, the shared **pagination engine** (used by PDF/print and by the ed mode), and **print preview / printing**. Related: canonical Delta schema and Markdown codec [02-document-model.md](02-document-model.md); +Wonky Markdown import/export and how every exporter renders its elements +[11-wonky-markdown.md](11-wonky-markdown.md) §5, §9; themes [06-themes.md](06-themes.md) (every exporter renders through `ResolvedWriteTheme`); editor Pages/Pageless rendering and paste handling [04-editor.md](04-editor.md); menus [05-screens-menus-toolbar.md](05-screens-menus-toolbar.md); drive import/export diff --git a/specs/wonky_write/09-mcp-and-ai.md b/specs/wonky_write/09-mcp-and-ai.md index 903c837f..3fe54ecd 100644 --- a/specs/wonky_write/09-mcp-and-ai.md +++ b/specs/wonky_write/09-mcp-and-ai.md @@ -9,6 +9,7 @@ outline, proofread). The shared transport, auth, scopes, conventions and `drive. rules are in [../10-ai-assistant.md](../10-ai-assistant.md). Related Write specs: Delta schema & Markdown codec [02-document-model.md](02-document-model.md), +Wonky Markdown (flavor, `write.set_markdown_flavor`, prompts) [11-wonky-markdown.md](11-wonky-markdown.md) §10, OT [03-sync-protocol.md](03-sync-protocol.md), editor [04-editor.md](04-editor.md), themes [06-themes.md](06-themes.md) (theme tools §12), page setup/export [07-import-export-print.md](07-import-export-print.md), comments/suggestions/history diff --git a/specs/wonky_write/11-wonky-markdown.md b/specs/wonky_write/11-wonky-markdown.md new file mode 100644 index 00000000..56ea8267 --- /dev/null +++ b/specs/wonky_write/11-wonky-markdown.md @@ -0,0 +1,501 @@ +# Write 11 · Wonky Markdown + +**Wonky Markdown** is a second Markdown flavor for Wonky Write documents: GitHub-Flavored +Markdown plus the directives of the Serverpod blog (`serverpod_website`, +`serverpod_website_server/doc/serverpod_markdown_spec.md`). A document is written in exactly +one flavor. **GitHub** (GFM, everything in [02](02-document-model.md)) is the default; in +**Wonky** mode the editor offers callouts, expandable details, cards, grids, buttons, arrow +links, chips and numbered headings, edits them visually, and reads and writes them as the +blog's directive syntax, so a Wonky document submitted to the blog +([../18-publications-and-submissions.md](../18-publications-and-submissions.md)) renders there +as it looks in Write. + +Status: in progress. This spec is the source of truth for the feature; the specs it extends +(02, 04, 05, 06, 07, 09, 18) link here instead of repeating it. + +## 1. Decisions + +| # | Decision | Reason | +|---|----------|--------| +| WM1 | The flavor is a **document setting** (`markdownFlavor`: `gfm` \| `wonky`, default `gfm`), a meta change like the language (05 §13.1): LWW, undoable in `write.meta`, editors only | The content depends on it; every collaborator, export and MCP client must agree on it | +| WM2 | Switching **Wonky → GitHub** asks first, then converts every Wonky element to its closest GFM form in the same undo step (§3.2) | A GFM document never carries content GFM cannot write | +| WM3 | Switching **GitHub → Wonky** changes no content | GFM is a subset of Wonky Markdown, except literal text that would now read as a directive, which the exporter escapes (§5.3) | +| WM4 | The syntax is **exactly the blog's** (§4), limits included; Write never writes Markdown the blog would render differently | Submissions must render on the blog as they look in Write | +| WM5 | Containers (callout, details, card) are a **`box` stack on every line** they contain, like a quote, not embeds; they nest (§2.2) | Their content stays ordinary editable lines: lists, code, images, tables and other containers inside work with every existing editing feature, OT, comments and suggestions | +| WM6 | The grid is an **embed** with inline-Markdown items, edited in place like a table | A grid lays items out side by side, which a vertical document layout of lines cannot show; an embed renders the real grid | +| WM7 | Button and arrow link are a **`linkStyle`** of a link; a chip is a **`chip`** text attribute | They are text with a look: labels stay editable inline, and the link popover sets the style | +| WM8 | Numbered headings store their **explicit number** (`step`), as the Markdown does; commands propose the next number | User decision; round-trips exactly | +| WM9 | The look comes from the **document theme** (new elements, §8); built-in themes get defaults close to the blog's, in light and dark | Themes, not formatting (01 §2) | +| WM10 | Chip icons (`{icon=…}`) are **kept but not shown** | Out of scope for the UI; keeping the value makes import → export lossless | +| WM11 | A **publication** can declare Wonky Markdown; documents started from its link begin in Wonky mode and submit Wonky Markdown | The Serverpod blog takes directives | + +## 2. Delta schema additions (Wonky Delta Schema v1, 02 §1) + +All additions are valid in documents of either flavor (the flavor is a setting, not a schema +version), so a flavor change racing with an edit never makes an op invalid. The UI only offers +them in Wonky mode, and the GFM exporter writes them in their GFM form (§3.2). + +### 2.1 Inline attributes + +| Attribute | Value | Markdown (Wonky) | Rules | +|-----------|-------|------------------|-------| +| `linkStyle` | `"arrow"` \| `"button"` \| `"buttonSecondary"` | `:link[label](url)` · `:button[label](url)` · `:button[label](url){variant=secondary}` | Only with `link` (not a mention link). The label is plain text: excludes `bold`, `italic`, `strike`, `code`, `mention` (like `code`, 02 §1.4 rule 3) | +| `chip` | `true`, or a `String` icon name `[a-z0-9-]{1,32}` | `:chip[label]` · `:chip[label]{icon=name}` | Plain text: excludes every other inline attribute, `link` included | + +Labels cannot contain `]` (blog grammar `[^\]]*`), so the exporter writes a `]` in a label as +`)` (§5.3); neither label holds a soft break (exported as a space). Adjacent runs with equal +attributes merge in the canonical Delta, so `:chip[A]:chip[B]` (no space) imports as one chip +`AB`; the blog writes chips with a space between them. + +### 2.2 Block attributes + +| Attribute | Value | Markdown (Wonky) | Rules | +|-----------|-------|------------------|-------| +| `box` | `[Frame, …]`, outermost first, 1–3 frames | `:::callout`/`:::details`/`:::card` … `:::` around the lines | On any line, embed lines included; next to every other block attribute | +| `step` | `int` 0–9999 | `## (n) Title` / `### (n) Title` | Only with `header: 2` or `header: 3` | + +A **Frame** is a map: + +| Key | Value | Notes | +|-----|-------|-------| +| `id` | String, UUIDv7 | Identity of the container; new containers get a fresh id | +| `type` | `"callout"` \| `"details"` \| `"card"` | | +| `variant` | `"info"` \| `"tip"` \| `"note"` \| `"warning"` \| `"caution"` \| `"danger"` | Callouts only (required); `caution` is the blog's alias of `warning` with its own label | +| `title` | String, single line, ≤ 200 chars, no `]` | Callouts only, optional (`:::warning[Heads up]`); plain text | + +**Containers are runs.** At depth *k*, consecutive lines whose frame *k* has the same `id` +(and the same frames 0…*k*−1) form one container. A container's properties are those of its +first line's frame; the other lines' copies are ignored by renderers and exporters (an OT race +can leave them stale; the next edit of the container rewrites all of them). An id that comes +back after other lines starts a second container. These rules make a box interpretable from +any lines without cross-line normalization, so the normalizer's per-line window (02 §1.4, +`normalizedChange`) still holds. + +**Details summary.** A details container's summary is its first line when that line is a +`header: 3` directly in it (not in a nested container); otherwise the summary is empty. The +importer moves the blog's summary (the first own `###` anywhere in the block) to the front. + +**Lists in containers.** A list run ends where the `box` path changes (indent and numbering +restart), like a quoted and an unquoted list (02 §1.2). + +**Quotes in containers** are allowed; a container cannot be inside a quote (a line with +`blockquote` keeps its `box`, and the quote is drawn inside the container). + +### 2.3 Block embeds `grid` and `youtube` + +| Embed | Value | Markdown (Wonky) | +|-------|-------|------------------| +| `grid` | `{"id", "columns": 1–4, "bullets": "check"\|"circle"\|"none", "items": [cellMarkdown, …]}` | `:::grid{columns=3 bullets=check}` + one `- item` line per item + `:::` | +| `youtube` | `{"id", "videoId": 11 chars [A-Za-z0-9_-], "start"?: seconds 0–360000, "title"?: single line ≤ 300 chars without `]`}` | `::youtube[Title]{id=AGAQ_N56wCs start=90}` (title and `start` optional) | + +The YouTube video is a Wonky extension of our own: the blog has no renderer for it yet +(`docs/blog-integration.md` describes the one it needs; existing posts embed `