From 4ae4d7e38f4bfb36632849851ab7c689e7ebdddc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 00:46:41 -0600 Subject: [PATCH 01/16] Add lossless round-trip with EditorJS 2.31 and harden parsing Opening a document saved by current EditorJS and saving it again lost data. Parse -> edit -> serialize now reproduces every block exactly. - Keep block id and tunes: read into BlockDocument.metadata (BlockMetadata) and written back. EditorController.blockIds holds the EditorJS ids; the new blockTunes getter exposes tunes. Both follow their block through update, move and undo/redo. - Keep unknown blocks: a block with no registered mapper, or whose mapper throws, becomes an UnknownBlock and is written back untouched. The viewer skips it without leaving a gap. - Keep backend-defined fields: TableBlock.stretched, ImageBlock.fileExtras, AttachesBlock.fileExtras, LinkToolMeta.extras. - Stamp version 2.31.7 (BlockDocument.editorJsVersion) instead of the hard-coded 2.19.0. - Read every mapper field through tolerant JsonReader helpers, so a mistyped value no longer throws a TypeError out of EditorJSView or EditorController.fromJson. The package version is not bumped: notes are under [Unreleased] in CHANGELOG.md and the bump to 1.0.0 happens on the release branch. Co-Authored-By: Claude --- CHANGELOG.md | 24 ++ CLAUDE.md | 4 +- README.md | 2 + lib/editorjs_flutter.dart | 2 + .../datasources/json_document_source.dart | 99 ++++-- lib/src/data/mappers/attaches_mapper.dart | 22 +- lib/src/data/mappers/checklist_mapper.dart | 16 +- lib/src/data/mappers/code_mapper.dart | 3 +- lib/src/data/mappers/embed_mapper.dart | 22 +- lib/src/data/mappers/header_mapper.dart | 7 +- lib/src/data/mappers/image_mapper.dart | 16 +- lib/src/data/mappers/link_tool_mapper.dart | 29 +- lib/src/data/mappers/list_mapper.dart | 19 +- lib/src/data/mappers/paragraph_mapper.dart | 3 +- lib/src/data/mappers/quote_mapper.dart | 7 +- lib/src/data/mappers/raw_mapper.dart | 3 +- lib/src/data/mappers/table_mapper.dart | 14 +- lib/src/data/mappers/warning_mapper.dart | 5 +- lib/src/data/utils/json_reader.dart | 50 +++ lib/src/domain/entities/block_document.dart | 37 ++- lib/src/domain/entities/block_metadata.dart | 20 ++ .../entities/blocks/attaches_block.dart | 6 + .../domain/entities/blocks/image_block.dart | 7 +- .../entities/blocks/link_tool_block.dart | 13 +- .../domain/entities/blocks/table_block.dart | 5 + .../domain/entities/blocks/unknown_block.dart | 20 ++ .../blocks/table/table_editor.dart | 1 + .../controller/editor_controller.dart | 112 +++++-- .../registry/block_renderer_registry.dart | 10 +- .../presentation/widgets/editorjs_view.dart | 15 +- .../unit/editor_controller_metadata_test.dart | 131 ++++++++ test/unit/editor_controller_test.dart | 7 +- test/unit/json_document_source_test.dart | 9 +- test/unit/json_reader_test.dart | 68 ++++ test/unit/lossless_roundtrip_test.dart | 301 ++++++++++++++++++ test/widget/unknown_block_test.dart | 104 ++++++ 36 files changed, 1048 insertions(+), 165 deletions(-) create mode 100644 lib/src/data/utils/json_reader.dart create mode 100644 lib/src/domain/entities/block_metadata.dart create mode 100644 lib/src/domain/entities/blocks/unknown_block.dart create mode 100644 test/unit/editor_controller_metadata_test.dart create mode 100644 test/unit/json_reader_test.dart create mode 100644 test/unit/lossless_roundtrip_test.dart create mode 100644 test/widget/unknown_block_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d507ce..c652bb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,27 @@ +## [Unreleased] — towards 1.0.0 + +### Lossless round-trip with current EditorJS (2.31) +* **Block ids and tunes are preserved.** `id` and `tunes` are read into the new `BlockDocument.metadata` (`BlockMetadata`) and written back on serialize. `EditorController.blockIds` now holds the EditorJS ids (kept from the document, generated in EditorJS's own 10-character format for new blocks) and the new `EditorController.blockTunes` exposes each block's tunes. Both follow their block through update, move and undo/redo. +* **Unknown blocks are no longer deleted.** A block with no registered mapper — or whose mapper throws — is kept verbatim as the new `UnknownBlock` entity and written back untouched. The viewer skips it (without leaving a gap) and the editor shows the existing "Unsupported block" placeholder. +* **Backend-defined fields survive.** `TableBlock.stretched`, `ImageBlock.fileExtras`, `AttachesBlock.fileExtras` and `LinkToolMeta.extras` carry fields such as image `width`/`height` or link `site_name` through a round-trip. +* **Version stamp updated.** `getContent()` writes `"version": "2.31.7"` (`BlockDocument.editorJsVersion`) instead of the hard-coded `2.19.0`. + +### Parser hardening +* A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. +* `time` accepts integers, doubles and numeric strings; header `level` accepts doubles. + +### Behaviour changes +* `BlockDocument.blocks`, `EditorController.blocks` and `blockCount` now include `UnknownBlock`s for unrecognised types, where such blocks used to be dropped. +* `EditorController.blockIds` values are EditorJS-style ids rather than `b0`, `b1`, … +* `getContent()` output now contains `id` on every block, `tunes` where present, and `stretched` on tables. +* `BlockRendererRegistry.buildRenderer` / `buildEditor` return `null` for an `UnknownBlock` even when a builder is registered for its type string. +* Blocks with a missing or non-string `type` are still dropped: they cannot be written back. + +### Tests +* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart` and `test/widget/unknown_block_test.dart` (281 tests in total, 88 % line coverage). + +--- + ## [0.5.0] - 2026-03-25 — Publication readiness ### New API diff --git a/CLAUDE.md b/CLAUDE.md index 4e92a59..6d028b0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -134,8 +134,8 @@ final config = EditorConfig( - **Controller**: `EditorController` - **Config**: `EditorConfig` - **Registries**: `BlockTypeRegistry`, `BlockRendererRegistry` -- **Contracts** (for custom block authors): `BlockMapper`, `BlockRenderer`, `BlockEditor`, `BlockEntity`, `BlockDocument`, `StyleConfig` -- **Built-in entities**: `HeaderBlock`, `ParagraphBlock`, `ListBlock`, `DelimiterBlock`, `ImageBlock` +- **Contracts** (for custom block authors): `BlockMapper`, `BlockRenderer`, `BlockEditor`, `BlockEntity`, `BlockDocument`, `BlockMetadata`, `StyleConfig` +- **Built-in entities**: `HeaderBlock`, `ParagraphBlock`, `ListBlock`, `DelimiterBlock`, `ImageBlock`, and the other block entities; `UnknownBlock` holds any block the package cannot interpret so it round-trips untouched Nothing from `lib/src/` should be imported directly by consumers. diff --git a/README.md b/README.md index c2e9f3b..85634df 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,8 @@ Load a previously saved JSON string directly: _controller = EditorController.fromJson(savedJsonString); ``` +Loading and saving is lossless: block ids, block tunes, and blocks from EditorJS plugins this package does not know are written back by `getContent()` exactly as they were read. Unknown blocks appear in the editor as an "Unsupported block" placeholder and are skipped by the viewer. + Or pass a parsed block list if you already have one: ```dart diff --git a/lib/editorjs_flutter.dart b/lib/editorjs_flutter.dart index 9dc6ce4..3b4f5e5 100644 --- a/lib/editorjs_flutter.dart +++ b/lib/editorjs_flutter.dart @@ -20,6 +20,7 @@ export 'src/presentation/blocks/base_block_editor.dart'; // Domain entities — needed for typed access in callbacks and custom blocks export 'src/domain/entities/block_entity.dart'; export 'src/domain/entities/block_document.dart'; +export 'src/domain/entities/block_metadata.dart'; export 'src/domain/entities/style_config.dart'; // Built-in block entities @@ -37,3 +38,4 @@ export 'src/domain/entities/blocks/embed_block.dart'; export 'src/domain/entities/blocks/link_tool_block.dart'; export 'src/domain/entities/blocks/attaches_block.dart'; export 'src/domain/entities/blocks/raw_block.dart'; +export 'src/domain/entities/blocks/unknown_block.dart'; diff --git a/lib/src/data/datasources/json_document_source.dart b/lib/src/data/datasources/json_document_source.dart index 0f834e2..4f8e75b 100644 --- a/lib/src/data/datasources/json_document_source.dart +++ b/lib/src/data/datasources/json_document_source.dart @@ -3,11 +3,20 @@ import 'dart:developer' as dev; import '../../domain/entities/block_document.dart'; import '../../domain/entities/block_entity.dart'; +import '../../domain/entities/block_metadata.dart'; +import '../../domain/entities/blocks/unknown_block.dart'; import '../../domain/repositories/document_repository.dart'; import '../registry/block_type_registry.dart'; +import '../utils/json_reader.dart'; /// Implements [DocumentRepository] using EditorJS JSON as the serialization format. +/// +/// Parsing is lossless for well-formed blocks: block ids and tunes are kept in +/// [BlockDocument.metadata], and a block that no mapper can read is kept +/// verbatim as an [UnknownBlock] instead of being discarded. class JsonDocumentSource implements DocumentRepository { + static const _logName = 'EditorJSFlutter'; + final BlockTypeRegistry registry; const JsonDocumentSource({required this.registry}); @@ -18,48 +27,74 @@ class JsonDocumentSource implements DocumentRepository { try { root = jsonDecode(jsonString) as Map; } on FormatException catch (_) { - return BlockDocument( - time: DateTime.now().millisecondsSinceEpoch, - version: '', - blocks: const [], - ); + return _emptyDocument(); } on TypeError catch (_) { - return BlockDocument( - time: DateTime.now().millisecondsSinceEpoch, - version: '', - blocks: const [], - ); + return _emptyDocument(); } - final rawBlocks = - root['blocks'] is List ? root['blocks'] as List : []; + final blocks = []; + final metadata = []; + + for (final raw in JsonReader.list(root['blocks'])) { + if (raw is! Map) continue; - final blocks = rawBlocks - .whereType>() - .map((b) { - final type = b['type'] is String ? b['type'] as String : ''; - final data = b['data'] is Map - ? b['data'] as Map - : {}; - final entity = registry.parse(type, data); - if (entity == null && type.isNotEmpty) { - dev.log( - 'Unknown block type ignored: "$type"', - name: 'EditorJSFlutter', - ); - } - return entity; - }) - .whereType() - .toList(); + // A block without a type cannot be rendered or written back. + final type = raw['type']; + if (type is! String || type.isEmpty) continue; + + final id = raw['id']; + final tunes = JsonReader.map(raw['tunes']); + + blocks.add(_parseBlock(type, JsonReader.map(raw['data']) ?? {})); + metadata.add(BlockMetadata( + id: id is String && id.isNotEmpty ? id : null, + tunes: tunes != null && tunes.isNotEmpty ? tunes : null, + )); + } return BlockDocument( - time: (root['time'] as int?) ?? DateTime.now().millisecondsSinceEpoch, - version: (root['version'] as String?) ?? '', + time: _readTime(root['time']), + version: JsonReader.string(root['version']), blocks: blocks, + metadata: metadata, ); } + BlockEntity _parseBlock(String type, Map data) { + try { + final entity = registry.parse(type, data); + if (entity != null) return entity; + dev.log( + 'Unknown block type "$type" kept as-is (not rendered)', + name: _logName, + ); + } catch (error, stackTrace) { + // Mappers are an extension point, so anything can be thrown here. + // One unreadable block must never take the whole document down. + dev.log( + 'Block "$type" could not be parsed and was kept as-is (not rendered)', + name: _logName, + error: error, + stackTrace: stackTrace, + ); + } + return UnknownBlock(type: type, data: data); + } + + static int _readTime(dynamic value) { + final parsed = switch (value) { + String v => int.tryParse(v), + _ => JsonReader.integer(value), + }; + return parsed ?? DateTime.now().millisecondsSinceEpoch; + } + + static BlockDocument _emptyDocument() => BlockDocument( + time: DateTime.now().millisecondsSinceEpoch, + version: '', + blocks: const [], + ); + @override String serialize(BlockDocument document) => jsonEncode(document.toJson()); } diff --git a/lib/src/data/mappers/attaches_mapper.dart b/lib/src/data/mappers/attaches_mapper.dart index 1a8e0f5..168d9d3 100644 --- a/lib/src/data/mappers/attaches_mapper.dart +++ b/lib/src/data/mappers/attaches_mapper.dart @@ -1,27 +1,25 @@ import '../../domain/entities/blocks/attaches_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class AttachesMapper implements BlockMapper { const AttachesMapper(); + static const _knownFileKeys = {'url', 'name', 'extension', 'size'}; + @override String get supportedType => 'attaches'; @override AttachesBlock fromJson(Map data) { - final file = data['file'] is Map ? data['file'] as Map : null; + final file = JsonReader.map(data['file']); return AttachesBlock( - url: file != null && file['url'] is String ? file['url'] as String : '', - name: file != null && file['name'] is String ? file['name'] as String : null, - extension: file != null && file['extension'] is String - ? file['extension'] as String - : null, - size: switch (file?['size']) { - int v => v, - num v => v.toInt(), - _ => null, - }, - title: data['title'] is String ? data['title'] as String : null, + url: JsonReader.string(file?['url']), + name: JsonReader.nullableString(file?['name']), + extension: JsonReader.nullableString(file?['extension']), + size: JsonReader.integer(file?['size']), + title: JsonReader.nullableString(data['title']), + fileExtras: JsonReader.extras(file, _knownFileKeys), ); } } diff --git a/lib/src/data/mappers/checklist_mapper.dart b/lib/src/data/mappers/checklist_mapper.dart index 03362cb..09a5ef3 100644 --- a/lib/src/data/mappers/checklist_mapper.dart +++ b/lib/src/data/mappers/checklist_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/checklist_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class ChecklistMapper implements BlockMapper { @@ -9,15 +10,14 @@ class ChecklistMapper implements BlockMapper { @override ChecklistBlock fromJson(Map data) { - final rawItems = - data['items'] is List ? data['items'] as List : []; return ChecklistBlock( - items: rawItems.whereType>().map((i) { - return ChecklistItem( - text: i['text'] is String ? i['text'] as String : '', - checked: i['checked'] is bool ? i['checked'] as bool : false, - ); - }).toList(), + items: JsonReader.list(data['items']) + .whereType>() + .map((i) => ChecklistItem( + text: JsonReader.string(i['text']), + checked: JsonReader.boolean(i['checked']), + )) + .toList(), ); } } diff --git a/lib/src/data/mappers/code_mapper.dart b/lib/src/data/mappers/code_mapper.dart index bdbe2de..b4ee846 100644 --- a/lib/src/data/mappers/code_mapper.dart +++ b/lib/src/data/mappers/code_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/code_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class CodeMapper implements BlockMapper { @@ -9,5 +10,5 @@ class CodeMapper implements BlockMapper { @override CodeBlock fromJson(Map data) => - CodeBlock(code: (data['code'] as String?) ?? ''); + CodeBlock(code: JsonReader.string(data['code'])); } diff --git a/lib/src/data/mappers/embed_mapper.dart b/lib/src/data/mappers/embed_mapper.dart index dc1af0b..42f0098 100644 --- a/lib/src/data/mappers/embed_mapper.dart +++ b/lib/src/data/mappers/embed_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/embed_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class EmbedMapper implements BlockMapper { @@ -9,20 +10,11 @@ class EmbedMapper implements BlockMapper { @override EmbedBlock fromJson(Map data) => EmbedBlock( - service: data['service'] is String ? data['service'] as String : '', - source: data['source'] is String ? data['source'] as String : '', - embed: data['embed'] is String ? data['embed'] as String : '', - width: switch (data['width']) { - int v => v, - num v => v.toInt(), - _ => null, - }, - height: switch (data['height']) { - int v => v, - num v => v.toInt(), - _ => null, - }, - caption: - data['caption'] is String ? data['caption'] as String : null, + service: JsonReader.string(data['service']), + source: JsonReader.string(data['source']), + embed: JsonReader.string(data['embed']), + width: JsonReader.integer(data['width']), + height: JsonReader.integer(data['height']), + caption: JsonReader.nullableString(data['caption']), ); } diff --git a/lib/src/data/mappers/header_mapper.dart b/lib/src/data/mappers/header_mapper.dart index 8fa6e0b..9148372 100644 --- a/lib/src/data/mappers/header_mapper.dart +++ b/lib/src/data/mappers/header_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/header_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class HeaderMapper implements BlockMapper { @@ -9,9 +10,7 @@ class HeaderMapper implements BlockMapper { @override HeaderBlock fromJson(Map data) => HeaderBlock( - text: data['text'] is String - ? data['text'] as String - : (data['text']?.toString() ?? ''), - level: data['level'] is int ? data['level'] as int : 1, + text: JsonReader.string(data['text']), + level: JsonReader.integer(data['level']) ?? 1, ); } diff --git a/lib/src/data/mappers/image_mapper.dart b/lib/src/data/mappers/image_mapper.dart index 85a79c8..9af55e7 100644 --- a/lib/src/data/mappers/image_mapper.dart +++ b/lib/src/data/mappers/image_mapper.dart @@ -1,21 +1,25 @@ import '../../domain/entities/blocks/image_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class ImageMapper implements BlockMapper { const ImageMapper(); + static const _knownFileKeys = {'url'}; + @override String get supportedType => 'image'; @override ImageBlock fromJson(Map data) { - final file = data['file'] is Map ? data['file'] as Map : null; + final file = JsonReader.map(data['file']); return ImageBlock( - url: file != null && file['url'] is String ? file['url'] as String : '', - caption: data['caption'] is String ? data['caption'] as String : null, - withBorder: data['withBorder'] is bool ? data['withBorder'] as bool : false, - stretched: data['stretched'] is bool ? data['stretched'] as bool : false, - withBackground: data['withBackground'] is bool ? data['withBackground'] as bool : false, + url: JsonReader.string(file?['url']), + caption: JsonReader.nullableString(data['caption']), + withBorder: JsonReader.boolean(data['withBorder']), + stretched: JsonReader.boolean(data['stretched']), + withBackground: JsonReader.boolean(data['withBackground']), + fileExtras: JsonReader.extras(file, _knownFileKeys), ); } } diff --git a/lib/src/data/mappers/link_tool_mapper.dart b/lib/src/data/mappers/link_tool_mapper.dart index 423b6c5..7d10254 100644 --- a/lib/src/data/mappers/link_tool_mapper.dart +++ b/lib/src/data/mappers/link_tool_mapper.dart @@ -1,28 +1,33 @@ import '../../domain/entities/blocks/link_tool_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class LinkToolMapper implements BlockMapper { const LinkToolMapper(); + static const _knownMetaKeys = {'title', 'description', 'image'}; + @override String get supportedType => 'linkTool'; @override LinkToolBlock fromJson(Map data) { - final rawMeta = data['meta'] as Map?; - final rawImage = rawMeta?['image'] is Map ? rawMeta!['image'] as Map : null; - - final meta = rawMeta == null - ? null - : LinkToolMeta( - title: rawMeta['title'] as String?, - description: rawMeta['description'] as String?, - imageUrl: rawImage?['url'] as String?, - ); + // Some backends emit `"meta": []` for "no metadata" — treat any + // non-object value as absent rather than failing the whole block. + final rawMeta = JsonReader.map(data['meta']); return LinkToolBlock( - link: (data['link'] as String?) ?? '', - meta: meta, + link: JsonReader.string(data['link']), + meta: rawMeta == null + ? null + : LinkToolMeta( + title: JsonReader.nullableString(rawMeta['title']), + description: JsonReader.nullableString(rawMeta['description']), + imageUrl: JsonReader.nullableString( + JsonReader.map(rawMeta['image'])?['url'], + ), + extras: JsonReader.extras(rawMeta, _knownMetaKeys), + ), ); } } diff --git a/lib/src/data/mappers/list_mapper.dart b/lib/src/data/mappers/list_mapper.dart index de34781..2acaf54 100644 --- a/lib/src/data/mappers/list_mapper.dart +++ b/lib/src/data/mappers/list_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/list_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class ListMapper implements BlockMapper { @@ -9,28 +10,22 @@ class ListMapper implements BlockMapper { @override ListBlock fromJson(Map data) { - final styleStr = (data['style'] as String?) ?? 'unordered'; - final rawItems = (data['items'] as List?) ?? []; - return ListBlock( - style: styleStr == 'ordered' ? ListStyle.ordered : ListStyle.unordered, - items: rawItems.map(_parseItem).toList(), + style: + data['style'] == 'ordered' ? ListStyle.ordered : ListStyle.unordered, + items: JsonReader.list(data['items']).map(_parseItem).toList(), ); } /// Handles both flat string items (standard @editorjs/list) and /// nested object items (@editorjs/nested-list). ListItem _parseItem(dynamic raw) { - if (raw is String) { - return ListItem(content: raw); - } if (raw is Map) { - final nestedRaw = (raw['items'] as List?) ?? []; return ListItem( - content: (raw['content'] as String?) ?? '', - items: nestedRaw.map(_parseItem).toList(), + content: JsonReader.string(raw['content']), + items: JsonReader.list(raw['items']).map(_parseItem).toList(), ); } - return ListItem(content: raw.toString()); + return ListItem(content: JsonReader.string(raw)); } } diff --git a/lib/src/data/mappers/paragraph_mapper.dart b/lib/src/data/mappers/paragraph_mapper.dart index 629d195..e44330a 100644 --- a/lib/src/data/mappers/paragraph_mapper.dart +++ b/lib/src/data/mappers/paragraph_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/paragraph_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class ParagraphMapper implements BlockMapper { @@ -9,6 +10,6 @@ class ParagraphMapper implements BlockMapper { @override ParagraphBlock fromJson(Map data) => ParagraphBlock( - html: (data['text'] as String?) ?? '', + html: JsonReader.string(data['text']), ); } diff --git a/lib/src/data/mappers/quote_mapper.dart b/lib/src/data/mappers/quote_mapper.dart index c126aa4..47a5ec5 100644 --- a/lib/src/data/mappers/quote_mapper.dart +++ b/lib/src/data/mappers/quote_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/quote_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class QuoteMapper implements BlockMapper { @@ -9,10 +10,10 @@ class QuoteMapper implements BlockMapper { @override QuoteBlock fromJson(Map data) { - final alignStr = (data['alignment'] as String?) ?? 'left'; + final alignStr = data['alignment']; return QuoteBlock( - text: (data['text'] as String?) ?? '', - caption: data['caption'] as String?, + text: JsonReader.string(data['text']), + caption: JsonReader.nullableString(data['caption']), alignment: QuoteAlignment.values.firstWhere( (a) => a.name == alignStr, orElse: () => QuoteAlignment.left, diff --git a/lib/src/data/mappers/raw_mapper.dart b/lib/src/data/mappers/raw_mapper.dart index 668529c..1a6808e 100644 --- a/lib/src/data/mappers/raw_mapper.dart +++ b/lib/src/data/mappers/raw_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/raw_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class RawMapper implements BlockMapper { @@ -9,5 +10,5 @@ class RawMapper implements BlockMapper { @override RawBlock fromJson(Map data) => - RawBlock(html: (data['html'] as String?) ?? ''); + RawBlock(html: JsonReader.string(data['html'])); } diff --git a/lib/src/data/mappers/table_mapper.dart b/lib/src/data/mappers/table_mapper.dart index 4268c97..72a246e 100644 --- a/lib/src/data/mappers/table_mapper.dart +++ b/lib/src/data/mappers/table_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/table_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class TableMapper implements BlockMapper { @@ -9,14 +10,13 @@ class TableMapper implements BlockMapper { @override TableBlock fromJson(Map data) { - final rawContent = - data['content'] is List ? data['content'] as List : []; return TableBlock( - withHeadings: data['withHeadings'] is bool ? data['withHeadings'] as bool : false, - content: rawContent.map((row) { - final List rowList = row is List ? row : []; - return rowList.map((cell) => cell.toString()).toList(); - }).toList(), + withHeadings: JsonReader.boolean(data['withHeadings']), + stretched: JsonReader.boolean(data['stretched']), + content: JsonReader.list(data['content']) + .map((row) => + JsonReader.list(row).map((cell) => cell.toString()).toList()) + .toList(), ); } } diff --git a/lib/src/data/mappers/warning_mapper.dart b/lib/src/data/mappers/warning_mapper.dart index 08ef5ab..bcd9d0f 100644 --- a/lib/src/data/mappers/warning_mapper.dart +++ b/lib/src/data/mappers/warning_mapper.dart @@ -1,4 +1,5 @@ import '../../domain/entities/blocks/warning_block.dart'; +import '../utils/json_reader.dart'; import 'block_mapper.dart'; class WarningMapper implements BlockMapper { @@ -9,7 +10,7 @@ class WarningMapper implements BlockMapper { @override WarningBlock fromJson(Map data) => WarningBlock( - title: (data['title'] as String?) ?? '', - message: (data['message'] as String?) ?? '', + title: JsonReader.string(data['title']), + message: JsonReader.string(data['message']), ); } diff --git a/lib/src/data/utils/json_reader.dart b/lib/src/data/utils/json_reader.dart new file mode 100644 index 0000000..c835ac7 --- /dev/null +++ b/lib/src/data/utils/json_reader.dart @@ -0,0 +1,50 @@ +/// Tolerant readers for the loosely-typed values found in EditorJS JSON. +/// +/// Documents come from many backends and plugin versions, so a field is not +/// guaranteed to hold the type the EditorJS docs describe. These helpers never +/// throw: a value of the wrong shape yields the fallback instead. +class JsonReader { + JsonReader._(); + + /// Strings pass through; numbers and booleans are stringified. + static String string(dynamic value, {String fallback = ''}) => + switch (value) { + String v => v, + num v => v.toString(), + bool v => v.toString(), + _ => fallback, + }; + + static String? nullableString(dynamic value) => + value is String ? value : null; + + /// Integers pass through; finite doubles are truncated. + static int? integer(dynamic value) => switch (value) { + int v => v, + num v when v.isFinite => v.toInt(), + _ => null, + }; + + static bool boolean(dynamic value, {bool fallback = false}) => + value is bool ? value : fallback; + + static Map? map(dynamic value) => + value is Map ? value : null; + + static List list(dynamic value) => + value is List ? value : const []; + + /// Returns the entries of [source] whose keys are not in [knownKeys]. + /// + /// Used to carry backend-defined fields through a round-trip untouched. + static Map extras( + Map? source, + Set knownKeys, + ) { + if (source == null) return const {}; + return { + for (final entry in source.entries) + if (!knownKeys.contains(entry.key)) entry.key: entry.value, + }; + } +} diff --git a/lib/src/domain/entities/block_document.dart b/lib/src/domain/entities/block_document.dart index 796df98..42a1621 100644 --- a/lib/src/domain/entities/block_document.dart +++ b/lib/src/domain/entities/block_document.dart @@ -1,21 +1,52 @@ import 'block_entity.dart'; +import 'block_metadata.dart'; class BlockDocument { + /// The EditorJS release whose output format this package reads and writes. + /// Stamped into the `version` field of documents produced by the editor. + static const String editorJsVersion = '2.31.7'; + final int time; final String version; final List blocks; + /// Per-block envelope data (id, tunes), parallel to [blocks]. + /// + /// May be shorter than [blocks], or empty: a block without a matching entry + /// is serialized with no `id` and no `tunes`. + final List metadata; + const BlockDocument({ required this.time, required this.version, required this.blocks, + this.metadata = const [], }); + /// Returns the envelope data for the block at [index]. + BlockMetadata metadataAt(int index) => index >= 0 && index < metadata.length + ? metadata[index] + : BlockMetadata.none; + Map toJson() => { 'time': time, 'version': version, - 'blocks': blocks - .map((b) => {'type': b.type, 'data': b.toJson()}) - .toList(), + 'blocks': [ + for (var i = 0; i < blocks.length; i++) + _blockToJson(blocks[i], metadataAt(i)), + ], }; + + static Map _blockToJson( + BlockEntity block, + BlockMetadata metadata, + ) { + final tunes = metadata.tunes; + return { + if (metadata.id != null) 'id': metadata.id, + 'type': block.type, + 'data': block.toJson(), + if (tunes != null && tunes.isNotEmpty) 'tunes': tunes, + }; + } } diff --git a/lib/src/domain/entities/block_metadata.dart b/lib/src/domain/entities/block_metadata.dart new file mode 100644 index 0000000..9c53c7c --- /dev/null +++ b/lib/src/domain/entities/block_metadata.dart @@ -0,0 +1,20 @@ +/// Envelope-level attributes of an EditorJS block: everything that sits next +/// to `type` and `data` in the saved JSON rather than inside `data`. +/// +/// ```json +/// { "id": "aB3xK9pQ2z", "type": "paragraph", "data": {...}, "tunes": {...} } +/// ``` +class BlockMetadata { + /// The EditorJS block id (written by EditorJS 2.21 and later). + /// Null when the source document had none. + final String? id; + + /// Block Tunes data keyed by tune name (e.g. `{"alignment": {...}}`). + /// Null when the block carries no tunes. + final Map? tunes; + + const BlockMetadata({this.id, this.tunes}); + + /// Metadata for a block that has neither an id nor tunes. + static const BlockMetadata none = BlockMetadata(); +} diff --git a/lib/src/domain/entities/blocks/attaches_block.dart b/lib/src/domain/entities/blocks/attaches_block.dart index c58ad05..d95406f 100644 --- a/lib/src/domain/entities/blocks/attaches_block.dart +++ b/lib/src/domain/entities/blocks/attaches_block.dart @@ -10,12 +10,17 @@ class AttachesBlock extends BlockEntity { final String? title; + /// Any fields the upload backend stored in the `file` object besides + /// `url`, `name`, `extension` and `size`. Preserved on serialize. + final Map fileExtras; + const AttachesBlock({ required this.url, this.name, this.extension, this.size, this.title, + this.fileExtras = const {}, }); @override @@ -24,6 +29,7 @@ class AttachesBlock extends BlockEntity { @override Map toJson() => { 'file': { + ...fileExtras, 'url': url, if (name != null) 'name': name, if (extension != null) 'extension': extension, diff --git a/lib/src/domain/entities/blocks/image_block.dart b/lib/src/domain/entities/blocks/image_block.dart index a5d8606..cab0d2e 100644 --- a/lib/src/domain/entities/blocks/image_block.dart +++ b/lib/src/domain/entities/blocks/image_block.dart @@ -7,12 +7,17 @@ class ImageBlock extends BlockEntity { final bool stretched; final bool withBackground; + /// Any fields the upload backend stored in the `file` object besides `url` + /// (for example `width`, `height` or an asset id). Preserved on serialize. + final Map fileExtras; + const ImageBlock({ required this.url, this.caption, this.withBorder = false, this.stretched = false, this.withBackground = false, + this.fileExtras = const {}, }); @override @@ -20,7 +25,7 @@ class ImageBlock extends BlockEntity { @override Map toJson() => { - 'file': {'url': url}, + 'file': {...fileExtras, 'url': url}, 'caption': caption ?? '', 'withBorder': withBorder, 'stretched': stretched, diff --git a/lib/src/domain/entities/blocks/link_tool_block.dart b/lib/src/domain/entities/blocks/link_tool_block.dart index c4a3464..704ec9c 100644 --- a/lib/src/domain/entities/blocks/link_tool_block.dart +++ b/lib/src/domain/entities/blocks/link_tool_block.dart @@ -5,9 +5,20 @@ class LinkToolMeta { final String? description; final String? imageUrl; - const LinkToolMeta({this.title, this.description, this.imageUrl}); + /// Any fields the link-fetching backend returned besides `title`, + /// `description` and `image` (for example `site_name`). Preserved on + /// serialize. + final Map extras; + + const LinkToolMeta({ + this.title, + this.description, + this.imageUrl, + this.extras = const {}, + }); Map toJson() => { + ...extras, if (title != null) 'title': title, if (description != null) 'description': description, if (imageUrl != null) 'image': {'url': imageUrl}, diff --git a/lib/src/domain/entities/blocks/table_block.dart b/lib/src/domain/entities/blocks/table_block.dart index 36b0745..3bb7671 100644 --- a/lib/src/domain/entities/blocks/table_block.dart +++ b/lib/src/domain/entities/blocks/table_block.dart @@ -4,12 +4,16 @@ class TableBlock extends BlockEntity { /// Whether the first row is a header row. final bool withHeadings; + /// Whether the table is stretched to the full width of its container. + final bool stretched; + /// 2-D list: content[row][column]. Each cell is plain text; any HTML will be rendered literally. final List> content; const TableBlock({ required this.content, this.withHeadings = false, + this.stretched = false, }); @override @@ -18,6 +22,7 @@ class TableBlock extends BlockEntity { @override Map toJson() => { 'withHeadings': withHeadings, + 'stretched': stretched, 'content': content, }; } diff --git a/lib/src/domain/entities/blocks/unknown_block.dart b/lib/src/domain/entities/blocks/unknown_block.dart new file mode 100644 index 0000000..aac9f66 --- /dev/null +++ b/lib/src/domain/entities/blocks/unknown_block.dart @@ -0,0 +1,20 @@ +import '../block_entity.dart'; + +/// A block this package cannot interpret, kept verbatim so that it survives a +/// parse → edit → serialize round-trip. +/// +/// Produced for block types with no registered mapper (for example a custom +/// EditorJS plugin) and for blocks whose `data` a mapper could not read. +/// It is never rendered by the viewer and shows as a placeholder in the editor. +class UnknownBlock extends BlockEntity { + @override + final String type; + + /// The untouched `data` payload from the source document. + final Map data; + + const UnknownBlock({required this.type, required this.data}); + + @override + Map toJson() => data; +} diff --git a/lib/src/presentation/blocks/table/table_editor.dart b/lib/src/presentation/blocks/table/table_editor.dart index 6d02a8e..758c060 100644 --- a/lib/src/presentation/blocks/table/table_editor.dart +++ b/lib/src/presentation/blocks/table/table_editor.dart @@ -45,6 +45,7 @@ class _TableEditorState extends State { void _notify() { widget.onChanged(TableBlock( withHeadings: _withHeadings, + stretched: widget.block.stretched, content: _controllers .map((row) => row.map((c) => c.text).toList()) .toList(), diff --git a/lib/src/presentation/controller/editor_controller.dart b/lib/src/presentation/controller/editor_controller.dart index f2a3440..a70b347 100644 --- a/lib/src/presentation/controller/editor_controller.dart +++ b/lib/src/presentation/controller/editor_controller.dart @@ -1,17 +1,26 @@ +import 'dart:math'; + import 'package:flutter/foundation.dart'; import '../../data/datasources/json_document_source.dart'; import '../../data/registry/block_type_registry.dart'; import '../../domain/entities/block_document.dart'; import '../../domain/entities/block_entity.dart'; +import '../../domain/entities/block_metadata.dart'; import '../../domain/usecases/parse_document.dart'; import '../../domain/usecases/serialize_document.dart'; -/// A paired snapshot of block data and their stable IDs, used by undo/redo. +/// A snapshot of block data together with each block's id and tunes, used by +/// undo/redo. class _EditorSnapshot { final List blocks; final List ids; - _EditorSnapshot({required this.blocks, required this.ids}); + final List?> tunes; + _EditorSnapshot({ + required this.blocks, + required this.ids, + required this.tunes, + }); } /// Manages editor state as a list of [BlockEntity] objects. @@ -24,10 +33,20 @@ class _EditorSnapshot { /// [updateBlock] call replaces the block in place without creating a history /// entry, keeping the history lean during typing. class EditorController extends ChangeNotifier { + /// Same alphabet and length EditorJS uses for its own block ids. + static const String _idAlphabet = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'; + static const int _idLength = 10; + final List _blocks; final List _blockIds; + final List?> _blockTunes; final SerializeDocument _serializer; - int _idCounter = 0; + final Random _random = Random(); + + /// Every id handed out or loaded by this controller, including those of + /// removed blocks that undo could still bring back. + final Set _usedIds = {}; // --- Undo / redo history --- final List<_EditorSnapshot> _history = []; @@ -49,9 +68,12 @@ class EditorController extends ChangeNotifier { } /// Creates a controller pre-populated with blocks parsed from an EditorJS - /// JSON string. Unknown block types are silently dropped (logged via - /// `dart:developer`). If [jsonString] is empty or invalid JSON the - /// controller starts empty. + /// JSON string. + /// + /// The document round-trips losslessly: block ids and tunes are kept, and + /// blocks of an unregistered type are preserved as `UnknownBlock`s (shown as + /// a placeholder in the editor) and written back untouched by [getContent]. + /// If [jsonString] is empty or invalid JSON the controller starts empty. factory EditorController.fromJson( String jsonString, { BlockTypeRegistry? typeRegistry, @@ -61,29 +83,42 @@ class EditorController extends ChangeNotifier { final document = ParseDocument(source)(jsonString); return EditorController._internal( initialBlocks: document.blocks, + initialMetadata: document.metadata, serializer: SerializeDocument(source), ); } EditorController._internal({ List? initialBlocks, + List initialMetadata = const [], required SerializeDocument serializer, }) : _blocks = List.from(initialBlocks ?? []), _blockIds = [], + _blockTunes = [], _serializer = serializer { - // Assign initial IDs for (var i = 0; i < _blocks.length; i++) { - _blockIds.add(_nextId()); + final metadata = + i < initialMetadata.length ? initialMetadata[i] : BlockMetadata.none; + final id = metadata.id; + // Keep the document's own id; mint one when it is missing or (in a + // corrupt document) repeated, since ids double as widget keys. + _blockIds.add(id != null && _usedIds.add(id) ? id : _nextId()); + _blockTunes.add(metadata.tunes); } _saveSnapshot(); // record the initial state as snapshot 0 } - /// Generates a short ID that is unique within this controller's lifetime. - /// - /// IDs are intentionally scoped to a single [EditorController] instance — - /// they are used only as Flutter [ValueKey]s within the same widget subtree - /// and do not need to be globally unique or persistent across sessions. - String _nextId() => 'b${_idCounter++}'; + /// Generates an EditorJS-style block id that is unique within this + /// controller's lifetime. + String _nextId() { + while (true) { + final id = String.fromCharCodes(Iterable.generate( + _idLength, + (_) => _idAlphabet.codeUnitAt(_random.nextInt(_idAlphabet.length)), + )); + if (_usedIds.add(id)) return id; + } + } // --------------------------------------------------------------------------- // History @@ -95,7 +130,7 @@ class EditorController extends ChangeNotifier { /// Whether there is a forward state to restore after an undo. bool get canRedo => _historyIndex < _history.length - 1; - /// Saves the current block list and IDs as a history snapshot. + /// Saves the current block list, IDs and tunes as a history snapshot. /// /// Any snapshots ahead of [_historyIndex] (from a prior undo) are discarded. /// The block list is stored as an unmodifiable copy so that mutable @@ -108,6 +143,7 @@ class EditorController extends ChangeNotifier { _history.add(_EditorSnapshot( blocks: List.unmodifiable(_blocks), ids: List.unmodifiable(_blockIds), + tunes: List?>.unmodifiable(_blockTunes), )); if (_history.length > _maxHistorySize) { _history.removeAt(0); @@ -119,27 +155,26 @@ class EditorController extends ChangeNotifier { void undo() { if (!canUndo) return; _historyIndex--; - final snapshot = _history[_historyIndex]; - _blocks - ..clear() - ..addAll(snapshot.blocks); - _blockIds - ..clear() - ..addAll(snapshot.ids); - notifyListeners(); + _restore(_history[_historyIndex]); } /// Restores the next snapshot after an undo, if any. void redo() { if (!canRedo) return; _historyIndex++; - final snapshot = _history[_historyIndex]; + _restore(_history[_historyIndex]); + } + + void _restore(_EditorSnapshot snapshot) { _blocks ..clear() ..addAll(snapshot.blocks); _blockIds ..clear() ..addAll(snapshot.ids); + _blockTunes + ..clear() + ..addAll(snapshot.tunes); notifyListeners(); } @@ -150,18 +185,30 @@ class EditorController extends ChangeNotifier { /// Unmodifiable view of the current block list. List get blocks => List.unmodifiable(_blocks); - /// Unmodifiable view of stable per-block IDs, parallel to [blocks]. + /// Unmodifiable view of the EditorJS block ids, parallel to [blocks]. + /// + /// Blocks loaded through [EditorController.fromJson] keep the id they had in + /// the document; every other block gets a freshly generated one. The ids are + /// written to the `id` field by [getContent]. /// - /// These IDs are stable across [updateBlock] calls and are preserved by + /// They are stable across [updateBlock] calls and are preserved by /// [undo]/[redo], making them suitable as Flutter widget keys to ensure /// State objects follow the correct block when the list is reordered. List get blockIds => List.unmodifiable(_blockIds); + /// Unmodifiable view of each block's Block Tunes data, parallel to [blocks]. + /// + /// An entry is `null` when the block has no tunes. Tunes are carried through + /// from the loaded document and written back by [getContent]; they follow + /// their block through [updateBlock], [moveBlock] and [undo]/[redo]. + List?> get blockTunes => List.unmodifiable(_blockTunes); + int get blockCount => _blocks.length; void addBlock(BlockEntity block) { _blocks.add(block); _blockIds.add(_nextId()); + _blockTunes.add(null); _saveSnapshot(); notifyListeners(); } @@ -169,6 +216,7 @@ class EditorController extends ChangeNotifier { void insertBlock(int index, BlockEntity block) { _blocks.insert(index, block); _blockIds.insert(index, _nextId()); + _blockTunes.insert(index, null); _saveSnapshot(); notifyListeners(); } @@ -177,7 +225,7 @@ class EditorController extends ChangeNotifier { /// /// Does NOT create a history snapshot — use this for live text updates. /// Structural changes (add, remove, move) are the undo boundaries. - /// The block's stable ID is preserved so that widget State objects bound + /// The block's id and tunes are preserved, so widget State objects bound /// via [blockIds] are not recreated on every keystroke. void updateBlock(int index, BlockEntity updated) { assert(index >= 0 && index < _blocks.length); @@ -189,6 +237,7 @@ class EditorController extends ChangeNotifier { assert(index >= 0 && index < _blocks.length); _blocks.removeAt(index); _blockIds.removeAt(index); + _blockTunes.removeAt(index); _saveSnapshot(); notifyListeners(); } @@ -200,6 +249,8 @@ class EditorController extends ChangeNotifier { _blocks.insert(toIndex, block); final id = _blockIds.removeAt(fromIndex); _blockIds.insert(toIndex, id); + final tunes = _blockTunes.removeAt(fromIndex); + _blockTunes.insert(toIndex, tunes); _saveSnapshot(); notifyListeners(); } @@ -207,6 +258,7 @@ class EditorController extends ChangeNotifier { void clear() { _blocks.clear(); _blockIds.clear(); + _blockTunes.clear(); _saveSnapshot(); notifyListeners(); } @@ -215,8 +267,12 @@ class EditorController extends ChangeNotifier { String getContent() { final document = BlockDocument( time: DateTime.now().millisecondsSinceEpoch, - version: '2.19.0', + version: BlockDocument.editorJsVersion, blocks: _blocks, + metadata: [ + for (var i = 0; i < _blocks.length; i++) + BlockMetadata(id: _blockIds[i], tunes: _blockTunes[i]), + ], ); return _serializer(document); } diff --git a/lib/src/presentation/registry/block_renderer_registry.dart b/lib/src/presentation/registry/block_renderer_registry.dart index e2da99e..0ef6086 100644 --- a/lib/src/presentation/registry/block_renderer_registry.dart +++ b/lib/src/presentation/registry/block_renderer_registry.dart @@ -10,6 +10,7 @@ import '../../domain/entities/blocks/list_block.dart'; import '../../domain/entities/blocks/paragraph_block.dart'; import '../../domain/entities/blocks/quote_block.dart'; import '../../domain/entities/blocks/table_block.dart'; +import '../../domain/entities/blocks/unknown_block.dart'; import '../../domain/entities/blocks/attaches_block.dart'; import '../../domain/entities/blocks/embed_block.dart'; import '../../domain/entities/blocks/link_tool_block.dart'; @@ -124,12 +125,19 @@ class BlockRendererRegistry { } /// Returns the renderer widget, or `null` for unregistered types. + /// + /// An [UnknownBlock] always yields `null`, even when its type string has a + /// registered builder: it holds raw data the builder's entity cast would + /// reject (this is how a block with unreadable `data` is represented). Widget? buildRenderer(BlockEntity block, StyleConfig? styleConfig) { + if (block is UnknownBlock) return null; return _renderers[block.type]?.call(block, styleConfig); } - /// Returns the editor widget, or `null` for unregistered types. + /// Returns the editor widget, or `null` for unregistered types and for + /// [UnknownBlock]s (see [buildRenderer]). Widget? buildEditor(BlockEntity block, ValueChanged onChanged) { + if (block is UnknownBlock) return null; return _editors[block.type]?.call(block, onChanged); } diff --git a/lib/src/presentation/widgets/editorjs_view.dart b/lib/src/presentation/widgets/editorjs_view.dart index e3b91bd..93ebb85 100644 --- a/lib/src/presentation/widgets/editorjs_view.dart +++ b/lib/src/presentation/widgets/editorjs_view.dart @@ -7,7 +7,7 @@ import '../config/editor_config.dart'; /// Read-only viewer for EditorJS JSON content. /// /// Parses [jsonData] and renders each block using the registered renderers. -/// Unknown block types are silently skipped. +/// Blocks without a registered renderer are skipped and take up no space. /// /// Example: /// ```dart @@ -28,15 +28,16 @@ class EditorJSView extends StatelessWidget { final source = JsonDocumentSource(registry: config.typeRegistry); final document = ParseDocument(source)(jsonData); + final rendered = [ + for (final block in document.blocks) + config.rendererRegistry.buildRenderer(block, config.styleConfig), + ].nonNulls; + return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - for (final block in document.blocks) ...[ - config.rendererRegistry.buildRenderer( - block, - config.styleConfig, - ) ?? - const SizedBox.shrink(), + for (final widget in rendered) ...[ + widget, const SizedBox(height: 8), ], ], diff --git a/test/unit/editor_controller_metadata_test.dart b/test/unit/editor_controller_metadata_test.dart new file mode 100644 index 0000000..0b97e9c --- /dev/null +++ b/test/unit/editor_controller_metadata_test.dart @@ -0,0 +1,131 @@ +import 'dart:convert'; + +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _document = ''' +{"blocks": [ + {"id": "first_id_1", "type": "header", "data": {"text": "A", "level": 1}, + "tunes": {"anchor": {"name": "intro"}}}, + {"id": "second_id2", "type": "paragraph", "data": {"text": "B"}}, + {"type": "delimiter", "data": {}} +]} +'''; + +final _idPattern = RegExp(r'^[A-Za-z0-9_-]{10}$'); + +List> _blocksOf(EditorController controller) => + ((jsonDecode(controller.getContent()) as Map)['blocks'] + as List) + .cast>(); + +void main() { + group('block ids', () { + test('ids from the document are kept', () { + final ctrl = EditorController.fromJson(_document); + expect(ctrl.blockIds[0], 'first_id_1'); + expect(ctrl.blockIds[1], 'second_id2'); + }); + + test('a block without an id gets an EditorJS-style one', () { + final ctrl = EditorController.fromJson(_document); + expect(ctrl.blockIds[2], matches(_idPattern)); + }); + + test('new blocks get unique EditorJS-style ids', () { + final ctrl = EditorController(); + for (var i = 0; i < 200; i++) { + ctrl.addBlock(const DelimiterBlock()); + } + ctrl.insertBlock(0, const DelimiterBlock()); + expect(ctrl.blockIds.toSet().length, 201); + expect(ctrl.blockIds.every(_idPattern.hasMatch), isTrue); + }); + + test('initialBlocks get ids too', () { + final ctrl = EditorController( + initialBlocks: const [DelimiterBlock(), DelimiterBlock()], + ); + expect(ctrl.blockIds.toSet().length, 2); + }); + + test('a repeated id in a corrupt document is replaced', () { + final ctrl = EditorController.fromJson(''' + {"blocks": [ + {"id": "dup", "type": "delimiter", "data": {}}, + {"id": "dup", "type": "delimiter", "data": {}} + ]} + '''); + expect(ctrl.blockIds[0], 'dup'); + expect(ctrl.blockIds[1], isNot('dup')); + }); + + test('getContent writes an id for every block', () { + final ctrl = EditorController.fromJson(_document) + ..addBlock(const ParagraphBlock(html: 'new')); + final blocks = _blocksOf(ctrl); + expect(blocks.map((b) => b['id']), ctrl.blockIds); + }); + + test('updateBlock keeps the id', () { + final ctrl = EditorController.fromJson(_document) + ..updateBlock(0, const HeaderBlock(text: 'Changed', level: 2)); + expect(ctrl.blockIds[0], 'first_id_1'); + }); + }); + + group('block tunes', () { + test('tunes from the document are exposed and written back', () { + final ctrl = EditorController.fromJson(_document); + expect(ctrl.blockTunes[0], { + 'anchor': {'name': 'intro'}, + }); + expect(ctrl.blockTunes[1], isNull); + + final blocks = _blocksOf(ctrl); + expect(blocks[0]['tunes'], { + 'anchor': {'name': 'intro'}, + }); + expect(blocks[1].containsKey('tunes'), isFalse); + }); + + test('tunes survive updateBlock', () { + final ctrl = EditorController.fromJson(_document) + ..updateBlock(0, const HeaderBlock(text: 'Changed', level: 2)); + expect(_blocksOf(ctrl)[0]['tunes'], isNotNull); + }); + + test('tunes follow their block through moveBlock', () { + final ctrl = EditorController.fromJson(_document)..moveBlock(0, 2); + expect(ctrl.blockTunes, [isNull, isNull, isNotNull]); + expect(ctrl.blockIds[2], 'first_id_1'); + }); + + test('tunes are removed with their block and restored by undo', () { + final ctrl = EditorController.fromJson(_document)..removeBlock(0); + expect(ctrl.blockTunes, [isNull, isNull]); + + ctrl.undo(); + expect(ctrl.blockTunes[0], isNotNull); + expect(ctrl.blockIds[0], 'first_id_1'); + + ctrl.redo(); + expect(ctrl.blockTunes, [isNull, isNull]); + }); + + test('new and inserted blocks start without tunes', () { + final ctrl = EditorController.fromJson(_document) + ..addBlock(const DelimiterBlock()) + ..insertBlock(0, const DelimiterBlock()); + expect(ctrl.blockTunes.first, isNull); + expect(ctrl.blockTunes.last, isNull); + expect(ctrl.blockTunes[1], isNotNull); + }); + + test('clear empties tunes and ids', () { + final ctrl = EditorController.fromJson(_document)..clear(); + expect(ctrl.blockTunes, isEmpty); + expect(ctrl.blockIds, isEmpty); + }); + }); +} diff --git a/test/unit/editor_controller_test.dart b/test/unit/editor_controller_test.dart index 828db29..5b436df 100644 --- a/test/unit/editor_controller_test.dart +++ b/test/unit/editor_controller_test.dart @@ -216,12 +216,13 @@ void main() { expect(ctrl.blockCount, 0); }); - test('unknown block types are silently dropped', () { + test('unknown block types are kept as UnknownBlock', () { const json = '{"blocks":[{"type":"unknown_xyz","data":{}},{"type":"header","data":{"text":"Known","level":1}}]}'; final ctrl = EditorController.fromJson(json); - expect(ctrl.blockCount, 1); - expect(ctrl.blocks.first, isA()); + expect(ctrl.blockCount, 2); + expect(ctrl.blocks.first, isA()); + expect(ctrl.blocks.last, isA()); }); test('multiple blocks parsed correctly', () { diff --git a/test/unit/json_document_source_test.dart b/test/unit/json_document_source_test.dart index 7a88f18..76e116a 100644 --- a/test/unit/json_document_source_test.dart +++ b/test/unit/json_document_source_test.dart @@ -35,7 +35,7 @@ void main() { expect(doc.blocks[1], isA()); }); - test('unknown block type is silently dropped, known blocks preserved', () { + test('unknown block type is kept verbatim as an UnknownBlock', () { const json = ''' { "time": 1610000000000, @@ -48,9 +48,12 @@ void main() { } '''; final doc = source.parse(json); - expect(doc.blocks.length, 2); + expect(doc.blocks.length, 3); expect(doc.blocks[0], isA()); - expect(doc.blocks[1], isA()); + final unknown = doc.blocks[1] as UnknownBlock; + expect(unknown.type, 'unknownCustomType'); + expect(unknown.data, {'foo': 'bar'}); + expect(doc.blocks[2], isA()); }); test('invalid JSON string returns empty BlockDocument without throwing', () { diff --git a/test/unit/json_reader_test.dart b/test/unit/json_reader_test.dart new file mode 100644 index 0000000..21ceafd --- /dev/null +++ b/test/unit/json_reader_test.dart @@ -0,0 +1,68 @@ +import 'package:editorjs_flutter/src/data/utils/json_reader.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('JsonReader.string', () { + test('passes strings through', () { + expect(JsonReader.string('abc'), 'abc'); + }); + + test('stringifies numbers and booleans', () { + expect(JsonReader.string(42), '42'); + expect(JsonReader.string(1.5), '1.5'); + expect(JsonReader.string(true), 'true'); + }); + + test('uses the fallback for null, maps and lists', () { + expect(JsonReader.string(null), ''); + expect(JsonReader.string({}), ''); + expect(JsonReader.string([], fallback: 'x'), 'x'); + }); + }); + + test('nullableString returns null for anything but a string', () { + expect(JsonReader.nullableString('a'), 'a'); + expect(JsonReader.nullableString(1), isNull); + expect(JsonReader.nullableString(null), isNull); + }); + + group('JsonReader.integer', () { + test('passes ints through and truncates doubles', () { + expect(JsonReader.integer(7), 7); + expect(JsonReader.integer(7.9), 7); + }); + + test('returns null for non-numbers and non-finite doubles', () { + expect(JsonReader.integer('7'), isNull); + expect(JsonReader.integer(null), isNull); + expect(JsonReader.integer(double.nan), isNull); + expect(JsonReader.integer(double.infinity), isNull); + }); + }); + + test('boolean falls back for non-bool values', () { + expect(JsonReader.boolean(true), isTrue); + expect(JsonReader.boolean('true'), isFalse); + expect(JsonReader.boolean(null, fallback: true), isTrue); + }); + + test('map and list reject values of the wrong shape', () { + expect(JsonReader.map({'a': 1}), {'a': 1}); + expect(JsonReader.map([]), isNull); + expect(JsonReader.list([1, 2]), [1, 2]); + expect(JsonReader.list('nope'), isEmpty); + }); + + group('JsonReader.extras', () { + test('keeps only the keys that are not known', () { + expect( + JsonReader.extras({'url': 'u', 'width': 800, 'id': 'x'}, {'url'}), + {'width': 800, 'id': 'x'}, + ); + }); + + test('returns an empty map for a null source', () { + expect(JsonReader.extras(null, {'url'}), isEmpty); + }); + }); +} diff --git a/test/unit/lossless_roundtrip_test.dart b/test/unit/lossless_roundtrip_test.dart new file mode 100644 index 0000000..0f0cb45 --- /dev/null +++ b/test/unit/lossless_roundtrip_test.dart @@ -0,0 +1,301 @@ +import 'dart:convert'; + +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/data/datasources/json_document_source.dart'; +import 'package:editorjs_flutter/src/data/mappers/attaches_mapper.dart'; +import 'package:editorjs_flutter/src/data/mappers/image_mapper.dart'; +import 'package:editorjs_flutter/src/data/mappers/link_tool_mapper.dart'; +import 'package:editorjs_flutter/src/data/mappers/table_mapper.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// A document in the shape EditorJS 2.31 writes: every block has an id, one +/// carries tunes, and one comes from a plugin this package does not know. +const _modernDocument = ''' +{ + "time": 1762700000000, + "version": "2.31.7", + "blocks": [ + {"id": "aB3xK9pQ2z", "type": "paragraph", "data": {"text": "Hello"}, + "tunes": {"alignment": {"alignment": "center"}}}, + {"id": "T1aaaaaaaa", "type": "table", "data": { + "withHeadings": true, "stretched": true, "content": [["a", "b"]]}}, + {"id": "I1aaaaaaaa", "type": "image", "data": { + "file": {"url": "https://x/y.png", "width": 800, "height": 600}, + "caption": "c", "withBorder": false, "stretched": false, + "withBackground": false}}, + {"id": "K1aaaaaaaa", "type": "linkTool", "data": { + "link": "https://codex.so", + "meta": {"title": "CodeX", "site_name": "CodeX", + "image": {"url": "https://x/i.png"}}}}, + {"id": "A1aaaaaaaa", "type": "attaches", "data": { + "file": {"url": "https://x/f.pdf", "size": 91, "name": "f.pdf", + "extension": "pdf", "assetId": 12}, + "title": "File"}}, + {"id": "U1aaaaaaaa", "type": "toggle", + "data": {"text": "custom plugin block", "items": [1, 2]}} + ] +} +'''; + +class _ThrowingMapper implements BlockMapper { + const _ThrowingMapper(); + + @override + String get supportedType => 'header'; + + @override + HeaderBlock fromJson(Map data) => + throw StateError('mapper bug'); +} + +void main() { + late JsonDocumentSource source; + + setUp(() => source = JsonDocumentSource(registry: BlockTypeRegistry())); + + List blocksOf(String json) => + (jsonDecode(json) as Map)['blocks'] as List; + + group('document round-trip', () { + test('parse → serialize reproduces every block exactly', () { + final serialized = source.serialize(source.parse(_modernDocument)); + expect(blocksOf(serialized), blocksOf(_modernDocument)); + }); + + test('time and version are carried through', () { + final doc = source.parse(_modernDocument); + expect(doc.time, 1762700000000); + expect(doc.version, '2.31.7'); + }); + + test('fromJson → getContent reproduces every block exactly', () { + final content = EditorController.fromJson(_modernDocument).getContent(); + expect(blocksOf(content), blocksOf(_modernDocument)); + }); + + test('getContent stamps the targeted EditorJS version', () { + final content = EditorController().getContent(); + final decoded = jsonDecode(content) as Map; + expect(decoded['version'], BlockDocument.editorJsVersion); + expect(BlockDocument.editorJsVersion, '2.31.7'); + }); + }); + + group('block metadata', () { + test('ids and tunes are parsed into metadata parallel to blocks', () { + final doc = source.parse(_modernDocument); + expect(doc.metadata.length, doc.blocks.length); + expect(doc.metadata[0].id, 'aB3xK9pQ2z'); + expect(doc.metadata[0].tunes, { + 'alignment': {'alignment': 'center'}, + }); + expect(doc.metadata[1].id, 'T1aaaaaaaa'); + expect(doc.metadata[1].tunes, isNull); + }); + + test('missing, empty or mistyped id and tunes become null', () { + final doc = source.parse(''' + {"blocks": [ + {"type": "delimiter", "data": {}}, + {"id": "", "type": "delimiter", "data": {}, "tunes": {}}, + {"id": 7, "type": "delimiter", "data": {}, "tunes": []} + ]} + '''); + for (final metadata in doc.metadata) { + expect(metadata.id, isNull); + expect(metadata.tunes, isNull); + } + }); + + test('a document without metadata serializes without id or tunes', () { + const doc = BlockDocument( + time: 1, + version: 'x', + blocks: [DelimiterBlock()], + ); + final block = + (doc.toJson()['blocks'] as List).single as Map; + expect(block.keys, ['type', 'data']); + expect(doc.metadataAt(0), same(BlockMetadata.none)); + expect(doc.metadataAt(-1), same(BlockMetadata.none)); + }); + + test('id is written before type, tunes after data', () { + const doc = BlockDocument( + time: 1, + version: 'x', + blocks: [DelimiterBlock()], + metadata: [ + BlockMetadata(id: 'abc', tunes: {'t': true}), + ], + ); + final block = + (doc.toJson()['blocks'] as List).single as Map; + expect(block.keys, ['id', 'type', 'data', 'tunes']); + }); + }); + + group('unknown and unreadable blocks', () { + test('a block with no type is dropped', () { + final doc = source.parse(''' + {"blocks": [ + {"data": {"text": "orphan"}}, + {"type": "", "data": {}}, + {"type": 3, "data": {}}, + {"type": "delimiter", "data": {}} + ]} + '''); + expect(doc.blocks.single, isA()); + expect(doc.metadata.length, 1); + }); + + test('a block whose data is missing still parses', () { + final doc = source.parse('{"blocks": [{"type": "paragraph"}]}'); + expect((doc.blocks.single as ParagraphBlock).html, ''); + }); + + test('a throwing mapper yields an UnknownBlock with the original data', () { + final throwing = JsonDocumentSource( + registry: BlockTypeRegistry()..register(const _ThrowingMapper()), + ); + final doc = throwing.parse(''' + {"blocks": [ + {"type": "header", "data": {"text": "T", "level": 2}}, + {"type": "paragraph", "data": {"text": "still here"}} + ]} + '''); + final unknown = doc.blocks[0] as UnknownBlock; + expect(unknown.type, 'header'); + expect(unknown.toJson(), {'text': 'T', 'level': 2}); + expect((doc.blocks[1] as ParagraphBlock).html, 'still here'); + }); + }); + + group('mistyped fields never throw', () { + BlockEntity parseOne(String block) => + source.parse('{"blocks": [$block]}').blocks.single; + + test('linkTool meta as an array', () { + final block = parseOne( + '{"type": "linkTool", "data": {"link": "https://x", "meta": []}}', + ) as LinkToolBlock; + expect(block.link, 'https://x'); + expect(block.meta, isNull); + }); + + test('linkTool meta fields of the wrong type', () { + final block = parseOne( + '{"type": "linkTool", "data": {"link": 5, ' + '"meta": {"title": 1, "description": [], "image": "str"}}}', + ) as LinkToolBlock; + expect(block.link, '5'); + expect(block.meta!.title, isNull); + expect(block.meta!.description, isNull); + expect(block.meta!.imageUrl, isNull); + }); + + test('list with a non-string style and non-list items', () { + final block = parseOne( + '{"type": "list", "data": {"style": 1, "items": "nope"}}', + ) as ListBlock; + expect(block.style, ListStyle.unordered); + expect(block.items, isEmpty); + }); + + test('list item content of the wrong type', () { + final block = parseOne( + '{"type": "list", "data": {"style": "ordered", ' + '"items": [7, {"content": 8, "items": null}]}}', + ) as ListBlock; + expect(block.items[0].content, '7'); + expect(block.items[1].content, '8'); + expect(block.items[1].items, isEmpty); + }); + + test('paragraph, code, raw, warning and quote text as numbers', () { + expect( + (parseOne('{"type": "paragraph", "data": {"text": 42}}') + as ParagraphBlock) + .html, + '42', + ); + expect( + (parseOne('{"type": "code", "data": {"code": 1}}') as CodeBlock).code, + '1', + ); + expect( + (parseOne('{"type": "raw", "data": {"html": 2}}') as RawBlock).html, + '2', + ); + final warning = + parseOne('{"type": "warning", "data": {"title": 3, "message": []}}') + as WarningBlock; + expect(warning.title, '3'); + expect(warning.message, ''); + final quote = parseOne( + '{"type": "quote", "data": {"text": 4, "caption": 5, "alignment": 6}}', + ) as QuoteBlock; + expect(quote.text, '4'); + expect(quote.caption, isNull); + expect(quote.alignment, QuoteAlignment.left); + }); + + test('header level as a double', () { + final block = + parseOne('{"type": "header", "data": {"text": "T", "level": 3.0}}') + as HeaderBlock; + expect(block.level, 3); + }); + + test('time as a double, a numeric string, or garbage', () { + expect(source.parse('{"time": 1762700000000.5}').time, 1762700000000); + expect(source.parse('{"time": "1762700000000"}').time, 1762700000000); + expect(source.parse('{"time": "soon"}').time, greaterThan(0)); + expect(source.parse('{"time": null, "version": 2}').version, '2'); + }); + }); + + group('preserved extra fields', () { + test('table keeps stretched', () { + final block = const TableMapper().fromJson({ + 'withHeadings': false, + 'stretched': true, + 'content': [], + }); + expect(block.stretched, isTrue); + expect(block.toJson()['stretched'], isTrue); + expect(const TableBlock(content: []).toJson()['stretched'], isFalse); + }); + + test('image keeps extra file fields and url always wins', () { + final block = const ImageMapper().fromJson({ + 'file': {'url': 'u', 'width': 800}, + }); + expect(block.fileExtras, {'width': 800}); + expect(block.toJson()['file'], {'width': 800, 'url': 'u'}); + expect( + const ImageBlock(url: 'real', fileExtras: {'url': 'stale'}) + .toJson()['file'], + {'url': 'real'}, + ); + }); + + test('attaches keeps extra file fields', () { + final block = const AttachesMapper().fromJson({ + 'file': {'url': 'u', 'size': 1, 'assetId': 12}, + 'title': 't', + }); + expect(block.fileExtras, {'assetId': 12}); + expect(block.toJson()['file'], {'assetId': 12, 'url': 'u', 'size': 1}); + }); + + test('linkTool keeps extra meta fields', () { + final block = const LinkToolMapper().fromJson({ + 'link': 'l', + 'meta': {'title': 't', 'site_name': 'CodeX'}, + }); + expect(block.meta!.extras, {'site_name': 'CodeX'}); + expect(block.toJson()['meta'], {'site_name': 'CodeX', 'title': 't'}); + }); + }); +} diff --git a/test/widget/unknown_block_test.dart b/test/widget/unknown_block_test.dart new file mode 100644 index 0000000..2f13841 --- /dev/null +++ b/test/widget/unknown_block_test.dart @@ -0,0 +1,104 @@ +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/table/table_editor.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _ThrowingHeaderMapper implements BlockMapper { + const _ThrowingHeaderMapper(); + + @override + String get supportedType => 'header'; + + @override + HeaderBlock fromJson(Map data) => + throw StateError('mapper bug'); +} + +Widget _host(Widget child) => MaterialApp(home: Scaffold(body: child)); + +void main() { + group('BlockRendererRegistry', () { + test('never dispatches an UnknownBlock, even for a registered type', () { + final registry = BlockRendererRegistry(); + const block = UnknownBlock(type: 'header', data: {'text': 1}); + expect(registry.buildRenderer(block, null), isNull); + expect(registry.buildEditor(block, (_) {}), isNull); + }); + }); + + group('EditorJSView', () { + testWidgets('an unknown block renders nothing and leaves no gap', + (tester) async { + await tester.pumpWidget(_host( + EditorJSView(jsonData: '{"blocks":[{"type":"toggle","data":{}}]}'), + )); + final column = tester.widget( + find.descendant( + of: find.byType(EditorJSView), + matching: find.byType(Column), + ), + ); + expect(column.children, isEmpty); + }); + + testWidgets('a block its mapper cannot read does not break the document', + (tester) async { + final config = EditorConfig( + typeRegistry: BlockTypeRegistry() + ..register(const _ThrowingHeaderMapper()), + ); + await tester.pumpWidget(_host( + EditorJSView( + config: config, + jsonData: '{"blocks":[' + '{"type":"header","data":{"text":"Broken","level":1}},' + '{"type":"warning","data":{"title":"Still shown","message":"m"}}' + ']}', + ), + )); + expect(tester.takeException(), isNull); + expect(find.text('Broken'), findsNothing); + expect(find.text('Still shown'), findsOneWidget); + }); + }); + + group('EditorJSEditor', () { + testWidgets('an unknown block shows a placeholder and is kept on save', + (tester) async { + final controller = EditorController.fromJson( + '{"blocks":[{"id":"keep_me_01","type":"toggle","data":{"text":"x"}}]}', + ); + await tester.pumpWidget(_host(EditorJSEditor(controller: controller))); + + expect(find.text('[Unsupported block: toggle]'), findsOneWidget); + expect( + controller.getContent(), + contains('{"id":"keep_me_01","type":"toggle","data":{"text":"x"}}'), + ); + }); + }); + + group('TableEditor', () { + testWidgets('editing keeps the stretched flag', (tester) async { + TableBlock? changed; + await tester.pumpWidget(_host( + TableEditor( + block: const TableBlock( + stretched: true, + content: [ + ['a'], + ], + ), + onChanged: (block) => changed = block, + ), + )); + + await tester.tap(find.byType(Checkbox)); + await tester.pump(); + + expect(changed, isNotNull); + expect(changed!.withHeadings, isTrue); + expect(changed!.stretched, isTrue); + }); + }); +} From 9f4de68b059709f98e7c896c166ff9a69ad51874 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 00:54:15 -0600 Subject: [PATCH 02/16] Add List 2.x support: checklist style and ordered numbering options @editorjs/list 2.x merged the nested-list and checklist tools into the list block. A checklist-style list was shown as bullets and lost its ticks on save, and an ordered list's start number and counter type were dropped. - Entity: ListStyle.checklist, ListItem.checked, ListBlock.start, ListBlock.counterType and the ListCounterType enum. - Mapper: read the 2.x format and normalize the legacy list 1.x, nested-list and checklist item shapes the way the EditorJS tool does. - Renderer: tick box per checklist item at every level; ordered lists honour start and counterType and number nested items 1.1., 1.2., ... - Editor: style selector, "Start with" and counter-type options for ordered lists, tick box per checklist item. - Lists are written in the 2.x shape (root and per-item meta). The toolbar's Checklist button still creates the legacy checklist block; nested items are rendered but not yet editable. Co-Authored-By: Claude --- CHANGELOG.md | 10 +- CLAUDE.md | 2 +- lib/src/data/mappers/list_mapper.dart | 51 ++- .../domain/entities/blocks/list_block.dart | 72 ++++- .../presentation/blocks/list/list_editor.dart | 150 ++++++++- .../blocks/list/list_renderer.dart | 110 +++++-- .../utils/list_counter_formatter.dart | 69 ++++ test/unit/list_v2_test.dart | 300 ++++++++++++++++++ test/widget/list_v2_test.dart | 280 ++++++++++++++++ 9 files changed, 979 insertions(+), 65 deletions(-) create mode 100644 lib/src/presentation/utils/list_counter_formatter.dart create mode 100644 test/unit/list_v2_test.dart create mode 100644 test/widget/list_v2_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index c652bb0..6136bb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,12 @@ * **Backend-defined fields survive.** `TableBlock.stretched`, `ImageBlock.fileExtras`, `AttachesBlock.fileExtras` and `LinkToolMeta.extras` carry fields such as image `width`/`height` or link `site_name` through a round-trip. * **Version stamp updated.** `getContent()` writes `"version": "2.31.7"` (`BlockDocument.editorJsVersion`) instead of the hard-coded `2.19.0`. +### List 2.x (`@editorjs/list` 2.x: nested lists and checklists in one block) +* **Checklist style.** `ListStyle.checklist` is read, rendered (a tick box per item, at every nesting level), edited and written back; the ticked state lives in the new `ListItem.checked`. Previously a `checklist`-style list was turned into a bullet list and its ticks were lost. +* **Ordered list numbering.** New `ListBlock.start` and `ListBlock.counterType` (`ListCounterType`: numeric, lower/upper roman, lower/upper alpha) are read, rendered and written back. Nested items are numbered `1.1.`, `1.2.`, … as EditorJS renders them, instead of restarting at `1.`. +* **List editor.** A style selector switches a list between unordered, ordered and checklist; ordered lists get "Start with" and counter-type options; checklist items get a tick box. +* **Legacy formats are still read:** `@editorjs/list` 1.x string items, `@editorjs/nested-list` items, and old checklist `{text, checked}` items stored under a list block. + ### Parser hardening * A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. * `time` accepts integers, doubles and numeric strings; header `level` accepts doubles. @@ -16,9 +22,11 @@ * `getContent()` output now contains `id` on every block, `tunes` where present, and `stretched` on tables. * `BlockRendererRegistry.buildRenderer` / `buildEditor` return `null` for an `UnknownBlock` even when a builder is registered for its type string. * Blocks with a missing or non-string `type` are still dropped: they cannot be written back. +* `ListStyle` has a third value, `checklist`: an exhaustive `switch` over `ListStyle` in consumer code needs a new case. +* Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart` and `test/widget/unknown_block_test.dart` (281 tests in total, 88 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart` and `test/widget/list_v2_test.dart` (313 tests in total, 90 % line coverage). --- diff --git a/CLAUDE.md b/CLAUDE.md index 6d028b0..c4a28a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -111,7 +111,7 @@ final config = EditorConfig( |---|---|---|---| | `header` | H1–H6 | ✅ | | | `paragraph` | HTML via flutter_html | ✅ | Inline format bar (B/I/U/S/code/mark) | -| `list` | Ordered / unordered / nested | ✅ | | +| `list` | Ordered (start, counter type) / unordered / checklist / nested | ✅ | `@editorjs/list` 2.x format; legacy list, nested-list and checklist data is read too. Nested items are rendered but not yet editable | | `delimiter` | Divider | ✅ | | | `image` | Network URL | ✅ | caption/border/stretch parsed; image_picker not wired | | `quote` | With alignment | ✅ | | diff --git a/lib/src/data/mappers/list_mapper.dart b/lib/src/data/mappers/list_mapper.dart index 2acaf54..2f71f7c 100644 --- a/lib/src/data/mappers/list_mapper.dart +++ b/lib/src/data/mappers/list_mapper.dart @@ -2,6 +2,13 @@ import '../../domain/entities/blocks/list_block.dart'; import '../utils/json_reader.dart'; import 'block_mapper.dart'; +/// Reads the `@editorjs/list` 2.x format and the three formats it replaced, +/// normalizing them the same way the EditorJS tool does: +/// +/// * `@editorjs/list` 1.x: items are plain strings +/// * `@editorjs/nested-list`: items are `{content, items}` without `meta` +/// * `@editorjs/checklist` data saved under a list block: items are +/// `{text, checked}` class ListMapper implements BlockMapper { const ListMapper(); @@ -10,22 +17,44 @@ class ListMapper implements BlockMapper { @override ListBlock fromJson(Map data) { + final rawItems = JsonReader.list(data['items']); + final meta = JsonReader.map(data['meta']); + return ListBlock( - style: - data['style'] == 'ordered' ? ListStyle.ordered : ListStyle.unordered, - items: JsonReader.list(data['items']).map(_parseItem).toList(), + style: _isLegacyChecklist(rawItems) + ? ListStyle.checklist + : _parseStyle(data['style']), + items: rawItems.map(_parseItem).toList(), + start: JsonReader.integer(meta?['start']), + counterType: ListCounterType.fromValue(meta?['counterType']), ); } - /// Handles both flat string items (standard @editorjs/list) and - /// nested object items (@editorjs/nested-list). + static ListStyle _parseStyle(dynamic style) => switch (style) { + 'ordered' => ListStyle.ordered, + 'checklist' => ListStyle.checklist, + _ => ListStyle.unordered, + }; + + /// Same test EditorJS applies: the first item has the old checklist shape. + static bool _isLegacyChecklist(List rawItems) { + final first = rawItems.isEmpty ? null : rawItems.first; + return first is Map && + first['text'] is String && + first['checked'] is bool; + } + ListItem _parseItem(dynamic raw) { - if (raw is Map) { - return ListItem( - content: JsonReader.string(raw['content']), - items: JsonReader.list(raw['items']).map(_parseItem).toList(), - ); + if (raw is! Map) { + return ListItem(content: JsonReader.string(raw)); } - return ListItem(content: JsonReader.string(raw)); + + final meta = JsonReader.map(raw['meta']); + return ListItem( + // `text` and a top-level `checked` are the old checklist spelling. + content: JsonReader.string(raw['content'] ?? raw['text']), + checked: JsonReader.boolean(meta?['checked'] ?? raw['checked']), + items: JsonReader.list(raw['items']).map(_parseItem).toList(), + ); } } diff --git a/lib/src/domain/entities/blocks/list_block.dart b/lib/src/domain/entities/blocks/list_block.dart index f386111..26e66ed 100644 --- a/lib/src/domain/entities/blocks/list_block.dart +++ b/lib/src/domain/entities/blocks/list_block.dart @@ -1,6 +1,31 @@ import '../block_entity.dart'; -enum ListStyle { ordered, unordered } +/// How a list is presented. Matches the `style` values of `@editorjs/list` 2.x, +/// which merged the former nested-list and checklist tools into one. +enum ListStyle { ordered, unordered, checklist } + +/// Numbering scheme of an ordered list (`meta.counterType` in EditorJS). +enum ListCounterType { + numeric('numeric'), + lowerRoman('lower-roman'), + upperRoman('upper-roman'), + lowerAlpha('lower-alpha'), + upperAlpha('upper-alpha'); + + const ListCounterType(this.value); + + /// The string EditorJS stores for this counter type. + final String value; + + /// Returns the counter type stored as [value], or `null` if it is not one + /// EditorJS defines. + static ListCounterType? fromValue(Object? value) { + for (final type in values) { + if (type.value == value) return type; + } + return null; + } +} class ListItem { /// HTML content of this item. @@ -9,16 +34,31 @@ class ListItem { /// Nested child items (empty for flat lists). final List items; - const ListItem({required this.content, this.items = const []}); + /// Whether the item is ticked. Only meaningful, and only serialized, when + /// the list's style is [ListStyle.checklist]. + final bool checked; - ListItem copyWith({String? content, List? items}) => ListItem( + const ListItem({ + required this.content, + this.items = const [], + this.checked = false, + }); + + ListItem copyWith({String? content, List? items, bool? checked}) => + ListItem( content: content ?? this.content, items: items ?? this.items, + checked: checked ?? this.checked, ); - Map toJson() => { + /// Serializes the item in the `@editorjs/list` 2.x shape. + /// + /// Pass [asChecklist] for items of a checklist so that `meta.checked` is + /// written; items of ordered and unordered lists carry an empty `meta`. + Map toJson({bool asChecklist = false}) => { 'content': content, - 'items': items.map((i) => i.toJson()).toList(), + 'meta': {if (asChecklist) 'checked': checked}, + 'items': items.map((i) => i.toJson(asChecklist: asChecklist)).toList(), }; } @@ -26,9 +66,19 @@ class ListBlock extends BlockEntity { final ListStyle style; final List items; + /// Number the first top-level item is counted from. Ordered lists only. + /// Null when the document does not specify it (counting starts at 1). + final int? start; + + /// Numbering scheme, applied at every nesting level. Ordered lists only. + /// Null when the document does not specify it (numeric). + final ListCounterType? counterType; + const ListBlock({ required this.style, required this.items, + this.start, + this.counterType, }); @override @@ -36,7 +86,15 @@ class ListBlock extends BlockEntity { @override Map toJson() => { - 'style': style == ListStyle.ordered ? 'ordered' : 'unordered', - 'items': items.map((i) => i.toJson()).toList(), + 'style': style.name, + 'meta': { + if (style == ListStyle.ordered) ...{ + if (start != null) 'start': start, + if (counterType != null) 'counterType': counterType!.value, + }, + }, + 'items': items + .map((i) => i.toJson(asChecklist: style == ListStyle.checklist)) + .toList(), }; } diff --git a/lib/src/presentation/blocks/list/list_editor.dart b/lib/src/presentation/blocks/list/list_editor.dart index d8efcdd..a173197 100644 --- a/lib/src/presentation/blocks/list/list_editor.dart +++ b/lib/src/presentation/blocks/list/list_editor.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../../../domain/entities/blocks/list_block.dart'; +import '../../utils/list_counter_formatter.dart'; import '../base_block_editor.dart'; class ListEditor extends BlockEditor { @@ -11,8 +13,27 @@ class ListEditor extends BlockEditor { } class _ListEditorState extends State { + /// Order of the buttons in the style selector. + static const _styles = [ + ListStyle.unordered, + ListStyle.ordered, + ListStyle.checklist, + ]; + + static const _counterTypeLabels = { + ListCounterType.numeric: 'Numeric', + ListCounterType.lowerRoman: 'Lower Roman', + ListCounterType.upperRoman: 'Upper Roman', + ListCounterType.lowerAlpha: 'Lower Alpha', + ListCounterType.upperAlpha: 'Upper Alpha', + }; + late List _controllers; late List _items; + late ListStyle _style; + late int? _start; + late ListCounterType? _counterType; + late final TextEditingController _startController; @override void initState() { @@ -20,6 +41,10 @@ class _ListEditorState extends State { _items = List.from(widget.block.items); _controllers = _items.map((i) => TextEditingController(text: i.content)).toList(); + _style = widget.block.style; + _start = widget.block.start; + _counterType = widget.block.counterType; + _startController = TextEditingController(text: _start?.toString() ?? ''); } @override @@ -27,6 +52,7 @@ class _ListEditorState extends State { for (final c in _controllers) { c.dispose(); } + _startController.dispose(); super.dispose(); } @@ -56,14 +82,24 @@ class _ListEditorState extends State { } _controllers = updated; _items = List.from(newItems); + _style = widget.block.style; + _counterType = widget.block.counterType; + // Same rule as the item fields: leave the text alone while it already + // says the same thing, so the cursor does not jump while typing. + if (_start != widget.block.start) { + _start = widget.block.start; + _startController.text = _start?.toString() ?? ''; + } }); } } void _notify() { widget.onChanged(ListBlock( - style: widget.block.style, + style: _style, items: List.unmodifiable(_items), + start: _start, + counterType: _counterType, )); } @@ -84,23 +120,39 @@ class _ListEditorState extends State { _notify(); } + void _toggleChecked(int index) { + setState(() { + _items[index] = _items[index].copyWith(checked: !_items[index].checked); + }); + _notify(); + } + + void _setStyle(ListStyle style) { + if (style == _style) return; + setState(() => _style = style); + _notify(); + } + + void _setStart(String text) { + setState(() => _start = int.tryParse(text)); + _notify(); + } + + void _setCounterType(ListCounterType? type) { + setState(() => _counterType = type); + _notify(); + } + @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ + _buildSettings(), for (var i = 0; i < _controllers.length; i++) Row( children: [ - Padding( - padding: const EdgeInsets.only(right: 8), - child: Text( - widget.block.style == ListStyle.ordered - ? '${i + 1}.' - : '\u2022', - style: const TextStyle(fontSize: 14), - ), - ), + _buildMarker(i), Expanded( child: TextField( controller: _controllers[i], @@ -125,4 +177,82 @@ class _ListEditorState extends State { ], ); } + + /// Style selector, plus the numbering options when the list is ordered. + Widget _buildSettings() { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + ToggleButtons( + isSelected: [for (final style in _styles) style == _style], + onPressed: (index) => _setStyle(_styles[index]), + constraints: const BoxConstraints(minHeight: 36, minWidth: 44), + borderRadius: BorderRadius.circular(4), + children: const [ + Tooltip( + message: 'Unordered', + child: Icon(Icons.format_list_bulleted, size: 18), + ), + Tooltip( + message: 'Ordered', + child: Icon(Icons.format_list_numbered, size: 18), + ), + Tooltip( + message: 'Checklist', + child: Icon(Icons.checklist, size: 18), + ), + ], + ), + if (_style == ListStyle.ordered) ...[ + const SizedBox(width: 12), + SizedBox( + width: 88, + child: TextField( + controller: _startController, + onChanged: _setStart, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + decoration: const InputDecoration( + labelText: 'Start with', + hintText: '1', + isDense: true, + ), + ), + ), + const SizedBox(width: 12), + DropdownButton( + value: _counterType ?? ListCounterType.numeric, + onChanged: _setCounterType, + isDense: true, + underline: const SizedBox.shrink(), + items: [ + for (final entry in _counterTypeLabels.entries) + DropdownMenuItem(value: entry.key, child: Text(entry.value)), + ], + ), + ], + ], + ), + ); + } + + Widget _buildMarker(int index) { + if (_style == ListStyle.checklist) { + return Checkbox( + value: _items[index].checked, + onChanged: (_) => _toggleChecked(index), + ); + } + + return Padding( + padding: const EdgeInsets.only(right: 8), + child: Text( + _style == ListStyle.ordered + ? ListCounterFormatter.marker([(_start ?? 1) + index], _counterType) + : '•', + style: const TextStyle(fontSize: 14), + ), + ); + } } diff --git a/lib/src/presentation/blocks/list/list_renderer.dart b/lib/src/presentation/blocks/list/list_renderer.dart index 6cc74b1..d5e58d4 100644 --- a/lib/src/presentation/blocks/list/list_renderer.dart +++ b/lib/src/presentation/blocks/list/list_renderer.dart @@ -3,57 +3,97 @@ import 'package:flutter_html/flutter_html.dart'; import '../../../data/utils/html_sanitizer.dart'; import '../../../domain/entities/blocks/list_block.dart'; -import '../../../domain/entities/style_config.dart'; import '../../utils/html_style_builder.dart'; +import '../../utils/list_counter_formatter.dart'; import '../base_block_renderer.dart'; class ListRenderer extends BlockRenderer { const ListRenderer({super.key, required super.block, super.styleConfig}); + static const double _indentPerLevel = 16; + @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, - children: _buildItems(block.items, block.style, 0, styleConfig), + children: _buildItems(context, block.items, const []), ); } - static List _buildItems( + /// Builds the rows for [items] and, recursively, their children. + /// + /// [parentPath] holds the counter values of the ancestors, outermost first, + /// so an ordered list can number nested items `1.1.`, `1.2.`, … + List _buildItems( + BuildContext context, List items, - ListStyle style, - int depth, - StyleConfig? styleConfig, + List parentPath, ) { - final indentLeft = depth * 16.0; - int counter = 1; - - return [ - for (final item in items) ...[ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox(width: indentLeft), - Padding( - padding: const EdgeInsets.only(top: 2, right: 6), - child: Text( - style == ListStyle.ordered ? '${counter++}.' : '\u2022', - style: TextStyle( - fontSize: 14, - fontFamily: styleConfig?.defaultFont, - ), - ), - ), - Expanded( - child: Html( - data: HtmlSanitizer.sanitize(item.content), - style: HtmlStyleBuilder.build(styleConfig), - ), + // Only the top level honours `start`; nested levels count from 1. + var counter = parentPath.isEmpty ? (block.start ?? 1) : 1; + + final rows = []; + for (final item in items) { + final path = [...parentPath, counter++]; + rows.add(Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(width: parentPath.length * _indentPerLevel), + _buildMarker(context, item, path), + Expanded( + child: Html( + data: HtmlSanitizer.sanitize(item.content), + style: _contentStyle(item), ), - ], + ), + ], + )); + rows.addAll(_buildItems(context, item.items, path)); + } + return rows; + } + + Widget _buildMarker(BuildContext context, ListItem item, List path) { + if (block.style == ListStyle.checklist) { + return Padding( + padding: const EdgeInsets.only(top: 2, right: 8), + child: Icon( + item.checked + ? Icons.check_box_outlined + : Icons.check_box_outline_blank, + size: 18, + color: item.checked + ? Theme.of(context).colorScheme.primary + : Colors.grey, ), - if (item.items.isNotEmpty) - ..._buildItems(item.items, style, depth + 1, styleConfig), - ], - ]; + ); + } + + return Padding( + padding: const EdgeInsets.only(top: 2, right: 6), + child: Text( + block.style == ListStyle.ordered + ? ListCounterFormatter.marker(path, block.counterType) + : '•', + style: TextStyle( + fontSize: 14, + fontFamily: styleConfig?.defaultFont, + ), + ), + ); + } + + /// Ticked checklist items are struck through, like the checklist block. + Map _contentStyle(ListItem item) { + final styles = HtmlStyleBuilder.build(styleConfig); + if (block.style != ListStyle.checklist || !item.checked) return styles; + + return { + ...styles, + 'body': (styles['body'] ?? Style()).copyWith( + textDecoration: TextDecoration.lineThrough, + color: Colors.grey, + ), + }; } } diff --git a/lib/src/presentation/utils/list_counter_formatter.dart b/lib/src/presentation/utils/list_counter_formatter.dart new file mode 100644 index 0000000..124dcba --- /dev/null +++ b/lib/src/presentation/utils/list_counter_formatter.dart @@ -0,0 +1,69 @@ +import '../../domain/entities/blocks/list_block.dart'; + +/// Formats ordered-list counters the way a browser renders the EditorJS list +/// tool, whose marker is CSS `counters(item, ".", ) "."`. +class ListCounterFormatter { + ListCounterFormatter._(); + + static const _romanNumerals = [ + (1000, 'M'), + (900, 'CM'), + (500, 'D'), + (400, 'CD'), + (100, 'C'), + (90, 'XC'), + (50, 'L'), + (40, 'XL'), + (10, 'X'), + (9, 'IX'), + (5, 'V'), + (4, 'IV'), + (1, 'I'), + ]; + + /// Builds the marker for an item from the counter values of its ancestors + /// and itself, outermost first: `[2, 1]` → `2.1.`, or `II.I.` in upper + /// roman. + static String marker(List path, ListCounterType? type) => + '${path.map((value) => format(value, type)).join('.')}.'; + + /// Formats a single counter [value]. Values a scheme cannot express (zero + /// and negatives, or roman numerals above 3999) fall back to plain digits, + /// as CSS does. + static String format(int value, ListCounterType? type) => + switch (type ?? ListCounterType.numeric) { + ListCounterType.numeric => '$value', + ListCounterType.upperRoman => _roman(value) ?? '$value', + ListCounterType.lowerRoman => + _roman(value)?.toLowerCase() ?? '$value', + ListCounterType.upperAlpha => _alpha(value) ?? '$value', + ListCounterType.lowerAlpha => + _alpha(value)?.toLowerCase() ?? '$value', + }; + + static String? _roman(int value) { + if (value < 1 || value > 3999) return null; + final buffer = StringBuffer(); + var remaining = value; + for (final (amount, numeral) in _romanNumerals) { + while (remaining >= amount) { + buffer.write(numeral); + remaining -= amount; + } + } + return buffer.toString(); + } + + /// A, B, … Z, AA, AB, … (bijective base 26). + static String? _alpha(int value) { + if (value < 1) return null; + final letters = []; + var remaining = value; + while (remaining > 0) { + remaining--; + letters.add(String.fromCharCode(0x41 + remaining % 26)); + remaining ~/= 26; + } + return letters.reversed.join(); + } +} diff --git a/test/unit/list_v2_test.dart b/test/unit/list_v2_test.dart new file mode 100644 index 0000000..cdb3b7a --- /dev/null +++ b/test/unit/list_v2_test.dart @@ -0,0 +1,300 @@ +import 'dart:convert'; + +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/data/mappers/list_mapper.dart'; +import 'package:editorjs_flutter/src/presentation/utils/list_counter_formatter.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// The three examples from the @editorjs/list 2.x README. +const _listV2Document = ''' +{ + "time": 1762700000000, + "version": "2.31.7", + "blocks": [ + {"id": "unordered1", "type": "list", "data": { + "style": "unordered", "meta": {}, + "items": [ + {"content": "Apples", "meta": {}, "items": [ + {"content": "Red", "meta": {}, "items": []} + ]} + ]}}, + {"id": "ordered001", "type": "list", "data": { + "style": "ordered", + "meta": {"start": 2, "counterType": "upper-roman"}, + "items": [ + {"content": "Apples", "meta": {}, "items": [ + {"content": "Red", "meta": {}, "items": []} + ]} + ]}}, + {"id": "checklist1", "type": "list", "data": { + "style": "checklist", "meta": {}, + "items": [ + {"content": "Apples", "meta": {"checked": false}, "items": [ + {"content": "Red", "meta": {"checked": true}, "items": []} + ]} + ]}} + ] +} +'''; + +void main() { + const mapper = ListMapper(); + + group('ListMapper — list 2.x', () { + test('checklist style keeps the checked state at every level', () { + final block = mapper.fromJson({ + 'style': 'checklist', + 'meta': {}, + 'items': [ + { + 'content': 'Parent', + 'meta': {'checked': false}, + 'items': [ + { + 'content': 'Child', + 'meta': {'checked': true}, + 'items': [], + }, + ], + }, + ], + }); + expect(block.style, ListStyle.checklist); + expect(block.items.single.checked, isFalse); + expect(block.items.single.items.single.checked, isTrue); + }); + + test('ordered style reads start and counterType', () { + final block = mapper.fromJson({ + 'style': 'ordered', + 'meta': {'start': 5, 'counterType': 'lower-alpha'}, + 'items': [], + }); + expect(block.start, 5); + expect(block.counterType, ListCounterType.lowerAlpha); + }); + + test('missing, mistyped or unknown meta values become null', () { + expect(mapper.fromJson({'style': 'ordered'}).start, isNull); + expect(mapper.fromJson({'style': 'ordered'}).counterType, isNull); + + final block = mapper.fromJson({ + 'style': 'ordered', + 'meta': {'start': 'three', 'counterType': 'hieroglyphs'}, + }); + expect(block.start, isNull); + expect(block.counterType, isNull); + + expect(mapper.fromJson({'style': 'ordered', 'meta': []}).start, isNull); + }); + + test('a mistyped checked flag reads as unchecked', () { + final block = mapper.fromJson({ + 'style': 'checklist', + 'items': [ + { + 'content': 'a', + 'meta': {'checked': 'yes'}, + }, + {'content': 'b', 'meta': 7}, + ], + }); + expect(block.items.map((i) => i.checked), [false, false]); + }); + }); + + group('ListMapper — legacy formats', () { + test('list 1.x string items are unchecked and childless', () { + final block = mapper.fromJson({ + 'style': 'unordered', + 'items': ['a', 'b'], + }); + expect(block.items.map((i) => i.content), ['a', 'b']); + expect(block.items.every((i) => !i.checked && i.items.isEmpty), isTrue); + }); + + test('old checklist data under a list block becomes a checklist', () { + final block = mapper.fromJson({ + 'items': [ + {'text': 'Done', 'checked': true}, + {'text': 'Todo', 'checked': false}, + ], + }); + expect(block.style, ListStyle.checklist); + expect(block.items.map((i) => i.content), ['Done', 'Todo']); + expect(block.items.map((i) => i.checked), [true, false]); + }); + }); + + group('ListBlock.toJson', () { + test('writes style, meta and items in the list 2.x shape', () { + const block = ListBlock( + style: ListStyle.unordered, + items: [ListItem(content: 'a')], + ); + expect(block.toJson(), { + 'style': 'unordered', + 'meta': {}, + 'items': [ + {'content': 'a', 'meta': {}, 'items': []}, + ], + }); + expect(block.toJson().keys, ['style', 'meta', 'items']); + }); + + test('ordered writes only the meta values that are set', () { + List metaKeys(ListBlock block) => + (block.toJson()['meta'] as Map).keys.toList(); + + expect( + metaKeys(const ListBlock(style: ListStyle.ordered, items: [])), + isEmpty, + ); + expect( + metaKeys(const ListBlock( + style: ListStyle.ordered, + items: [], + start: 3, + )), + ['start'], + ); + expect( + const ListBlock( + style: ListStyle.ordered, + items: [], + start: 3, + counterType: ListCounterType.upperAlpha, + ).toJson()['meta'], + {'start': 3, 'counterType': 'upper-alpha'}, + ); + }); + + test('start and counterType are not written for other styles', () { + const block = ListBlock( + style: ListStyle.unordered, + items: [], + start: 3, + counterType: ListCounterType.upperAlpha, + ); + expect(block.toJson()['meta'], isEmpty); + }); + + test('checklist writes checked for every item, nested ones included', () { + const block = ListBlock( + style: ListStyle.checklist, + items: [ + ListItem( + content: 'p', + checked: true, + items: [ListItem(content: 'c')], + ), + ], + ); + final parent = + (block.toJson()['items'] as List).single as Map; + expect(parent['meta'], {'checked': true}); + final child = (parent['items'] as List).single as Map; + expect(child['meta'], {'checked': false}); + }); + + test('checked is not written outside a checklist', () { + const block = ListBlock( + style: ListStyle.ordered, + items: [ListItem(content: 'a', checked: true)], + ); + final item = + (block.toJson()['items'] as List).single as Map; + expect(item['meta'], isEmpty); + }); + }); + + test('ListItem.copyWith changes only what is passed', () { + const item = ListItem(content: 'a', items: [ListItem(content: 'b')]); + final ticked = item.copyWith(checked: true); + expect(ticked.checked, isTrue); + expect(ticked.content, 'a'); + expect(ticked.items.single.content, 'b'); + expect(ticked.copyWith(content: 'z').checked, isTrue); + }); + + test('ListCounterType.fromValue maps every EditorJS value', () { + for (final type in ListCounterType.values) { + expect(ListCounterType.fromValue(type.value), type); + } + expect(ListCounterType.fromValue('nope'), isNull); + expect(ListCounterType.fromValue(null), isNull); + }); + + group('round-trip', () { + List blocksOf(String json) => + (jsonDecode(json) as Map)['blocks'] as List; + + test('the list 2.x README examples survive fromJson → getContent', () { + final content = EditorController.fromJson(_listV2Document).getContent(); + expect(blocksOf(content), blocksOf(_listV2Document)); + }); + + test('a legacy nested list is written back in the 2.x shape', () { + const legacy = '{"blocks":[{"id":"legacy0001","type":"list","data":' + '{"style":"ordered","items":[{"content":"a","items":[]}]}}]}'; + final content = EditorController.fromJson(legacy).getContent(); + expect((blocksOf(content).single as Map)['data'], { + 'style': 'ordered', + 'meta': {}, + 'items': [ + {'content': 'a', 'meta': {}, 'items': []}, + ], + }); + }); + }); + + group('ListCounterFormatter', () { + test('numeric is the default', () { + expect(ListCounterFormatter.format(7, null), '7'); + expect(ListCounterFormatter.format(7, ListCounterType.numeric), '7'); + }); + + test('roman numerals', () { + const upper = ListCounterType.upperRoman; + expect(ListCounterFormatter.format(1, upper), 'I'); + expect(ListCounterFormatter.format(4, upper), 'IV'); + expect(ListCounterFormatter.format(9, upper), 'IX'); + expect(ListCounterFormatter.format(14, upper), 'XIV'); + expect(ListCounterFormatter.format(1994, upper), 'MCMXCIV'); + expect(ListCounterFormatter.format(3999, upper), 'MMMCMXCIX'); + expect( + ListCounterFormatter.format(8, ListCounterType.lowerRoman), + 'viii', + ); + }); + + test('alphabetic counters continue past Z', () { + const upper = ListCounterType.upperAlpha; + expect(ListCounterFormatter.format(1, upper), 'A'); + expect(ListCounterFormatter.format(26, upper), 'Z'); + expect(ListCounterFormatter.format(27, upper), 'AA'); + expect(ListCounterFormatter.format(52, upper), 'AZ'); + expect(ListCounterFormatter.format(703, upper), 'AAA'); + expect(ListCounterFormatter.format(3, ListCounterType.lowerAlpha), 'c'); + }); + + test('values a scheme cannot express fall back to digits', () { + expect(ListCounterFormatter.format(0, ListCounterType.upperRoman), '0'); + expect( + ListCounterFormatter.format(4000, ListCounterType.lowerRoman), + '4000', + ); + expect(ListCounterFormatter.format(0, ListCounterType.upperAlpha), '0'); + expect(ListCounterFormatter.format(-2, ListCounterType.lowerAlpha), '-2'); + }); + + test('marker joins the levels with dots', () { + expect(ListCounterFormatter.marker([3], null), '3.'); + expect(ListCounterFormatter.marker([2, 1, 4], null), '2.1.4.'); + expect( + ListCounterFormatter.marker([2, 1], ListCounterType.upperRoman), + 'II.I.', + ); + }); + }); +} diff --git a/test/widget/list_v2_test.dart b/test/widget/list_v2_test.dart new file mode 100644 index 0000000..582e1aa --- /dev/null +++ b/test/widget/list_v2_test.dart @@ -0,0 +1,280 @@ +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/list/list_editor.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/list/list_renderer.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _host(Widget child) => MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SizedBox(width: 400, child: child), + ), + ), + ); + +void main() { + group('ListRenderer', () { + testWidgets('ordered list numbers nested items as 1.1.', (tester) async { + await tester.pumpWidget(_host(const ListRenderer( + block: ListBlock( + style: ListStyle.ordered, + items: [ + ListItem( + content: 'One', + items: [ListItem(content: 'A'), ListItem(content: 'B')], + ), + ListItem(content: 'Two'), + ], + ), + ))); + + for (final marker in ['1.', '1.1.', '1.2.', '2.']) { + expect(find.text(marker), findsOneWidget); + } + }); + + testWidgets('ordered list honours start and counterType', (tester) async { + await tester.pumpWidget(_host(const ListRenderer( + block: ListBlock( + style: ListStyle.ordered, + start: 4, + counterType: ListCounterType.upperRoman, + items: [ + ListItem(content: 'Four', items: [ListItem(content: 'Child')]), + ListItem(content: 'Five'), + ], + ), + ))); + + expect(find.text('IV.'), findsOneWidget); + // `start` shifts the top level only; children still count from one. + expect(find.text('IV.I.'), findsOneWidget); + expect(find.text('V.'), findsOneWidget); + }); + + testWidgets('unordered list shows a bullet per item', (tester) async { + await tester.pumpWidget(_host(const ListRenderer( + block: ListBlock( + style: ListStyle.unordered, + items: [ListItem(content: 'a'), ListItem(content: 'b')], + ), + ))); + + expect(find.text('•'), findsNWidgets(2)); + expect(find.byIcon(Icons.check_box_outlined), findsNothing); + }); + + testWidgets('checklist shows a box per item reflecting its state', + (tester) async { + await tester.pumpWidget(_host(const ListRenderer( + block: ListBlock( + style: ListStyle.checklist, + items: [ + ListItem( + content: 'Done', + checked: true, + items: [ListItem(content: 'Nested todo')], + ), + ListItem(content: 'Todo'), + ], + ), + ))); + + expect(find.byIcon(Icons.check_box_outlined), findsOneWidget); + expect(find.byIcon(Icons.check_box_outline_blank), findsNWidgets(2)); + expect(find.text('•'), findsNothing); + }); + + testWidgets('a v2 checklist renders through EditorJSView', (tester) async { + await tester.pumpWidget(_host(EditorJSView( + jsonData: '{"blocks":[{"type":"list","data":{"style":"checklist",' + '"items":[{"content":"Ship it","meta":{"checked":true},' + '"items":[]}]}}]}', + ))); + await tester.pumpAndSettle(); + + expect(find.byIcon(Icons.check_box_outlined), findsOneWidget); + }); + }); + + group('ListEditor', () { + Future> pumpEditor( + WidgetTester tester, + ListBlock block, + ) async { + final changes = []; + await tester.pumpWidget(_host( + ListEditor(block: block, onChanged: changes.add), + )); + return changes; + } + + testWidgets('checklist items toggle and keep the rest of the block', + (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock( + style: ListStyle.checklist, + items: [ + ListItem( + content: 'a', + items: [ListItem(content: 'child', checked: true)], + ), + ListItem(content: 'b', checked: true), + ], + ), + ); + + expect(find.byType(Checkbox), findsNWidgets(2)); + await tester.tap(find.byType(Checkbox).first); + await tester.pump(); + + final block = changes.single; + expect(block.style, ListStyle.checklist); + expect(block.items.map((i) => i.checked), [true, true]); + // Nested items are not editable here, but must not be lost. + expect(block.items.first.items.single.checked, isTrue); + }); + + testWidgets('editing text keeps style, start and counterType', + (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock( + style: ListStyle.ordered, + start: 3, + counterType: ListCounterType.lowerAlpha, + items: [ListItem(content: 'a')], + ), + ); + + expect(find.text('c.'), findsOneWidget); + await tester.enterText(find.widgetWithText(TextField, 'a'), 'edited'); + await tester.pump(); + + final block = changes.last; + expect(block.items.single.content, 'edited'); + expect(block.style, ListStyle.ordered); + expect(block.start, 3); + expect(block.counterType, ListCounterType.lowerAlpha); + }); + + testWidgets('the style selector switches the list style', (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock( + style: ListStyle.unordered, + items: [ListItem(content: 'a')], + ), + ); + expect(find.byType(Checkbox), findsNothing); + + await tester.tap(find.byTooltip('Checklist')); + await tester.pump(); + expect(changes.last.style, ListStyle.checklist); + expect(find.byType(Checkbox), findsOneWidget); + + await tester.tap(find.byTooltip('Ordered')); + await tester.pump(); + expect(changes.last.style, ListStyle.ordered); + expect(find.text('1.'), findsOneWidget); + + // Selecting the current style again changes nothing. + final count = changes.length; + await tester.tap(find.byTooltip('Ordered')); + await tester.pump(); + expect(changes.length, count); + + await tester.tap(find.byTooltip('Unordered')); + await tester.pump(); + expect(changes.last.style, ListStyle.unordered); + }); + + testWidgets('numbering options appear only for ordered lists', + (tester) async { + await pumpEditor( + tester, + const ListBlock( + style: ListStyle.unordered, + items: [ListItem(content: 'a')], + ), + ); + expect(find.text('Start with'), findsNothing); + expect(find.byType(DropdownButton), findsNothing); + + await tester.tap(find.byTooltip('Ordered')); + await tester.pump(); + expect(find.text('Start with'), findsOneWidget); + expect(find.byType(DropdownButton), findsOneWidget); + }); + + testWidgets('start number updates the markers and the block', + (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock( + style: ListStyle.ordered, + items: [ListItem(content: 'a'), ListItem(content: 'b')], + ), + ); + + final startField = find.widgetWithText(TextField, 'Start with'); + await tester.enterText(startField, '7'); + await tester.pump(); + expect(changes.last.start, 7); + expect(find.text('7.'), findsOneWidget); + expect(find.text('8.'), findsOneWidget); + + await tester.enterText(startField, ''); + await tester.pump(); + expect(changes.last.start, isNull); + expect(find.text('1.'), findsOneWidget); + }); + + testWidgets('counter type can be changed from the dropdown', + (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock( + style: ListStyle.ordered, + items: [ListItem(content: 'a')], + ), + ); + + await tester.tap(find.byType(DropdownButton)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Upper Roman').last); + await tester.pumpAndSettle(); + + expect(changes.last.counterType, ListCounterType.upperRoman); + expect(find.text('I.'), findsOneWidget); + }); + + testWidgets('follows a block replaced from outside', (tester) async { + Widget editor(ListBlock block) => + _host(ListEditor(block: block, onChanged: (_) {})); + + await tester.pumpWidget(editor(const ListBlock( + style: ListStyle.ordered, + start: 2, + items: [ListItem(content: 'a')], + ))); + expect(find.text('2.'), findsOneWidget); + + await tester.pumpWidget(editor(const ListBlock( + style: ListStyle.ordered, + start: 9, + counterType: ListCounterType.upperAlpha, + items: [ListItem(content: 'a')], + ))); + expect(find.text('I.'), findsOneWidget); + expect(find.widgetWithText(TextField, '9'), findsOneWidget); + + await tester.pumpWidget(editor(const ListBlock( + style: ListStyle.checklist, + items: [ListItem(content: 'a', checked: true)], + ))); + expect(tester.widget(find.byType(Checkbox)).value, isTrue); + }); + }); +} From 702ed964bace98ad6033fc6745fc1f62298716bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 00:59:23 -0600 Subject: [PATCH 03/16] Offer both checklist kinds in the editor toolbar Which checklist a document can use depends on the tools installed in the EditorJS instance that reads it, so the toolbar now has a button for each: "Checklist" adds a list 2.x checklist (a list block with the checklist style) and "Checklist (legacy)" adds the older checklist block the button used to create. The extra button pushes the link button past the default test viewport, so the two hyperlink tests scroll it into view first. Co-Authored-By: Claude --- CHANGELOG.md | 4 ++- CLAUDE.md | 2 +- .../widgets/editorjs_toolbar.dart | 14 ++++++++ test/widget/toolbar_test.dart | 35 +++++++++++++++++-- 4 files changed, 51 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6136bb4..9cb8de8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ * **Checklist style.** `ListStyle.checklist` is read, rendered (a tick box per item, at every nesting level), edited and written back; the ticked state lives in the new `ListItem.checked`. Previously a `checklist`-style list was turned into a bullet list and its ticks were lost. * **Ordered list numbering.** New `ListBlock.start` and `ListBlock.counterType` (`ListCounterType`: numeric, lower/upper roman, lower/upper alpha) are read, rendered and written back. Nested items are numbered `1.1.`, `1.2.`, … as EditorJS renders them, instead of restarting at `1.`. * **List editor.** A style selector switches a list between unordered, ordered and checklist; ordered lists get "Start with" and counter-type options; checklist items get a tick box. +* **Two checklist buttons in the toolbar.** "Checklist" now adds a list 2.x checklist (a `list` block with `style: "checklist"`); "Checklist (legacy)" adds the older `checklist` block that the button used to create. Which one a site can read depends on the tools installed in its EditorJS instance. * **Legacy formats are still read:** `@editorjs/list` 1.x string items, `@editorjs/nested-list` items, and old checklist `{text, checked}` items stored under a list block. ### Parser hardening @@ -22,11 +23,12 @@ * `getContent()` output now contains `id` on every block, `tunes` where present, and `stretched` on tables. * `BlockRendererRegistry.buildRenderer` / `buildEditor` return `null` for an `UnknownBlock` even when a builder is registered for its type string. * Blocks with a missing or non-string `type` are still dropped: they cannot be written back. +* The toolbar's "Checklist" button creates a `list` block with the checklist style, no longer a `checklist` block; the previous behaviour moved to the new "Checklist (legacy)" button. * `ListStyle` has a third value, `checklist`: an exhaustive `switch` over `ListStyle` in consumer code needs a new case. * Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart` and `test/widget/list_v2_test.dart` (313 tests in total, 90 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart` and `test/widget/list_v2_test.dart` (314 tests in total, 90 % line coverage). --- diff --git a/CLAUDE.md b/CLAUDE.md index c4a28a1..87c20f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -116,7 +116,7 @@ final config = EditorConfig( | `image` | Network URL | ✅ | caption/border/stretch parsed; image_picker not wired | | `quote` | With alignment | ✅ | | | `code` | Monospace + copy button | ✅ | | -| `checklist` | Checked / unchecked | ✅ | | +| `checklist` | Checked / unchecked | ✅ | Legacy `@editorjs/checklist` block; toolbar button "Checklist (legacy)". The toolbar's "Checklist" button creates a `list` block with the checklist style | | `table` | With optional heading row | ✅ | | | `warning` | Title + message | ✅ | | | `embed` | Tappable card | Viewer only | | diff --git a/lib/src/presentation/widgets/editorjs_toolbar.dart b/lib/src/presentation/widgets/editorjs_toolbar.dart index 99c9968..71b228b 100644 --- a/lib/src/presentation/widgets/editorjs_toolbar.dart +++ b/lib/src/presentation/widgets/editorjs_toolbar.dart @@ -84,9 +84,23 @@ class EditorJSToolbar extends StatelessWidget { ), ), ), + // Two checklists on purpose: which one a document can use depends + // on the tools installed in the EditorJS instance that reads it. + // `@editorjs/list` 2.x stores a checklist as a list block … _ToolbarButton( icon: Icons.checklist, tooltip: 'Checklist', + onTap: () => controller.addBlock( + const ListBlock( + style: ListStyle.checklist, + items: [ListItem(content: '')], + ), + ), + ), + // … while the older `@editorjs/checklist` tool has its own block. + _ToolbarButton( + icon: Icons.check_box_outlined, + tooltip: 'Checklist (legacy)', onTap: () => controller.addBlock( const ChecklistBlock( items: [ChecklistItem(text: '')], diff --git a/test/widget/toolbar_test.dart b/test/widget/toolbar_test.dart index 7ca3409..7c60b80 100644 --- a/test/widget/toolbar_test.dart +++ b/test/widget/toolbar_test.dart @@ -117,15 +117,32 @@ void main() { expect((controller.blocks.first as ListBlock).style, ListStyle.ordered); }); - testWidgets('tapping checklist button adds checklist block', (tester) async { + testWidgets('tapping checklist button adds a list 2.x checklist', + (tester) async { + final controller = EditorController(); + await tester.pumpWidget(_wrapToolbar(controller)); + await tester.pumpAndSettle(); + + await tester.tap(find.byTooltip('Checklist')); + await tester.pumpAndSettle(); + expect(controller.blockCount, 1); + final block = controller.blocks.first as ListBlock; + expect(block.style, ListStyle.checklist); + expect(block.items.single.checked, isFalse); + expect(controller.getContent(), contains('"style":"checklist"')); + }); + + testWidgets('tapping legacy checklist button adds a checklist block', + (tester) async { final controller = EditorController(); await tester.pumpWidget(_wrapToolbar(controller)); await tester.pumpAndSettle(); - await tester.tap(find.byIcon(Icons.checklist)); + await tester.tap(find.byTooltip('Checklist (legacy)')); await tester.pumpAndSettle(); expect(controller.blockCount, 1); expect(controller.blocks.first, isA()); + expect(controller.getContent(), contains('"type":"checklist"')); }); testWidgets('tapping table button adds table block', (tester) async { @@ -221,6 +238,13 @@ void main() { )); await tester.pumpAndSettle(); + // The toolbar scrolls horizontally and the link button sits past the + // edge of the default test viewport. + await tester.scrollUntilVisible( + find.byIcon(Icons.link), + 100, + scrollable: find.byType(Scrollable).first, + ); await tester.tap(find.byIcon(Icons.link)); await tester.pumpAndSettle(); @@ -245,6 +269,13 @@ void main() { )); await tester.pumpAndSettle(); + // The toolbar scrolls horizontally and the link button sits past the + // edge of the default test viewport. + await tester.scrollUntilVisible( + find.byIcon(Icons.link), + 100, + scrollable: find.byType(Scrollable).first, + ); await tester.tap(find.byIcon(Icons.link)); await tester.pumpAndSettle(); From 12c02ca4e8c1756590bbb13c413e2ac6703bfda7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 01:16:35 -0600 Subject: [PATCH 04/16] Improve viewer fidelity: visible tables, inline HTML, tappable links EditorJS saves every editable field as HTML, but the viewer only treated paragraph, list and quote text that way. - Tables: flex columns inside a horizontal scroll view gave the table zero width, so it showed as a strip with one letter per line. Columns now take the width of their content; a stretched table fills the available width. - Inline formatting and entities now render in headers, table cells, legacy checklist items, warnings and image, embed and quote captions. All text goes through one widget, InlineHtml. - Links: taps did nothing. They now open externally (http, https, mailto, tel) or go to the new EditorConfig.onLinkTap. Link, embed and attachment cards use the same path, exposed to custom renderers as EditorLinkScope.open. - Alignment: paragraph, quote and raw text lose their extra horizontal margin, and list markers line up with their item's text. Co-Authored-By: Claude --- CHANGELOG.md | 10 +- CLAUDE.md | 10 +- README.md | 15 + lib/editorjs_flutter.dart | 1 + .../blocks/attaches/attaches_renderer.dart | 12 +- .../blocks/checklist/checklist_renderer.dart | 17 +- .../blocks/embed/embed_renderer.dart | 25 +- .../blocks/header/header_renderer.dart | 10 +- .../blocks/image/image_renderer.dart | 10 +- .../blocks/link_tool/link_tool_renderer.dart | 18 +- .../blocks/list/list_renderer.dart | 50 +- .../blocks/paragraph/paragraph_renderer.dart | 11 +- .../blocks/quote/quote_renderer.dart | 32 +- .../presentation/blocks/raw/raw_renderer.dart | 11 +- .../blocks/table/table_renderer.dart | 80 ++-- .../blocks/warning/warning_renderer.dart | 15 +- .../presentation/config/editor_config.dart | 10 + .../widgets/editor_link_scope.dart | 74 +++ .../presentation/widgets/editorjs_view.dart | 18 +- lib/src/presentation/widgets/inline_html.dart | 62 +++ test/widget/viewer_fidelity_test.dart | 450 ++++++++++++++++++ 21 files changed, 771 insertions(+), 170 deletions(-) create mode 100644 lib/src/presentation/widgets/editor_link_scope.dart create mode 100644 lib/src/presentation/widgets/inline_html.dart create mode 100644 test/widget/viewer_fidelity_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cb8de8..50f42af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,12 @@ * **Two checklist buttons in the toolbar.** "Checklist" now adds a list 2.x checklist (a `list` block with `style: "checklist"`); "Checklist (legacy)" adds the older `checklist` block that the button used to create. Which one a site can read depends on the tools installed in its EditorJS instance. * **Legacy formats are still read:** `@editorjs/list` 1.x string items, `@editorjs/nested-list` items, and old checklist `{text, checked}` items stored under a list block. +### Viewer fidelity +* **Tables are now visible.** The table renderer laid its columns out at zero width, so every table showed as a thin strip with one letter per line. Columns now take the width of their content and the table scrolls sideways when it is wider than the screen. A `stretched` table fills the available width. +* **Inline formatting and entities are rendered everywhere.** Headers, table cells, legacy checklist items, warning title and message, and image, embed and quote captions showed markup such as `` and `&` literally. All text now goes through one widget, so bold, italic, links, marker, inline code and entities render in every block. +* **Links can be tapped.** `` links did nothing. They now open in the external application (`http`, `https`, `mailto` and `tel` only), or are passed to the new `EditorConfig.onLinkTap`. Link, embed and attachment cards go through the same handler. Custom renderers can join in with `EditorLinkScope.open(context, url)`. +* **Blocks line up.** Paragraph, quote and raw text had an extra 8 px left and right margin that headers and tables did not; list markers sat about 6 px above their item's text. Both are fixed, and list items are spaced 8 px apart. + ### Parser hardening * A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. * `time` accepts integers, doubles and numeric strings; header `level` accepts doubles. @@ -24,11 +30,13 @@ * `BlockRendererRegistry.buildRenderer` / `buildEditor` return `null` for an `UnknownBlock` even when a builder is registered for its type string. * Blocks with a missing or non-string `type` are still dropped: they cannot be written back. * The toolbar's "Checklist" button creates a `list` block with the checklist style, no longer a `checklist` block; the previous behaviour moved to the new "Checklist (legacy)" button. +* Link, embed and attachment cards now also open `mailto` and `tel` targets, and no longer raise an unhandled error when the platform cannot open a link. +* Paragraph, quote and raw blocks are 16 px wider (no horizontal margin) and list rows are closer together. * `ListStyle` has a third value, `checklist`: an exhaustive `switch` over `ListStyle` in consumer code needs a new case. * Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart` and `test/widget/list_v2_test.dart` (314 tests in total, 90 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart` and `test/widget/viewer_fidelity_test.dart` (337 tests in total, 92 % line coverage). --- diff --git a/CLAUDE.md b/CLAUDE.md index 87c20f3..3679c91 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -109,7 +109,7 @@ final config = EditorConfig( | Block | Viewer | Editor | Notes | |---|---|---|---| -| `header` | H1–H6 | ✅ | | +| `header` | H1–H6, inline HTML | ✅ | | | `paragraph` | HTML via flutter_html | ✅ | Inline format bar (B/I/U/S/code/mark) | | `list` | Ordered (start, counter type) / unordered / checklist / nested | ✅ | `@editorjs/list` 2.x format; legacy list, nested-list and checklist data is read too. Nested items are rendered but not yet editable | | `delimiter` | Divider | ✅ | | @@ -117,8 +117,8 @@ final config = EditorConfig( | `quote` | With alignment | ✅ | | | `code` | Monospace + copy button | ✅ | | | `checklist` | Checked / unchecked | ✅ | Legacy `@editorjs/checklist` block; toolbar button "Checklist (legacy)". The toolbar's "Checklist" button creates a `list` block with the checklist style | -| `table` | With optional heading row | ✅ | | -| `warning` | Title + message | ✅ | | +| `table` | Optional heading row, `stretched`, inline HTML in cells | ✅ | Columns sized to content; scrolls horizontally | +| `warning` | Title + message, inline HTML | ✅ | | | `embed` | Tappable card | Viewer only | | | `linkTool` | Link preview card | Viewer only | | | `attaches` | File download card | Viewer only | | @@ -130,7 +130,7 @@ final config = EditorConfig( `lib/editorjs_flutter.dart` is the sole entry point. It exports: -- **Widgets**: `EditorJSView`, `EditorJSEditor` +- **Widgets**: `EditorJSView`, `EditorJSEditor`, `EditorLinkScope` (lets custom renderers open links through `EditorConfig.onLinkTap`) - **Controller**: `EditorController` - **Config**: `EditorConfig` - **Registries**: `BlockTypeRegistry`, `BlockRendererRegistry` @@ -159,7 +159,7 @@ When building new features, always work bottom-up: - `lib/src/data/registry/block_type_registry.dart` — JSON parsing extension point - `lib/src/presentation/registry/block_renderer_registry.dart` — rendering extension point - `lib/src/presentation/controller/editor_controller.dart` — editor state + `getContent()` -- `lib/src/presentation/widgets/` — thin shell widgets +- `lib/src/presentation/widgets/` — thin shell widgets, plus `inline_html.dart`: the one widget every renderer uses to show EditorJS text (sanitizing, styling, link taps) - `demo/lib/main.dart` — viewer usage example - `demo/lib/createnote.dart` — editor usage example - `demo/test_data/` — sample EditorJS JSON and styles JSON diff --git a/README.md b/README.md index 85634df..8c3c179 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,21 @@ EditorJSView( ) ``` +### Handling link taps + +Links in the content open in the external application by default (`http`, `https`, `mailto` and `tel` only). To handle them yourself, for example with an in-app browser or your own router, pass `onLinkTap`: + +```dart +EditorJSView( + jsonData: myJsonString, + config: EditorConfig( + onLinkTap: (url) => myRouter.open(url), + ), +) +``` + +The callback receives the URL exactly as it appears in the document, so check the scheme before opening it. + ### Full viewer example ```dart diff --git a/lib/editorjs_flutter.dart b/lib/editorjs_flutter.dart index 3b4f5e5..89b8fea 100644 --- a/lib/editorjs_flutter.dart +++ b/lib/editorjs_flutter.dart @@ -1,6 +1,7 @@ // Widgets export 'src/presentation/widgets/editorjs_view.dart'; export 'src/presentation/widgets/editorjs_editor.dart'; +export 'src/presentation/widgets/editor_link_scope.dart'; // Controller export 'src/presentation/controller/editor_controller.dart'; diff --git a/lib/src/presentation/blocks/attaches/attaches_renderer.dart b/lib/src/presentation/blocks/attaches/attaches_renderer.dart index 29467aa..441f541 100644 --- a/lib/src/presentation/blocks/attaches/attaches_renderer.dart +++ b/lib/src/presentation/blocks/attaches/attaches_renderer.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; -import 'package:url_launcher/url_launcher.dart'; import '../../../domain/entities/blocks/attaches_block.dart'; +import '../../widgets/editor_link_scope.dart'; import '../base_block_renderer.dart'; class AttachesRenderer extends BlockRenderer { @@ -16,15 +16,7 @@ class AttachesRenderer extends BlockRenderer { return InkWell( onTap: block.url.isNotEmpty - ? () async { - final uri = Uri.tryParse(block.url); - if (uri == null) return; - final scheme = uri.scheme.toLowerCase(); - if (scheme != 'http' && scheme != 'https') return; - if (await canLaunchUrl(uri)) { - await launchUrl(uri, mode: LaunchMode.externalApplication); - } - } + ? () => EditorLinkScope.open(context, block.url) : null, borderRadius: BorderRadius.circular(8), child: Container( diff --git a/lib/src/presentation/blocks/checklist/checklist_renderer.dart b/lib/src/presentation/blocks/checklist/checklist_renderer.dart index f421513..48c3a09 100644 --- a/lib/src/presentation/blocks/checklist/checklist_renderer.dart +++ b/lib/src/presentation/blocks/checklist/checklist_renderer.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_html/flutter_html.dart'; import '../../../domain/entities/blocks/checklist_block.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class ChecklistRenderer extends BlockRenderer { @@ -27,14 +29,15 @@ class ChecklistRenderer extends BlockRenderer { ), ), Expanded( - child: Text( + child: InlineHtml( item.text, - style: TextStyle( - fontFamily: styleConfig?.defaultFont, - decoration: - item.checked ? TextDecoration.lineThrough : null, - color: item.checked ? Colors.grey : null, - ), + styleConfig: styleConfig, + bodyStyle: item.checked + ? Style( + textDecoration: TextDecoration.lineThrough, + color: Colors.grey, + ) + : null, ), ), ], diff --git a/lib/src/presentation/blocks/embed/embed_renderer.dart b/lib/src/presentation/blocks/embed/embed_renderer.dart index 0c14d99..c49b503 100644 --- a/lib/src/presentation/blocks/embed/embed_renderer.dart +++ b/lib/src/presentation/blocks/embed/embed_renderer.dart @@ -1,7 +1,9 @@ import 'package:flutter/material.dart'; -import 'package:url_launcher/url_launcher.dart'; +import 'package:flutter_html/flutter_html.dart'; import '../../../domain/entities/blocks/embed_block.dart'; +import '../../widgets/editor_link_scope.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class EmbedRenderer extends BlockRenderer { @@ -11,18 +13,7 @@ class EmbedRenderer extends BlockRenderer { Widget build(BuildContext context) { return InkWell( onTap: block.source.isNotEmpty - ? () async { - final uri = Uri.tryParse(block.source); - if (uri == null) return; - final scheme = uri.scheme.toLowerCase(); - if (scheme != 'http' && scheme != 'https') return; - if (await canLaunchUrl(uri)) { - await launchUrl( - uri, - mode: LaunchMode.externalApplication, - ); - } - } + ? () => EditorLinkScope.open(context, block.source) : null, borderRadius: BorderRadius.circular(8), child: Container( @@ -87,13 +78,13 @@ class EmbedRenderer extends BlockRenderer { if (block.caption != null && block.caption!.isNotEmpty) Padding( padding: const EdgeInsets.fromLTRB(12, 0, 12, 10), - child: Text( + child: InlineHtml( block.caption!, - style: TextStyle( - fontSize: 12, + styleConfig: styleConfig, + bodyStyle: Style( + fontSize: FontSize(12), color: Colors.grey.shade600, fontStyle: FontStyle.italic, - fontFamily: styleConfig?.defaultFont, ), ), ), diff --git a/lib/src/presentation/blocks/header/header_renderer.dart b/lib/src/presentation/blocks/header/header_renderer.dart index fcc1de3..7357373 100644 --- a/lib/src/presentation/blocks/header/header_renderer.dart +++ b/lib/src/presentation/blocks/header/header_renderer.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_html/flutter_html.dart'; import '../../../domain/entities/blocks/header_block.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class HeaderRenderer extends BlockRenderer { @@ -10,12 +12,12 @@ class HeaderRenderer extends BlockRenderer { Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 4), - child: Text( + child: InlineHtml( block.text, - style: TextStyle( - fontSize: _fontSize(block.level), + styleConfig: styleConfig, + bodyStyle: Style( + fontSize: FontSize(_fontSize(block.level)), fontWeight: _fontWeight(block.level), - fontFamily: styleConfig?.defaultFont, ), ), ); diff --git a/lib/src/presentation/blocks/image/image_renderer.dart b/lib/src/presentation/blocks/image/image_renderer.dart index 2b79734..ea453d2 100644 --- a/lib/src/presentation/blocks/image/image_renderer.dart +++ b/lib/src/presentation/blocks/image/image_renderer.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_html/flutter_html.dart'; import '../../../domain/entities/blocks/image_block.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class ImageRenderer extends BlockRenderer { @@ -47,13 +49,13 @@ class ImageRenderer extends BlockRenderer { if (block.caption != null && block.caption!.isNotEmpty) Padding( padding: const EdgeInsets.only(top: 4), - child: Text( + child: InlineHtml( block.caption!, - style: TextStyle( - fontSize: 12, + styleConfig: styleConfig, + bodyStyle: Style( + fontSize: FontSize(12), color: Colors.grey.shade600, fontStyle: FontStyle.italic, - fontFamily: styleConfig?.defaultFont, ), ), ), diff --git a/lib/src/presentation/blocks/link_tool/link_tool_renderer.dart b/lib/src/presentation/blocks/link_tool/link_tool_renderer.dart index 7cb5ef9..c7f9aab 100644 --- a/lib/src/presentation/blocks/link_tool/link_tool_renderer.dart +++ b/lib/src/presentation/blocks/link_tool/link_tool_renderer.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; -import 'package:url_launcher/url_launcher.dart'; import '../../../domain/entities/blocks/link_tool_block.dart'; +import '../../widgets/editor_link_scope.dart'; import '../base_block_renderer.dart'; class LinkToolRenderer extends BlockRenderer { @@ -14,21 +14,7 @@ class LinkToolRenderer extends BlockRenderer { return InkWell( onTap: block.link.isNotEmpty - ? () async { - final uri = Uri.tryParse(block.link); - if (uri == null) { - return; - } - if (uri.scheme != 'http' && uri.scheme != 'https') { - return; - } - if (await canLaunchUrl(uri)) { - await launchUrl( - uri, - mode: LaunchMode.externalApplication, - ); - } - } + ? () => EditorLinkScope.open(context, block.link) : null, borderRadius: BorderRadius.circular(8), child: Container( diff --git a/lib/src/presentation/blocks/list/list_renderer.dart b/lib/src/presentation/blocks/list/list_renderer.dart index d5e58d4..4381099 100644 --- a/lib/src/presentation/blocks/list/list_renderer.dart +++ b/lib/src/presentation/blocks/list/list_renderer.dart @@ -1,10 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart'; -import '../../../data/utils/html_sanitizer.dart'; import '../../../domain/entities/blocks/list_block.dart'; -import '../../utils/html_style_builder.dart'; import '../../utils/list_counter_formatter.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class ListRenderer extends BlockRenderer { @@ -35,18 +34,22 @@ class ListRenderer extends BlockRenderer { final rows = []; for (final item in items) { final path = [...parentPath, counter++]; - rows.add(Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - SizedBox(width: parentPath.length * _indentPerLevel), - _buildMarker(context, item, path), - Expanded( - child: Html( - data: HtmlSanitizer.sanitize(item.content), - style: _contentStyle(item), + rows.add(Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox(width: parentPath.length * _indentPerLevel), + _buildMarker(context, item, path), + Expanded( + child: InlineHtml( + item.content, + styleConfig: styleConfig, + bodyStyle: _contentStyle(item), + ), ), - ), - ], + ], + ), )); rows.addAll(_buildItems(context, item.items, path)); } @@ -56,7 +59,7 @@ class ListRenderer extends BlockRenderer { Widget _buildMarker(BuildContext context, ListItem item, List path) { if (block.style == ListStyle.checklist) { return Padding( - padding: const EdgeInsets.only(top: 2, right: 8), + padding: const EdgeInsets.only(top: 1, right: 8), child: Icon( item.checked ? Icons.check_box_outlined @@ -70,7 +73,7 @@ class ListRenderer extends BlockRenderer { } return Padding( - padding: const EdgeInsets.only(top: 2, right: 6), + padding: const EdgeInsets.only(right: 8), child: Text( block.style == ListStyle.ordered ? ListCounterFormatter.marker(path, block.counterType) @@ -84,16 +87,11 @@ class ListRenderer extends BlockRenderer { } /// Ticked checklist items are struck through, like the checklist block. - Map _contentStyle(ListItem item) { - final styles = HtmlStyleBuilder.build(styleConfig); - if (block.style != ListStyle.checklist || !item.checked) return styles; - - return { - ...styles, - 'body': (styles['body'] ?? Style()).copyWith( - textDecoration: TextDecoration.lineThrough, - color: Colors.grey, - ), - }; + Style? _contentStyle(ListItem item) { + if (block.style != ListStyle.checklist || !item.checked) return null; + return Style( + textDecoration: TextDecoration.lineThrough, + color: Colors.grey, + ); } } diff --git a/lib/src/presentation/blocks/paragraph/paragraph_renderer.dart b/lib/src/presentation/blocks/paragraph/paragraph_renderer.dart index bbfdd44..bb13d1c 100644 --- a/lib/src/presentation/blocks/paragraph/paragraph_renderer.dart +++ b/lib/src/presentation/blocks/paragraph/paragraph_renderer.dart @@ -1,19 +1,18 @@ import 'package:flutter/material.dart'; -import 'package:flutter_html/flutter_html.dart'; -import '../../../data/utils/html_sanitizer.dart'; import '../../../domain/entities/blocks/paragraph_block.dart'; import '../base_block_renderer.dart'; -import '../../utils/html_style_builder.dart'; +import '../../widgets/inline_html.dart'; class ParagraphRenderer extends BlockRenderer { const ParagraphRenderer({super.key, required super.block, super.styleConfig}); @override Widget build(BuildContext context) { - return Html( - data: HtmlSanitizer.sanitize(block.html), - style: HtmlStyleBuilder.build(styleConfig), + return InlineHtml( + block.html, + styleConfig: styleConfig, + compact: false, ); } } diff --git a/lib/src/presentation/blocks/quote/quote_renderer.dart b/lib/src/presentation/blocks/quote/quote_renderer.dart index f39bb9f..d7cb646 100644 --- a/lib/src/presentation/blocks/quote/quote_renderer.dart +++ b/lib/src/presentation/blocks/quote/quote_renderer.dart @@ -1,9 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter_html/flutter_html.dart'; -import '../../../data/utils/html_sanitizer.dart'; import '../../../domain/entities/blocks/quote_block.dart'; -import '../../utils/html_style_builder.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class QuoteRenderer extends BlockRenderer { @@ -17,17 +16,6 @@ class QuoteRenderer extends BlockRenderer { QuoteAlignment.left => TextAlign.left, }; - final baseStyles = HtmlStyleBuilder.build(styleConfig); - final baseBodyStyle = baseStyles['body'] ?? Style(); - final mergedBodyStyle = baseBodyStyle.copyWith( - textAlign: align, - fontFamily: styleConfig?.defaultFont, - ); - final styleMap = { - ...baseStyles, - 'body': mergedBodyStyle, - }; - return Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), decoration: BoxDecoration( @@ -42,21 +30,23 @@ class QuoteRenderer extends BlockRenderer { child: Column( crossAxisAlignment: _crossAlignment(block.alignment), children: [ - Html( - data: HtmlSanitizer.sanitize(block.text), - style: styleMap, + InlineHtml( + block.text, + styleConfig: styleConfig, + bodyStyle: Style(textAlign: align), + compact: false, ), if (block.caption != null && block.caption!.isNotEmpty) Padding( padding: const EdgeInsets.only(top: 4), - child: Text( + child: InlineHtml( '— ${block.caption}', - textAlign: align, - style: TextStyle( + styleConfig: styleConfig, + bodyStyle: Style( + textAlign: align, fontStyle: FontStyle.italic, color: Colors.grey.shade600, - fontSize: 12, - fontFamily: styleConfig?.defaultFont, + fontSize: FontSize(12), ), ), ), diff --git a/lib/src/presentation/blocks/raw/raw_renderer.dart b/lib/src/presentation/blocks/raw/raw_renderer.dart index 58fe172..bb25a1f 100644 --- a/lib/src/presentation/blocks/raw/raw_renderer.dart +++ b/lib/src/presentation/blocks/raw/raw_renderer.dart @@ -1,9 +1,7 @@ import 'package:flutter/material.dart'; -import 'package:flutter_html/flutter_html.dart'; -import '../../../data/utils/html_sanitizer.dart'; import '../../../domain/entities/blocks/raw_block.dart'; -import '../../utils/html_style_builder.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; /// Renders raw HTML content. Content is sanitized before display. @@ -12,9 +10,10 @@ class RawRenderer extends BlockRenderer { @override Widget build(BuildContext context) { - return Html( - data: HtmlSanitizer.sanitize(block.html), - style: HtmlStyleBuilder.build(styleConfig), + return InlineHtml( + block.html, + styleConfig: styleConfig, + compact: false, ); } } diff --git a/lib/src/presentation/blocks/table/table_renderer.dart b/lib/src/presentation/blocks/table/table_renderer.dart index d615420..3068d35 100644 --- a/lib/src/presentation/blocks/table/table_renderer.dart +++ b/lib/src/presentation/blocks/table/table_renderer.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_html/flutter_html.dart'; import '../../../domain/entities/blocks/table_block.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class TableRenderer extends BlockRenderer { @@ -15,38 +17,54 @@ class TableRenderer extends BlockRenderer { ); if (columnCount == 0) return const SizedBox.shrink(); - return SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Table( - border: TableBorder.all(color: Colors.grey.shade300), - children: block.content.asMap().entries.map((entry) { - final rowIndex = entry.key; - final row = entry.value; - final isHeader = block.withHeadings && rowIndex == 0; - - return TableRow( - decoration: isHeader - ? BoxDecoration(color: Colors.grey.shade100) - : null, - children: List.generate(columnCount, (colIndex) { - final cell = - colIndex < row.length ? row[colIndex] : ''; - return Padding( - padding: const EdgeInsets.symmetric( - horizontal: 12, vertical: 8), - child: Text( - cell, - style: TextStyle( - fontWeight: - isHeader ? FontWeight.bold : FontWeight.normal, - fontFamily: styleConfig?.defaultFont, - ), - ), - ); - }), - ); - }).toList(), + final table = Table( + // Columns are as wide as their content. The table scrolls sideways, so + // its width is unbounded and a flex-only column would collapse to zero. + // A stretched table additionally shares out any leftover width. + defaultColumnWidth: IntrinsicColumnWidth( + flex: block.stretched ? 1 : null, ), + border: TableBorder.all(color: Colors.grey.shade300), + children: block.content.asMap().entries.map((entry) { + final rowIndex = entry.key; + final row = entry.value; + final isHeader = block.withHeadings && rowIndex == 0; + + return TableRow( + decoration: isHeader + ? BoxDecoration(color: Colors.grey.shade100) + : null, + children: List.generate(columnCount, (colIndex) { + final cell = + colIndex < row.length ? row[colIndex] : ''; + return Padding( + padding: const EdgeInsets.symmetric( + horizontal: 12, vertical: 8), + child: InlineHtml( + cell, + styleConfig: styleConfig, + bodyStyle: + isHeader ? Style(fontWeight: FontWeight.bold) : null, + ), + ); + }), + ); + }).toList(), + ); + + return LayoutBuilder( + builder: (context, constraints) { + final fillWidth = block.stretched && constraints.hasBoundedWidth; + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: fillWidth + ? ConstrainedBox( + constraints: BoxConstraints(minWidth: constraints.maxWidth), + child: table, + ) + : table, + ); + }, ); } } diff --git a/lib/src/presentation/blocks/warning/warning_renderer.dart b/lib/src/presentation/blocks/warning/warning_renderer.dart index d7a2bed..864c518 100644 --- a/lib/src/presentation/blocks/warning/warning_renderer.dart +++ b/lib/src/presentation/blocks/warning/warning_renderer.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; +import 'package:flutter_html/flutter_html.dart'; import '../../../domain/entities/blocks/warning_block.dart'; +import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; class WarningRenderer extends BlockRenderer { @@ -30,18 +32,13 @@ class WarningRenderer extends BlockRenderer { if (block.title.isNotEmpty) Padding( padding: const EdgeInsets.only(bottom: 4), - child: Text( + child: InlineHtml( block.title, - style: TextStyle( - fontWeight: FontWeight.bold, - fontFamily: styleConfig?.defaultFont, - ), + styleConfig: styleConfig, + bodyStyle: Style(fontWeight: FontWeight.bold), ), ), - Text( - block.message, - style: TextStyle(fontFamily: styleConfig?.defaultFont), - ), + InlineHtml(block.message, styleConfig: styleConfig), ], ), ), diff --git a/lib/src/presentation/config/editor_config.dart b/lib/src/presentation/config/editor_config.dart index cd807e9..4ffd9cd 100644 --- a/lib/src/presentation/config/editor_config.dart +++ b/lib/src/presentation/config/editor_config.dart @@ -1,6 +1,7 @@ import '../../data/registry/block_type_registry.dart'; import '../../domain/entities/style_config.dart'; import '../registry/block_renderer_registry.dart'; +import '../widgets/editor_link_scope.dart'; /// Configuration object shared by [EditorJSView] and [EditorJSEditor]. /// @@ -11,10 +12,19 @@ class EditorConfig { final BlockRendererRegistry rendererRegistry; final StyleConfig? styleConfig; + /// Called when the reader taps a link in rendered content: an `` inside + /// any text, or a link, embed or attachment card. + /// + /// Leave it null to open `http`, `https`, `mailto` and `tel` links in the + /// external application and ignore every other scheme. A handler receives + /// the URL unfiltered, so it can route app-specific links itself. + final LinkTapCallback? onLinkTap; + EditorConfig({ BlockTypeRegistry? typeRegistry, BlockRendererRegistry? rendererRegistry, this.styleConfig, + this.onLinkTap, }) : typeRegistry = typeRegistry ?? BlockTypeRegistry(), rendererRegistry = rendererRegistry ?? BlockRendererRegistry(); } diff --git a/lib/src/presentation/widgets/editor_link_scope.dart b/lib/src/presentation/widgets/editor_link_scope.dart new file mode 100644 index 0000000..7421713 --- /dev/null +++ b/lib/src/presentation/widgets/editor_link_scope.dart @@ -0,0 +1,74 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:url_launcher/url_launcher.dart'; + +/// Called with the target of a link the reader tapped. +/// +/// The URL is passed exactly as it appears in the document, so a handler that +/// opens it should decide which schemes it trusts. +typedef LinkTapCallback = void Function(String url); + +/// Tells the block renderers below it what to do when a link is tapped. +/// +/// `EditorJSView` inserts one from `EditorConfig.onLinkTap`. Custom renderers +/// should route their own links through [open] so they follow the same rule +/// as the built-in blocks: +/// +/// ```dart +/// onTap: () => EditorLinkScope.open(context, block.url), +/// ``` +class EditorLinkScope extends InheritedWidget { + /// Handler for tapped links, or `null` to open them externally. + final LinkTapCallback? onLinkTap; + + const EditorLinkScope({ + super.key, + required this.onLinkTap, + required super.child, + }); + + /// Schemes the default behaviour will hand to the operating system. + /// Anything else (`javascript:`, `file:`, app-specific schemes) is ignored. + static const Set defaultSchemes = {'http', 'https', 'mailto', 'tel'}; + + /// Opens [url] using the nearest scope's handler. + /// + /// Without a handler (or without a scope, as when a renderer is used on its + /// own) the link is opened in the external application via + /// [launchExternally]. Null and blank URLs are ignored. + static void open(BuildContext context, String? url) { + if (url == null || url.trim().isEmpty) return; + + final handler = context + .getInheritedWidgetOfExactType() + ?.onLinkTap; + if (handler != null) { + handler(url); + } else { + unawaited(launchExternally(url)); + } + } + + /// Opens [url] in the external application if its scheme is one of + /// [defaultSchemes]. Returns whether the link was opened. + static Future launchExternally(String url) async { + final uri = Uri.tryParse(url.trim()); + if (uri == null || !defaultSchemes.contains(uri.scheme.toLowerCase())) { + return false; + } + try { + if (!await canLaunchUrl(uri)) return false; + return await launchUrl(uri, mode: LaunchMode.externalApplication); + } on PlatformException { + return false; + } on MissingPluginException { + return false; + } + } + + @override + bool updateShouldNotify(EditorLinkScope oldWidget) => + onLinkTap != oldWidget.onLinkTap; +} diff --git a/lib/src/presentation/widgets/editorjs_view.dart b/lib/src/presentation/widgets/editorjs_view.dart index 93ebb85..913785b 100644 --- a/lib/src/presentation/widgets/editorjs_view.dart +++ b/lib/src/presentation/widgets/editorjs_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../data/datasources/json_document_source.dart'; import '../../domain/usecases/parse_document.dart'; import '../config/editor_config.dart'; +import 'editor_link_scope.dart'; /// Read-only viewer for EditorJS JSON content. /// @@ -33,14 +34,17 @@ class EditorJSView extends StatelessWidget { config.rendererRegistry.buildRenderer(block, config.styleConfig), ].nonNulls; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (final widget in rendered) ...[ - widget, - const SizedBox(height: 8), + return EditorLinkScope( + onLinkTap: config.onLinkTap, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final widget in rendered) ...[ + widget, + const SizedBox(height: 8), + ], ], - ], + ), ); } } diff --git a/lib/src/presentation/widgets/inline_html.dart b/lib/src/presentation/widgets/inline_html.dart new file mode 100644 index 0000000..6a52fe2 --- /dev/null +++ b/lib/src/presentation/widgets/inline_html.dart @@ -0,0 +1,62 @@ +import 'package:flutter/widgets.dart'; +import 'package:flutter_html/flutter_html.dart'; + +import '../../data/utils/html_sanitizer.dart'; +import '../../domain/entities/style_config.dart'; +import '../utils/html_style_builder.dart'; +import 'editor_link_scope.dart'; + +/// Renders a piece of EditorJS text. +/// +/// Every editable field in EditorJS is `contenteditable`, so its saved value +/// is HTML: it can carry inline formatting (``, ``, ``, ``, +/// ``) and always carries entities such as ` ` and `&`. This +/// widget is the single place that turns such a string into widgets, so every +/// block sanitizes, styles and handles link taps the same way. +class InlineHtml extends StatelessWidget { + final String html; + final StyleConfig? styleConfig; + + /// Extra styling for the text as a whole (size, weight, colour, alignment), + /// applied on top of [styleConfig]. + final Style? bodyStyle; + + /// Whether the text is a fragment inside another widget (a heading, a table + /// cell, a caption) rather than a block of its own. + /// + /// A compact fragment has no outer margin and is only as wide as its + /// content. A block keeps a vertical margin and spans the available width. + /// Neither has a horizontal margin, so all blocks share one left edge. + final bool compact; + + static const double _blockMargin = 8; + + const InlineHtml( + this.html, { + super.key, + this.styleConfig, + this.bodyStyle, + this.compact = true, + }); + + @override + Widget build(BuildContext context) { + final styles = HtmlStyleBuilder.build(styleConfig); + + // flutter_html gives `` an 8px margin on every side by default. + var body = (styles['body'] ?? Style()).copyWith( + margin: compact + ? Margins.zero + : Margins.symmetric(horizontal: 0, vertical: _blockMargin), + padding: HtmlPaddings.zero, + ); + if (bodyStyle != null) body = body.merge(bodyStyle!); + + return Html( + data: HtmlSanitizer.sanitize(html), + shrinkWrap: compact, + style: {...styles, 'body': body}, + onLinkTap: (url, _, __) => EditorLinkScope.open(context, url), + ); + } +} diff --git a/test/widget/viewer_fidelity_test.dart b/test/widget/viewer_fidelity_test.dart new file mode 100644 index 0000000..54250f0 --- /dev/null +++ b/test/widget/viewer_fidelity_test.dart @@ -0,0 +1,450 @@ +import 'dart:convert'; + +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/header/header_renderer.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/table/table_renderer.dart'; +import 'package:editorjs_flutter/src/presentation/widgets/inline_html.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const double _hostWidth = 600; + +Widget _host(Widget child) => MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: Align( + alignment: Alignment.topLeft, + child: SizedBox(width: _hostWidth, child: child), + ), + ), + ), + ); + +String _doc(List> blocks) => jsonEncode({'blocks': blocks}); + +Map _block(String type, Map data) => + {'type': type, 'data': data}; + +/// Pumps a viewer whose link taps are collected into the returned list. +Future> _pumpView( + WidgetTester tester, + List> blocks, +) async { + final tapped = []; + await tester.pumpWidget(_host(EditorJSView( + jsonData: _doc(blocks), + config: EditorConfig(onLinkTap: tapped.add), + ))); + await tester.pumpAndSettle(); + return tapped; +} + +/// Taps the start of the text [label]. A block-level text widget spans the +/// full width, so its centre is usually empty space rather than the link. +Future _tapText(WidgetTester tester, String label) { + final rect = tester.getRect(find.text(label)); + return tester.tapAt(Offset(rect.left + 8, rect.center.dy)); +} + +void main() { + group('inline HTML and entities are rendered, not shown as markup', () { + testWidgets('header', (tester) async { + await _pumpView(tester, [ + _block('header', { + 'text': 'Fish & chips guide', + 'level': 2, + }), + ]); + expect(find.text('Fish & chips guide'), findsOneWidget); + expect(find.textContaining(''), findsNothing); + expect(find.textContaining('&'), findsNothing); + }); + + testWidgets('header size still follows its level', (tester) async { + Future heightOf(int level) async { + await tester.pumpWidget(_host( + HeaderRenderer(block: HeaderBlock(text: 'Title', level: level)), + )); + return tester.getSize(find.text('Title')).height; + } + + final h1 = await heightOf(1); + final h3 = await heightOf(3); + final h6 = await heightOf(6); + expect(h1, greaterThan(h3)); + expect(h3, greaterThan(h6)); + }); + + testWidgets('table cells', (tester) async { + await _pumpView(tester, [ + _block('table', { + 'withHeadings': true, + 'content': [ + ['Pigs & co', 'Chicken'], + ['1 pcs', '12 pcs'], + ], + }), + ]); + expect(find.text('Pigs & co'), findsOneWidget); + expect(find.text('1 pcs'), findsOneWidget); + expect(find.text('12 pcs'), findsOneWidget); + }); + + testWidgets('legacy checklist items', (tester) async { + await _pumpView(tester, [ + _block('checklist', { + 'items': [ + {'text': 'Done & dusted', 'checked': true}, + {'text': 'Open <item>', 'checked': false}, + ], + }), + ]); + expect(find.text('Done & dusted'), findsOneWidget); + expect(find.text('Open '), findsOneWidget); + }); + + testWidgets('warning title and message', (tester) async { + await _pumpView(tester, [ + _block('warning', { + 'title': 'Note & care', + 'message': 'Avoid this method.', + }), + ]); + expect(find.text('Note & care'), findsOneWidget); + expect(find.text('Avoid this method.'), findsOneWidget); + }); + + testWidgets('quote, embed and image captions', (tester) async { + await _pumpView(tester, [ + _block('quote', { + 'text': 'Quote', + 'caption': 'Socrates & co', + 'alignment': 'center', + }), + _block('embed', { + 'service': 'youtube', + 'source': 'https://youtu.be/x', + 'embed': 'https://youtube.com/embed/x', + 'caption': 'Clip & notes', + }), + _block('image', { + 'file': {'url': 'https://example.com/a.png'}, + 'caption': 'Photo & credit', + }), + ]); + expect(find.text('— Socrates & co'), findsOneWidget); + expect(find.text('Clip & notes'), findsOneWidget); + expect(find.text('Photo & credit'), findsOneWidget); + }); + }); + + group('layout', () { + testWidgets('a table is as wide as its content, not collapsed', + (tester) async { + await _pumpView(tester, [ + _block('table', { + 'content': [ + ['Kine', 'Pigs'], + ['1 pcs', '3 pcs'], + ], + }), + ]); + expect(tester.takeException(), isNull); + + final table = tester.getSize(find.byType(Table)); + expect(table.width, greaterThan(0)); + expect(table.width, lessThan(_hostWidth)); + expect(tester.getSize(find.text('Kine')).width, greaterThan(0)); + }); + + testWidgets('a stretched table fills the available width', (tester) async { + await _pumpView(tester, [ + _block('table', { + 'stretched': true, + 'content': [ + ['a', 'b'], + ], + }), + ]); + expect(tester.getSize(find.byType(Table)).width, _hostWidth); + }); + + testWidgets('a table wider than the screen scrolls instead of overflowing', + (tester) async { + final wide = List.filled(12, 'a fairly long cell of text'); + for (final stretched in [false, true]) { + await _pumpView(tester, [ + _block('table', { + 'stretched': stretched, + 'content': [wide], + }), + ]); + expect(tester.takeException(), isNull); + expect( + tester.getSize(find.byType(Table)).width, + greaterThan(_hostWidth), + ); + } + }); + + testWidgets('empty and ragged tables do not throw', (tester) async { + await tester.pumpWidget(_host(const Column( + children: [ + TableRenderer(block: TableBlock(content: [])), + TableRenderer(block: TableBlock(content: [[]])), + TableRenderer( + block: TableBlock( + content: [ + ['only one'], + ['two', 'cells'], + ], + ), + ), + ], + ))); + expect(tester.takeException(), isNull); + expect(find.byType(Table), findsOneWidget); + }); + + testWidgets('blocks share one left edge', (tester) async { + await _pumpView(tester, [ + _block('header', {'text': 'Title', 'level': 2}), + _block('paragraph', {'text': 'Body'}), + _block('raw', {'html': 'Raw'}), + ]); + final left = tester.getTopLeft(find.text('Title')).dx; + expect(tester.getTopLeft(find.text('Body')).dx, left); + expect(tester.getTopLeft(find.text('Raw')).dx, left); + }); + + testWidgets('a list marker starts on the same line as its item', + (tester) async { + await _pumpView(tester, [ + _block('list', { + 'style': 'ordered', + 'items': [ + {'content': 'First', 'meta': {}, 'items': []}, + ], + }), + ]); + expect( + tester.getTopLeft(find.text('1.')).dy, + closeTo(tester.getTopLeft(find.text('First')).dy, 1), + ); + }); + }); + + group('links', () { + testWidgets('links inside text reach EditorConfig.onLinkTap', + (tester) async { + final tapped = await _pumpView(tester, [ + _block('paragraph', {'text': 'Para'}), + _block('header', { + 'text': 'Head', + 'level': 3, + }), + _block('list', { + 'style': 'unordered', + 'items': [ + { + 'content': 'Item', + 'meta': {}, + 'items': [], + }, + ], + }), + _block('table', { + 'content': [ + ['Cell'], + ], + }), + _block('quote', { + 'text': 'Quote', + 'caption': '', + 'alignment': 'left', + }), + ]); + + for (final label in ['Para', 'Head', 'Item', 'Cell', 'Quote']) { + await _tapText(tester, label); + } + expect(tapped, [ + 'https://p.example', + 'https://h.example', + 'https://l.example', + 'https://t.example', + 'https://q.example', + ]); + }); + + testWidgets('link, embed and attachment cards reach onLinkTap', + (tester) async { + final tapped = await _pumpView(tester, [ + _block('linkTool', { + 'link': 'https://link.example', + 'meta': {'title': 'Link card'}, + }), + _block('embed', { + 'service': 'vimeo', + 'source': 'https://embed.example', + 'embed': 'https://embed.example/e', + }), + _block('attaches', { + 'file': {'url': 'https://file.example/a.pdf'}, + 'title': 'Attachment card', + }), + ]); + + await tester.tap(find.text('Link card')); + await tester.tap(find.text('Vimeo')); + await tester.tap(find.text('Attachment card')); + expect(tapped, [ + 'https://link.example', + 'https://embed.example', + 'https://file.example/a.pdf', + ]); + }); + + testWidgets('a handler receives the URL unfiltered', (tester) async { + final tapped = await _pumpView(tester, [ + _block('paragraph', {'text': 'Deep'}), + ]); + await _tapText(tester, 'Deep'); + expect(tapped, ['myapp://item/7']); + }); + }); + + group('EditorLinkScope default behaviour', () { + const channel = MethodChannel('plugins.flutter.io/url_launcher'); + late List calls; + late Object? Function(MethodCall call) respond; + + setUp(() { + calls = []; + respond = (call) => true; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return respond(call); + }); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + }); + + List launched() => [ + for (final call in calls) + if (call.method == 'launch') (call.arguments as Map)['url'], + ]; + + test('opens http, https, mailto and tel links', () async { + for (final url in [ + 'http://a.example', + 'https://a.example/path?q=1', + 'mailto:hi@a.example', + 'tel:+123456', + ]) { + expect(await EditorLinkScope.launchExternally(url), isTrue); + } + expect(launched(), hasLength(4)); + expect(launched().first, 'http://a.example'); + }); + + test('ignores other schemes, relative and malformed URLs', () async { + for (final url in [ + 'javascript:alert(1)', + 'file:///etc/passwd', + 'myapp://item/7', + '/relative/path', + 'not a url', + '::::', + ]) { + expect(await EditorLinkScope.launchExternally(url), isFalse); + } + expect(calls, isEmpty); + }); + + test('reports false when the platform cannot open the link', () async { + respond = (call) => call.method != 'canLaunch'; + expect(await EditorLinkScope.launchExternally('https://a.example'), + isFalse); + expect(launched(), isEmpty); + }); + + test('reports false instead of throwing when the platform fails', + () async { + respond = (call) => throw PlatformException(code: 'ACTIVITY_NOT_FOUND'); + expect(await EditorLinkScope.launchExternally('https://a.example'), + isFalse); + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + expect(await EditorLinkScope.launchExternally('https://a.example'), + isFalse); + }); + + testWidgets('a viewer without onLinkTap opens links externally', + (tester) async { + await tester.pumpWidget(_host(EditorJSView( + jsonData: _doc([ + _block('paragraph', {'text': 'Go'}), + _block('paragraph', {'text': 'No'}), + ]), + ))); + await tester.pumpAndSettle(); + + await _tapText(tester, 'Go'); + await _tapText(tester, 'No'); + await tester.pumpAndSettle(); + expect(launched(), ['https://d.example']); + }); + + testWidgets('a renderer used on its own opens links externally', + (tester) async { + await tester.pumpWidget(_host( + const InlineHtml('Solo'), + )); + await _tapText(tester, 'Solo'); + await tester.pumpAndSettle(); + expect(launched(), ['https://s.example']); + }); + + testWidgets('null and blank URLs are ignored', (tester) async { + final tapped = []; + late BuildContext context; + await tester.pumpWidget(EditorLinkScope( + onLinkTap: tapped.add, + child: Builder(builder: (c) { + context = c; + return const SizedBox(); + }), + )); + EditorLinkScope.open(context, null); + EditorLinkScope.open(context, ' '); + EditorLinkScope.open(context, 'https://ok.example'); + expect(tapped, ['https://ok.example']); + expect(calls, isEmpty); + }); + + test('notifies dependants only when the handler changes', () { + void handler(String url) {} + const child = SizedBox(); + final scope = EditorLinkScope(onLinkTap: handler, child: child); + expect( + scope.updateShouldNotify( + EditorLinkScope(onLinkTap: handler, child: child), + ), + isFalse, + ); + expect( + scope.updateShouldNotify( + const EditorLinkScope(onLinkTap: null, child: child), + ), + isTrue, + ); + }); + }); +} From 30281ca9f31393c716bef05b7fc1ac595a1c3037 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 01:21:42 -0600 Subject: [PATCH 05/16] Open only web links by default; make tables full width Review feedback on the viewer fidelity change. - Links: the default now opens http and https only. Other schemes are opt-in through the new EditorConfig.allowedLinkSchemes, which EditorLinkScope carries down to the renderers. - Tables: as in EditorJS, a table spans the full width with equal columns and wraps the text in its cells, instead of sizing columns to their content. A table whose columns would be narrower than 96 px keeps that width and scrolls sideways. stretched no longer changes the layout; it is still read and written back. Co-Authored-By: Claude --- CHANGELOG.md | 8 +- CLAUDE.md | 2 +- README.md | 13 +- .../blocks/table/table_renderer.dart | 52 ++--- .../presentation/config/editor_config.dart | 15 +- .../widgets/editor_link_scope.dart | 39 ++-- .../presentation/widgets/editorjs_view.dart | 1 + test/widget/viewer_fidelity_test.dart | 177 +++++++++++++----- 8 files changed, 215 insertions(+), 92 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 50f42af..3031e23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,9 +14,9 @@ * **Legacy formats are still read:** `@editorjs/list` 1.x string items, `@editorjs/nested-list` items, and old checklist `{text, checked}` items stored under a list block. ### Viewer fidelity -* **Tables are now visible.** The table renderer laid its columns out at zero width, so every table showed as a thin strip with one letter per line. Columns now take the width of their content and the table scrolls sideways when it is wider than the screen. A `stretched` table fills the available width. +* **Tables are now visible.** The table renderer laid its columns out at zero width, so every table showed as a thin strip with one letter per line. As in EditorJS, a table now spans the full width with equal columns and wraps the text in its cells. A table with too many columns to keep them 96 px wide scrolls sideways instead of squeezing them. * **Inline formatting and entities are rendered everywhere.** Headers, table cells, legacy checklist items, warning title and message, and image, embed and quote captions showed markup such as `` and `&` literally. All text now goes through one widget, so bold, italic, links, marker, inline code and entities render in every block. -* **Links can be tapped.** `` links did nothing. They now open in the external application (`http`, `https`, `mailto` and `tel` only), or are passed to the new `EditorConfig.onLinkTap`. Link, embed and attachment cards go through the same handler. Custom renderers can join in with `EditorLinkScope.open(context, url)`. +* **Links can be tapped.** `` links did nothing. Web links (`http`, `https`) now open in the external application; other schemes are opt-in through the new `EditorConfig.allowedLinkSchemes` (for example `{'http', 'https', 'mailto', 'tel'}`). To handle taps yourself, pass the new `EditorConfig.onLinkTap`. Link, embed and attachment cards go through the same path. Custom renderers can join in with `EditorLinkScope.open(context, url)`. * **Blocks line up.** Paragraph, quote and raw text had an extra 8 px left and right margin that headers and tables did not; list markers sat about 6 px above their item's text. Both are fixed, and list items are spaced 8 px apart. ### Parser hardening @@ -30,13 +30,13 @@ * `BlockRendererRegistry.buildRenderer` / `buildEditor` return `null` for an `UnknownBlock` even when a builder is registered for its type string. * Blocks with a missing or non-string `type` are still dropped: they cannot be written back. * The toolbar's "Checklist" button creates a `list` block with the checklist style, no longer a `checklist` block; the previous behaviour moved to the new "Checklist (legacy)" button. -* Link, embed and attachment cards now also open `mailto` and `tel` targets, and no longer raise an unhandled error when the platform cannot open a link. +* Link, embed and attachment cards no longer raise an unhandled error when the platform cannot open a link. * Paragraph, quote and raw blocks are 16 px wider (no horizontal margin) and list rows are closer together. * `ListStyle` has a third value, `checklist`: an exhaustive `switch` over `ListStyle` in consumer code needs a new case. * Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart` and `test/widget/viewer_fidelity_test.dart` (337 tests in total, 92 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart` and `test/widget/viewer_fidelity_test.dart` (340 tests in total, 92 % line coverage). --- diff --git a/CLAUDE.md b/CLAUDE.md index 3679c91..444ebda 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -117,7 +117,7 @@ final config = EditorConfig( | `quote` | With alignment | ✅ | | | `code` | Monospace + copy button | ✅ | | | `checklist` | Checked / unchecked | ✅ | Legacy `@editorjs/checklist` block; toolbar button "Checklist (legacy)". The toolbar's "Checklist" button creates a `list` block with the checklist style | -| `table` | Optional heading row, `stretched`, inline HTML in cells | ✅ | Columns sized to content; scrolls horizontally | +| `table` | Optional heading row, inline HTML in cells | ✅ | Full width with equal columns, text wraps; scrolls horizontally when columns would be narrower than 96 px. `stretched` is preserved but has no visual effect | | `warning` | Title + message, inline HTML | ✅ | | | `embed` | Tappable card | Viewer only | | | `linkTool` | Link preview card | Viewer only | | diff --git a/README.md b/README.md index 8c3c179..3d13088 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,18 @@ EditorJSView( ### Handling link taps -Links in the content open in the external application by default (`http`, `https`, `mailto` and `tel` only). To handle them yourself, for example with an in-app browser or your own router, pass `onLinkTap`: +Web links (`http` and `https`) in the content open in the external application by default; links with any other scheme do nothing. To allow more schemes, list them: + +```dart +EditorJSView( + jsonData: myJsonString, + config: EditorConfig( + allowedLinkSchemes: const {'http', 'https', 'mailto', 'tel'}, + ), +) +``` + +To handle taps yourself, for example with an in-app browser or your own router, pass `onLinkTap`: ```dart EditorJSView( diff --git a/lib/src/presentation/blocks/table/table_renderer.dart b/lib/src/presentation/blocks/table/table_renderer.dart index 3068d35..0d5ea92 100644 --- a/lib/src/presentation/blocks/table/table_renderer.dart +++ b/lib/src/presentation/blocks/table/table_renderer.dart @@ -8,6 +8,9 @@ import '../base_block_renderer.dart'; class TableRenderer extends BlockRenderer { const TableRenderer({super.key, required super.block, super.styleConfig}); + /// Narrowest a column may get before the table scrolls instead of shrinking. + static const double _minColumnWidth = 96; + @override Widget build(BuildContext context) { if (block.content.isEmpty) return const SizedBox.shrink(); @@ -17,13 +20,33 @@ class TableRenderer extends BlockRenderer { ); if (columnCount == 0) return const SizedBox.shrink(); - final table = Table( - // Columns are as wide as their content. The table scrolls sideways, so - // its width is unbounded and a flex-only column would collapse to zero. - // A stretched table additionally shares out any leftover width. - defaultColumnWidth: IntrinsicColumnWidth( - flex: block.stretched ? 1 : null, - ), + return LayoutBuilder( + builder: (context, constraints) { + // Without a width to fill (e.g. inside a horizontal scroll view), + // fall back to columns as wide as their content. + if (!constraints.hasBoundedWidth) { + return _buildTable(columnCount, const IntrinsicColumnWidth()); + } + + // Like EditorJS, a table spans the full width with equal columns and + // wraps the text in its cells. + final table = _buildTable(columnCount, const FlexColumnWidth()); + final minWidth = columnCount * _minColumnWidth; + if (minWidth <= constraints.maxWidth) return table; + + // Too many columns to stay readable: keep them at the minimum width + // and let the table scroll sideways instead. + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox(width: minWidth, child: table), + ); + }, + ); + } + + Widget _buildTable(int columnCount, TableColumnWidth columnWidth) { + return Table( + defaultColumnWidth: columnWidth, border: TableBorder.all(color: Colors.grey.shade300), children: block.content.asMap().entries.map((entry) { final rowIndex = entry.key; @@ -51,20 +74,5 @@ class TableRenderer extends BlockRenderer { ); }).toList(), ); - - return LayoutBuilder( - builder: (context, constraints) { - final fillWidth = block.stretched && constraints.hasBoundedWidth; - return SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: fillWidth - ? ConstrainedBox( - constraints: BoxConstraints(minWidth: constraints.maxWidth), - child: table, - ) - : table, - ); - }, - ); } } diff --git a/lib/src/presentation/config/editor_config.dart b/lib/src/presentation/config/editor_config.dart index 4ffd9cd..8866b76 100644 --- a/lib/src/presentation/config/editor_config.dart +++ b/lib/src/presentation/config/editor_config.dart @@ -15,16 +15,25 @@ class EditorConfig { /// Called when the reader taps a link in rendered content: an `` inside /// any text, or a link, embed or attachment card. /// - /// Leave it null to open `http`, `https`, `mailto` and `tel` links in the - /// external application and ignore every other scheme. A handler receives - /// the URL unfiltered, so it can route app-specific links itself. + /// Leave it null to open links in the external application, limited to + /// [allowedLinkSchemes]. A handler receives the URL unfiltered, so it can + /// route app-specific links itself. final LinkTapCallback? onLinkTap; + /// URL schemes the viewer may open externally when [onLinkTap] is null. + /// + /// Defaults to web links only (`http` and `https`). Add the schemes you + /// want to allow, for example + /// `{'http', 'https', 'mailto', 'tel'}` to also open e-mail and phone + /// links. Links with any other scheme do nothing when tapped. + final Set allowedLinkSchemes; + EditorConfig({ BlockTypeRegistry? typeRegistry, BlockRendererRegistry? rendererRegistry, this.styleConfig, this.onLinkTap, + this.allowedLinkSchemes = EditorLinkScope.defaultSchemes, }) : typeRegistry = typeRegistry ?? BlockTypeRegistry(), rendererRegistry = rendererRegistry ?? BlockRendererRegistry(); } diff --git a/lib/src/presentation/widgets/editor_link_scope.dart b/lib/src/presentation/widgets/editor_link_scope.dart index 7421713..0523c25 100644 --- a/lib/src/presentation/widgets/editor_link_scope.dart +++ b/lib/src/presentation/widgets/editor_link_scope.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:url_launcher/url_launcher.dart'; @@ -12,7 +13,8 @@ typedef LinkTapCallback = void Function(String url); /// Tells the block renderers below it what to do when a link is tapped. /// -/// `EditorJSView` inserts one from `EditorConfig.onLinkTap`. Custom renderers +/// `EditorJSView` inserts one from `EditorConfig.onLinkTap` and +/// `EditorConfig.allowedLinkSchemes`. Custom renderers /// should route their own links through [open] so they follow the same rule /// as the built-in blocks: /// @@ -23,15 +25,20 @@ class EditorLinkScope extends InheritedWidget { /// Handler for tapped links, or `null` to open them externally. final LinkTapCallback? onLinkTap; + /// URL schemes that may be opened externally when [onLinkTap] is null. + final Set allowedSchemes; + const EditorLinkScope({ super.key, required this.onLinkTap, + this.allowedSchemes = defaultSchemes, required super.child, }); - /// Schemes the default behaviour will hand to the operating system. - /// Anything else (`javascript:`, `file:`, app-specific schemes) is ignored. - static const Set defaultSchemes = {'http', 'https', 'mailto', 'tel'}; + /// Schemes opened externally unless configured otherwise: web links only. + /// Anything else (`mailto:`, `tel:`, `javascript:`, `file:`, app-specific + /// schemes) is ignored until it is added to the allowed schemes. + static const Set defaultSchemes = {'http', 'https'}; /// Opens [url] using the nearest scope's handler. /// @@ -41,21 +48,28 @@ class EditorLinkScope extends InheritedWidget { static void open(BuildContext context, String? url) { if (url == null || url.trim().isEmpty) return; - final handler = context - .getInheritedWidgetOfExactType() - ?.onLinkTap; + final scope = context.getInheritedWidgetOfExactType(); + final handler = scope?.onLinkTap; if (handler != null) { handler(url); } else { - unawaited(launchExternally(url)); + unawaited(launchExternally( + url, + allowedSchemes: scope?.allowedSchemes ?? defaultSchemes, + )); } } /// Opens [url] in the external application if its scheme is one of - /// [defaultSchemes]. Returns whether the link was opened. - static Future launchExternally(String url) async { + /// [allowedSchemes] (compared case-insensitively). Returns whether the link + /// was opened. + static Future launchExternally( + String url, { + Set allowedSchemes = defaultSchemes, + }) async { final uri = Uri.tryParse(url.trim()); - if (uri == null || !defaultSchemes.contains(uri.scheme.toLowerCase())) { + if (uri == null || + !allowedSchemes.any((s) => s.toLowerCase() == uri.scheme)) { return false; } try { @@ -70,5 +84,6 @@ class EditorLinkScope extends InheritedWidget { @override bool updateShouldNotify(EditorLinkScope oldWidget) => - onLinkTap != oldWidget.onLinkTap; + onLinkTap != oldWidget.onLinkTap || + !setEquals(allowedSchemes, oldWidget.allowedSchemes); } diff --git a/lib/src/presentation/widgets/editorjs_view.dart b/lib/src/presentation/widgets/editorjs_view.dart index 913785b..128b27b 100644 --- a/lib/src/presentation/widgets/editorjs_view.dart +++ b/lib/src/presentation/widgets/editorjs_view.dart @@ -36,6 +36,7 @@ class EditorJSView extends StatelessWidget { return EditorLinkScope( onLinkTap: config.onLinkTap, + allowedSchemes: config.allowedLinkSchemes, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ diff --git a/test/widget/viewer_fidelity_test.dart b/test/widget/viewer_fidelity_test.dart index 54250f0..e1c5fcd 100644 --- a/test/widget/viewer_fidelity_test.dart +++ b/test/widget/viewer_fidelity_test.dart @@ -140,52 +140,87 @@ void main() { }); group('layout', () { - testWidgets('a table is as wide as its content, not collapsed', + testWidgets('a table spans the full width with equal columns', (tester) async { - await _pumpView(tester, [ - _block('table', { - 'content': [ - ['Kine', 'Pigs'], - ['1 pcs', '3 pcs'], - ], - }), - ]); - expect(tester.takeException(), isNull); + for (final stretched in [false, true]) { + await _pumpView(tester, [ + _block('table', { + 'stretched': stretched, + 'content': [ + ['Kine', 'A much longer heading'], + ['1 pcs', '3 pcs'], + ], + }), + ]); + expect(tester.takeException(), isNull); + expect(tester.getSize(find.byType(Table)).width, _hostWidth); + + // Equal columns: the second one starts at the halfway point, however + // different the content of the two is. + final first = tester.getTopLeft(find.text('Kine')).dx; + final second = tester.getTopLeft(find.text('A much longer heading')).dx; + expect(second - first, _hostWidth / 2); + } + }); - final table = tester.getSize(find.byType(Table)); - expect(table.width, greaterThan(0)); - expect(table.width, lessThan(_hostWidth)); - expect(tester.getSize(find.text('Kine')).width, greaterThan(0)); + testWidgets('long cell text wraps instead of widening the table', + (tester) async { + Future tableSize(String cell) async { + await _pumpView(tester, [ + _block('table', { + 'content': [ + [cell, 'b'], + ], + }), + ]); + return tester.getSize(find.byType(Table)); + } + + final short = await tableSize('a'); + final long = await tableSize(List.filled(30, 'word').join(' ')); + expect(long.width, _hostWidth); + expect(long.height, greaterThan(short.height)); }); - testWidgets('a stretched table fills the available width', (tester) async { + testWidgets('a table with too many columns scrolls instead of squeezing', + (tester) async { await _pumpView(tester, [ _block('table', { - 'stretched': true, - 'content': [ - ['a', 'b'], - ], + 'content': [List.filled(12, 'cell')], }), ]); - expect(tester.getSize(find.byType(Table)).width, _hostWidth); + expect(tester.takeException(), isNull); + // 12 columns at the 96 px minimum. + expect(tester.getSize(find.byType(Table)).width, 12 * 96); + expect( + find.ancestor( + of: find.byType(Table), + matching: find.byWidgetPredicate( + (w) => + w is SingleChildScrollView && + w.scrollDirection == Axis.horizontal, + ), + ), + findsOneWidget, + ); }); - testWidgets('a table wider than the screen scrolls instead of overflowing', + testWidgets('a table with no width to fill sizes columns to content', (tester) async { - final wide = List.filled(12, 'a fairly long cell of text'); - for (final stretched in [false, true]) { - await _pumpView(tester, [ - _block('table', { - 'stretched': stretched, - 'content': [wide], - }), - ]); - expect(tester.takeException(), isNull); - expect( - tester.getSize(find.byType(Table)).width, - greaterThan(_hostWidth), - ); - } + await tester.pumpWidget(_host(const SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: TableRenderer( + block: TableBlock( + content: [ + ['Kine', 'Pigs'], + ], + ), + ), + ))); + expect(tester.takeException(), isNull); + final width = tester.getSize(find.byType(Table)).width; + expect(width, greaterThan(0)); + expect(width, lessThan(_hostWidth)); }); testWidgets('empty and ragged tables do not throw', (tester) async { @@ -340,21 +375,19 @@ void main() { if (call.method == 'launch') (call.arguments as Map)['url'], ]; - test('opens http, https, mailto and tel links', () async { - for (final url in [ - 'http://a.example', - 'https://a.example/path?q=1', - 'mailto:hi@a.example', - 'tel:+123456', - ]) { - expect(await EditorLinkScope.launchExternally(url), isTrue); - } - expect(launched(), hasLength(4)); - expect(launched().first, 'http://a.example'); + test('opens web links by default', () async { + expect(await EditorLinkScope.launchExternally('http://a.example'), isTrue); + expect( + await EditorLinkScope.launchExternally('https://a.example/path?q=1'), + isTrue, + ); + expect(launched(), ['http://a.example', 'https://a.example/path?q=1']); }); - test('ignores other schemes, relative and malformed URLs', () async { + test('ignores every other scheme by default', () async { for (final url in [ + 'mailto:hi@a.example', + 'tel:+123456', 'javascript:alert(1)', 'file:///etc/passwd', 'myapp://item/7', @@ -367,6 +400,19 @@ void main() { expect(calls, isEmpty); }); + test('opens exactly the schemes that are allowed', () async { + const allowed = {'https', 'MAILTO', 'tel'}; + Future open(String url) => + EditorLinkScope.launchExternally(url, allowedSchemes: allowed); + + expect(await open('mailto:hi@a.example'), isTrue); + expect(await open('tel:+123456'), isTrue); + expect(await open('https://a.example'), isTrue); + // Not in this set, even though it is allowed by default. + expect(await open('http://a.example'), isFalse); + expect(launched(), hasLength(3)); + }); + test('reports false when the platform cannot open the link', () async { respond = (call) => call.method != 'canLaunch'; expect(await EditorLinkScope.launchExternally('https://a.example'), @@ -402,7 +448,32 @@ void main() { expect(launched(), ['https://d.example']); }); - testWidgets('a renderer used on its own opens links externally', + testWidgets('allowedLinkSchemes widens what a viewer opens', + (tester) async { + Future pumpAndTap(EditorConfig? config) async { + await tester.pumpWidget(_host(EditorJSView( + config: config, + jsonData: _doc([ + _block('paragraph', { + 'text': 'Mail', + }), + ]), + ))); + await tester.pumpAndSettle(); + await _tapText(tester, 'Mail'); + await tester.pumpAndSettle(); + } + + await pumpAndTap(null); + expect(launched(), isEmpty); + + await pumpAndTap(EditorConfig( + allowedLinkSchemes: const {'http', 'https', 'mailto'}, + )); + expect(launched(), ['mailto:hi@a.example']); + }); + + testWidgets('a renderer used on its own opens web links externally', (tester) async { await tester.pumpWidget(_host( const InlineHtml('Solo'), @@ -429,7 +500,7 @@ void main() { expect(calls, isEmpty); }); - test('notifies dependants only when the handler changes', () { + test('notifies dependants only when its configuration changes', () { void handler(String url) {} const child = SizedBox(); final scope = EditorLinkScope(onLinkTap: handler, child: child); @@ -445,6 +516,14 @@ void main() { ), isTrue, ); + expect( + scope.updateShouldNotify(EditorLinkScope( + onLinkTap: handler, + allowedSchemes: const {'http', 'https', 'tel'}, + child: child, + )), + isTrue, + ); }); }); } From 3d9a7541db5e7514377087c191b47a9e3f4284f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 01:24:37 -0600 Subject: [PATCH 06/16] Let the header editor change the heading level A heading's level was fixed at creation: the only way to turn an H2 into an H3 was to delete the block and add a new one. The header editor now has an H1-H6 selector next to the text. A level outside that range in a loaded document is shown as the nearest valid one. Co-Authored-By: Claude --- .../blocks/header/header_editor.dart | 74 ++++++++--- test/widget/header_level_test.dart | 117 ++++++++++++++++++ 2 files changed, 176 insertions(+), 15 deletions(-) create mode 100644 test/widget/header_level_test.dart diff --git a/lib/src/presentation/blocks/header/header_editor.dart b/lib/src/presentation/blocks/header/header_editor.dart index 1626f9c..1067a0b 100644 --- a/lib/src/presentation/blocks/header/header_editor.dart +++ b/lib/src/presentation/blocks/header/header_editor.dart @@ -15,12 +15,25 @@ class HeaderEditor extends BlockEditor { } class _HeaderEditorState extends State { + static const int _minLevel = 1; + static const int _maxLevel = 6; + late final TextEditingController _textController; + late int _level; @override void initState() { super.initState(); _textController = TextEditingController(text: widget.block.text); + _level = widget.block.level; + } + + @override + void didUpdateWidget(covariant HeaderEditor oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.block.level != widget.block.level) { + _level = widget.block.level; + } } @override @@ -30,12 +43,18 @@ class _HeaderEditorState extends State { } void _onTextChanged(String value) { - widget.onChanged(HeaderBlock(text: value, level: widget.block.level)); + widget.onChanged(HeaderBlock(text: value, level: _level)); + } + + void _setLevel(int? level) { + if (level == null || level == _level) return; + setState(() => _level = level); + widget.onChanged(HeaderBlock(text: _textController.text, level: level)); } @override Widget build(BuildContext context) { - final fontSize = switch (widget.block.level) { + final fontSize = switch (_level) { 1 => 32.0, 2 => 24.0, 3 => 20.0, @@ -46,19 +65,44 @@ class _HeaderEditorState extends State { return Padding( padding: const EdgeInsets.symmetric(vertical: 4), - child: TextField( - controller: _textController, - onChanged: _onTextChanged, - style: TextStyle( - fontSize: fontSize, - fontWeight: widget.block.level <= 3 ? FontWeight.bold : FontWeight.w500, - ), - decoration: InputDecoration( - hintText: 'Heading ${widget.block.level}', - border: InputBorder.none, - ), - maxLines: null, - keyboardType: TextInputType.multiline, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 12, right: 8), + child: Tooltip( + message: 'Heading level', + child: DropdownButton( + // A document can carry a level outside H1–H6; show the + // nearest one rather than failing to build. + value: _level.clamp(_minLevel, _maxLevel), + onChanged: _setLevel, + isDense: true, + underline: const SizedBox.shrink(), + items: [ + for (var level = _minLevel; level <= _maxLevel; level++) + DropdownMenuItem(value: level, child: Text('H$level')), + ], + ), + ), + ), + Expanded( + child: TextField( + controller: _textController, + onChanged: _onTextChanged, + style: TextStyle( + fontSize: fontSize, + fontWeight: _level <= 3 ? FontWeight.bold : FontWeight.w500, + ), + decoration: InputDecoration( + hintText: 'Heading $_level', + border: InputBorder.none, + ), + maxLines: null, + keyboardType: TextInputType.multiline, + ), + ), + ], ), ); } diff --git a/test/widget/header_level_test.dart b/test/widget/header_level_test.dart new file mode 100644 index 0000000..6d25ed8 --- /dev/null +++ b/test/widget/header_level_test.dart @@ -0,0 +1,117 @@ +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/header/header_editor.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _host(Widget child) => MaterialApp( + home: Scaffold(body: SizedBox(width: 400, child: child)), + ); + +Future _pickLevel(WidgetTester tester, String label) async { + await tester.tap(find.byType(DropdownButton)); + await tester.pumpAndSettle(); + await tester.tap(find.text(label).last); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('the level selector shows the current level', (tester) async { + await tester.pumpWidget(_host(HeaderEditor( + block: const HeaderBlock(text: 'Title', level: 3), + onChanged: (_) {}, + ))); + expect( + tester.widget>(find.byType(DropdownButton)).value, + 3, + ); + }); + + testWidgets('choosing a level changes the block and keeps the text', + (tester) async { + final changes = []; + await tester.pumpWidget(_host(HeaderEditor( + block: const HeaderBlock(text: 'Title', level: 2), + onChanged: changes.add, + ))); + + await _pickLevel(tester, 'H5'); + + expect(changes.single.level, 5); + expect(changes.single.text, 'Title'); + expect( + tester.widget(find.byType(TextField)).style!.fontSize, + 14, + ); + }); + + testWidgets('choosing the current level changes nothing', (tester) async { + final changes = []; + await tester.pumpWidget(_host(HeaderEditor( + block: const HeaderBlock(text: 'Title', level: 2), + onChanged: changes.add, + ))); + + await _pickLevel(tester, 'H2'); + expect(changes, isEmpty); + }); + + testWidgets('text typed after a level change keeps the new level', + (tester) async { + final changes = []; + await tester.pumpWidget(_host(HeaderEditor( + block: const HeaderBlock(text: 'Title', level: 2), + onChanged: changes.add, + ))); + + await _pickLevel(tester, 'H4'); + await tester.enterText(find.byType(TextField), 'Renamed'); + + expect(changes.last.text, 'Renamed'); + expect(changes.last.level, 4); + }); + + testWidgets('a level outside H1–H6 still builds', (tester) async { + for (final (level, shown) in [(0, 1), (9, 6)]) { + await tester.pumpWidget(_host(HeaderEditor( + key: ValueKey(level), + block: HeaderBlock(text: 'Odd', level: level), + onChanged: (_) {}, + ))); + expect(tester.takeException(), isNull); + expect( + tester + .widget>(find.byType(DropdownButton)) + .value, + shown, + ); + } + }); + + testWidgets('follows a level changed from outside', (tester) async { + Widget editor(int level) => _host(HeaderEditor( + block: HeaderBlock(text: 'Title', level: level), + onChanged: (_) {}, + )); + + await tester.pumpWidget(editor(1)); + await tester.pumpWidget(editor(6)); + expect( + tester.widget>(find.byType(DropdownButton)).value, + 6, + ); + }); + + testWidgets('the level can be changed inside the full editor', + (tester) async { + final controller = EditorController( + initialBlocks: const [HeaderBlock(text: 'Title', level: 1)], + ); + await tester.pumpWidget(_host(EditorJSEditor(controller: controller))); + await tester.pumpAndSettle(); + + await _pickLevel(tester, 'H3'); + + expect((controller.blocks.single as HeaderBlock).level, 3); + expect(controller.getContent(), contains('"level":3')); + }); +} From 0ff8e9ad91cda4e746e1e29fd6ffa7d463d55ded Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 01:25:51 -0600 Subject: [PATCH 07/16] Make the editor toolbar buttons configurable The toolbar always showed every button, so an app could not hide the ones its EditorJS setup cannot read (for example one of the two checklist kinds). EditorConfig.toolbarItems now takes the buttons to show, in order, as EditorToolbarItem values; the default is every button in the previous order. The toolbar builds its buttons from that list instead of a fixed sequence of widgets. Co-Authored-By: Claude --- lib/editorjs_flutter.dart | 1 + .../presentation/config/editor_config.dart | 14 + .../config/editor_toolbar_item.dart | 32 +++ .../presentation/widgets/editorjs_editor.dart | 1 + .../widgets/editorjs_toolbar.dart | 257 +++++++++--------- test/widget/toolbar_items_test.dart | 138 ++++++++++ 6 files changed, 322 insertions(+), 121 deletions(-) create mode 100644 lib/src/presentation/config/editor_toolbar_item.dart create mode 100644 test/widget/toolbar_items_test.dart diff --git a/lib/editorjs_flutter.dart b/lib/editorjs_flutter.dart index 89b8fea..4e36e05 100644 --- a/lib/editorjs_flutter.dart +++ b/lib/editorjs_flutter.dart @@ -8,6 +8,7 @@ export 'src/presentation/controller/editor_controller.dart'; // Configuration export 'src/presentation/config/editor_config.dart'; +export 'src/presentation/config/editor_toolbar_item.dart'; // Registries — needed only by callers registering custom block types export 'src/data/registry/block_type_registry.dart'; diff --git a/lib/src/presentation/config/editor_config.dart b/lib/src/presentation/config/editor_config.dart index 8866b76..025fb29 100644 --- a/lib/src/presentation/config/editor_config.dart +++ b/lib/src/presentation/config/editor_config.dart @@ -2,6 +2,7 @@ import '../../data/registry/block_type_registry.dart'; import '../../domain/entities/style_config.dart'; import '../registry/block_renderer_registry.dart'; import '../widgets/editor_link_scope.dart'; +import 'editor_toolbar_item.dart'; /// Configuration object shared by [EditorJSView] and [EditorJSEditor]. /// @@ -28,12 +29,25 @@ class EditorConfig { /// links. Links with any other scheme do nothing when tapped. final Set allowedLinkSchemes; + /// The buttons of the editor toolbar, in the order they are shown. + /// + /// Defaults to every button. Pass a shorter list to hide some, for example + /// to offer only the kind of checklist your EditorJS setup can read: + /// + /// ```dart + /// toolbarItems: EditorToolbarItem.values + /// .where((item) => item != EditorToolbarItem.legacyChecklist) + /// .toList(), + /// ``` + final List toolbarItems; + EditorConfig({ BlockTypeRegistry? typeRegistry, BlockRendererRegistry? rendererRegistry, this.styleConfig, this.onLinkTap, this.allowedLinkSchemes = EditorLinkScope.defaultSchemes, + this.toolbarItems = EditorToolbarItem.values, }) : typeRegistry = typeRegistry ?? BlockTypeRegistry(), rendererRegistry = rendererRegistry ?? BlockRendererRegistry(); } diff --git a/lib/src/presentation/config/editor_toolbar_item.dart b/lib/src/presentation/config/editor_toolbar_item.dart new file mode 100644 index 0000000..a8150c6 --- /dev/null +++ b/lib/src/presentation/config/editor_toolbar_item.dart @@ -0,0 +1,32 @@ +/// The buttons the editor toolbar can show. +/// +/// Pass a selection to `EditorConfig.toolbarItems` to choose which buttons +/// appear and in what order. The order of the values below is the default. +enum EditorToolbarItem { + paragraph, + heading1, + heading2, + heading3, + heading4, + heading5, + heading6, + quote, + code, + unorderedList, + orderedList, + + /// A checklist stored the `@editorjs/list` 2.x way: a `list` block with the + /// checklist style. + checklist, + + /// A checklist stored as the older `@editorjs/checklist` block. + legacyChecklist, + table, + delimiter, + warning, + image, + hyperlink, + undo, + redo, + removeLastBlock, +} diff --git a/lib/src/presentation/widgets/editorjs_editor.dart b/lib/src/presentation/widgets/editorjs_editor.dart index a1654d4..45e0a83 100644 --- a/lib/src/presentation/widgets/editorjs_editor.dart +++ b/lib/src/presentation/widgets/editorjs_editor.dart @@ -96,6 +96,7 @@ class _EditorJSEditorState extends State { EditorJSToolbar( controller: widget.controller, rendererRegistry: widget.config.rendererRegistry, + items: widget.config.toolbarItems, ), ], ); diff --git a/lib/src/presentation/widgets/editorjs_toolbar.dart b/lib/src/presentation/widgets/editorjs_toolbar.dart index 71b228b..ffcde1d 100644 --- a/lib/src/presentation/widgets/editorjs_toolbar.dart +++ b/lib/src/presentation/widgets/editorjs_toolbar.dart @@ -10,6 +10,7 @@ import '../../domain/entities/blocks/paragraph_block.dart'; import '../../domain/entities/blocks/quote_block.dart'; import '../../domain/entities/blocks/table_block.dart'; import '../../domain/entities/blocks/warning_block.dart'; +import '../config/editor_toolbar_item.dart'; import '../controller/editor_controller.dart'; import '../registry/block_renderer_registry.dart'; @@ -21,10 +22,14 @@ class EditorJSToolbar extends StatelessWidget { final EditorController controller; final BlockRendererRegistry rendererRegistry; + /// The buttons to show, in order. Defaults to every button. + final List items; + const EditorJSToolbar({ super.key, required this.controller, required this.rendererRegistry, + this.items = EditorToolbarItem.values, }); @override @@ -39,127 +44,7 @@ class EditorJSToolbar extends StatelessWidget { scrollDirection: Axis.horizontal, child: Row( children: [ - // --- Text blocks --- - _ToolbarButton( - label: 'T', - tooltip: 'Paragraph', - onTap: () => controller.addBlock(const ParagraphBlock(html: '')), - ), - for (int level = 1; level <= 6; level++) - _ToolbarButton( - label: 'H$level', - tooltip: 'Heading $level', - onTap: () => - controller.addBlock(HeaderBlock(text: '', level: level)), - ), - _ToolbarButton( - icon: Icons.format_quote, - tooltip: 'Quote', - onTap: () => - controller.addBlock(const QuoteBlock(text: '')), - ), - _ToolbarButton( - icon: Icons.code, - tooltip: 'Code', - onTap: () => controller.addBlock(const CodeBlock(code: '')), - ), - // --- Lists --- - _ToolbarButton( - icon: Icons.format_list_bulleted, - tooltip: 'Unordered list', - onTap: () => controller.addBlock( - const ListBlock( - style: ListStyle.unordered, - items: [ListItem(content: '')], - ), - ), - ), - _ToolbarButton( - icon: Icons.format_list_numbered, - tooltip: 'Ordered list', - onTap: () => controller.addBlock( - const ListBlock( - style: ListStyle.ordered, - items: [ListItem(content: '')], - ), - ), - ), - // Two checklists on purpose: which one a document can use depends - // on the tools installed in the EditorJS instance that reads it. - // `@editorjs/list` 2.x stores a checklist as a list block … - _ToolbarButton( - icon: Icons.checklist, - tooltip: 'Checklist', - onTap: () => controller.addBlock( - const ListBlock( - style: ListStyle.checklist, - items: [ListItem(content: '')], - ), - ), - ), - // … while the older `@editorjs/checklist` tool has its own block. - _ToolbarButton( - icon: Icons.check_box_outlined, - tooltip: 'Checklist (legacy)', - onTap: () => controller.addBlock( - const ChecklistBlock( - items: [ChecklistItem(text: '')], - ), - ), - ), - // --- Structural --- - _ToolbarButton( - icon: Icons.table_chart_outlined, - tooltip: 'Table', - onTap: () => controller.addBlock( - const TableBlock( - content: [ - ['', ''], - ['', ''], - ], - ), - ), - ), - _ToolbarButton( - icon: Icons.horizontal_rule, - tooltip: 'Delimiter', - onTap: () => controller.addBlock(const DelimiterBlock()), - ), - _ToolbarButton( - icon: Icons.warning_amber_outlined, - tooltip: 'Warning', - onTap: () => - controller.addBlock(const WarningBlock(title: '', message: '')), - ), - // --- Media --- - _ToolbarButton( - icon: Icons.image_outlined, - tooltip: 'Image', - onTap: () => controller.addBlock(const ImageBlock(url: '')), - ), - _ToolbarButton( - icon: Icons.link, - tooltip: 'Hyperlink', - onTap: () => _showHyperlinkDialog(context), - ), - // --- Actions --- - _ToolbarButton( - icon: Icons.undo, - tooltip: 'Undo', - onTap: controller.canUndo ? controller.undo : null, - ), - _ToolbarButton( - icon: Icons.redo, - tooltip: 'Redo', - onTap: controller.canRedo ? controller.redo : null, - ), - _ToolbarButton( - icon: Icons.delete_outline, - tooltip: 'Remove last block', - onTap: controller.blockCount > 0 - ? () => controller.removeBlock(controller.blockCount - 1) - : null, - ), + for (final item in items) _buildButton(context, item), ], ), ), @@ -167,6 +52,136 @@ class EditorJSToolbar extends StatelessWidget { ); } + Widget _buildButton(BuildContext context, EditorToolbarItem item) { + return switch (item) { + // --- Text blocks --- + EditorToolbarItem.paragraph => _ToolbarButton( + label: 'T', + tooltip: 'Paragraph', + onTap: () => controller.addBlock(const ParagraphBlock(html: '')), + ), + EditorToolbarItem.heading1 => _headingButton(1), + EditorToolbarItem.heading2 => _headingButton(2), + EditorToolbarItem.heading3 => _headingButton(3), + EditorToolbarItem.heading4 => _headingButton(4), + EditorToolbarItem.heading5 => _headingButton(5), + EditorToolbarItem.heading6 => _headingButton(6), + EditorToolbarItem.quote => _ToolbarButton( + icon: Icons.format_quote, + tooltip: 'Quote', + onTap: () => controller.addBlock(const QuoteBlock(text: '')), + ), + EditorToolbarItem.code => _ToolbarButton( + icon: Icons.code, + tooltip: 'Code', + onTap: () => controller.addBlock(const CodeBlock(code: '')), + ), + // --- Lists --- + EditorToolbarItem.unorderedList => _ToolbarButton( + icon: Icons.format_list_bulleted, + tooltip: 'Unordered list', + onTap: () => controller.addBlock( + const ListBlock( + style: ListStyle.unordered, + items: [ListItem(content: '')], + ), + ), + ), + EditorToolbarItem.orderedList => _ToolbarButton( + icon: Icons.format_list_numbered, + tooltip: 'Ordered list', + onTap: () => controller.addBlock( + const ListBlock( + style: ListStyle.ordered, + items: [ListItem(content: '')], + ), + ), + ), + // Two checklists on purpose: which one a document can use depends on + // the tools installed in the EditorJS instance that reads it. + // `@editorjs/list` 2.x stores a checklist as a list block … + EditorToolbarItem.checklist => _ToolbarButton( + icon: Icons.checklist, + tooltip: 'Checklist', + onTap: () => controller.addBlock( + const ListBlock( + style: ListStyle.checklist, + items: [ListItem(content: '')], + ), + ), + ), + // … while the older `@editorjs/checklist` tool has its own block. + EditorToolbarItem.legacyChecklist => _ToolbarButton( + icon: Icons.check_box_outlined, + tooltip: 'Checklist (legacy)', + onTap: () => controller.addBlock( + const ChecklistBlock( + items: [ChecklistItem(text: '')], + ), + ), + ), + // --- Structural --- + EditorToolbarItem.table => _ToolbarButton( + icon: Icons.table_chart_outlined, + tooltip: 'Table', + onTap: () => controller.addBlock( + const TableBlock( + content: [ + ['', ''], + ['', ''], + ], + ), + ), + ), + EditorToolbarItem.delimiter => _ToolbarButton( + icon: Icons.horizontal_rule, + tooltip: 'Delimiter', + onTap: () => controller.addBlock(const DelimiterBlock()), + ), + EditorToolbarItem.warning => _ToolbarButton( + icon: Icons.warning_amber_outlined, + tooltip: 'Warning', + onTap: () => + controller.addBlock(const WarningBlock(title: '', message: '')), + ), + // --- Media --- + EditorToolbarItem.image => _ToolbarButton( + icon: Icons.image_outlined, + tooltip: 'Image', + onTap: () => controller.addBlock(const ImageBlock(url: '')), + ), + EditorToolbarItem.hyperlink => _ToolbarButton( + icon: Icons.link, + tooltip: 'Hyperlink', + onTap: () => _showHyperlinkDialog(context), + ), + // --- Actions --- + EditorToolbarItem.undo => _ToolbarButton( + icon: Icons.undo, + tooltip: 'Undo', + onTap: controller.canUndo ? controller.undo : null, + ), + EditorToolbarItem.redo => _ToolbarButton( + icon: Icons.redo, + tooltip: 'Redo', + onTap: controller.canRedo ? controller.redo : null, + ), + EditorToolbarItem.removeLastBlock => _ToolbarButton( + icon: Icons.delete_outline, + tooltip: 'Remove last block', + onTap: controller.blockCount > 0 + ? () => controller.removeBlock(controller.blockCount - 1) + : null, + ), + }; + } + + Widget _headingButton(int level) => _ToolbarButton( + label: 'H$level', + tooltip: 'Heading $level', + onTap: () => controller.addBlock(HeaderBlock(text: '', level: level)), + ); + void _showHyperlinkDialog(BuildContext context) { final titleController = TextEditingController(); final urlController = TextEditingController(); diff --git a/test/widget/toolbar_items_test.dart b/test/widget/toolbar_items_test.dart new file mode 100644 index 0000000..ea62b28 --- /dev/null +++ b/test/widget/toolbar_items_test.dart @@ -0,0 +1,138 @@ +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/widgets/editorjs_toolbar.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _tooltips = { + EditorToolbarItem.paragraph: 'Paragraph', + EditorToolbarItem.heading1: 'Heading 1', + EditorToolbarItem.heading2: 'Heading 2', + EditorToolbarItem.heading3: 'Heading 3', + EditorToolbarItem.heading4: 'Heading 4', + EditorToolbarItem.heading5: 'Heading 5', + EditorToolbarItem.heading6: 'Heading 6', + EditorToolbarItem.quote: 'Quote', + EditorToolbarItem.code: 'Code', + EditorToolbarItem.unorderedList: 'Unordered list', + EditorToolbarItem.orderedList: 'Ordered list', + EditorToolbarItem.checklist: 'Checklist', + EditorToolbarItem.legacyChecklist: 'Checklist (legacy)', + EditorToolbarItem.table: 'Table', + EditorToolbarItem.delimiter: 'Delimiter', + EditorToolbarItem.warning: 'Warning', + EditorToolbarItem.image: 'Image', + EditorToolbarItem.hyperlink: 'Hyperlink', + EditorToolbarItem.undo: 'Undo', + EditorToolbarItem.redo: 'Redo', + EditorToolbarItem.removeLastBlock: 'Remove last block', +}; + +Widget _toolbar( + EditorController controller, [ + List items = EditorToolbarItem.values, +]) => + MaterialApp( + home: Scaffold( + // Wide enough that every button is laid out without scrolling. + body: OverflowBox( + alignment: Alignment.topLeft, + maxWidth: 2000, + child: EditorJSToolbar( + controller: controller, + rendererRegistry: BlockRendererRegistry(), + items: items, + ), + ), + ), + ); + +List _shownTooltips(WidgetTester tester) => tester + .widgetList(find.descendant( + of: find.byType(EditorJSToolbar), + matching: find.byType(Tooltip), + )) + .map((t) => t.message!) + .toList(); + +void main() { + test('every toolbar item is covered by this test', () { + expect(_tooltips.keys, EditorToolbarItem.values); + }); + + testWidgets('shows every button, in enum order, by default', (tester) async { + await tester.pumpWidget(_toolbar(EditorController())); + expect(_shownTooltips(tester), _tooltips.values); + }); + + testWidgets('shows only the chosen buttons, in the chosen order', + (tester) async { + await tester.pumpWidget(_toolbar(EditorController(), const [ + EditorToolbarItem.undo, + EditorToolbarItem.checklist, + EditorToolbarItem.paragraph, + ])); + expect(_shownTooltips(tester), ['Undo', 'Checklist', 'Paragraph']); + }); + + testWidgets('an empty selection shows no buttons', (tester) async { + await tester.pumpWidget(_toolbar(EditorController(), const [])); + expect(_shownTooltips(tester), isEmpty); + }); + + testWidgets('each block button adds the block it names', (tester) async { + final expected = { + EditorToolbarItem.paragraph: (b) => b is ParagraphBlock, + for (var level = 1; level <= 6; level++) + EditorToolbarItem.values[level]: (b) => + b is HeaderBlock && b.level == level, + EditorToolbarItem.quote: (b) => b is QuoteBlock, + EditorToolbarItem.code: (b) => b is CodeBlock, + EditorToolbarItem.unorderedList: (b) => + b is ListBlock && b.style == ListStyle.unordered, + EditorToolbarItem.orderedList: (b) => + b is ListBlock && b.style == ListStyle.ordered, + EditorToolbarItem.checklist: (b) => + b is ListBlock && b.style == ListStyle.checklist, + EditorToolbarItem.legacyChecklist: (b) => b is ChecklistBlock, + EditorToolbarItem.table: (b) => b is TableBlock, + EditorToolbarItem.delimiter: (b) => b is DelimiterBlock, + EditorToolbarItem.warning: (b) => b is WarningBlock, + EditorToolbarItem.image: (b) => b is ImageBlock, + }; + + for (final entry in expected.entries) { + final controller = EditorController(); + await tester.pumpWidget(_toolbar(controller)); + await tester.tap(find.byTooltip(_tooltips[entry.key]!)); + expect( + entry.value(controller.blocks.single), + isTrue, + reason: '${entry.key} added ${controller.blocks.single.runtimeType}', + ); + } + }); + + testWidgets('EditorConfig.toolbarItems reaches the editor toolbar', + (tester) async { + final controller = EditorController(); + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: EditorJSEditor( + controller: controller, + config: EditorConfig( + toolbarItems: EditorToolbarItem.values + .where((item) => item != EditorToolbarItem.legacyChecklist) + .toList(), + ), + ), + ), + )); + + expect(find.byTooltip('Checklist (legacy)'), findsNothing); + expect(find.byTooltip('Checklist'), findsOneWidget); + }); + + test('EditorConfig shows every button unless told otherwise', () { + expect(EditorConfig().toolbarItems, EditorToolbarItem.values); + }); +} From c9ce9745f7669bc4e01ebd6dbf53285a751dd204 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 01:28:11 -0600 Subject: [PATCH 08/16] Rework the image editor: upload hook, URL, caption and options Picking a new image replaced the whole block, which reset its caption and its border, stretch and background flags, and always stored the path of the file on the device. There was no way to enter a URL or a caption. - EditorConfig.imageUploader stores a picked image and returns its public URL plus any extra file fields, like the uploader of the EditorJS image tool. Without one the local path is stored as before. - The editor shows upload progress and reports picker and upload failures without losing the current image. - New fields for the image URL and the caption, and toggles for border, stretch and background. - Picking or retyping the URL keeps the caption and options, and drops only the fields that described the previous file. - ImageBlock.copyWith. Co-Authored-By: Claude --- lib/editorjs_flutter.dart | 1 + .../domain/entities/blocks/image_block.dart | 18 + .../blocks/image/image_editor.dart | 191 ++++++++- .../presentation/config/editor_config.dart | 9 + .../presentation/config/image_uploader.dart | 46 +++ .../presentation/widgets/editorjs_editor.dart | 76 ++-- .../widgets/image_upload_scope.dart | 23 ++ test/widget/image_editor_test.dart | 366 ++++++++++++++++++ 8 files changed, 675 insertions(+), 55 deletions(-) create mode 100644 lib/src/presentation/config/image_uploader.dart create mode 100644 lib/src/presentation/widgets/image_upload_scope.dart create mode 100644 test/widget/image_editor_test.dart diff --git a/lib/editorjs_flutter.dart b/lib/editorjs_flutter.dart index 4e36e05..a8b6f2e 100644 --- a/lib/editorjs_flutter.dart +++ b/lib/editorjs_flutter.dart @@ -9,6 +9,7 @@ export 'src/presentation/controller/editor_controller.dart'; // Configuration export 'src/presentation/config/editor_config.dart'; export 'src/presentation/config/editor_toolbar_item.dart'; +export 'src/presentation/config/image_uploader.dart'; // Registries — needed only by callers registering custom block types export 'src/data/registry/block_type_registry.dart'; diff --git a/lib/src/domain/entities/blocks/image_block.dart b/lib/src/domain/entities/blocks/image_block.dart index cab0d2e..ddc731e 100644 --- a/lib/src/domain/entities/blocks/image_block.dart +++ b/lib/src/domain/entities/blocks/image_block.dart @@ -20,6 +20,24 @@ class ImageBlock extends BlockEntity { this.fileExtras = const {}, }); + /// Returns a copy with the given fields replaced. + ImageBlock copyWith({ + String? url, + String? caption, + bool? withBorder, + bool? stretched, + bool? withBackground, + Map? fileExtras, + }) => + ImageBlock( + url: url ?? this.url, + caption: caption ?? this.caption, + withBorder: withBorder ?? this.withBorder, + stretched: stretched ?? this.stretched, + withBackground: withBackground ?? this.withBackground, + fileExtras: fileExtras ?? this.fileExtras, + ); + @override String get type => 'image'; diff --git a/lib/src/presentation/blocks/image/image_editor.dart b/lib/src/presentation/blocks/image/image_editor.dart index 6919d54..8aad54f 100644 --- a/lib/src/presentation/blocks/image/image_editor.dart +++ b/lib/src/presentation/blocks/image/image_editor.dart @@ -1,9 +1,13 @@ import 'dart:io'; +import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; import '../../../domain/entities/blocks/image_block.dart'; +import '../../config/image_uploader.dart'; +import '../../widgets/image_upload_scope.dart'; import '../base_block_editor.dart'; class ImageEditor extends BlockEditor { @@ -19,49 +23,198 @@ class ImageEditor extends BlockEditor { class _ImageEditorState extends State { final ImagePicker _picker = ImagePicker(); - String? _localPath; + late final TextEditingController _urlController; + late final TextEditingController _captionController; + + /// The block as last edited here. Kept locally so that several edits in a + /// row build on each other even before the parent hands the block back. + late ImageBlock _block; + bool _uploading = false; + String? _error; + + @override + void initState() { + super.initState(); + _block = widget.block; + _urlController = TextEditingController(text: _block.url); + _captionController = TextEditingController(text: _block.caption ?? ''); + } + + @override + void didUpdateWidget(covariant ImageEditor oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.block != widget.block) { + _block = widget.block; + // Leave a field alone while it already says the same thing, so the + // cursor does not jump while the user is typing in it. + if (_urlController.text.trim() != _block.url) { + _urlController.text = _block.url; + } + if (_captionController.text != (_block.caption ?? '')) { + _captionController.text = _block.caption ?? ''; + } + } + } + + @override + void dispose() { + _urlController.dispose(); + _captionController.dispose(); + super.dispose(); + } + + void _update(ImageBlock block) { + setState(() => _block = block); + widget.onChanged(block); + } + + /// Replaces the image itself. Fields describing the previous file are + /// dropped; caption and display options stay. + void _setImage(String url, {Map extras = const {}}) { + _update(_block.copyWith(url: url, fileExtras: extras)); + } Future _pickImage(ImageSource source) async { - final file = await _picker.pickImage(source: source); - if (file == null) return; - setState(() => _localPath = file.path); - // Local images are represented by their path as the URL until uploaded. - widget.onChanged(ImageBlock(url: file.path)); + final uploader = ImageUploadScope.of(context); + setState(() => _error = null); + + final XFile? file; + try { + file = await _picker.pickImage(source: source); + } on PlatformException { + if (mounted) setState(() => _error = 'Could not open the image.'); + return; + } + if (file == null || !mounted) return; + + if (uploader == null) { + // No upload configured: the block points at the file on this device. + _urlController.text = file.path; + _setImage(file.path); + return; + } + + setState(() => _uploading = true); + try { + final uploaded = await uploader(PickedImage( + path: file.path, + name: file.name, + mimeType: file.mimeType, + readAsBytes: file.readAsBytes, + )); + if (!mounted) return; + _urlController.text = uploaded.url; + _setImage(uploaded.url, extras: uploaded.extras); + } catch (_) { + // The uploader is app code and may throw anything. The block keeps the + // image it had. + if (mounted) setState(() => _error = 'Upload failed. Try again.'); + } finally { + if (mounted) setState(() => _uploading = false); + } + } + + static bool _isRemote(String url) { + final scheme = Uri.tryParse(url)?.scheme.toLowerCase(); + return scheme == 'http' || scheme == 'https'; } @override Widget build(BuildContext context) { - final hasImage = _localPath != null || widget.block.url.isNotEmpty; - return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (hasImage) - _localPath != null - ? Image.file(File(_localPath!), fit: BoxFit.cover) - : Image.network( - widget.block.url, - fit: BoxFit.cover, - errorBuilder: (_, __, ___) => - const _ImageErrorPlaceholder(), - ), + if (_block.url.isNotEmpty) _buildPreview(), + if (_uploading) const LinearProgressIndicator(), Row( children: [ TextButton.icon( - onPressed: () => _pickImage(ImageSource.camera), + onPressed: + _uploading ? null : () => _pickImage(ImageSource.camera), icon: const Icon(Icons.camera_alt_outlined), label: const Text('Camera'), ), TextButton.icon( - onPressed: () => _pickImage(ImageSource.gallery), + onPressed: + _uploading ? null : () => _pickImage(ImageSource.gallery), icon: const Icon(Icons.photo_library_outlined), label: const Text('Gallery'), ), ], ), + if (_error != null) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + _error!, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + fontSize: 12, + ), + ), + ), + TextField( + controller: _urlController, + onChanged: (value) => _setImage(value.trim()), + keyboardType: TextInputType.url, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Image URL', + hintText: 'https://...', + isDense: true, + ), + ), + TextField( + controller: _captionController, + onChanged: (value) => _update(_block.copyWith(caption: value)), + decoration: const InputDecoration( + labelText: 'Caption', + isDense: true, + ), + ), + const SizedBox(height: 4), + Wrap( + spacing: 8, + children: [ + FilterChip( + label: const Text('Border'), + selected: _block.withBorder, + onSelected: (value) => + _update(_block.copyWith(withBorder: value)), + ), + FilterChip( + label: const Text('Stretch'), + selected: _block.stretched, + onSelected: (value) => _update(_block.copyWith(stretched: value)), + ), + FilterChip( + label: const Text('Background'), + selected: _block.withBackground, + onSelected: (value) => + _update(_block.copyWith(withBackground: value)), + ), + ], + ), ], ); } + + Widget _buildPreview() { + // On the web a picked file is a blob URL, which only the network image + // loader can read. + if (kIsWeb || _isRemote(_block.url)) { + return Image.network( + _block.url, + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => const _ImageErrorPlaceholder(), + ); + } + return Image.file( + File(_block.url), + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => const _ImageErrorPlaceholder(), + ); + } } class _ImageErrorPlaceholder extends StatelessWidget { diff --git a/lib/src/presentation/config/editor_config.dart b/lib/src/presentation/config/editor_config.dart index 025fb29..20d870f 100644 --- a/lib/src/presentation/config/editor_config.dart +++ b/lib/src/presentation/config/editor_config.dart @@ -3,6 +3,7 @@ import '../../domain/entities/style_config.dart'; import '../registry/block_renderer_registry.dart'; import '../widgets/editor_link_scope.dart'; import 'editor_toolbar_item.dart'; +import 'image_uploader.dart'; /// Configuration object shared by [EditorJSView] and [EditorJSEditor]. /// @@ -41,6 +42,13 @@ class EditorConfig { /// ``` final List toolbarItems; + /// Stores an image the user picks in the editor and returns its public URL. + /// + /// Without an uploader the image block keeps the path of the file on the + /// device, which no other device can load. Set this for any document that + /// is meant to be read elsewhere. + final ImageUploader? imageUploader; + EditorConfig({ BlockTypeRegistry? typeRegistry, BlockRendererRegistry? rendererRegistry, @@ -48,6 +56,7 @@ class EditorConfig { this.onLinkTap, this.allowedLinkSchemes = EditorLinkScope.defaultSchemes, this.toolbarItems = EditorToolbarItem.values, + this.imageUploader, }) : typeRegistry = typeRegistry ?? BlockTypeRegistry(), rendererRegistry = rendererRegistry ?? BlockRendererRegistry(); } diff --git a/lib/src/presentation/config/image_uploader.dart b/lib/src/presentation/config/image_uploader.dart new file mode 100644 index 0000000..094ae85 --- /dev/null +++ b/lib/src/presentation/config/image_uploader.dart @@ -0,0 +1,46 @@ +import 'dart:typed_data'; + +/// An image the user picked from the camera or gallery, handed to an +/// [ImageUploader]. +class PickedImage { + /// Location of the file on the device. On the web this is a blob URL. + final String path; + + /// File name, including the extension. + final String name; + + /// MIME type reported by the platform, when it knows it. + final String? mimeType; + + final Future Function() _readAsBytes; + + const PickedImage({ + required this.path, + required this.name, + this.mimeType, + required Future Function() readAsBytes, + }) : _readAsBytes = readAsBytes; + + /// Reads the whole file. Works on every platform, including the web. + Future readAsBytes() => _readAsBytes(); +} + +/// What an [ImageUploader] returns once the image is stored. +/// +/// Mirrors the `file` object of the EditorJS image tool: the public [url], +/// plus any additional fields the backend wants saved with the block. +class UploadedImage { + /// Public URL of the stored image. + final String url; + + /// Extra fields to save in the block's `file` object next to `url` + /// (for example `width`, `height` or an asset id). + final Map extras; + + const UploadedImage({required this.url, this.extras = const {}}); +} + +/// Stores a picked image where readers of the document can reach it and +/// returns its public URL. Throw to report a failed upload; the editor keeps +/// the previous image and shows an error. +typedef ImageUploader = Future Function(PickedImage image); diff --git a/lib/src/presentation/widgets/editorjs_editor.dart b/lib/src/presentation/widgets/editorjs_editor.dart index 45e0a83..55a0005 100644 --- a/lib/src/presentation/widgets/editorjs_editor.dart +++ b/lib/src/presentation/widgets/editorjs_editor.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../config/editor_config.dart'; import '../controller/editor_controller.dart'; import 'editorjs_toolbar.dart'; +import 'image_upload_scope.dart'; /// Interactive editor for EditorJS content. /// @@ -62,43 +63,46 @@ class _EditorJSEditorState extends State { final ids = widget.controller.blockIds; - return Column( - children: [ - Expanded( - child: ListView.builder( - padding: const EdgeInsets.all(12), - itemCount: blocks.length, - itemBuilder: (context, index) { - final block = blocks[index]; - final editor = widget.config.rendererRegistry.buildEditor( - block, - (updated) => widget.controller.updateBlock(index, updated), - ) ?? - _UnknownBlockWidget(type: block.type); - - return Padding( - key: ValueKey(ids[index]), - padding: const EdgeInsets.only(bottom: 8), - child: _BlockWrap( - onMoveUp: index > 0 - ? () => widget.controller.moveBlock(index, index - 1) - : null, - onMoveDown: index < blocks.length - 1 - ? () => widget.controller.moveBlock(index, index + 1) - : null, - onDelete: () => widget.controller.removeBlock(index), - child: editor, - ), - ); - }, + return ImageUploadScope( + uploader: widget.config.imageUploader, + child: Column( + children: [ + Expanded( + child: ListView.builder( + padding: const EdgeInsets.all(12), + itemCount: blocks.length, + itemBuilder: (context, index) { + final block = blocks[index]; + final editor = widget.config.rendererRegistry.buildEditor( + block, + (updated) => widget.controller.updateBlock(index, updated), + ) ?? + _UnknownBlockWidget(type: block.type); + + return Padding( + key: ValueKey(ids[index]), + padding: const EdgeInsets.only(bottom: 8), + child: _BlockWrap( + onMoveUp: index > 0 + ? () => widget.controller.moveBlock(index, index - 1) + : null, + onMoveDown: index < blocks.length - 1 + ? () => widget.controller.moveBlock(index, index + 1) + : null, + onDelete: () => widget.controller.removeBlock(index), + child: editor, + ), + ); + }, + ), ), - ), - EditorJSToolbar( - controller: widget.controller, - rendererRegistry: widget.config.rendererRegistry, - items: widget.config.toolbarItems, - ), - ], + EditorJSToolbar( + controller: widget.controller, + rendererRegistry: widget.config.rendererRegistry, + items: widget.config.toolbarItems, + ), + ], + ), ); } } diff --git a/lib/src/presentation/widgets/image_upload_scope.dart b/lib/src/presentation/widgets/image_upload_scope.dart new file mode 100644 index 0000000..ba7928c --- /dev/null +++ b/lib/src/presentation/widgets/image_upload_scope.dart @@ -0,0 +1,23 @@ +import 'package:flutter/widgets.dart'; + +import '../config/image_uploader.dart'; + +/// Carries `EditorConfig.imageUploader` down to the image editor, which is +/// built by the block registry and therefore cannot receive it as an argument. +class ImageUploadScope extends InheritedWidget { + final ImageUploader? uploader; + + const ImageUploadScope({ + super.key, + required this.uploader, + required super.child, + }); + + /// The uploader configured for the surrounding editor, if any. + static ImageUploader? of(BuildContext context) => + context.getInheritedWidgetOfExactType()?.uploader; + + @override + bool updateShouldNotify(ImageUploadScope oldWidget) => + uploader != oldWidget.uploader; +} diff --git a/test/widget/image_editor_test.dart b/test/widget/image_editor_test.dart new file mode 100644 index 0000000..ff1c85c --- /dev/null +++ b/test/widget/image_editor_test.dart @@ -0,0 +1,366 @@ +import 'dart:async'; + +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/image/image_editor.dart'; +import 'package:editorjs_flutter/src/presentation/widgets/image_upload_scope.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _pickerChannel = MethodChannel('plugins.flutter.io/image_picker'); + +const _existing = ImageBlock( + url: 'https://example.com/old.png', + caption: 'Old caption', + withBorder: true, + stretched: true, + withBackground: true, + fileExtras: {'width': 800}, +); + +Widget _host(Widget child, {ImageUploader? uploader}) => MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: ImageUploadScope( + uploader: uploader, + child: SizedBox(width: 400, child: child), + ), + ), + ), + ); + +void main() { + /// What the fake picker hands back: a path, null (cancelled), or an + /// exception to throw. + Object? picked; + + setUp(() { + picked = '/tmp/picked/photo.png'; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_pickerChannel, (call) async { + final result = picked; + if (result is Exception) throw result; + return result; + }); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_pickerChannel, null); + }); + + Future> pumpEditor( + WidgetTester tester, + ImageBlock block, { + ImageUploader? uploader, + }) async { + final changes = []; + await tester.pumpWidget(_host( + ImageEditor(block: block, onChanged: changes.add), + uploader: uploader, + )); + await tester.pumpAndSettle(); + return changes; + } + + Future pickFromGallery(WidgetTester tester) async { + await tester.tap(find.text('Gallery')); + await tester.pumpAndSettle(); + } + + group('fields', () { + testWidgets('show the URL and caption of the block', (tester) async { + await pumpEditor(tester, _existing); + expect( + find.widgetWithText(TextField, 'https://example.com/old.png'), + findsOneWidget, + ); + expect(find.widgetWithText(TextField, 'Old caption'), findsOneWidget); + }); + + testWidgets('editing the caption keeps everything else', (tester) async { + final changes = await pumpEditor(tester, _existing); + await tester.enterText( + find.widgetWithText(TextField, 'Old caption'), + 'New caption', + ); + + final block = changes.last; + expect(block.caption, 'New caption'); + expect(block.url, _existing.url); + expect(block.withBorder, isTrue); + expect(block.fileExtras, {'width': 800}); + }); + + testWidgets('typing a URL replaces the image and drops its file fields', + (tester) async { + final changes = await pumpEditor(tester, _existing); + await tester.enterText( + find.widgetWithText(TextField, 'https://example.com/old.png'), + ' https://example.com/new.png ', + ); + + final block = changes.last; + expect(block.url, 'https://example.com/new.png'); + expect(block.fileExtras, isEmpty); + expect(block.caption, 'Old caption'); + expect(block.stretched, isTrue); + }); + + testWidgets('the three display options toggle independently', + (tester) async { + final changes = await pumpEditor( + tester, + const ImageBlock(url: 'https://example.com/a.png'), + ); + + await tester.tap(find.text('Border')); + await tester.pump(); + await tester.tap(find.text('Background')); + await tester.pump(); + + // The second change builds on the first even though the parent never + // handed the updated block back. + final block = changes.last; + expect(block.withBorder, isTrue); + expect(block.withBackground, isTrue); + expect(block.stretched, isFalse); + + await tester.tap(find.text('Stretch')); + await tester.pump(); + await tester.tap(find.text('Border')); + await tester.pump(); + expect(changes.last.stretched, isTrue); + expect(changes.last.withBorder, isFalse); + }); + + testWidgets('follow a block replaced from outside', (tester) async { + Widget editor(ImageBlock block) => + _host(ImageEditor(block: block, onChanged: (_) {})); + + await tester.pumpWidget(editor(_existing)); + await tester.pumpWidget(editor(const ImageBlock( + url: 'https://example.com/other.png', + caption: 'Other', + ))); + await tester.pumpAndSettle(); + + expect( + find.widgetWithText(TextField, 'https://example.com/other.png'), + findsOneWidget, + ); + expect(find.widgetWithText(TextField, 'Other'), findsOneWidget); + expect( + tester.widget(find.widgetWithText(FilterChip, 'Border')).selected, + isFalse, + ); + }); + }); + + group('picking without an uploader', () { + testWidgets('stores the local path and keeps caption and options', + (tester) async { + final changes = await pumpEditor(tester, _existing); + await pickFromGallery(tester); + + final block = changes.single; + expect(block.url, '/tmp/picked/photo.png'); + expect(block.caption, 'Old caption'); + expect(block.withBorder, isTrue); + expect(block.stretched, isTrue); + expect(block.withBackground, isTrue); + // Described the previous file, so it does not carry over. + expect(block.fileExtras, isEmpty); + expect( + find.widgetWithText(TextField, '/tmp/picked/photo.png'), + findsOneWidget, + ); + }); + + testWidgets('the camera button picks too', (tester) async { + final changes = await pumpEditor(tester, const ImageBlock(url: '')); + await tester.tap(find.text('Camera')); + await tester.pumpAndSettle(); + expect(changes.single.url, '/tmp/picked/photo.png'); + }); + + testWidgets('cancelling the picker changes nothing', (tester) async { + picked = null; + final changes = await pumpEditor(tester, _existing); + await pickFromGallery(tester); + expect(changes, isEmpty); + }); + + testWidgets('a picker failure shows an error and changes nothing', + (tester) async { + picked = PlatformException(code: 'photo_access_denied'); + final changes = await pumpEditor(tester, _existing); + await pickFromGallery(tester); + + expect(changes, isEmpty); + expect(find.text('Could not open the image.'), findsOneWidget); + }); + }); + + group('picking with an uploader', () { + testWidgets('uploads the file and stores the returned URL and fields', + (tester) async { + PickedImage? received; + final changes = await pumpEditor( + tester, + _existing, + uploader: (image) async { + received = image; + return const UploadedImage( + url: 'https://cdn.example.com/photo.png', + extras: {'width': 1024, 'id': 'asset-7'}, + ); + }, + ); + await pickFromGallery(tester); + + expect(received!.path, '/tmp/picked/photo.png'); + expect(received!.name, 'photo.png'); + + final block = changes.single; + expect(block.url, 'https://cdn.example.com/photo.png'); + expect(block.fileExtras, {'width': 1024, 'id': 'asset-7'}); + expect(block.caption, 'Old caption'); + expect(block.toJson()['file'], { + 'width': 1024, + 'id': 'asset-7', + 'url': 'https://cdn.example.com/photo.png', + }); + }); + + testWidgets('shows progress and blocks picking while uploading', + (tester) async { + final upload = Completer(); + final changes = await pumpEditor( + tester, + _existing, + uploader: (_) => upload.future, + ); + + await tester.tap(find.text('Gallery')); + await tester.pump(); + await tester.pump(); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + expect( + tester + .widget(find.widgetWithText(TextButton, 'Gallery')) + .onPressed, + isNull, + ); + expect(changes, isEmpty); + + upload.complete(const UploadedImage(url: 'https://cdn.example.com/x')); + await tester.pumpAndSettle(); + expect(find.byType(LinearProgressIndicator), findsNothing); + expect(changes.single.url, 'https://cdn.example.com/x'); + }); + + testWidgets('a failed upload shows an error and keeps the old image', + (tester) async { + final changes = await pumpEditor( + tester, + _existing, + uploader: (_) async => throw StateError('server said no'), + ); + await pickFromGallery(tester); + + expect(tester.takeException(), isNull); + expect(changes, isEmpty); + expect(find.text('Upload failed. Try again.'), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsNothing); + + // The error clears on the next attempt. + picked = null; + await pickFromGallery(tester); + expect(find.text('Upload failed. Try again.'), findsNothing); + }); + + testWidgets('EditorConfig.imageUploader reaches the image editor', + (tester) async { + final controller = EditorController( + initialBlocks: const [ImageBlock(url: '')], + ); + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: EditorJSEditor( + controller: controller, + config: EditorConfig( + imageUploader: (_) async => + const UploadedImage(url: 'https://cdn.example.com/y.png'), + ), + ), + ), + )); + await tester.pumpAndSettle(); + await pickFromGallery(tester); + + expect( + (controller.blocks.single as ImageBlock).url, + 'https://cdn.example.com/y.png', + ); + }); + }); + + group('value types', () { + test('ImageBlock.copyWith replaces only what is passed', () { + final copy = _existing.copyWith(url: 'u', withBorder: false); + expect(copy.url, 'u'); + expect(copy.withBorder, isFalse); + expect(copy.caption, 'Old caption'); + expect(copy.stretched, isTrue); + expect(copy.withBackground, isTrue); + expect(copy.fileExtras, {'width': 800}); + + final other = _existing.copyWith( + caption: 'c', + stretched: false, + withBackground: false, + fileExtras: const {}, + ); + expect(other.caption, 'c'); + expect(other.stretched, isFalse); + expect(other.withBackground, isFalse); + expect(other.fileExtras, isEmpty); + expect(other.url, _existing.url); + }); + + test('PickedImage reads its bytes through the given reader', () async { + final image = PickedImage( + path: '/p/a.jpg', + name: 'a.jpg', + mimeType: 'image/jpeg', + readAsBytes: () async => Uint8List.fromList([1, 2, 3]), + ); + expect(await image.readAsBytes(), [1, 2, 3]); + expect(image.mimeType, 'image/jpeg'); + }); + + test('UploadedImage has no extra fields by default', () { + expect(const UploadedImage(url: 'u').extras, isEmpty); + }); + + test('ImageUploadScope notifies only when the uploader changes', () { + Future uploader(PickedImage image) async => + const UploadedImage(url: 'u'); + const child = SizedBox(); + final scope = ImageUploadScope(uploader: uploader, child: child); + expect( + scope.updateShouldNotify( + ImageUploadScope(uploader: uploader, child: child), + ), + isFalse, + ); + expect( + scope.updateShouldNotify( + const ImageUploadScope(uploader: null, child: child), + ), + isTrue, + ); + }); + }); +} From d021161d783becb31c53f51e5743d0574110ed23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 01:31:42 -0600 Subject: [PATCH 09/16] Make nested list items editable The list editor only showed top-level items: nested items were kept but could not be seen, changed, added or removed. The editor now treats the list as an outline. Every item is a row with a depth, shown indented, and each row can be indented under the item above it, outdented, or removed. Moving an item takes its children along; removing one moves its children up a level instead of deleting them. Enter in an item adds a sibling below it and moves the cursor there. Ordered markers follow the nesting (3.1., 3.1.1.) and checklist items can be ticked at any depth. The per-row buttons are narrower than a default icon button so the item text still has room on a phone. Co-Authored-By: Claude --- .../presentation/blocks/list/list_editor.dart | 313 ++++++++++++++---- test/widget/list_v2_test.dart | 4 +- test/widget/nested_list_editor_test.dart | 312 +++++++++++++++++ 3 files changed, 567 insertions(+), 62 deletions(-) create mode 100644 test/widget/nested_list_editor_test.dart diff --git a/lib/src/presentation/blocks/list/list_editor.dart b/lib/src/presentation/blocks/list/list_editor.dart index a173197..0c0f0e6 100644 --- a/lib/src/presentation/blocks/list/list_editor.dart +++ b/lib/src/presentation/blocks/list/list_editor.dart @@ -12,6 +12,27 @@ class ListEditor extends BlockEditor { State createState() => _ListEditorState(); } +/// One editable line of the list. +/// +/// The nested [ListItem] tree is edited as a flat outline: every item is a +/// row with a depth, and a row's children are the deeper rows that follow it. +/// Indenting and outdenting then only change depths, and the tree is rebuilt +/// from the rows whenever the block is reported upward. +class _Row { + _Row({required String text, required this.depth, required this.checked}) + : controller = TextEditingController(text: text); + + final TextEditingController controller; + final FocusNode focusNode = FocusNode(); + int depth; + bool checked; + + void dispose() { + controller.dispose(); + focusNode.dispose(); + } +} + class _ListEditorState extends State { /// Order of the buttons in the style selector. static const _styles = [ @@ -28,8 +49,9 @@ class _ListEditorState extends State { ListCounterType.upperAlpha: 'Upper Alpha', }; - late List _controllers; - late List _items; + static const double _indentPerLevel = 16; + + late List<_Row> _rows; late ListStyle _style; late int? _start; late ListCounterType? _counterType; @@ -38,9 +60,7 @@ class _ListEditorState extends State { @override void initState() { super.initState(); - _items = List.from(widget.block.items); - _controllers = - _items.map((i) => TextEditingController(text: i.content)).toList(); + _rows = _flatten(widget.block.items); _style = widget.block.style; _start = widget.block.start; _counterType = widget.block.counterType; @@ -49,8 +69,8 @@ class _ListEditorState extends State { @override void dispose() { - for (final c in _controllers) { - c.dispose(); + for (final row in _rows) { + row.dispose(); } _startController.dispose(); super.dispose(); @@ -60,28 +80,8 @@ class _ListEditorState extends State { void didUpdateWidget(covariant ListEditor oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.block != widget.block) { - final newItems = widget.block.items; setState(() { - final updated = []; - for (var i = 0; i < newItems.length; i++) { - if (i < _controllers.length) { - // Only update text when the content actually differs to avoid - // resetting the cursor during normal typing round-trips. - if (_controllers[i].text != newItems[i].content) { - _controllers[i].text = newItems[i].content; - } - updated.add(_controllers[i]); - } else { - updated.add(TextEditingController(text: newItems[i].content)); - } - } - // Dispose extra controllers only after building the updated list so - // that an unexpected error cannot leave _controllers in a partial state. - for (var i = newItems.length; i < _controllers.length; i++) { - _controllers[i].dispose(); - } - _controllers = updated; - _items = List.from(newItems); + _syncRows(widget.block.items); _style = widget.block.style; _counterType = widget.block.counterType; // Same rule as the item fields: leave the text alone while it already @@ -94,10 +94,106 @@ class _ListEditorState extends State { } } + // --------------------------------------------------------------------------- + // Tree <-> rows + // --------------------------------------------------------------------------- + + /// The items of a tree in display order, each with its nesting depth. + static List<(ListItem, int)> _outline(List items) { + final outline = <(ListItem, int)>[]; + void visit(List level, int depth) { + for (final item in level) { + outline.add((item, depth)); + visit(item.items, depth + 1); + } + } + + visit(items, 0); + return outline; + } + + static List<_Row> _flatten(List items) => [ + for (final (item, depth) in _outline(items)) + _Row(text: item.content, depth: depth, checked: item.checked), + ]; + + /// Brings the rows in line with [items], reusing the existing rows so that + /// text fields keep their cursor and focus across the parent's rebuilds. + void _syncRows(List items) { + final outline = _outline(items); + final synced = <_Row>[]; + for (var i = 0; i < outline.length; i++) { + final (item, depth) = outline[i]; + if (i < _rows.length) { + final row = _rows[i]; + // Only update text when the content actually differs to avoid + // resetting the cursor during normal typing round-trips. + if (row.controller.text != item.content) { + row.controller.text = item.content; + } + row + ..depth = depth + ..checked = item.checked; + synced.add(row); + } else { + synced.add( + _Row(text: item.content, depth: depth, checked: item.checked), + ); + } + } + // Dispose extra rows only after building the new list so that an + // unexpected error cannot leave _rows in a partial state. + for (var i = outline.length; i < _rows.length; i++) { + _rows[i].dispose(); + } + _rows = synced; + } + + List _toTree() { + var index = 0; + List build(int depth) { + final items = []; + while (index < _rows.length && _rows[index].depth >= depth) { + final row = _rows[index++]; + items.add(ListItem( + content: row.controller.text, + checked: row.checked, + items: build(depth + 1), + )); + } + return items; + } + + return build(0); + } + + /// Index just past the last descendant of the row at [index]. + int _subtreeEnd(int index) { + var end = index + 1; + while (end < _rows.length && _rows[end].depth > _rows[index].depth) { + end++; + } + return end; + } + + /// Restores the outline invariant: the first row is at the top level and no + /// row is more than one level deeper than the row before it. + void _normalizeDepths() { + var previous = -1; + for (final row in _rows) { + if (row.depth > previous + 1) row.depth = previous + 1; + previous = row.depth; + } + } + + // --------------------------------------------------------------------------- + // Edits + // --------------------------------------------------------------------------- + void _notify() { widget.onChanged(ListBlock( style: _style, - items: List.unmodifiable(_items), + items: _toTree(), start: _start, counterType: _counterType, )); @@ -105,28 +201,57 @@ class _ListEditorState extends State { void _addItem() { setState(() { - _items.add(const ListItem(content: '')); - _controllers.add(TextEditingController()); + _rows.add(_Row(text: '', depth: 0, checked: false)); }); _notify(); } + /// Adds an empty sibling below the row at [index] (after its children) and + /// moves the cursor into it. + void _insertAfter(int index) { + final row = _Row(text: '', depth: _rows[index].depth, checked: false); + setState(() => _rows.insert(_subtreeEnd(index), row)); + _notify(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _rows.contains(row)) row.focusNode.requestFocus(); + }); + } + + /// Removes one row. Its children move up a level rather than disappearing. void _removeItem(int index) { setState(() { - _controllers[index].dispose(); - _controllers.removeAt(index); - _items.removeAt(index); + final end = _subtreeEnd(index); + for (var i = index + 1; i < end; i++) { + _rows[i].depth--; + } + _rows.removeAt(index).dispose(); + _normalizeDepths(); }); _notify(); } - void _toggleChecked(int index) { + /// A row can become a child of the row above it. + bool _canIndent(int index) => + index > 0 && _rows[index].depth <= _rows[index - 1].depth; + + bool _canOutdent(int index) => _rows[index].depth > 0; + + /// Moves a row and its children one level in ([delta] 1) or out (-1). + void _shift(int index, int delta) { setState(() { - _items[index] = _items[index].copyWith(checked: !_items[index].checked); + final end = _subtreeEnd(index); + for (var i = index; i < end; i++) { + _rows[i].depth += delta; + } }); _notify(); } + void _toggleChecked(int index) { + setState(() => _rows[index].checked = !_rows[index].checked); + _notify(); + } + void _setStyle(ListStyle style) { if (style == _style) return; setState(() => _style = style); @@ -143,31 +268,52 @@ class _ListEditorState extends State { _notify(); } + // --------------------------------------------------------------------------- + // Build + // --------------------------------------------------------------------------- + @override Widget build(BuildContext context) { + final markers = _style == ListStyle.ordered ? _orderedMarkers() : null; + return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildSettings(), - for (var i = 0; i < _controllers.length; i++) - Row( - children: [ - _buildMarker(i), - Expanded( - child: TextField( - controller: _controllers[i], - onChanged: (v) { - _items[i] = _items[i].copyWith(content: v); - _notify(); - }, - decoration: const InputDecoration(border: InputBorder.none), + for (var i = 0; i < _rows.length; i++) + Padding( + padding: EdgeInsets.only(left: _rows[i].depth * _indentPerLevel), + child: Row( + children: [ + _buildMarker(i, markers?[i]), + Expanded( + child: TextField( + controller: _rows[i].controller, + focusNode: _rows[i].focusNode, + onChanged: (_) => _notify(), + // Enter starts the next item, as in any list editor. + textInputAction: TextInputAction.next, + onEditingComplete: () => _insertAfter(i), + decoration: const InputDecoration(border: InputBorder.none), + ), ), - ), - IconButton( - icon: const Icon(Icons.remove_circle_outline, size: 18), - onPressed: _controllers.length > 1 ? () => _removeItem(i) : null, - ), - ], + _RowButton( + icon: Icons.format_indent_decrease, + tooltip: 'Outdent', + onPressed: _canOutdent(i) ? () => _shift(i, -1) : null, + ), + _RowButton( + icon: Icons.format_indent_increase, + tooltip: 'Indent', + onPressed: _canIndent(i) ? () => _shift(i, 1) : null, + ), + _RowButton( + icon: Icons.remove_circle_outline, + tooltip: 'Remove item', + onPressed: _rows.length > 1 ? () => _removeItem(i) : null, + ), + ], + ), ), TextButton.icon( onPressed: _addItem, @@ -207,7 +353,7 @@ class _ListEditorState extends State { if (_style == ListStyle.ordered) ...[ const SizedBox(width: 12), SizedBox( - width: 88, + width: 72, child: TextField( controller: _startController, onChanged: _setStart, @@ -237,10 +383,30 @@ class _ListEditorState extends State { ); } - Widget _buildMarker(int index) { + /// The marker of every row of an ordered list, numbered as the viewer + /// numbers them: `start` applies to the top level, children count from 1. + List _orderedMarkers() { + // Counter of each open level, outermost first, for the row being visited. + final counters = []; + final markers = []; + for (final row in _rows) { + if (counters.length > row.depth + 1) { + counters.removeRange(row.depth + 1, counters.length); + } + if (counters.length == row.depth + 1) { + counters[row.depth]++; + } else { + counters.add(row.depth == 0 ? (_start ?? 1) : 1); + } + markers.add(ListCounterFormatter.marker(counters, _counterType)); + } + return markers; + } + + Widget _buildMarker(int index, String? orderedMarker) { if (_style == ListStyle.checklist) { return Checkbox( - value: _items[index].checked, + value: _rows[index].checked, onChanged: (_) => _toggleChecked(index), ); } @@ -248,11 +414,38 @@ class _ListEditorState extends State { return Padding( padding: const EdgeInsets.only(right: 8), child: Text( - _style == ListStyle.ordered - ? ListCounterFormatter.marker([(_start ?? 1) + index], _counterType) - : '•', + orderedMarker ?? '•', style: const TextStyle(fontSize: 14), ), ); } } + +/// Compact per-row action button. +class _RowButton extends StatelessWidget { + final IconData icon; + final String tooltip; + final VoidCallback? onPressed; + + const _RowButton({ + required this.icon, + required this.tooltip, + required this.onPressed, + }); + + @override + Widget build(BuildContext context) { + // Three of these sit in every row, so they are narrower than the default + // 48 px icon button to leave room for the item text on a phone. + return IconButton( + icon: Icon(icon, size: 18), + tooltip: tooltip, + onPressed: onPressed, + style: IconButton.styleFrom( + padding: EdgeInsets.zero, + minimumSize: const Size(36, 40), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ); + } +} diff --git a/test/widget/list_v2_test.dart b/test/widget/list_v2_test.dart index 582e1aa..f2277b4 100644 --- a/test/widget/list_v2_test.dart +++ b/test/widget/list_v2_test.dart @@ -125,14 +125,14 @@ void main() { ), ); - expect(find.byType(Checkbox), findsNWidgets(2)); + // One box per item, the nested one included. + expect(find.byType(Checkbox), findsNWidgets(3)); await tester.tap(find.byType(Checkbox).first); await tester.pump(); final block = changes.single; expect(block.style, ListStyle.checklist); expect(block.items.map((i) => i.checked), [true, true]); - // Nested items are not editable here, but must not be lost. expect(block.items.first.items.single.checked, isTrue); }); diff --git a/test/widget/nested_list_editor_test.dart b/test/widget/nested_list_editor_test.dart new file mode 100644 index 0000000..d388c5e --- /dev/null +++ b/test/widget/nested_list_editor_test.dart @@ -0,0 +1,312 @@ +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/list/list_editor.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _host(Widget child) => MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SizedBox(width: 400, child: child), + ), + ), + ); + +/// Renders a tree as an indented outline, e.g. `a\n b\nc`, so structure +/// assertions read like the list they describe. +String _outline(List items, [int depth = 0]) => [ + for (final item in items) ...[ + '${' ' * depth}${item.content}${item.checked ? ' [x]' : ''}', + if (item.items.isNotEmpty) _outline(item.items, depth + 1), + ], + ].join('\n'); + +const _nested = ListBlock( + style: ListStyle.unordered, + items: [ + ListItem( + content: 'a', + items: [ + ListItem(content: 'a1', items: [ListItem(content: 'a1x')]), + ListItem(content: 'a2'), + ], + ), + ListItem(content: 'b'), + ], +); + +void main() { + Future> pumpEditor( + WidgetTester tester, + ListBlock block, + ) async { + final changes = []; + await tester.pumpWidget(_host( + ListEditor(block: block, onChanged: changes.add), + )); + return changes; + } + + /// The nth button with [tooltip], counting rows from the top. + Finder button(String tooltip, int row) => find.byTooltip(tooltip).at(row); + + bool enabled(WidgetTester tester, String tooltip, int row) => + tester + .widget(find + .ancestor( + of: button(tooltip, row), + matching: find.byType(IconButton), + ) + .first) + .onPressed != + null; + + testWidgets('every item is editable, nested ones included', (tester) async { + final changes = await pumpEditor(tester, _nested); + + for (final text in ['a', 'a1', 'a1x', 'a2', 'b']) { + expect(find.widgetWithText(TextField, text), findsOneWidget); + } + + await tester.enterText(find.widgetWithText(TextField, 'a1x'), 'deep'); + expect(_outline(changes.last.items), 'a\n a1\n deep\n a2\nb'); + }); + + testWidgets('nested rows are indented under their parent', (tester) async { + await pumpEditor(tester, _nested); + double left(String text) => + tester.getTopLeft(find.widgetWithText(TextField, text)).dx; + + expect(left('a1'), greaterThan(left('a'))); + expect(left('a1x'), greaterThan(left('a1'))); + expect(left('a2'), left('a1')); + expect(left('b'), left('a')); + }); + + testWidgets('indent makes an item a child of the one above it', + (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock( + style: ListStyle.unordered, + items: [ + ListItem(content: 'a'), + ListItem(content: 'b'), + ListItem(content: 'c'), + ], + ), + ); + + await tester.tap(button('Indent', 1)); + await tester.pump(); + expect(_outline(changes.last.items), 'a\n b\nc'); + + await tester.tap(button('Indent', 2)); + await tester.pump(); + await tester.tap(button('Indent', 2)); + await tester.pump(); + expect(_outline(changes.last.items), 'a\n b\n c'); + }); + + testWidgets('indent is offered only where there is a parent to nest under', + (tester) async { + await pumpEditor(tester, _nested); + // Rows: a, a1, a1x, a2, b + expect(enabled(tester, 'Indent', 0), isFalse, reason: 'first row'); + expect(enabled(tester, 'Indent', 1), isFalse, reason: 'already a child'); + expect(enabled(tester, 'Indent', 2), isFalse, reason: 'already a child'); + expect(enabled(tester, 'Indent', 3), isTrue, reason: 'can go under a1'); + expect(enabled(tester, 'Indent', 4), isTrue, reason: 'can go under a'); + }); + + testWidgets('outdent is offered only below the top level', (tester) async { + await pumpEditor(tester, _nested); + expect(enabled(tester, 'Outdent', 0), isFalse); + expect(enabled(tester, 'Outdent', 1), isTrue); + expect(enabled(tester, 'Outdent', 4), isFalse); + }); + + testWidgets('indent and outdent move an item together with its children', + (tester) async { + final changes = await pumpEditor(tester, _nested); + + // Outdent a1: it leaves `a`, takes a1x along, and adopts the sibling + // that followed it. + await tester.tap(button('Outdent', 1)); + await tester.pump(); + expect(_outline(changes.last.items), 'a\na1\n a1x\n a2\nb'); + + // Indent it back under `a`. + await tester.tap(button('Indent', 1)); + await tester.pump(); + expect(_outline(changes.last.items), 'a\n a1\n a1x\n a2\nb'); + }); + + testWidgets('removing an item moves its children up a level', + (tester) async { + final changes = await pumpEditor(tester, _nested); + + await tester.tap(button('Remove item', 1)); // a1 + await tester.pump(); + expect(_outline(changes.last.items), 'a\n a1x\n a2\nb'); + expect(find.widgetWithText(TextField, 'a1'), findsNothing); + }); + + testWidgets('removing the first item keeps the outline valid', + (tester) async { + final changes = await pumpEditor(tester, _nested); + + await tester.tap(button('Remove item', 0)); // a + await tester.pump(); + expect(_outline(changes.last.items), 'a1\n a1x\na2\nb'); + }); + + testWidgets('the last remaining item cannot be removed', (tester) async { + await pumpEditor( + tester, + const ListBlock( + style: ListStyle.unordered, + items: [ListItem(content: 'only')], + ), + ); + expect(enabled(tester, 'Remove item', 0), isFalse); + }); + + testWidgets('Enter adds a sibling after the item and its children', + (tester) async { + final changes = await pumpEditor(tester, _nested); + + await tester.tap(find.widgetWithText(TextField, 'a1')); + await tester.pump(); + await tester.testTextInput.receiveAction(TextInputAction.next); + await tester.pumpAndSettle(); + + // The new item sits beside a1, below a1's own child. + expect(_outline(changes.last.items), 'a\n a1\n a1x\n \n a2\nb'); + + // The cursor is in the new item: typing fills it. + tester.testTextInput.enterText('new'); + await tester.pump(); + expect(_outline(changes.last.items), 'a\n a1\n a1x\n new\n a2\nb'); + }); + + testWidgets('Add item appends at the top level', (tester) async { + final changes = await pumpEditor(tester, _nested); + await tester.tap(find.text('Add item')); + await tester.pump(); + expect(_outline(changes.last.items), 'a\n a1\n a1x\n a2\nb\n'); + expect(changes.last.items.length, 3); + }); + + testWidgets('an empty list can be started with Add item', (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock(style: ListStyle.unordered, items: []), + ); + expect(find.byTooltip('Remove item'), findsNothing); + + await tester.tap(find.text('Add item')); + await tester.pump(); + expect(changes.last.items.single.content, ''); + }); + + testWidgets('ordered markers follow the nesting', (tester) async { + await pumpEditor( + tester, + ListBlock( + style: ListStyle.ordered, + start: 3, + items: _nested.items, + ), + ); + for (final marker in ['3.', '3.1.', '3.1.1.', '3.2.', '4.']) { + expect(find.text(marker), findsOneWidget); + } + + // Restructuring renumbers. + await tester.tap(button('Outdent', 3)); // a2 leaves `a` + await tester.pump(); + for (final marker in ['3.', '3.1.', '3.1.1.', '4.', '5.']) { + expect(find.text(marker), findsOneWidget); + } + }); + + testWidgets('nested checklist items can be ticked', (tester) async { + final changes = await pumpEditor( + tester, + ListBlock(style: ListStyle.checklist, items: _nested.items), + ); + + await tester.tap(find.byType(Checkbox).at(2)); // a1x + await tester.pump(); + expect(_outline(changes.last.items), 'a\n a1\n a1x [x]\n a2\nb'); + }); + + testWidgets('ticks survive restructuring', (tester) async { + final changes = await pumpEditor( + tester, + const ListBlock( + style: ListStyle.checklist, + items: [ + ListItem(content: 'a'), + ListItem(content: 'b', checked: true), + ], + ), + ); + + await tester.tap(button('Indent', 1)); + await tester.pump(); + expect(_outline(changes.last.items), 'a\n b [x]'); + }); + + testWidgets('follows a block replaced from outside', (tester) async { + Widget editor(ListBlock block) => + _host(ListEditor(block: block, onChanged: (_) {})); + + await tester.pumpWidget(editor(_nested)); + await tester.pumpWidget(editor(const ListBlock( + style: ListStyle.unordered, + items: [ + ListItem(content: 'x', items: [ListItem(content: 'y')]), + ], + ))); + await tester.pump(); + + expect(find.byType(TextField), findsNWidgets(2)); + expect(find.widgetWithText(TextField, 'x'), findsOneWidget); + expect(find.widgetWithText(TextField, 'y'), findsOneWidget); + + // And grows again when the new block has more rows. + await tester.pumpWidget(editor(_nested)); + await tester.pump(); + expect(find.byType(TextField), findsNWidgets(5)); + expect(tester.takeException(), isNull); + }); + + testWidgets('nested edits made in the full editor are saved', + (tester) async { + final controller = EditorController( + initialBlocks: const [ + ListBlock( + style: ListStyle.unordered, + items: [ListItem(content: 'a'), ListItem(content: 'b')], + ), + ], + ); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: EditorJSEditor(controller: controller)), + )); + await tester.pumpAndSettle(); + + await tester.tap(find.byTooltip('Indent').at(1)); + await tester.pumpAndSettle(); + await tester.enterText(find.widgetWithText(TextField, 'b'), 'child'); + await tester.pumpAndSettle(); + + final block = controller.blocks.single as ListBlock; + expect(_outline(block.items), 'a\n child'); + expect( + controller.getContent(), + contains('"items":[{"content":"child","meta":{},"items":[]}]'), + ); + }); +} From d8e4894565075f37b281ec3d6feeb1d158ca7fce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 01:32:21 -0600 Subject: [PATCH 10/16] Document the editor improvements Changelog entry under [Unreleased], README sections on uploading images and choosing the toolbar buttons, and the block table and backlog in CLAUDE.md. Co-Authored-By: Claude --- CHANGELOG.md | 9 ++++++++- CLAUDE.md | 8 ++++---- README.md | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3031e23..d6a10e7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,13 @@ * **Links can be tapped.** `` links did nothing. Web links (`http`, `https`) now open in the external application; other schemes are opt-in through the new `EditorConfig.allowedLinkSchemes` (for example `{'http', 'https', 'mailto', 'tel'}`). To handle taps yourself, pass the new `EditorConfig.onLinkTap`. Link, embed and attachment cards go through the same path. Custom renderers can join in with `EditorLinkScope.open(context, url)`. * **Blocks line up.** Paragraph, quote and raw text had an extra 8 px left and right margin that headers and tables did not; list markers sat about 6 px above their item's text. Both are fixed, and list items are spaced 8 px apart. +### Editor improvements +* **Image editor.** New `EditorConfig.imageUploader` stores a picked image and returns its public URL (and any extra file fields), like the uploader of the EditorJS image tool; without one the path of the file on the device is stored, as before. The editor gained fields for the image URL and the caption, toggles for border, stretch and background, an upload progress bar, and error messages for failed picks and uploads. Picking a new image no longer resets the caption and the display options. +* **Heading level.** The header editor has an H1–H6 selector; the level used to be fixed when the block was created. +* **Nested lists.** Every list item is editable, at any depth: items can be indented under the one above, outdented, and removed (children move up a level instead of being deleted). Enter adds an item below the current one. Nested items used to be invisible in the editor. +* **Configurable toolbar.** `EditorConfig.toolbarItems` takes the `EditorToolbarItem` buttons to show, in order; the default is every button. +* New `ImageBlock.copyWith`. + ### Parser hardening * A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. * `time` accepts integers, doubles and numeric strings; header `level` accepts doubles. @@ -36,7 +43,7 @@ * Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart` and `test/widget/viewer_fidelity_test.dart` (340 tests in total, 92 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart`, `test/widget/viewer_fidelity_test.dart`, `test/widget/header_level_test.dart`, `test/widget/toolbar_items_test.dart`, `test/widget/image_editor_test.dart` and `test/widget/nested_list_editor_test.dart` (388 tests in total, 94 % line coverage). --- diff --git a/CLAUDE.md b/CLAUDE.md index 444ebda..36425fe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -111,9 +111,9 @@ final config = EditorConfig( |---|---|---|---| | `header` | H1–H6, inline HTML | ✅ | | | `paragraph` | HTML via flutter_html | ✅ | Inline format bar (B/I/U/S/code/mark) | -| `list` | Ordered (start, counter type) / unordered / checklist / nested | ✅ | `@editorjs/list` 2.x format; legacy list, nested-list and checklist data is read too. Nested items are rendered but not yet editable | +| `list` | Ordered (start, counter type) / unordered / checklist / nested | ✅ | `@editorjs/list` 2.x format; legacy list, nested-list and checklist data is read too. Nested items are edited as an outline (indent / outdent) | | `delimiter` | Divider | ✅ | | -| `image` | Network URL | ✅ | caption/border/stretch parsed; image_picker not wired | +| `image` | Network URL, caption, border / stretch / background | ✅ | Editor picks from camera or gallery and uploads through `EditorConfig.imageUploader`; without an uploader the local file path is stored | | `quote` | With alignment | ✅ | | | `code` | Monospace + copy button | ✅ | | | `checklist` | Checked / unchecked | ✅ | Legacy `@editorjs/checklist` block; toolbar button "Checklist (legacy)". The toolbar's "Checklist" button creates a `list` block with the checklist style | @@ -132,7 +132,7 @@ final config = EditorConfig( - **Widgets**: `EditorJSView`, `EditorJSEditor`, `EditorLinkScope` (lets custom renderers open links through `EditorConfig.onLinkTap`) - **Controller**: `EditorController` -- **Config**: `EditorConfig` +- **Config**: `EditorConfig`, `EditorToolbarItem`, `ImageUploader` / `PickedImage` / `UploadedImage` - **Registries**: `BlockTypeRegistry`, `BlockRendererRegistry` - **Contracts** (for custom block authors): `BlockMapper`, `BlockRenderer`, `BlockEditor`, `BlockEntity`, `BlockDocument`, `BlockMetadata`, `StyleConfig` - **Built-in entities**: `HeaderBlock`, `ParagraphBlock`, `ListBlock`, `DelimiterBlock`, `ImageBlock`, and the other block entities; `UnknownBlock` holds any block the package cannot interpret so it round-trips untouched @@ -239,7 +239,7 @@ When making changes, always update `CHANGELOG.md` with a new entry at the top fo ## Known Issues / Backlog -- `image_picker` is declared as a dependency but `ImageEditor` only accepts a URL string — picker not wired up +- `ImageEditor` imports `dart:io` for the local-file preview; on the web it falls back to `Image.network`, but this path is untested - No `EditorController` content persistence to local storage (save/load) - No inline link editor in paragraph (currently inserts a `` paragraph block via dialog) - No drag-to-reorder for blocks (only up/down buttons) diff --git a/README.md b/README.md index 3d13088..ff1dba1 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,41 @@ class CreateNoteState extends State { } ``` +### Uploading images + +When the user picks an image, the editor needs somewhere to put it. Pass an `imageUploader` that stores the file and returns its public URL: + +```dart +EditorJSEditor( + controller: _controller, + config: EditorConfig( + imageUploader: (image) async { + final bytes = await image.readAsBytes(); + final url = await myApi.upload(image.name, bytes); + return UploadedImage(url: url); + }, + ), +) +``` + +`UploadedImage` also takes `extras`, a map saved next to `url` in the block's `file` object (for example `width` and `height`). Throw from the uploader to report a failure; the editor keeps the previous image and shows an error. + +Without an uploader the image block stores the path of the file on the device, which no other device can load. + +### Choosing the toolbar buttons + +`toolbarItems` sets which buttons the toolbar shows, and in what order. For example, to offer only the newer of the two checklist kinds: + +```dart +EditorConfig( + toolbarItems: EditorToolbarItem.values + .where((item) => item != EditorToolbarItem.legacyChecklist) + .toList(), +) +``` + +"Checklist" creates a `list` block with the checklist style (`@editorjs/list` 2.x); "Checklist (legacy)" creates the older `checklist` block. Offer the one your EditorJS setup can read. + ### Pre-loading existing content into the editor Load a previously saved JSON string directly: From 4519314b5e31f3f22f623ceaa22001f15ec3ad19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 09:36:01 -0600 Subject: [PATCH 11/16] Remove a list item's children together with the item Removing an item that had nested items kept them and moved them up a level. Per review, removing an item now removes its whole subtree. The list still always keeps at least one item, so the remove button is disabled when the item and its children are all that is left. The depth-repair helper is no longer needed: removing a complete subtree cannot leave an invalid outline. Co-Authored-By: Claude --- CHANGELOG.md | 4 +- .../presentation/blocks/list/list_editor.dart | 25 ++++------- test/widget/nested_list_editor_test.dart | 41 +++++++++++++++---- 3 files changed, 45 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d6a10e7..4f2dfb1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,7 @@ ### Editor improvements * **Image editor.** New `EditorConfig.imageUploader` stores a picked image and returns its public URL (and any extra file fields), like the uploader of the EditorJS image tool; without one the path of the file on the device is stored, as before. The editor gained fields for the image URL and the caption, toggles for border, stretch and background, an upload progress bar, and error messages for failed picks and uploads. Picking a new image no longer resets the caption and the display options. * **Heading level.** The header editor has an H1–H6 selector; the level used to be fixed when the block was created. -* **Nested lists.** Every list item is editable, at any depth: items can be indented under the one above, outdented, and removed (children move up a level instead of being deleted). Enter adds an item below the current one. Nested items used to be invisible in the editor. +* **Nested lists.** Every list item is editable, at any depth: items can be indented under the one above, outdented, and removed (removing an item removes its children too). Enter adds an item below the current one. Nested items used to be invisible in the editor. * **Configurable toolbar.** `EditorConfig.toolbarItems` takes the `EditorToolbarItem` buttons to show, in order; the default is every button. * New `ImageBlock.copyWith`. @@ -43,7 +43,7 @@ * Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart`, `test/widget/viewer_fidelity_test.dart`, `test/widget/header_level_test.dart`, `test/widget/toolbar_items_test.dart`, `test/widget/image_editor_test.dart` and `test/widget/nested_list_editor_test.dart` (388 tests in total, 94 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart`, `test/widget/viewer_fidelity_test.dart`, `test/widget/header_level_test.dart`, `test/widget/toolbar_items_test.dart`, `test/widget/image_editor_test.dart` and `test/widget/nested_list_editor_test.dart` (390 tests in total, 94 % line coverage). --- diff --git a/lib/src/presentation/blocks/list/list_editor.dart b/lib/src/presentation/blocks/list/list_editor.dart index 0c0f0e6..dcd104a 100644 --- a/lib/src/presentation/blocks/list/list_editor.dart +++ b/lib/src/presentation/blocks/list/list_editor.dart @@ -176,16 +176,6 @@ class _ListEditorState extends State { return end; } - /// Restores the outline invariant: the first row is at the top level and no - /// row is more than one level deeper than the row before it. - void _normalizeDepths() { - var previous = -1; - for (final row in _rows) { - if (row.depth > previous + 1) row.depth = previous + 1; - previous = row.depth; - } - } - // --------------------------------------------------------------------------- // Edits // --------------------------------------------------------------------------- @@ -217,19 +207,22 @@ class _ListEditorState extends State { }); } - /// Removes one row. Its children move up a level rather than disappearing. + /// Removes a row together with all of its children. void _removeItem(int index) { setState(() { final end = _subtreeEnd(index); - for (var i = index + 1; i < end; i++) { - _rows[i].depth--; + for (var i = index; i < end; i++) { + _rows[i].dispose(); } - _rows.removeAt(index).dispose(); - _normalizeDepths(); + _rows.removeRange(index, end); }); _notify(); } + /// A row can be removed unless that would empty the list: the list always + /// keeps at least one item. + bool _canRemove(int index) => _subtreeEnd(index) - index < _rows.length; + /// A row can become a child of the row above it. bool _canIndent(int index) => index > 0 && _rows[index].depth <= _rows[index - 1].depth; @@ -310,7 +303,7 @@ class _ListEditorState extends State { _RowButton( icon: Icons.remove_circle_outline, tooltip: 'Remove item', - onPressed: _rows.length > 1 ? () => _removeItem(i) : null, + onPressed: _canRemove(i) ? () => _removeItem(i) : null, ), ], ), diff --git a/test/widget/nested_list_editor_test.dart b/test/widget/nested_list_editor_test.dart index d388c5e..80177b2 100644 --- a/test/widget/nested_list_editor_test.dart +++ b/test/widget/nested_list_editor_test.dart @@ -141,23 +141,34 @@ void main() { expect(_outline(changes.last.items), 'a\n a1\n a1x\n a2\nb'); }); - testWidgets('removing an item moves its children up a level', - (tester) async { + testWidgets('removing an item removes its children too', (tester) async { final changes = await pumpEditor(tester, _nested); - await tester.tap(button('Remove item', 1)); // a1 + await tester.tap(button('Remove item', 1)); // a1, parent of a1x await tester.pump(); - expect(_outline(changes.last.items), 'a\n a1x\n a2\nb'); + expect(_outline(changes.last.items), 'a\n a2\nb'); expect(find.widgetWithText(TextField, 'a1'), findsNothing); + expect(find.widgetWithText(TextField, 'a1x'), findsNothing); + expect(find.byType(TextField), findsNWidgets(3)); + }); + + testWidgets('removing a top-level item removes its whole subtree', + (tester) async { + final changes = await pumpEditor(tester, _nested); + + await tester.tap(button('Remove item', 0)); // a, with a1, a1x and a2 + await tester.pump(); + expect(_outline(changes.last.items), 'b'); + expect(find.byType(TextField), findsOneWidget); }); - testWidgets('removing the first item keeps the outline valid', + testWidgets('removing an item without children leaves the rest alone', (tester) async { final changes = await pumpEditor(tester, _nested); - await tester.tap(button('Remove item', 0)); // a + await tester.tap(button('Remove item', 3)); // a2 await tester.pump(); - expect(_outline(changes.last.items), 'a1\n a1x\na2\nb'); + expect(_outline(changes.last.items), 'a\n a1\n a1x\nb'); }); testWidgets('the last remaining item cannot be removed', (tester) async { @@ -171,6 +182,22 @@ void main() { expect(enabled(tester, 'Remove item', 0), isFalse); }); + testWidgets('an item cannot be removed if that would empty the list', + (tester) async { + await pumpEditor( + tester, + const ListBlock( + style: ListStyle.unordered, + items: [ + ListItem(content: 'root', items: [ListItem(content: 'child')]), + ], + ), + ); + // Removing `root` would take `child` with it and leave nothing. + expect(enabled(tester, 'Remove item', 0), isFalse); + expect(enabled(tester, 'Remove item', 1), isTrue); + }); + testWidgets('Enter adds a sibling after the item and its children', (tester) async { final changes = await pumpEditor(tester, _nested); From dcc3352f1da3301233769f27f8e4dcda81e4993d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 09:47:06 -0600 Subject: [PATCH 12/16] Add editors for embed, link, attachment and raw blocks These four block types were viewer-only: the editor showed an "Unsupported block" placeholder for them and could not create them. - Embed: link and caption. The service and embed URL are derived from the link with the patterns and templates of @editorjs/embed. - Link: link, title, description and preview image, with an optional EditorConfig.linkPreviewFetcher behind a "Fetch preview" button. - Attachment: file URL and title, with an optional EditorConfig.attachmentPicker behind a "Choose file" button, since the package bundles no file picker. - Raw: the HTML source. Each has a toolbar button (EditorToolbarItem.embed, linkPreview, attachment, rawHtml). The image editor's ImageUploadScope becomes a general EditorConfigScope so block editors can read any EditorConfig hook. Co-Authored-By: Claude --- CHANGELOG.md | 5 + CLAUDE.md | 10 +- README.md | 28 + lib/editorjs_flutter.dart | 1 + lib/src/data/utils/embed_services.dart | 281 +++++++++ .../blocks/attaches/attaches_editor.dart | 188 ++++++ .../blocks/embed/embed_editor.dart | 131 ++++ .../blocks/image/image_editor.dart | 4 +- .../blocks/link_tool/link_tool_editor.dart | 195 ++++++ .../presentation/blocks/raw/raw_editor.dart | 55 ++ .../config/block_editor_hooks.dart | 19 + .../presentation/config/editor_config.dart | 15 + .../config/editor_toolbar_item.dart | 8 + .../registry/block_renderer_registry.dart | 12 + .../widgets/editor_config_scope.dart | 27 + .../presentation/widgets/editorjs_editor.dart | 6 +- .../widgets/editorjs_toolbar.dart | 26 + .../widgets/image_upload_scope.dart | 23 - test/unit/embed_services_test.dart | 204 +++++++ test/widget/image_editor_test.dart | 17 +- test/widget/media_block_editors_test.dart | 571 ++++++++++++++++++ test/widget/toolbar_items_test.dart | 12 + 22 files changed, 1796 insertions(+), 42 deletions(-) create mode 100644 lib/src/data/utils/embed_services.dart create mode 100644 lib/src/presentation/blocks/attaches/attaches_editor.dart create mode 100644 lib/src/presentation/blocks/embed/embed_editor.dart create mode 100644 lib/src/presentation/blocks/link_tool/link_tool_editor.dart create mode 100644 lib/src/presentation/blocks/raw/raw_editor.dart create mode 100644 lib/src/presentation/config/block_editor_hooks.dart create mode 100644 lib/src/presentation/widgets/editor_config_scope.dart delete mode 100644 lib/src/presentation/widgets/image_upload_scope.dart create mode 100644 test/unit/embed_services_test.dart create mode 100644 test/widget/media_block_editors_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index d6a10e7..cc35629 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,11 @@ * **Nested lists.** Every list item is editable, at any depth: items can be indented under the one above, outdented, and removed (children move up a level instead of being deleted). Enter adds an item below the current one. Nested items used to be invisible in the editor. * **Configurable toolbar.** `EditorConfig.toolbarItems` takes the `EditorToolbarItem` buttons to show, in order; the default is every button. * New `ImageBlock.copyWith`. +* **Editors for embed, link, attachment and raw blocks.** These four were viewer-only and showed an "Unsupported block" placeholder in the editor; each now has an editor and a toolbar button (`EditorToolbarItem.embed`, `linkPreview`, `attachment`, `rawHtml`). + * *Embed:* give a link; the service and embed URL are worked out with the patterns of `@editorjs/embed` (YouTube, Vimeo, X/Twitter, Instagram, CodePen, Figma and others). + * *Link:* link, title, description and preview image; the new `EditorConfig.linkPreviewFetcher` adds a "Fetch preview" button, the counterpart of the link tool's backend endpoint. + * *Attachment:* file URL and title; the new `EditorConfig.attachmentPicker` adds a "Choose file" button for apps that bring their own file picker and upload. + * *Raw:* the HTML source. ### Parser hardening * A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. diff --git a/CLAUDE.md b/CLAUDE.md index 36425fe..cb51aa1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -119,10 +119,10 @@ final config = EditorConfig( | `checklist` | Checked / unchecked | ✅ | Legacy `@editorjs/checklist` block; toolbar button "Checklist (legacy)". The toolbar's "Checklist" button creates a `list` block with the checklist style | | `table` | Optional heading row, inline HTML in cells | ✅ | Full width with equal columns, text wraps; scrolls horizontally when columns would be narrower than 96 px. `stretched` is preserved but has no visual effect | | `warning` | Title + message, inline HTML | ✅ | | -| `embed` | Tappable card | Viewer only | | -| `linkTool` | Link preview card | Viewer only | | -| `attaches` | File download card | Viewer only | | -| `raw` | Sanitized HTML | Viewer only | | +| `embed` | Tappable card | ✅ | Service and embed URL derived from the link with the `@editorjs/embed` patterns (`data/utils/embed_services.dart`) | +| `linkTool` | Link preview card | ✅ | Preview fields typed by hand or fetched through `EditorConfig.linkPreviewFetcher` | +| `attaches` | File download card | ✅ | File given as a URL or through `EditorConfig.attachmentPicker` (no bundled file picker) | +| `raw` | Sanitized HTML | ✅ | Editor shows the HTML source | --- @@ -132,7 +132,7 @@ final config = EditorConfig( - **Widgets**: `EditorJSView`, `EditorJSEditor`, `EditorLinkScope` (lets custom renderers open links through `EditorConfig.onLinkTap`) - **Controller**: `EditorController` -- **Config**: `EditorConfig`, `EditorToolbarItem`, `ImageUploader` / `PickedImage` / `UploadedImage` +- **Config**: `EditorConfig`, `EditorToolbarItem`, `ImageUploader` / `PickedImage` / `UploadedImage`, `LinkPreviewFetcher`, `AttachmentPicker` - **Registries**: `BlockTypeRegistry`, `BlockRendererRegistry` - **Contracts** (for custom block authors): `BlockMapper`, `BlockRenderer`, `BlockEditor`, `BlockEntity`, `BlockDocument`, `BlockMetadata`, `StyleConfig` - **Built-in entities**: `HeaderBlock`, `ParagraphBlock`, `ListBlock`, `DelimiterBlock`, `ImageBlock`, and the other block entities; `UnknownBlock` holds any block the package cannot interpret so it round-trips untouched diff --git a/README.md b/README.md index ff1dba1..e898c73 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,34 @@ EditorConfig( "Checklist" creates a `list` block with the checklist style (`@editorjs/list` 2.x); "Checklist (legacy)" creates the older `checklist` block. Offer the one your EditorJS setup can read. +### Link previews and attachments + +Link and attachment blocks can be filled in by hand: a link block has fields for the title, description and preview image, and an attachment block takes the URL of the file. Two optional hooks automate that: + +```dart +EditorConfig( + // Adds a "Fetch preview" button to link blocks. + linkPreviewFetcher: (url) async { + final page = await myApi.fetchLinkPreview(url); + return LinkToolMeta( + title: page.title, + description: page.description, + imageUrl: page.imageUrl, + ); + }, + // Adds a "Choose file" button to attachment blocks. This package does not + // bundle a file picker, so the app picks and uploads the file itself. + attachmentPicker: () async { + final file = await myFilePicker.pick(); + if (file == null) return null; // cancelled + final url = await myApi.upload(file); + return AttachesBlock(url: url, name: file.name, size: file.size); + }, +) +``` + +Embed blocks need no setup: paste a link from YouTube, Vimeo, X, Instagram, CodePen, Figma or another service the EditorJS embed tool supports, and the embed URL is worked out from it. + ### Pre-loading existing content into the editor Load a previously saved JSON string directly: diff --git a/lib/editorjs_flutter.dart b/lib/editorjs_flutter.dart index a8b6f2e..9d34e76 100644 --- a/lib/editorjs_flutter.dart +++ b/lib/editorjs_flutter.dart @@ -7,6 +7,7 @@ export 'src/presentation/widgets/editor_link_scope.dart'; export 'src/presentation/controller/editor_controller.dart'; // Configuration +export 'src/presentation/config/block_editor_hooks.dart'; export 'src/presentation/config/editor_config.dart'; export 'src/presentation/config/editor_toolbar_item.dart'; export 'src/presentation/config/image_uploader.dart'; diff --git a/lib/src/data/utils/embed_services.dart b/lib/src/data/utils/embed_services.dart new file mode 100644 index 0000000..b505876 --- /dev/null +++ b/lib/src/data/utils/embed_services.dart @@ -0,0 +1,281 @@ +/// What a pasted URL resolves to when it belongs to a known embed service. +class EmbedMatch { + /// Service name as the EditorJS embed tool stores it (e.g. `youtube`). + final String service; + + /// URL of the embeddable page (the iframe `src` on the web). + final String embed; + + /// Default size EditorJS gives the embed, when the service defines one. + final int? width; + final int? height; + + const EmbedMatch({ + required this.service, + required this.embed, + this.width, + this.height, + }); +} + +/// Recognizes the services of the EditorJS embed tool and builds their embed +/// URLs. +/// +/// The patterns and URL templates are those of `@editorjs/embed`, so an embed +/// block created here carries the same `service` and `embed` values the web +/// editor would have written for the same link. The discontinued Vine and +/// Gfycat services are left out. +class EmbedServices { + EmbedServices._(); + + /// Returns the service [url] belongs to, or `null` if it is not a link the + /// embed tool understands. + static EmbedMatch? resolve(String url) { + final source = url.trim(); + if (source.isEmpty) return null; + + for (final service in _services) { + final match = service.pattern.firstMatch(source); + if (match == null) continue; + + final groups = [ + for (var i = 1; i <= match.groupCount; i++) match.group(i), + ]; + final id = service.id(groups); + if (id == null || id.isEmpty) continue; + + return EmbedMatch( + service: service.name, + embed: service.template.replaceAll(_placeholder, id), + width: service.width, + height: service.height, + ); + } + return null; + } + + static const _placeholder = '{id}'; + + /// The embed tool's default: the first captured group is the id. + static String? _first(List groups) => + groups.isEmpty ? null : groups.first; + + static String? _second(List groups) => + groups.length < 2 ? null : groups[1]; + + static String? Function(List) _joined(String separator) => + (groups) => groups.any((g) => g == null || g.isEmpty) + ? null + : groups.join(separator); + + /// Query parameters YouTube's player understands, keyed by the names they + /// have in a watch URL. + static const _youtubeParams = { + 'start': 'start', + 'end': 'end', + 't': 'start', + 'time_continue': 'start', + 'list': 'list', + }; + + static String? _youtubeId(List groups) { + var id = groups.isNotEmpty ? groups[0] ?? '' : ''; + final query = groups.length > 1 ? groups[1] ?? '' : ''; + if (query.isEmpty) return id; + + final params = []; + for (final param in query.substring(1).split('&')) { + final separator = param.indexOf('='); + if (separator < 0) continue; + final name = param.substring(0, separator); + final value = param.substring(separator + 1); + + // `watch?feature=share&v=ID` carries the id as a parameter. + if (id.isEmpty && name == 'v') { + id = value; + continue; + } + final playerName = _youtubeParams[name]; + if (playerName == null) continue; + // Personal lists (liked videos, mixes, favourites) cannot be embedded. + if (value == 'LL' || value.startsWith('RDMM') || value.startsWith('FL')) { + continue; + } + params.add('$playerName=$value'); + } + if (id.isEmpty) return null; + return params.isEmpty ? id : '$id?${params.join('&')}'; + } + + static final List<_Service> _services = [ + _Service( + 'vimeo', + r'(?:http[s]?:\/\/)?(?:www.)?(?:player.)?vimeo\.co(?:.+\/([^\/]\d+)(?:#t=[\d]+)?s?$)', + 'https://player.vimeo.com/video/{id}?title=0&byline=0', + width: 580, + height: 320, + ), + _Service( + 'youtube', + r'(?:https?:\/\/)?(?:www\.)?(?:(?:youtu\.be\/)|(?:youtube\.com)\/(?:v\/|u\/\w\/|embed\/|watch|shorts\/))(?:(?:\?v=)?([^#&?=]*))?((?:[?&]\w*=[\w%+]*)*)', + 'https://www.youtube.com/embed/{id}', + width: 580, + height: 320, + id: _youtubeId, + ), + _Service( + 'coub', + r'https?:\/\/coub\.com\/view\/([^\/\?\&]+)', + 'https://coub.com/embed/{id}', + width: 580, + height: 320, + ), + _Service( + 'imgur', + r'https?:\/\/(?:i\.)?imgur\.com.*\/([a-zA-Z0-9]+)(?:\.gifv)?', + 'http://imgur.com/{id}/embed', + width: 540, + height: 500, + ), + _Service( + 'twitch-channel', + r'https?:\/\/www\.twitch\.tv\/([^\/\?\&]*)\/?$', + 'https://player.twitch.tv/?channel={id}', + width: 600, + height: 366, + ), + _Service( + 'twitch-video', + r'https?:\/\/www\.twitch\.tv\/(?:[^\/\?\&]*\/v|videos)\/([0-9]*)', + 'https://player.twitch.tv/?video=v{id}', + width: 600, + height: 366, + ), + _Service( + 'yandex-music-album', + r'https?:\/\/music\.yandex\.ru\/album\/([0-9]*)\/?$', + 'https://music.yandex.ru/iframe/#album/{id}/', + width: 540, + height: 400, + ), + _Service( + 'yandex-music-track', + r'https?:\/\/music\.yandex\.ru\/track\/([0-9]*)(?:\?.*)?', + 'https://music.yandex.ru/iframe/#track/{id}/', + width: 540, + height: 100, + ), + _Service( + 'yandex-music-playlist', + r'https?:\/\/music\.yandex\.ru\/users\/([^\/\?\&]*)\/playlists\/([0-9]*)', + 'https://music.yandex.ru/iframe/#playlist/{id}/show/cover/description/', + width: 540, + height: 400, + id: _joined('/'), + ), + _Service( + 'codepen', + r'https?:\/\/codepen\.io\/([^\/\?\&]*)\/pen\/([^\/\?\&]*)', + 'https://codepen.io/{id}?height=300&theme-id=0&default-tab=css,result&embed-version=2', + width: 600, + height: 300, + id: _joined('/embed/'), + ), + _Service( + 'instagram', + r'^https:\/\/(?:www\.)?instagram\.com\/(?:reel|p)\/(.*)', + 'https://www.instagram.com/p/{id}/embed', + width: 400, + height: 505, + id: (groups) => _first(groups)?.split('/').first, + ), + _Service( + 'twitter', + r'^https?:\/\/(www\.)?(?:twitter\.com|x\.com)\/.+\/status\/(\d+)', + 'https://platform.twitter.com/embed/Tweet.html?id={id}', + width: 600, + height: 300, + id: _second, + ), + _Service( + 'reddit', + r'https:\/\/www\.reddit\.com\/(.*)', + 'https://www.redditmedia.com/{id}?ref_source=embed&ref=share&embed=true', + width: 600, + height: 300, + ), + _Service( + 'pinterest', + r'https?:\/\/([^\/\?\&]*).pinterest.com\/pin\/([^\/\?\&]*)\/?$', + 'https://assets.pinterest.com/ext/embed.html?id={id}', + id: _second, + ), + _Service( + 'facebook', + r'https?:\/\/www.facebook.com\/([^\/\?\&]*)\/(.*)', + 'https://www.facebook.com/plugins/post.php?href=https://www.facebook.com/{id}&width=500', + id: _joined('/'), + ), + _Service( + 'aparat', + r'(?:http[s]?:\/\/)?(?:www.)?aparat\.com\/v\/([^\/\?\&]+)\/?', + 'https://www.aparat.com/video/video/embed/videohash/{id}/vt/frame', + width: 600, + height: 300, + ), + _Service( + 'miro', + r'https:\/\/miro.com\/\S+(\S{12})\/(\S+)?', + 'https://miro.com/app/live-embed/{id}', + ), + _Service( + 'github', + r'https?:\/\/gist.github.com\/([^\/\?\&]*)\/([^\/\?\&]*)', + 'data:text/html;charset=utf-8,', + width: 600, + height: 300, + id: (groups) { + final path = _joined('/')(groups); + return path == null ? null : '$path.js'; + }, + ), + _Service( + 'whimsical', + r'(https:\/\/)?whimsical.com\/(?:[a-zA-Z0-9\-]+\-)?([a-km-zA-HJ-NP-Z1-9]{16,22})(@[a-km-zA-HJ-NP-Z1-9]+)?', + 'https://whimsical.com/embed/{id}', + width: 600, + height: 300, + id: _second, + ), + _Service( + 'figma', + r'(https:\/\/www\.figma\.com\/.+)', + 'https://www.figma.com/embed?embed_host=share&url={id}', + width: 600, + height: 300, + ), + ]; +} + +class _Service { + _Service( + this.name, + String pattern, + this.template, { + this.width, + this.height, + String? Function(List groups)? id, + }) : pattern = RegExp(pattern), + id = id ?? EmbedServices._first; + + final String name; + final RegExp pattern; + + /// Embed URL with `{id}` where the resource id goes. + final String template; + final int? width; + final int? height; + + /// Builds the resource id from the pattern's captured groups. + final String? Function(List groups) id; +} diff --git a/lib/src/presentation/blocks/attaches/attaches_editor.dart b/lib/src/presentation/blocks/attaches/attaches_editor.dart new file mode 100644 index 0000000..591a0ff --- /dev/null +++ b/lib/src/presentation/blocks/attaches/attaches_editor.dart @@ -0,0 +1,188 @@ +import 'package:flutter/material.dart'; + +import '../../../domain/entities/blocks/attaches_block.dart'; +import '../../config/block_editor_hooks.dart'; +import '../../widgets/editor_config_scope.dart'; +import '../base_block_editor.dart'; + +/// Edits an attachment block: where the file is and the title shown for it. +/// +/// The file can be given as a URL, or chosen and uploaded through +/// `EditorConfig.attachmentPicker` when the app provides one. +class AttachesEditor extends BlockEditor { + const AttachesEditor({ + super.key, + required super.block, + required super.onChanged, + }); + + @override + State createState() => _AttachesEditorState(); +} + +class _AttachesEditorState extends State { + late final TextEditingController _urlController; + late final TextEditingController _titleController; + late AttachesBlock _block; + bool _picking = false; + String? _error; + + @override + void initState() { + super.initState(); + _block = widget.block; + _urlController = TextEditingController(text: _block.url); + _titleController = TextEditingController(text: _block.title ?? ''); + } + + @override + void didUpdateWidget(covariant AttachesEditor oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.block != widget.block) { + _block = widget.block; + if (_urlController.text.trim() != _block.url) { + _urlController.text = _block.url; + } + if (_titleController.text != (_block.title ?? '')) { + _titleController.text = _block.title ?? ''; + } + } + } + + @override + void dispose() { + _urlController.dispose(); + _titleController.dispose(); + super.dispose(); + } + + void _update(AttachesBlock block) { + setState(() => _block = block); + widget.onChanged(block); + } + + /// A typed URL points at a different file, so the name and extension are + /// read from the URL and the size and backend fields of the previous file + /// are dropped. + void _setUrl(String value) { + final url = value.trim(); + final name = _fileName(url); + _update(AttachesBlock( + url: url, + name: name, + extension: _extension(name), + title: _block.title, + )); + } + + void _setTitle(String value) { + _update(AttachesBlock( + url: _block.url, + name: _block.name, + extension: _block.extension, + size: _block.size, + title: value, + fileExtras: _block.fileExtras, + )); + } + + static String? _fileName(String url) { + final segments = Uri.tryParse(url)?.pathSegments ?? const []; + final last = segments.isEmpty ? '' : segments.last; + return last.isEmpty ? null : last; + } + + static String? _extension(String? name) { + if (name == null) return null; + final dot = name.lastIndexOf('.'); + return dot <= 0 || dot == name.length - 1 ? null : name.substring(dot + 1); + } + + Future _pick(AttachmentPicker pick) async { + setState(() { + _picking = true; + _error = null; + }); + try { + final picked = await pick(); + if (!mounted || picked == null) return; + + final title = picked.title; + // A title the user already typed wins over an empty one from the picker. + final block = AttachesBlock( + url: picked.url, + name: picked.name, + extension: picked.extension, + size: picked.size, + title: title == null || title.isEmpty ? _block.title : title, + fileExtras: picked.fileExtras, + ); + _urlController.text = block.url; + _titleController.text = block.title ?? ''; + _update(block); + } catch (_) { + // The picker is app code and may throw anything. The block keeps the + // file it had. + if (mounted) setState(() => _error = 'Could not attach the file.'); + } finally { + if (mounted) setState(() => _picking = false); + } + } + + @override + Widget build(BuildContext context) { + final picker = EditorConfigScope.maybeOf(context)?.attachmentPicker; + final details = [ + if (_block.name != null) _block.name!, + if (_block.size != null) '${_block.size} bytes', + ].join(' · '); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (picker != null) + TextButton.icon( + onPressed: _picking ? null : () => _pick(picker), + icon: const Icon(Icons.attach_file, size: 18), + label: const Text('Choose file'), + ), + if (_picking) const LinearProgressIndicator(), + if (_error != null) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + _error!, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + fontSize: 12, + ), + ), + ), + TextField( + controller: _urlController, + onChanged: _setUrl, + keyboardType: TextInputType.url, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'File URL', + hintText: 'https://...', + isDense: true, + ), + ), + if (details.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + details, + style: TextStyle(fontSize: 12, color: Colors.grey.shade600), + ), + ), + TextField( + controller: _titleController, + onChanged: _setTitle, + decoration: const InputDecoration(labelText: 'Title', isDense: true), + ), + ], + ); + } +} diff --git a/lib/src/presentation/blocks/embed/embed_editor.dart b/lib/src/presentation/blocks/embed/embed_editor.dart new file mode 100644 index 0000000..90db7b6 --- /dev/null +++ b/lib/src/presentation/blocks/embed/embed_editor.dart @@ -0,0 +1,131 @@ +import 'package:flutter/material.dart'; + +import '../../../data/utils/embed_services.dart'; +import '../../../domain/entities/blocks/embed_block.dart'; +import '../base_block_editor.dart'; + +/// Edits an embed block: the link to the content and its caption. +/// +/// The service and the embed URL are worked out from the link, as the +/// EditorJS embed tool does when a link is pasted. +class EmbedEditor extends BlockEditor { + const EmbedEditor({ + super.key, + required super.block, + required super.onChanged, + }); + + @override + State createState() => _EmbedEditorState(); +} + +class _EmbedEditorState extends State { + late final TextEditingController _sourceController; + late final TextEditingController _captionController; + late EmbedBlock _block; + + @override + void initState() { + super.initState(); + _block = widget.block; + _sourceController = TextEditingController(text: _block.source); + _captionController = TextEditingController(text: _block.caption ?? ''); + } + + @override + void didUpdateWidget(covariant EmbedEditor oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.block != widget.block) { + _block = widget.block; + if (_sourceController.text.trim() != _block.source) { + _sourceController.text = _block.source; + } + if (_captionController.text != (_block.caption ?? '')) { + _captionController.text = _block.caption ?? ''; + } + } + } + + @override + void dispose() { + _sourceController.dispose(); + _captionController.dispose(); + super.dispose(); + } + + void _update(EmbedBlock block) { + setState(() => _block = block); + widget.onChanged(block); + } + + void _setSource(String value) { + final source = value.trim(); + final match = EmbedServices.resolve(source); + _update(EmbedBlock( + service: match?.service ?? '', + source: source, + embed: match?.embed ?? '', + width: match?.width, + height: match?.height, + caption: _block.caption, + )); + } + + void _setCaption(String value) { + // Only the caption changes: a block from a service this package does not + // know keeps the service and embed URL it was saved with. + _update(EmbedBlock( + service: _block.service, + source: _block.source, + embed: _block.embed, + width: _block.width, + height: _block.height, + caption: value, + )); + } + + @override + Widget build(BuildContext context) { + final recognized = _block.service.isNotEmpty; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: _sourceController, + onChanged: _setSource, + keyboardType: TextInputType.url, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Embed link', + hintText: 'https://www.youtube.com/watch?v=...', + isDense: true, + ), + ), + if (_block.source.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text( + recognized + ? 'Service: ${_block.service}' + : 'This link is not from a supported service.', + style: TextStyle( + fontSize: 12, + color: recognized + ? Colors.grey.shade600 + : Theme.of(context).colorScheme.error, + ), + ), + ), + TextField( + controller: _captionController, + onChanged: _setCaption, + decoration: const InputDecoration( + labelText: 'Caption', + isDense: true, + ), + ), + ], + ); + } +} diff --git a/lib/src/presentation/blocks/image/image_editor.dart b/lib/src/presentation/blocks/image/image_editor.dart index 8aad54f..5979201 100644 --- a/lib/src/presentation/blocks/image/image_editor.dart +++ b/lib/src/presentation/blocks/image/image_editor.dart @@ -7,7 +7,7 @@ import 'package:image_picker/image_picker.dart'; import '../../../domain/entities/blocks/image_block.dart'; import '../../config/image_uploader.dart'; -import '../../widgets/image_upload_scope.dart'; +import '../../widgets/editor_config_scope.dart'; import '../base_block_editor.dart'; class ImageEditor extends BlockEditor { @@ -75,7 +75,7 @@ class _ImageEditorState extends State { } Future _pickImage(ImageSource source) async { - final uploader = ImageUploadScope.of(context); + final uploader = EditorConfigScope.maybeOf(context)?.imageUploader; setState(() => _error = null); final XFile? file; diff --git a/lib/src/presentation/blocks/link_tool/link_tool_editor.dart b/lib/src/presentation/blocks/link_tool/link_tool_editor.dart new file mode 100644 index 0000000..f73ea4e --- /dev/null +++ b/lib/src/presentation/blocks/link_tool/link_tool_editor.dart @@ -0,0 +1,195 @@ +import 'package:flutter/material.dart'; + +import '../../../domain/entities/blocks/link_tool_block.dart'; +import '../../config/block_editor_hooks.dart'; +import '../../widgets/editor_config_scope.dart'; +import '../base_block_editor.dart'; + +/// Edits a link block: the link and the preview shown with it. +/// +/// The preview fields can be filled in by hand, or fetched for the link when +/// `EditorConfig.linkPreviewFetcher` is set. +class LinkToolEditor extends BlockEditor { + const LinkToolEditor({ + super.key, + required super.block, + required super.onChanged, + }); + + @override + State createState() => _LinkToolEditorState(); +} + +class _LinkToolEditorState extends State { + late final TextEditingController _linkController; + late final TextEditingController _titleController; + late final TextEditingController _descriptionController; + late final TextEditingController _imageController; + + /// Preview fields the backend sent that this editor has no input for. + late Map _extras; + bool _fetching = false; + String? _error; + + @override + void initState() { + super.initState(); + final block = widget.block; + _extras = block.meta?.extras ?? const {}; + _linkController = TextEditingController(text: block.link); + _titleController = TextEditingController(text: block.meta?.title ?? ''); + _descriptionController = + TextEditingController(text: block.meta?.description ?? ''); + _imageController = TextEditingController(text: block.meta?.imageUrl ?? ''); + } + + @override + void didUpdateWidget(covariant LinkToolEditor oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.block != widget.block) { + final block = widget.block; + _extras = block.meta?.extras ?? const {}; + _sync(_linkController, block.link, trimmed: true); + _sync(_titleController, block.meta?.title ?? ''); + _sync(_descriptionController, block.meta?.description ?? ''); + _sync(_imageController, block.meta?.imageUrl ?? '', trimmed: true); + } + } + + /// Leaves a field alone while it already says the same thing, so the cursor + /// does not jump while the user is typing in it. + static void _sync( + TextEditingController controller, + String value, { + bool trimmed = false, + }) { + final current = trimmed ? controller.text.trim() : controller.text; + if (current != value) controller.text = value; + } + + @override + void dispose() { + _linkController.dispose(); + _titleController.dispose(); + _descriptionController.dispose(); + _imageController.dispose(); + super.dispose(); + } + + static String? _orNull(String text) => text.isEmpty ? null : text; + + void _notify() { + final title = _orNull(_titleController.text); + final description = _orNull(_descriptionController.text); + final imageUrl = _orNull(_imageController.text.trim()); + final hasMeta = title != null || + description != null || + imageUrl != null || + _extras.isNotEmpty; + + widget.onChanged(LinkToolBlock( + link: _linkController.text.trim(), + meta: hasMeta + ? LinkToolMeta( + title: title, + description: description, + imageUrl: imageUrl, + extras: _extras, + ) + : null, + )); + } + + Future _fetchPreview(LinkPreviewFetcher fetch) async { + final link = _linkController.text.trim(); + if (link.isEmpty) return; + + setState(() { + _fetching = true; + _error = null; + }); + try { + final meta = await fetch(link); + if (!mounted) return; + if (meta == null) { + setState(() => _error = 'No preview available for this link.'); + return; + } + _titleController.text = meta.title ?? ''; + _descriptionController.text = meta.description ?? ''; + _imageController.text = meta.imageUrl ?? ''; + _extras = meta.extras; + _notify(); + } catch (_) { + // The fetcher is app code and may throw anything. The fields keep what + // they had. + if (mounted) setState(() => _error = 'Could not fetch the preview.'); + } finally { + if (mounted) setState(() => _fetching = false); + } + } + + @override + Widget build(BuildContext context) { + final fetcher = EditorConfigScope.maybeOf(context)?.linkPreviewFetcher; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: _linkController, + onChanged: (_) => _notify(), + keyboardType: TextInputType.url, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Link', + hintText: 'https://...', + isDense: true, + ), + ), + if (fetcher != null) + TextButton.icon( + onPressed: _fetching ? null : () => _fetchPreview(fetcher), + icon: const Icon(Icons.travel_explore, size: 18), + label: const Text('Fetch preview'), + ), + if (_fetching) const LinearProgressIndicator(), + if (_error != null) + Padding( + padding: const EdgeInsets.only(bottom: 4), + child: Text( + _error!, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + fontSize: 12, + ), + ), + ), + TextField( + controller: _titleController, + onChanged: (_) => _notify(), + decoration: const InputDecoration(labelText: 'Title', isDense: true), + ), + TextField( + controller: _descriptionController, + onChanged: (_) => _notify(), + maxLines: null, + decoration: const InputDecoration( + labelText: 'Description', + isDense: true, + ), + ), + TextField( + controller: _imageController, + onChanged: (_) => _notify(), + keyboardType: TextInputType.url, + autocorrect: false, + decoration: const InputDecoration( + labelText: 'Preview image URL', + isDense: true, + ), + ), + ], + ); + } +} diff --git a/lib/src/presentation/blocks/raw/raw_editor.dart b/lib/src/presentation/blocks/raw/raw_editor.dart new file mode 100644 index 0000000..71bd2fb --- /dev/null +++ b/lib/src/presentation/blocks/raw/raw_editor.dart @@ -0,0 +1,55 @@ +import 'package:flutter/material.dart'; + +import '../../../domain/entities/blocks/raw_block.dart'; +import '../base_block_editor.dart'; + +/// Edits the HTML source of a raw block. +class RawEditor extends BlockEditor { + const RawEditor({super.key, required super.block, required super.onChanged}); + + @override + State createState() => _RawEditorState(); +} + +class _RawEditorState extends State { + late final TextEditingController _controller; + + @override + void initState() { + super.initState(); + _controller = TextEditingController(text: widget.block.html); + } + + @override + void didUpdateWidget(covariant RawEditor oldWidget) { + super.didUpdateWidget(oldWidget); + if (_controller.text != widget.block.html) { + _controller.text = widget.block.html; + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return TextField( + controller: _controller, + onChanged: (value) => widget.onChanged(RawBlock(html: value)), + maxLines: null, + keyboardType: TextInputType.multiline, + autocorrect: false, + enableSuggestions: false, + style: const TextStyle(fontFamily: 'monospace', fontSize: 13), + decoration: const InputDecoration( + labelText: 'Raw HTML', + hintText: '
...
', + alignLabelWithHint: true, + border: OutlineInputBorder(), + ), + ); + } +} diff --git a/lib/src/presentation/config/block_editor_hooks.dart b/lib/src/presentation/config/block_editor_hooks.dart new file mode 100644 index 0000000..042dae1 --- /dev/null +++ b/lib/src/presentation/config/block_editor_hooks.dart @@ -0,0 +1,19 @@ +import '../../domain/entities/blocks/attaches_block.dart'; +import '../../domain/entities/blocks/link_tool_block.dart'; + +/// Fetches the preview data (title, description, image) of the page at [url] +/// for a link block, the way the backend endpoint of the EditorJS link tool +/// does. +/// +/// Return `null` when the page has no usable preview. Throw to report a +/// failure; the editor keeps the fields as they were and shows an error. +typedef LinkPreviewFetcher = Future Function(String url); + +/// Lets the user choose a file, stores it where readers of the document can +/// reach it, and returns the attachment describing it. +/// +/// This package does not bundle a file picker, so the app supplies both the +/// picking and the uploading. Return `null` if the user cancelled. Throw to +/// report a failure; the editor keeps the current attachment and shows an +/// error. +typedef AttachmentPicker = Future Function(); diff --git a/lib/src/presentation/config/editor_config.dart b/lib/src/presentation/config/editor_config.dart index 20d870f..b393370 100644 --- a/lib/src/presentation/config/editor_config.dart +++ b/lib/src/presentation/config/editor_config.dart @@ -2,6 +2,7 @@ import '../../data/registry/block_type_registry.dart'; import '../../domain/entities/style_config.dart'; import '../registry/block_renderer_registry.dart'; import '../widgets/editor_link_scope.dart'; +import 'block_editor_hooks.dart'; import 'editor_toolbar_item.dart'; import 'image_uploader.dart'; @@ -49,6 +50,18 @@ class EditorConfig { /// is meant to be read elsewhere. final ImageUploader? imageUploader; + /// Fetches title, description and image for the link of a link block. + /// + /// When set, the link editor offers a "Fetch preview" button. Without it + /// the preview fields are filled in by hand. + final LinkPreviewFetcher? linkPreviewFetcher; + + /// Lets the user choose and upload a file for an attachment block. + /// + /// When set, the attachment editor offers a "Choose file" button. Without + /// it an attachment is given as a URL. + final AttachmentPicker? attachmentPicker; + EditorConfig({ BlockTypeRegistry? typeRegistry, BlockRendererRegistry? rendererRegistry, @@ -57,6 +70,8 @@ class EditorConfig { this.allowedLinkSchemes = EditorLinkScope.defaultSchemes, this.toolbarItems = EditorToolbarItem.values, this.imageUploader, + this.linkPreviewFetcher, + this.attachmentPicker, }) : typeRegistry = typeRegistry ?? BlockTypeRegistry(), rendererRegistry = rendererRegistry ?? BlockRendererRegistry(); } diff --git a/lib/src/presentation/config/editor_toolbar_item.dart b/lib/src/presentation/config/editor_toolbar_item.dart index a8150c6..c6ae6ff 100644 --- a/lib/src/presentation/config/editor_toolbar_item.dart +++ b/lib/src/presentation/config/editor_toolbar_item.dart @@ -25,6 +25,14 @@ enum EditorToolbarItem { delimiter, warning, image, + + /// Content from a service such as YouTube or Vimeo, given as a link. + embed, + + /// A link shown as a preview card (the EditorJS link tool). + linkPreview, + attachment, + rawHtml, hyperlink, undo, redo, diff --git a/lib/src/presentation/registry/block_renderer_registry.dart b/lib/src/presentation/registry/block_renderer_registry.dart index 0ef6086..2de4eb3 100644 --- a/lib/src/presentation/registry/block_renderer_registry.dart +++ b/lib/src/presentation/registry/block_renderer_registry.dart @@ -17,10 +17,14 @@ import '../../domain/entities/blocks/link_tool_block.dart'; import '../../domain/entities/blocks/raw_block.dart'; import '../../domain/entities/blocks/warning_block.dart'; import '../../domain/entities/style_config.dart'; +import '../blocks/attaches/attaches_editor.dart'; import '../blocks/attaches/attaches_renderer.dart'; import '../blocks/checklist/checklist_editor.dart'; +import '../blocks/embed/embed_editor.dart'; import '../blocks/embed/embed_renderer.dart'; +import '../blocks/link_tool/link_tool_editor.dart'; import '../blocks/link_tool/link_tool_renderer.dart'; +import '../blocks/raw/raw_editor.dart'; import '../blocks/raw/raw_renderer.dart'; import '../blocks/checklist/checklist_renderer.dart'; import '../blocks/code/code_editor.dart'; @@ -114,6 +118,14 @@ class BlockRendererRegistry { (b, cb) => TableEditor(block: b as TableBlock, onChanged: (u) => cb(u))); registerEditor('warning', (b, cb) => WarningEditor(block: b as WarningBlock, onChanged: (u) => cb(u))); + registerEditor('embed', + (b, cb) => EmbedEditor(block: b as EmbedBlock, onChanged: (u) => cb(u))); + registerEditor('linkTool', + (b, cb) => LinkToolEditor(block: b as LinkToolBlock, onChanged: (u) => cb(u))); + registerEditor('attaches', + (b, cb) => AttachesEditor(block: b as AttachesBlock, onChanged: (u) => cb(u))); + registerEditor('raw', + (b, cb) => RawEditor(block: b as RawBlock, onChanged: (u) => cb(u))); } void registerRenderer(String type, BlockRendererBuilder builder) { diff --git a/lib/src/presentation/widgets/editor_config_scope.dart b/lib/src/presentation/widgets/editor_config_scope.dart new file mode 100644 index 0000000..32c2eb0 --- /dev/null +++ b/lib/src/presentation/widgets/editor_config_scope.dart @@ -0,0 +1,27 @@ +import 'package:flutter/widgets.dart'; + +import '../config/editor_config.dart'; + +/// Makes the [EditorConfig] of the surrounding `EditorJSEditor` available to +/// the block editors below it. +/// +/// Block editors are built by the registry from a block and a callback, so +/// they cannot receive configuration as arguments. They read it from here. +class EditorConfigScope extends InheritedWidget { + final EditorConfig config; + + const EditorConfigScope({ + super.key, + required this.config, + required super.child, + }); + + /// The configuration of the surrounding editor, or `null` when a block + /// editor is used on its own. + static EditorConfig? maybeOf(BuildContext context) => + context.getInheritedWidgetOfExactType()?.config; + + @override + bool updateShouldNotify(EditorConfigScope oldWidget) => + config != oldWidget.config; +} diff --git a/lib/src/presentation/widgets/editorjs_editor.dart b/lib/src/presentation/widgets/editorjs_editor.dart index 55a0005..f61430d 100644 --- a/lib/src/presentation/widgets/editorjs_editor.dart +++ b/lib/src/presentation/widgets/editorjs_editor.dart @@ -2,8 +2,8 @@ import 'package:flutter/material.dart'; import '../config/editor_config.dart'; import '../controller/editor_controller.dart'; +import 'editor_config_scope.dart'; import 'editorjs_toolbar.dart'; -import 'image_upload_scope.dart'; /// Interactive editor for EditorJS content. /// @@ -63,8 +63,8 @@ class _EditorJSEditorState extends State { final ids = widget.controller.blockIds; - return ImageUploadScope( - uploader: widget.config.imageUploader, + return EditorConfigScope( + config: widget.config, child: Column( children: [ Expanded( diff --git a/lib/src/presentation/widgets/editorjs_toolbar.dart b/lib/src/presentation/widgets/editorjs_toolbar.dart index ffcde1d..df99eb7 100644 --- a/lib/src/presentation/widgets/editorjs_toolbar.dart +++ b/lib/src/presentation/widgets/editorjs_toolbar.dart @@ -1,13 +1,17 @@ import 'package:flutter/material.dart'; +import '../../domain/entities/blocks/attaches_block.dart'; import '../../domain/entities/blocks/checklist_block.dart'; import '../../domain/entities/blocks/code_block.dart'; import '../../domain/entities/blocks/delimiter_block.dart'; +import '../../domain/entities/blocks/embed_block.dart'; import '../../domain/entities/blocks/header_block.dart'; import '../../domain/entities/blocks/image_block.dart'; +import '../../domain/entities/blocks/link_tool_block.dart'; import '../../domain/entities/blocks/list_block.dart'; import '../../domain/entities/blocks/paragraph_block.dart'; import '../../domain/entities/blocks/quote_block.dart'; +import '../../domain/entities/blocks/raw_block.dart'; import '../../domain/entities/blocks/table_block.dart'; import '../../domain/entities/blocks/warning_block.dart'; import '../config/editor_toolbar_item.dart'; @@ -150,6 +154,28 @@ class EditorJSToolbar extends StatelessWidget { tooltip: 'Image', onTap: () => controller.addBlock(const ImageBlock(url: '')), ), + EditorToolbarItem.embed => _ToolbarButton( + icon: Icons.smart_display_outlined, + tooltip: 'Embed', + onTap: () => controller.addBlock( + const EmbedBlock(service: '', source: '', embed: ''), + ), + ), + EditorToolbarItem.linkPreview => _ToolbarButton( + icon: Icons.add_link, + tooltip: 'Link preview', + onTap: () => controller.addBlock(const LinkToolBlock(link: '')), + ), + EditorToolbarItem.attachment => _ToolbarButton( + icon: Icons.attach_file, + tooltip: 'Attachment', + onTap: () => controller.addBlock(const AttachesBlock(url: '')), + ), + EditorToolbarItem.rawHtml => _ToolbarButton( + icon: Icons.html, + tooltip: 'Raw HTML', + onTap: () => controller.addBlock(const RawBlock(html: '')), + ), EditorToolbarItem.hyperlink => _ToolbarButton( icon: Icons.link, tooltip: 'Hyperlink', diff --git a/lib/src/presentation/widgets/image_upload_scope.dart b/lib/src/presentation/widgets/image_upload_scope.dart deleted file mode 100644 index ba7928c..0000000 --- a/lib/src/presentation/widgets/image_upload_scope.dart +++ /dev/null @@ -1,23 +0,0 @@ -import 'package:flutter/widgets.dart'; - -import '../config/image_uploader.dart'; - -/// Carries `EditorConfig.imageUploader` down to the image editor, which is -/// built by the block registry and therefore cannot receive it as an argument. -class ImageUploadScope extends InheritedWidget { - final ImageUploader? uploader; - - const ImageUploadScope({ - super.key, - required this.uploader, - required super.child, - }); - - /// The uploader configured for the surrounding editor, if any. - static ImageUploader? of(BuildContext context) => - context.getInheritedWidgetOfExactType()?.uploader; - - @override - bool updateShouldNotify(ImageUploadScope oldWidget) => - uploader != oldWidget.uploader; -} diff --git a/test/unit/embed_services_test.dart b/test/unit/embed_services_test.dart new file mode 100644 index 0000000..5198ec3 --- /dev/null +++ b/test/unit/embed_services_test.dart @@ -0,0 +1,204 @@ +import 'package:editorjs_flutter/src/data/utils/embed_services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + void expectEmbed(String url, String service, String embed) { + final match = EmbedServices.resolve(url); + expect(match, isNotNull, reason: '$url was not recognised'); + expect(match!.service, service, reason: url); + expect(match.embed, embed, reason: url); + } + + group('YouTube', () { + const base = 'https://www.youtube.com/embed/'; + + test('watch, short, shorts and embed links', () { + expectEmbed( + 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', + 'youtube', + '${base}dQw4w9WgXcQ', + ); + expectEmbed('https://youtu.be/dQw4w9WgXcQ', 'youtube', '${base}dQw4w9WgXcQ'); + expectEmbed( + 'https://www.youtube.com/shorts/abc123XYZ_-', + 'youtube', + '${base}abc123XYZ_-', + ); + expectEmbed('https://www.youtube.com/embed/ID123', 'youtube', '${base}ID123'); + }); + + test('start time and playlist are carried over', () { + expectEmbed( + 'https://www.youtube.com/watch?v=ID123&t=42', + 'youtube', + '${base}ID123?start=42', + ); + expectEmbed( + 'https://www.youtube.com/watch?v=ID123&list=PL123&start=10', + 'youtube', + '${base}ID123?list=PL123&start=10', + ); + }); + + test('the id is found when it is not the first parameter', () { + expectEmbed( + 'https://www.youtube.com/watch?feature=share&v=ID123', + 'youtube', + '${base}ID123', + ); + }); + + test('personal lists and unknown parameters are dropped', () { + expectEmbed( + 'https://www.youtube.com/watch?v=ID123&list=LL&si=abc', + 'youtube', + '${base}ID123', + ); + expectEmbed( + 'https://www.youtube.com/watch?v=ID123&list=RDMMxyz', + 'youtube', + '${base}ID123', + ); + }); + + test('has the size EditorJS gives it', () { + final match = EmbedServices.resolve('https://youtu.be/ID123')!; + expect(match.width, 580); + expect(match.height, 320); + }); + }); + + test('video services', () { + expectEmbed( + 'https://vimeo.com/123456789', + 'vimeo', + 'https://player.vimeo.com/video/123456789?title=0&byline=0', + ); + expectEmbed( + 'https://coub.com/view/1czcdf', + 'coub', + 'https://coub.com/embed/1czcdf', + ); + expectEmbed( + 'https://www.twitch.tv/ninja', + 'twitch-channel', + 'https://player.twitch.tv/?channel=ninja', + ); + expectEmbed( + 'https://www.twitch.tv/videos/123456', + 'twitch-video', + 'https://player.twitch.tv/?video=v123456', + ); + expectEmbed( + 'https://www.aparat.com/v/abc12', + 'aparat', + 'https://www.aparat.com/video/video/embed/videohash/abc12/vt/frame', + ); + }); + + test('social services', () { + expectEmbed( + 'https://twitter.com/codex_team/status/1234567890', + 'twitter', + 'https://platform.twitter.com/embed/Tweet.html?id=1234567890', + ); + expectEmbed( + 'https://x.com/someone/status/987', + 'twitter', + 'https://platform.twitter.com/embed/Tweet.html?id=987', + ); + expectEmbed( + 'https://www.instagram.com/p/CODE123/?utm_source=share', + 'instagram', + 'https://www.instagram.com/p/CODE123/embed', + ); + expectEmbed( + 'https://www.facebook.com/someone/posts/123', + 'facebook', + 'https://www.facebook.com/plugins/post.php' + '?href=https://www.facebook.com/someone/posts/123&width=500', + ); + expectEmbed( + 'https://www.pinterest.com/pin/123456/', + 'pinterest', + 'https://assets.pinterest.com/ext/embed.html?id=123456', + ); + expectEmbed( + 'https://www.reddit.com/r/flutter/comments/abc/title/', + 'reddit', + 'https://www.redditmedia.com/r/flutter/comments/abc/title/' + '?ref_source=embed&ref=share&embed=true', + ); + }); + + test('design, code and image services', () { + expectEmbed( + 'https://codepen.io/team/pen/abcDEF', + 'codepen', + 'https://codepen.io/team/embed/abcDEF' + '?height=300&theme-id=0&default-tab=css,result&embed-version=2', + ); + expectEmbed( + 'https://www.figma.com/file/abc/Design', + 'figma', + 'https://www.figma.com/embed?embed_host=share' + '&url=https://www.figma.com/file/abc/Design', + ); + expectEmbed( + 'https://miro.com/app/board/o9J_k1JKioQ=/', + 'miro', + 'https://miro.com/app/live-embed/o9J_k1JKioQ=', + ); + expectEmbed( + 'https://whimsical.com/my-board-ABCDEFGHJKMNPQRS', + 'whimsical', + 'https://whimsical.com/embed/ABCDEFGHJKMNPQRS', + ); + expectEmbed( + 'https://i.imgur.com/abc123.gifv', + 'imgur', + 'http://imgur.com/abc123/embed', + ); + + final gist = EmbedServices.resolve('https://gist.github.com/user/abcdef123')!; + expect(gist.service, 'github'); + expect(gist.embed, contains('https://gist.github.com/user/abcdef123.js')); + }); + + test('Yandex Music albums, tracks and playlists', () { + expectEmbed( + 'https://music.yandex.ru/album/5307396', + 'yandex-music-album', + 'https://music.yandex.ru/iframe/#album/5307396/', + ); + expectEmbed( + 'https://music.yandex.ru/track/42', + 'yandex-music-track', + 'https://music.yandex.ru/iframe/#track/42/', + ); + expectEmbed( + 'https://music.yandex.ru/users/someone/playlists/1000', + 'yandex-music-playlist', + 'https://music.yandex.ru/iframe/#playlist/someone/1000' + '/show/cover/description/', + ); + }); + + test('surrounding whitespace is ignored', () { + expect(EmbedServices.resolve(' https://youtu.be/ID123 \n')?.service, + 'youtube'); + }); + + test('links from unknown sites and non-links resolve to nothing', () { + for (final url in [ + '', + ' ', + 'not a link', + 'https://example.com/watch?v=ID123', + 'https://www.youtube.com/', + 'https://vimeo.com/', + ]) { + expect(EmbedServices.resolve(url), isNull, reason: url); + } + }); +} diff --git a/test/widget/image_editor_test.dart b/test/widget/image_editor_test.dart index ff1c85c..84b3e6c 100644 --- a/test/widget/image_editor_test.dart +++ b/test/widget/image_editor_test.dart @@ -2,7 +2,7 @@ import 'dart:async'; import 'package:editorjs_flutter/editorjs_flutter.dart'; import 'package:editorjs_flutter/src/presentation/blocks/image/image_editor.dart'; -import 'package:editorjs_flutter/src/presentation/widgets/image_upload_scope.dart'; +import 'package:editorjs_flutter/src/presentation/widgets/editor_config_scope.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -21,8 +21,8 @@ const _existing = ImageBlock( Widget _host(Widget child, {ImageUploader? uploader}) => MaterialApp( home: Scaffold( body: SingleChildScrollView( - child: ImageUploadScope( - uploader: uploader, + child: EditorConfigScope( + config: EditorConfig(imageUploader: uploader), child: SizedBox(width: 400, child: child), ), ), @@ -344,20 +344,19 @@ void main() { expect(const UploadedImage(url: 'u').extras, isEmpty); }); - test('ImageUploadScope notifies only when the uploader changes', () { - Future uploader(PickedImage image) async => - const UploadedImage(url: 'u'); + test('EditorConfigScope notifies only when the config changes', () { const child = SizedBox(); - final scope = ImageUploadScope(uploader: uploader, child: child); + final config = EditorConfig(); + final scope = EditorConfigScope(config: config, child: child); expect( scope.updateShouldNotify( - ImageUploadScope(uploader: uploader, child: child), + EditorConfigScope(config: config, child: child), ), isFalse, ); expect( scope.updateShouldNotify( - const ImageUploadScope(uploader: null, child: child), + EditorConfigScope(config: EditorConfig(), child: child), ), isTrue, ); diff --git a/test/widget/media_block_editors_test.dart b/test/widget/media_block_editors_test.dart new file mode 100644 index 0000000..0845dbd --- /dev/null +++ b/test/widget/media_block_editors_test.dart @@ -0,0 +1,571 @@ +import 'dart:async'; + +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/attaches/attaches_editor.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/embed/embed_editor.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/link_tool/link_tool_editor.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/raw/raw_editor.dart'; +import 'package:editorjs_flutter/src/presentation/widgets/editor_config_scope.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _host(Widget child, {EditorConfig? config}) => MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: EditorConfigScope( + config: config ?? EditorConfig(), + child: SizedBox(width: 400, child: child), + ), + ), + ), + ); + +Finder _field(String label) => find.widgetWithText(TextField, label); + +void main() { + group('RawEditor', () { + testWidgets('shows and edits the HTML source', (tester) async { + final changes = []; + await tester.pumpWidget(_host(RawEditor( + block: const RawBlock(html: '
old
'), + onChanged: changes.add, + ))); + expect(find.text('
old
'), findsOneWidget); + + await tester.enterText(find.byType(TextField), '

new

'); + expect(changes.single.html, '

new

'); + }); + + testWidgets('follows a block replaced from outside', (tester) async { + Widget editor(String html) => + _host(RawEditor(block: RawBlock(html: html), onChanged: (_) {})); + await tester.pumpWidget(editor('a')); + await tester.pumpWidget(editor('b')); + expect(find.text('b'), findsOneWidget); + }); + }); + + group('EmbedEditor', () { + Future> pumpEditor( + WidgetTester tester, + EmbedBlock block, + ) async { + final changes = []; + await tester.pumpWidget(_host( + EmbedEditor(block: block, onChanged: changes.add), + )); + return changes; + } + + testWidgets('a link from a known service fills in service and embed URL', + (tester) async { + final changes = await pumpEditor( + tester, + const EmbedBlock(service: '', source: '', embed: '', caption: 'Keep'), + ); + + await tester.enterText( + _field('Embed link'), + ' https://www.youtube.com/watch?v=ID123 ', + ); + await tester.pump(); + + final block = changes.last; + expect(block.service, 'youtube'); + expect(block.source, 'https://www.youtube.com/watch?v=ID123'); + expect(block.embed, 'https://www.youtube.com/embed/ID123'); + expect(block.width, 580); + expect(block.height, 320); + expect(block.caption, 'Keep'); + expect(find.text('Service: youtube'), findsOneWidget); + }); + + testWidgets('a link from an unknown site is kept and flagged', + (tester) async { + final changes = await pumpEditor( + tester, + const EmbedBlock( + service: 'youtube', + source: 'https://youtu.be/ID123', + embed: 'https://www.youtube.com/embed/ID123', + width: 580, + height: 320, + ), + ); + + await tester.enterText(_field('Embed link'), 'https://example.com/clip'); + await tester.pump(); + + final block = changes.last; + expect(block.source, 'https://example.com/clip'); + expect(block.service, ''); + expect(block.embed, ''); + expect(block.width, isNull); + expect( + find.text('This link is not from a supported service.'), + findsOneWidget, + ); + }); + + testWidgets('editing only the caption keeps an unrecognised service', + (tester) async { + // A service configured on the web side that this package has no + // pattern for. + final changes = await pumpEditor( + tester, + const EmbedBlock( + service: 'my-video-host', + source: 'https://videos.example.com/42', + embed: 'https://videos.example.com/embed/42', + width: 640, + height: 360, + caption: 'Old', + ), + ); + + await tester.enterText(_field('Old'), 'New caption'); + + final block = changes.single; + expect(block.caption, 'New caption'); + expect(block.service, 'my-video-host'); + expect(block.embed, 'https://videos.example.com/embed/42'); + expect(block.width, 640); + expect(block.height, 360); + }); + + testWidgets('an empty block shows no service line', (tester) async { + await pumpEditor( + tester, + const EmbedBlock(service: '', source: '', embed: ''), + ); + expect(find.textContaining('Service:'), findsNothing); + expect(find.textContaining('not from a supported'), findsNothing); + }); + + testWidgets('follows a block replaced from outside', (tester) async { + Widget editor(EmbedBlock block) => + _host(EmbedEditor(block: block, onChanged: (_) {})); + await tester.pumpWidget(editor( + const EmbedBlock(service: '', source: 'a', embed: '', caption: 'x'), + )); + await tester.pumpWidget(editor(const EmbedBlock( + service: 'vimeo', + source: 'https://vimeo.com/1234', + embed: 'e', + caption: 'y', + ))); + expect(_field('https://vimeo.com/1234'), findsOneWidget); + expect(_field('y'), findsOneWidget); + expect(find.text('Service: vimeo'), findsOneWidget); + }); + }); + + group('LinkToolEditor', () { + const existing = LinkToolBlock( + link: 'https://codex.so', + meta: LinkToolMeta( + title: 'CodeX', + description: 'A team', + imageUrl: 'https://codex.so/logo.png', + extras: {'site_name': 'CodeX'}, + ), + ); + + Future> pumpEditor( + WidgetTester tester, + LinkToolBlock block, { + LinkPreviewFetcher? fetcher, + }) async { + final changes = []; + await tester.pumpWidget(_host( + LinkToolEditor(block: block, onChanged: changes.add), + config: EditorConfig(linkPreviewFetcher: fetcher), + )); + return changes; + } + + testWidgets('shows the link and its preview fields', (tester) async { + await pumpEditor(tester, existing); + for (final text in [ + 'https://codex.so', + 'CodeX', + 'A team', + 'https://codex.so/logo.png', + ]) { + expect(_field(text), findsOneWidget); + } + }); + + testWidgets('editing a field keeps the others and the extra fields', + (tester) async { + final changes = await pumpEditor(tester, existing); + await tester.enterText(_field('CodeX'), 'CodeX Team'); + + final block = changes.single; + expect(block.link, 'https://codex.so'); + expect(block.meta!.title, 'CodeX Team'); + expect(block.meta!.description, 'A team'); + expect(block.meta!.imageUrl, 'https://codex.so/logo.png'); + expect(block.meta!.extras, {'site_name': 'CodeX'}); + }); + + testWidgets('a link with no preview data has no meta', (tester) async { + final changes = await pumpEditor(tester, const LinkToolBlock(link: '')); + await tester.enterText(_field('Link'), ' https://example.com '); + + expect(changes.single.link, 'https://example.com'); + expect(changes.single.meta, isNull); + expect(changes.single.toJson(), {'link': 'https://example.com'}); + }); + + testWidgets('there is no fetch button without a fetcher', (tester) async { + await pumpEditor(tester, existing); + expect(find.text('Fetch preview'), findsNothing); + }); + + testWidgets('fetching fills the preview fields', (tester) async { + String? requested; + final changes = await pumpEditor( + tester, + const LinkToolBlock(link: 'https://example.com/page'), + fetcher: (url) async { + requested = url; + return const LinkToolMeta( + title: 'Fetched title', + description: 'Fetched description', + imageUrl: 'https://example.com/og.png', + extras: {'site_name': 'Example'}, + ); + }, + ); + + await tester.tap(find.text('Fetch preview')); + await tester.pumpAndSettle(); + + expect(requested, 'https://example.com/page'); + final meta = changes.single.meta!; + expect(meta.title, 'Fetched title'); + expect(meta.description, 'Fetched description'); + expect(meta.imageUrl, 'https://example.com/og.png'); + expect(meta.extras, {'site_name': 'Example'}); + expect(_field('Fetched title'), findsOneWidget); + }); + + testWidgets('shows progress and blocks a second fetch while one runs', + (tester) async { + final pending = Completer(); + await pumpEditor(tester, existing, fetcher: (_) => pending.future); + + await tester.tap(find.text('Fetch preview')); + await tester.pump(); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(TextButton, 'Fetch preview'), + ) + .onPressed, + isNull, + ); + + pending.complete(const LinkToolMeta(title: 'Done')); + await tester.pumpAndSettle(); + expect(find.byType(LinearProgressIndicator), findsNothing); + }); + + testWidgets('no preview and a failed fetch keep the fields', + (tester) async { + var fail = false; + final changes = await pumpEditor( + tester, + existing, + fetcher: (_) async => fail ? throw StateError('offline') : null, + ); + + await tester.tap(find.text('Fetch preview')); + await tester.pumpAndSettle(); + expect(find.text('No preview available for this link.'), findsOneWidget); + + fail = true; + await tester.tap(find.text('Fetch preview')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.text('Could not fetch the preview.'), findsOneWidget); + expect(find.text('No preview available for this link.'), findsNothing); + + expect(changes, isEmpty); + expect(_field('CodeX'), findsOneWidget); + }); + + testWidgets('fetching does nothing while the link is empty', + (tester) async { + var calls = 0; + await pumpEditor( + tester, + const LinkToolBlock(link: ''), + fetcher: (_) async { + calls++; + return null; + }, + ); + await tester.tap(find.text('Fetch preview')); + await tester.pumpAndSettle(); + expect(calls, 0); + }); + + testWidgets('follows a block replaced from outside', (tester) async { + Widget editor(LinkToolBlock block) => + _host(LinkToolEditor(block: block, onChanged: (_) {})); + await tester.pumpWidget(editor(existing)); + await tester.pumpWidget(editor(const LinkToolBlock( + link: 'https://other.example', + meta: LinkToolMeta(title: 'Other'), + ))); + expect(_field('https://other.example'), findsOneWidget); + expect(_field('Other'), findsOneWidget); + expect(_field('A team'), findsNothing); + }); + }); + + group('AttachesEditor', () { + const existing = AttachesBlock( + url: 'https://files.example.com/report.pdf', + name: 'report.pdf', + extension: 'pdf', + size: 2048, + title: 'Annual report', + fileExtras: {'assetId': 7}, + ); + + Future> pumpEditor( + WidgetTester tester, + AttachesBlock block, { + AttachmentPicker? picker, + }) async { + final changes = []; + await tester.pumpWidget(_host( + AttachesEditor(block: block, onChanged: changes.add), + config: EditorConfig(attachmentPicker: picker), + )); + return changes; + } + + testWidgets('shows the URL, title and file details', (tester) async { + await pumpEditor(tester, existing); + expect(_field('https://files.example.com/report.pdf'), findsOneWidget); + expect(_field('Annual report'), findsOneWidget); + expect(find.text('report.pdf · 2048 bytes'), findsOneWidget); + }); + + testWidgets('editing the title keeps everything about the file', + (tester) async { + final changes = await pumpEditor(tester, existing); + await tester.enterText(_field('Annual report'), 'Report 2026'); + + final block = changes.single; + expect(block.title, 'Report 2026'); + expect(block.url, existing.url); + expect(block.name, 'report.pdf'); + expect(block.extension, 'pdf'); + expect(block.size, 2048); + expect(block.fileExtras, {'assetId': 7}); + }); + + testWidgets('typing a URL describes the new file from the URL', + (tester) async { + final changes = await pumpEditor(tester, existing); + await tester.enterText( + _field('https://files.example.com/report.pdf'), + ' https://cdn.example.com/docs/slides.final.pptx?dl=1 ', + ); + await tester.pump(); + + final block = changes.last; + expect(block.url, 'https://cdn.example.com/docs/slides.final.pptx?dl=1'); + expect(block.name, 'slides.final.pptx'); + expect(block.extension, 'pptx'); + expect(block.title, 'Annual report'); + // These described the previous file. + expect(block.size, isNull); + expect(block.fileExtras, isEmpty); + expect(find.text('slides.final.pptx'), findsOneWidget); + }); + + testWidgets('a URL without a file name or extension gives none', + (tester) async { + final changes = await pumpEditor(tester, const AttachesBlock(url: '')); + + await tester.enterText(_field('File URL'), 'https://example.com/'); + expect(changes.last.name, isNull); + expect(changes.last.extension, isNull); + + await tester.enterText(_field('https://example.com/'), 'https://x.io/README'); + expect(changes.last.name, 'README'); + expect(changes.last.extension, isNull); + + await tester.enterText(_field('https://x.io/README'), 'https://x.io/.env'); + expect(changes.last.name, '.env'); + expect(changes.last.extension, isNull); + }); + + testWidgets('there is no picker button without a picker', (tester) async { + await pumpEditor(tester, existing); + expect(find.text('Choose file'), findsNothing); + }); + + testWidgets('a picked file replaces the attachment', (tester) async { + final changes = await pumpEditor( + tester, + existing, + picker: () async => const AttachesBlock( + url: 'https://cdn.example.com/new.zip', + name: 'new.zip', + extension: 'zip', + size: 99, + fileExtras: {'assetId': 8}, + ), + ); + + await tester.tap(find.text('Choose file')); + await tester.pumpAndSettle(); + + final block = changes.single; + expect(block.url, 'https://cdn.example.com/new.zip'); + expect(block.name, 'new.zip'); + expect(block.size, 99); + expect(block.fileExtras, {'assetId': 8}); + // The picker gave no title, so the one already typed stays. + expect(block.title, 'Annual report'); + expect(_field('https://cdn.example.com/new.zip'), findsOneWidget); + }); + + testWidgets('a title from the picker replaces the current one', + (tester) async { + final changes = await pumpEditor( + tester, + existing, + picker: () async => + const AttachesBlock(url: 'https://x.io/a.txt', title: 'Notes'), + ); + await tester.tap(find.text('Choose file')); + await tester.pumpAndSettle(); + expect(changes.single.title, 'Notes'); + expect(_field('Notes'), findsOneWidget); + }); + + testWidgets('cancelling and failing keep the current attachment', + (tester) async { + var fail = false; + final changes = await pumpEditor( + tester, + existing, + picker: () async => fail ? throw StateError('denied') : null, + ); + + await tester.tap(find.text('Choose file')); + await tester.pumpAndSettle(); + expect(changes, isEmpty); + expect(find.text('Could not attach the file.'), findsNothing); + + fail = true; + await tester.tap(find.text('Choose file')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(changes, isEmpty); + expect(find.text('Could not attach the file.'), findsOneWidget); + }); + + testWidgets('shows progress while the picker runs', (tester) async { + final pending = Completer(); + await pumpEditor(tester, existing, picker: () => pending.future); + + await tester.tap(find.text('Choose file')); + await tester.pump(); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + + pending.complete(null); + await tester.pumpAndSettle(); + expect(find.byType(LinearProgressIndicator), findsNothing); + }); + + testWidgets('follows a block replaced from outside', (tester) async { + Widget editor(AttachesBlock block) => + _host(AttachesEditor(block: block, onChanged: (_) {})); + await tester.pumpWidget(editor(existing)); + await tester.pumpWidget(editor( + const AttachesBlock(url: 'https://x.io/b.txt', title: 'B'), + )); + expect(_field('https://x.io/b.txt'), findsOneWidget); + expect(_field('B'), findsOneWidget); + }); + }); + + group('in the full editor', () { + const document = '{"blocks":[' + '{"id":"embed00001","type":"embed","data":{"service":"coub",' + '"source":"https://coub.com/view/1czcdf",' + '"embed":"https://coub.com/embed/1czcdf","caption":"Clip"}},' + '{"id":"link000001","type":"linkTool","data":' + '{"link":"https://codex.so","meta":{"title":"CodeX"}}},' + '{"id":"file000001","type":"attaches","data":' + '{"file":{"url":"https://x.io/a.pdf","name":"a.pdf"},"title":"Doc"}},' + '{"id":"raw0000001","type":"raw","data":{"html":"
"}}' + ']}'; + + test('the registry has an editor for all four block types', () { + final registry = BlockRendererRegistry(); + for (final type in ['embed', 'linkTool', 'attaches', 'raw']) { + expect(registry.supportsEditing(type), isTrue, reason: type); + } + }); + + testWidgets('the blocks get editors instead of a placeholder', + (tester) async { + await tester.binding.setSurfaceSize(const Size(500, 1600)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + final controller = EditorController.fromJson(document); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: EditorJSEditor(controller: controller)), + )); + await tester.pumpAndSettle(); + + expect(find.textContaining('Unsupported block'), findsNothing); + expect(find.byType(EmbedEditor), findsOneWidget); + expect(find.byType(LinkToolEditor), findsOneWidget); + expect(find.byType(AttachesEditor), findsOneWidget); + expect(find.byType(RawEditor), findsOneWidget); + + await tester.enterText(_field('Doc'), 'Document'); + await tester.pumpAndSettle(); + expect(controller.getContent(), contains('"title":"Document"')); + // Untouched blocks are written back as they were read. + expect( + controller.getContent(), + contains('{"id":"raw0000001","type":"raw","data":{"html":"
"}}'), + ); + }); + + testWidgets('EditorConfig hooks reach the link and attachment editors', + (tester) async { + await tester.binding.setSurfaceSize(const Size(500, 1600)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: EditorJSEditor( + controller: EditorController.fromJson(document), + config: EditorConfig( + linkPreviewFetcher: (_) async => null, + attachmentPicker: () async => null, + ), + ), + ), + )); + await tester.pumpAndSettle(); + + expect(find.text('Fetch preview'), findsOneWidget); + expect(find.text('Choose file'), findsOneWidget); + }); + }); +} diff --git a/test/widget/toolbar_items_test.dart b/test/widget/toolbar_items_test.dart index ea62b28..80cbcd8 100644 --- a/test/widget/toolbar_items_test.dart +++ b/test/widget/toolbar_items_test.dart @@ -21,6 +21,10 @@ const _tooltips = { EditorToolbarItem.delimiter: 'Delimiter', EditorToolbarItem.warning: 'Warning', EditorToolbarItem.image: 'Image', + EditorToolbarItem.embed: 'Embed', + EditorToolbarItem.linkPreview: 'Link preview', + EditorToolbarItem.attachment: 'Attachment', + EditorToolbarItem.rawHtml: 'Raw HTML', EditorToolbarItem.hyperlink: 'Hyperlink', EditorToolbarItem.undo: 'Undo', EditorToolbarItem.redo: 'Redo', @@ -80,6 +84,10 @@ void main() { }); testWidgets('each block button adds the block it names', (tester) async { + // Wide enough that every button is on screen and can be tapped. + await tester.binding.setSurfaceSize(const Size(2000, 600)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final expected = { EditorToolbarItem.paragraph: (b) => b is ParagraphBlock, for (var level = 1; level <= 6; level++) @@ -98,6 +106,10 @@ void main() { EditorToolbarItem.delimiter: (b) => b is DelimiterBlock, EditorToolbarItem.warning: (b) => b is WarningBlock, EditorToolbarItem.image: (b) => b is ImageBlock, + EditorToolbarItem.embed: (b) => b is EmbedBlock, + EditorToolbarItem.linkPreview: (b) => b is LinkToolBlock, + EditorToolbarItem.attachment: (b) => b is AttachesBlock, + EditorToolbarItem.rawHtml: (b) => b is RawBlock, }; for (final entry in expected.entries) { From 0be8fb6b7a2f6c8961f20e2835a71696dc72b4bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 09:50:11 -0600 Subject: [PATCH 13/16] Add, edit and remove links from the paragraph format bar The only way to add a link was the toolbar's Hyperlink button, which appends a new paragraph containing nothing but the link. The paragraph format bar now has a Link button. With text selected it wraps the selection in a link; with nothing selected it inserts the address as the link text. With the caret in an existing link it opens that link for editing: saving replaces only the address and keeps the text, inner formatting and other attributes, and "Remove link" keeps the text. A bare address is completed to https://; mailto:, tel: and in-site targets are left as typed. The address is escaped for the attribute. Co-Authored-By: Claude --- CHANGELOG.md | 1 + CLAUDE.md | 4 +- .../blocks/paragraph/paragraph_editor.dart | 220 ++++++++++++- test/widget/paragraph_link_test.dart | 290 ++++++++++++++++++ 4 files changed, 511 insertions(+), 4 deletions(-) create mode 100644 test/widget/paragraph_link_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index d6a10e7..6768664 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ ### Editor improvements * **Image editor.** New `EditorConfig.imageUploader` stores a picked image and returns its public URL (and any extra file fields), like the uploader of the EditorJS image tool; without one the path of the file on the device is stored, as before. The editor gained fields for the image URL and the caption, toggles for border, stretch and background, an upload progress bar, and error messages for failed picks and uploads. Picking a new image no longer resets the caption and the display options. +* **Links in paragraphs.** The paragraph format bar has a "Link" button: it links the selected text (or inserts the address as a link when nothing is selected), and when the caret is in an existing link it edits or removes that link. A bare address such as `example.com` is completed to `https://example.com`. * **Heading level.** The header editor has an H1–H6 selector; the level used to be fixed when the block was created. * **Nested lists.** Every list item is editable, at any depth: items can be indented under the one above, outdented, and removed (children move up a level instead of being deleted). Enter adds an item below the current one. Nested items used to be invisible in the editor. * **Configurable toolbar.** `EditorConfig.toolbarItems` takes the `EditorToolbarItem` buttons to show, in order; the default is every button. diff --git a/CLAUDE.md b/CLAUDE.md index 36425fe..69feb5a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -110,7 +110,7 @@ final config = EditorConfig( | Block | Viewer | Editor | Notes | |---|---|---|---| | `header` | H1–H6, inline HTML | ✅ | | -| `paragraph` | HTML via flutter_html | ✅ | Inline format bar (B/I/U/S/code/mark) | +| `paragraph` | HTML via flutter_html | ✅ | Inline format bar (B/I/U/S/code/mark/link); the link button adds, edits and removes `
` | | `list` | Ordered (start, counter type) / unordered / checklist / nested | ✅ | `@editorjs/list` 2.x format; legacy list, nested-list and checklist data is read too. Nested items are edited as an outline (indent / outdent) | | `delimiter` | Divider | ✅ | | | `image` | Network URL, caption, border / stretch / background | ✅ | Editor picks from camera or gallery and uploads through `EditorConfig.imageUploader`; without an uploader the local file path is stored | @@ -241,7 +241,7 @@ When making changes, always update `CHANGELOG.md` with a new entry at the top fo - `ImageEditor` imports `dart:io` for the local-file preview; on the web it falls back to `Image.network`, but this path is untested - No `EditorController` content persistence to local storage (save/load) -- No inline link editor in paragraph (currently inserts a `` paragraph block via dialog) +- The paragraph editor shows the HTML source (tags are visible while editing); the format bar inserts tags rather than styling text in place - No drag-to-reorder for blocks (only up/down buttons) - Typing history not tracked by undo/redo (only structural operations are undoable) - pub.dev publication pending — description, topics, and example are ready but package has not been published yet diff --git a/lib/src/presentation/blocks/paragraph/paragraph_editor.dart b/lib/src/presentation/blocks/paragraph/paragraph_editor.dart index 57a958a..8bdf0b0 100644 --- a/lib/src/presentation/blocks/paragraph/paragraph_editor.dart +++ b/lib/src/presentation/blocks/paragraph/paragraph_editor.dart @@ -14,7 +14,54 @@ class ParagraphEditor extends BlockEditor { State createState() => _ParagraphEditorState(); } +/// An `` element found in the paragraph's HTML. +class _Anchor { + const _Anchor({ + required this.start, + required this.end, + required this.attributes, + required this.href, + required this.inner, + }); + + /// Range of the whole element, tags included. + final int start; + final int end; + + /// Everything inside the opening tag after ` { + static final _anchorPattern = RegExp( + r']*)>(.*?)', + caseSensitive: false, + dotAll: true, + ); + static final _hrefPattern = RegExp( + r'''href\s*=\s*(?:"([^"]*)"|'([^']*)')''', + caseSensitive: false, + ); + static final _explicitScheme = RegExp( + r'^(?:[a-z][a-z0-9+.-]*://|mailto:|tel:)', + caseSensitive: false, + ); + late final TextEditingController _textController; late final FocusNode _focusNode; bool _showFormatBar = false; @@ -76,6 +123,106 @@ class _ParagraphEditorState extends State { _onTextChanged(newText); } + // --------------------------------------------------------------------------- + // Links + // --------------------------------------------------------------------------- + + /// The link the caret at [offset] is in or next to, if any. + static _Anchor? _anchorAt(String html, int offset) { + for (final match in _anchorPattern.allMatches(html)) { + if (offset < match.start || offset > match.end) continue; + final href = _hrefPattern.firstMatch(match.group(1)!); + return _Anchor( + start: match.start, + end: match.end, + attributes: match.group(1)!, + href: _decodeAttribute(href?.group(1) ?? href?.group(2) ?? ''), + inner: match.group(2)!, + ); + } + return null; + } + + static String _encodeAttribute(String value) => value + .replaceAll('&', '&') + .replaceAll('"', '"') + .replaceAll('<', '<') + .replaceAll('>', '>'); + + static String _decodeAttribute(String value) => value + .replaceAll('"', '"') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('&', '&'); + + /// Returns the attributes of an opening ` _editLink() async { + // The dialog takes the focus, so remember where the caret was. + final selection = _textController.selection; + if (!selection.isValid) return; + final html = _textController.text; + final anchor = _anchorAt(html, selection.start); + + final choice = await showDialog<_LinkChoice>( + context: context, + builder: (_) => _LinkDialog(initialUrl: anchor?.href), + ); + if (!mounted || choice == null) return; + + final url = choice.url == null ? null : _normalizeUrl(choice.url!); + if (url != null && url.isEmpty) return; + + final int start; + final int end; + final String replacement; + if (anchor != null) { + start = anchor.start; + end = anchor.end; + replacement = url == null + ? anchor.inner + : '${anchor.inner}'; + } else { + if (url == null) return; + start = selection.start; + end = selection.end; + // With nothing selected the address itself becomes the link text. + final label = selection.isCollapsed ? url : html.substring(start, end); + replacement = '$label'; + } + + final updated = html.replaceRange(start, end, replacement); + _textController.value = TextEditingValue( + text: updated, + selection: TextSelection.collapsed(offset: start + replacement.length), + ); + _focusNode.requestFocus(); + _onTextChanged(updated); + } + @override Widget build(BuildContext context) { return Padding( @@ -84,7 +231,7 @@ class _ParagraphEditorState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (_showFormatBar) - _InlineFormatBar(onFormat: _applyFormat), + _InlineFormatBar(onFormat: _applyFormat, onLink: _editLink), TextField( controller: _textController, focusNode: _focusNode, @@ -104,8 +251,9 @@ class _ParagraphEditorState extends State { class _InlineFormatBar extends StatelessWidget { final void Function(String openTag, String closeTag) onFormat; + final VoidCallback onLink; - const _InlineFormatBar({required this.onFormat}); + const _InlineFormatBar({required this.onFormat, required this.onLink}); @override Widget build(BuildContext context) { @@ -149,12 +297,80 @@ class _InlineFormatBar extends StatelessWidget { tooltip: 'Highlight', onTap: () => onFormat('', ''), ), + _FormatButton( + label: 'link', + underline: true, + tooltip: 'Link', + onTap: onLink, + ), ], ), ); } } +/// Asks for the target of a link. Pops with a [_LinkChoice], or with nothing +/// when cancelled. +class _LinkDialog extends StatefulWidget { + /// The current target when an existing link is being edited. + final String? initialUrl; + + const _LinkDialog({this.initialUrl}); + + @override + State<_LinkDialog> createState() => _LinkDialogState(); +} + +class _LinkDialogState extends State<_LinkDialog> { + late final TextEditingController _controller = + TextEditingController(text: widget.initialUrl ?? ''); + + bool get _editing => widget.initialUrl != null; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _save() { + final url = _controller.text.trim(); + if (url.isEmpty) return; + Navigator.pop(context, _LinkChoice.save(url)); + } + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(_editing ? 'Edit link' : 'Add link'), + content: TextField( + controller: _controller, + autofocus: true, + keyboardType: TextInputType.url, + autocorrect: false, + onSubmitted: (_) => _save(), + decoration: const InputDecoration( + labelText: 'Link address', + hintText: 'https://...', + ), + ), + actions: [ + if (_editing) + TextButton( + onPressed: () => + Navigator.pop(context, const _LinkChoice.remove()), + child: const Text('Remove link'), + ), + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + TextButton(onPressed: _save, child: const Text('Save')), + ], + ); + } +} + class _FormatButton extends StatelessWidget { final String label; final String tooltip; diff --git a/test/widget/paragraph_link_test.dart b/test/widget/paragraph_link_test.dart new file mode 100644 index 0000000..f4b3e1f --- /dev/null +++ b/test/widget/paragraph_link_test.dart @@ -0,0 +1,290 @@ +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/paragraph/paragraph_editor.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _host(Widget child) => MaterialApp( + home: Scaffold(body: SizedBox(width: 400, child: child)), + ); + +void main() { + late List changes; + + /// Pumps the editor with [html], focuses it and puts the caret or selection + /// at [selection]. + Future pumpEditor( + WidgetTester tester, + String html, + TextSelection selection, + ) async { + changes = []; + await tester.pumpWidget(_host(ParagraphEditor( + // A fresh editor every time: a focused editor deliberately ignores a + // block replaced from outside, which would carry text over between the + // cases of one test. + key: UniqueKey(), + block: ParagraphBlock(html: html), + onChanged: (block) => changes.add(block.html), + ))); + await tester.tap(find.byType(TextField)); + await tester.pump(); + tester.widget(find.byType(TextField)).controller!.selection = + selection; + await tester.pump(); + } + + TextSelection select(String html, String part) { + final start = html.indexOf(part); + return TextSelection(baseOffset: start, extentOffset: start + part.length); + } + + TextSelection caretIn(String html, String part) => + TextSelection.collapsed(offset: html.indexOf(part) + 1); + + Finder addressField() => find.widgetWithText(TextField, 'Link address'); + + Future openDialog(WidgetTester tester) async { + await tester.tap(find.byTooltip('Link')); + await tester.pumpAndSettle(); + } + + Future saveLink(WidgetTester tester, String address) async { + await openDialog(tester); + await tester.enterText(addressField(), address); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + } + + testWidgets('the link button is part of the format bar', (tester) async { + await tester.pumpWidget(_host(ParagraphEditor( + block: const ParagraphBlock(html: 'Text'), + onChanged: (_) {}, + ))); + expect(find.byTooltip('Link'), findsNothing); + + await tester.tap(find.byType(TextField)); + await tester.pump(); + expect(find.byTooltip('Link'), findsOneWidget); + }); + + group('adding a link', () { + testWidgets('wraps the selected text', (tester) async { + const html = 'Visit our site today'; + await pumpEditor(tester, html, select(html, 'our site')); + await saveLink(tester, 'https://example.com'); + + expect( + changes.last, + 'Visit our site today', + ); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('keeps formatting inside the selection', (tester) async { + const html = 'See this page'; + await pumpEditor(tester, html, select(html, 'this page')); + await saveLink(tester, 'https://example.com'); + expect( + changes.last, + 'See this page', + ); + }); + + testWidgets('with nothing selected the address becomes the text', + (tester) async { + const html = 'Docs: '; + await pumpEditor( + tester, + html, + const TextSelection.collapsed(offset: html.length), + ); + await saveLink(tester, 'https://example.com/docs'); + expect( + changes.last, + 'Docs: https://example.com/docs', + ); + }); + + testWidgets('completes a bare address to a web link', (tester) async { + const html = 'site'; + await pumpEditor(tester, html, select(html, 'site')); + await saveLink(tester, ' example.com/page '); + expect(changes.last, 'site'); + }); + + testWidgets('leaves mail, phone and in-site targets as typed', + (tester) async { + for (final address in [ + 'mailto:hi@example.com', + 'tel:+123456', + '/docs/intro', + '#section', + 'http://plain.example', + ]) { + const html = 'x'; + await pumpEditor(tester, html, select(html, 'x')); + await saveLink(tester, address); + expect(changes.last, 'x', reason: address); + } + }); + + testWidgets('escapes characters that would break the attribute', + (tester) async { + const html = 'x'; + await pumpEditor(tester, html, select(html, 'x')); + await saveLink(tester, 'https://a.b/?q="1"&r=2'); + expect( + changes.last, + 'x', + ); + }); + + testWidgets('the keyboard action saves too', (tester) async { + const html = 'x'; + await pumpEditor(tester, html, select(html, 'x')); + await openDialog(tester); + await tester.enterText(addressField(), 'https://example.com'); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pumpAndSettle(); + expect(changes.last, 'x'); + }); + + testWidgets('typing continues after the new link', (tester) async { + const html = 'ab'; + await pumpEditor(tester, html, select(html, 'a')); + await saveLink(tester, 'https://e.io'); + + final controller = + tester.widget(find.byType(TextField)).controller!; + expect(controller.text, 'ab'); + expect(controller.selection.baseOffset, controller.text.length - 1); + }); + + testWidgets('cancelling or saving an empty address changes nothing', + (tester) async { + const html = 'x'; + await pumpEditor(tester, html, select(html, 'x')); + + await openDialog(tester); + expect(find.text('Add link'), findsOneWidget); + expect(find.text('Remove link'), findsNothing); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + // An empty address is not accepted: the dialog stays open. + expect(find.byType(AlertDialog), findsOneWidget); + + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changes, isEmpty); + }); + }); + + group('editing an existing link', () { + const html = 'Go to the old page now'; + + testWidgets('the dialog opens with the current address', (tester) async { + await pumpEditor(tester, html, caretIn(html, 'the old')); + await openDialog(tester); + + expect(find.text('Edit link'), findsOneWidget); + expect( + find.widgetWithText(TextField, 'https://old.example/?a=1&b=2'), + findsOneWidget, + ); + expect(find.text('Remove link'), findsOneWidget); + }); + + testWidgets('saving replaces the address and keeps text and attributes', + (tester) async { + await pumpEditor(tester, html, caretIn(html, 'the old')); + await saveLink(tester, 'https://new.example'); + expect( + changes.last, + 'Go to ' + 'the old page now', + ); + }); + + testWidgets('a caret anywhere in the element counts, tags included', + (tester) async { + for (final part in ['', ' now']) { + await pumpEditor(tester, html, caretIn(html, part)); + await openDialog(tester); + expect(find.text('Edit link'), findsOneWidget, reason: part); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + } + }); + + testWidgets('a caret outside the element adds a new link', (tester) async { + await pumpEditor(tester, html, caretIn(html, 'Go to')); + await openDialog(tester); + expect(find.text('Add link'), findsOneWidget); + }); + + testWidgets('removing the link keeps its text', (tester) async { + await pumpEditor(tester, html, caretIn(html, 'the old')); + await openDialog(tester); + await tester.tap(find.text('Remove link')); + await tester.pumpAndSettle(); + expect(changes.last, 'Go to the old page now'); + }); + + testWidgets('single-quoted and attribute-less anchors are handled', + (tester) async { + const single = "one"; + await pumpEditor(tester, single, caretIn(single, 'one<')); + await saveLink(tester, 'https://two.example'); + expect(changes.last, 'one'); + + const bare = 'anchor'; + await pumpEditor(tester, bare, caretIn(bare, 'anchor')); + await openDialog(tester); + // No address yet, but it is still an existing link being edited. + expect(find.text('Edit link'), findsOneWidget); + await tester.enterText(addressField(), 'https://x.example'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + expect(changes.last, 'anchor'); + }); + + testWidgets('only the link under the caret changes', (tester) async { + const two = 'A and ' + 'B'; + await pumpEditor(tester, two, caretIn(two, 'B')); + await saveLink(tester, 'https://c.example'); + expect( + changes.last, + 'A and B', + ); + }); + }); + + testWidgets('a link added in the full editor is saved and rendered', + (tester) async { + final controller = EditorController( + initialBlocks: const [ParagraphBlock(html: 'Read the docs')], + ); + await tester.pumpWidget(MaterialApp( + home: Scaffold(body: EditorJSEditor(controller: controller)), + )); + await tester.pumpAndSettle(); + + await tester.tap(find.widgetWithText(TextField, 'Read the docs')); + await tester.pump(); + tester + .widget(find.widgetWithText(TextField, 'Read the docs')) + .controller! + .selection = const TextSelection(baseOffset: 9, extentOffset: 13); + await tester.pump(); + + await saveLink(tester, 'example.com/docs'); + + expect( + (controller.blocks.single as ParagraphBlock).html, + 'Read the docs', + ); + }); +} From 1e7ac3cfb194db575c88746e3d98b612582ad4c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 10:02:44 -0600 Subject: [PATCH 14/16] Make all editor and viewer text translatable Every label, tooltip, hint and message was hard-coded in English across the toolbar, the block controls, the block editors and three viewer cards. EditorStrings now holds all 104 of those texts with English defaults; the ones that include a value are functions. EditorConfig.strings takes an instance, so an app overrides only what it wants. Widgets read the texts through EditorConfigScope.stringsOf, which EditorJSView now provides as well and which falls back to the defaults for a widget used on its own. The two dialogs are handed the texts because they are built outside the editor's subtree. localization_test renders every block editor and the toolbar with all texts marked and fails if anything on screen was not looked up. Co-Authored-By: Claude --- CHANGELOG.md | 5 +- CLAUDE.md | 3 +- README.md | 18 + lib/editorjs_flutter.dart | 1 + .../blocks/attaches/attaches_editor.dart | 14 +- .../blocks/attaches/attaches_renderer.dart | 4 +- .../blocks/checklist/checklist_editor.dart | 8 +- .../presentation/blocks/code/code_editor.dart | 8 +- .../blocks/code/code_renderer.dart | 4 +- .../blocks/embed/embed_editor.dart | 14 +- .../blocks/embed/embed_renderer.dart | 4 +- .../blocks/header/header_editor.dart | 8 +- .../blocks/image/image_editor.dart | 24 +- .../blocks/link_tool/link_tool_editor.dart | 22 +- .../presentation/blocks/list/list_editor.dart | 51 +-- .../blocks/paragraph/paragraph_editor.dart | 69 ++-- .../blocks/quote/quote_editor.dart | 21 +- .../presentation/blocks/raw/raw_editor.dart | 8 +- .../blocks/table/table_editor.dart | 12 +- .../blocks/warning/warning_editor.dart | 10 +- .../presentation/config/editor_config.dart | 7 + .../presentation/config/editor_strings.dart | 335 +++++++++++++++ .../widgets/editor_config_scope.dart | 16 +- .../presentation/widgets/editorjs_editor.dart | 9 +- .../widgets/editorjs_toolbar.dart | 84 ++-- .../presentation/widgets/editorjs_view.dart | 24 +- test/widget/localization_test.dart | 384 ++++++++++++++++++ 27 files changed, 997 insertions(+), 170 deletions(-) create mode 100644 lib/src/presentation/config/editor_strings.dart create mode 100644 test/widget/localization_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index edeef10..ec4c140 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,9 @@ * *Attachment:* file URL and title; the new `EditorConfig.attachmentPicker` adds a "Choose file" button for apps that bring their own file picker and upload. * *Raw:* the HTML source. +### Translatable text +* **Every label, tooltip, hint and message can be translated or reworded.** New `EditorConfig.strings` takes an `EditorStrings`, which holds all 104 texts the editor and the viewer show on their own, with English defaults; override only the ones you need. Texts that include a value (a heading level, a file size) are functions. Until now all text was hard-coded in English. + ### Parser hardening * A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. * `time` accepts integers, doubles and numeric strings; header `level` accepts doubles. @@ -49,7 +52,7 @@ * Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `test/unit/editor_controller_metadata_test.dart`, `test/unit/json_reader_test.dart`, `test/unit/list_v2_test.dart`, `test/widget/unknown_block_test.dart`, `test/widget/list_v2_test.dart`, `test/widget/viewer_fidelity_test.dart`, `test/widget/header_level_test.dart`, `test/widget/toolbar_items_test.dart`, `test/widget/image_editor_test.dart` and `test/widget/nested_list_editor_test.dart` (390 tests in total, 94 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `editor_controller_metadata_test.dart`, `json_reader_test.dart`, `list_v2_test.dart` and `embed_services_test.dart`; and `test/widget/unknown_block_test.dart`, `list_v2_test.dart`, `viewer_fidelity_test.dart`, `header_level_test.dart`, `toolbar_items_test.dart`, `image_editor_test.dart`, `nested_list_editor_test.dart`, `media_block_editors_test.dart`, `paragraph_link_test.dart` and `localization_test.dart` (458 tests in total, 95 % line coverage). --- diff --git a/CLAUDE.md b/CLAUDE.md index 0a0fe27..c717787 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -132,7 +132,7 @@ final config = EditorConfig( - **Widgets**: `EditorJSView`, `EditorJSEditor`, `EditorLinkScope` (lets custom renderers open links through `EditorConfig.onLinkTap`) - **Controller**: `EditorController` -- **Config**: `EditorConfig`, `EditorToolbarItem`, `ImageUploader` / `PickedImage` / `UploadedImage`, `LinkPreviewFetcher`, `AttachmentPicker` +- **Config**: `EditorConfig`, `EditorToolbarItem`, `ImageUploader` / `PickedImage` / `UploadedImage`, `LinkPreviewFetcher`, `AttachmentPicker`, `EditorStrings` - **Registries**: `BlockTypeRegistry`, `BlockRendererRegistry` - **Contracts** (for custom block authors): `BlockMapper`, `BlockRenderer`, `BlockEditor`, `BlockEntity`, `BlockDocument`, `BlockMetadata`, `StyleConfig` - **Built-in entities**: `HeaderBlock`, `ParagraphBlock`, `ListBlock`, `DelimiterBlock`, `ImageBlock`, and the other block entities; `UnknownBlock` holds any block the package cannot interpret so it round-trips untouched @@ -172,6 +172,7 @@ When building new features, always work bottom-up: 4. Run `fvm flutter test --coverage` locally and verify the coverage threshold. 5. Follow the Clean Architecture layer rules: no Flutter imports in `domain/`, no direct widget dependencies in `data/`. 6. New block types must be added bottom-up: entity → mapper → renderer → (editor) → register in both registries → export from barrel. +7. No hard-coded user-visible text in widgets. Add a field to `EditorStrings` and read it with `EditorConfigScope.stringsOf(context)`; `test/widget/localization_test.dart` fails when a widget shows text that did not come from there. ## Git Workflow diff --git a/README.md b/README.md index e898c73..8833ae9 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,24 @@ EditorConfig( Embed blocks need no setup: paste a link from YouTube, Vimeo, X, Instagram, CodePen, Figma or another service the EditorJS embed tool supports, and the embed URL is worked out from it. +### Translating the editor + +All the text the editor and the viewer show on their own (button labels, tooltips, field labels, hints, messages) comes from `EditorStrings`, in English by default. Pass your own to translate or reword it; anything you leave out keeps its default: + +```dart +EditorConfig( + strings: EditorStrings( + paragraph: 'Párrafo', + addItem: 'Agregar elemento', + cancel: 'Cancelar', + save: 'Guardar', + heading: (level) => 'Encabezado $level', + ), +) +``` + +Texts that include a value, such as a heading level or a file size, are functions. The same `EditorConfig` works for `EditorJSView`, which uses a few of these texts too. + ### Pre-loading existing content into the editor Load a previously saved JSON string directly: diff --git a/lib/editorjs_flutter.dart b/lib/editorjs_flutter.dart index 9d34e76..74af085 100644 --- a/lib/editorjs_flutter.dart +++ b/lib/editorjs_flutter.dart @@ -9,6 +9,7 @@ export 'src/presentation/controller/editor_controller.dart'; // Configuration export 'src/presentation/config/block_editor_hooks.dart'; export 'src/presentation/config/editor_config.dart'; +export 'src/presentation/config/editor_strings.dart'; export 'src/presentation/config/editor_toolbar_item.dart'; export 'src/presentation/config/image_uploader.dart'; diff --git a/lib/src/presentation/blocks/attaches/attaches_editor.dart b/lib/src/presentation/blocks/attaches/attaches_editor.dart index 591a0ff..b0a4d32 100644 --- a/lib/src/presentation/blocks/attaches/attaches_editor.dart +++ b/lib/src/presentation/blocks/attaches/attaches_editor.dart @@ -99,6 +99,7 @@ class _AttachesEditorState extends State { } Future _pick(AttachmentPicker pick) async { + final strings = EditorConfigScope.stringsOf(context); setState(() { _picking = true; _error = null; @@ -123,7 +124,7 @@ class _AttachesEditorState extends State { } catch (_) { // The picker is app code and may throw anything. The block keeps the // file it had. - if (mounted) setState(() => _error = 'Could not attach the file.'); + if (mounted) setState(() => _error = strings.attachFailed); } finally { if (mounted) setState(() => _picking = false); } @@ -131,10 +132,11 @@ class _AttachesEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); final picker = EditorConfigScope.maybeOf(context)?.attachmentPicker; final details = [ if (_block.name != null) _block.name!, - if (_block.size != null) '${_block.size} bytes', + if (_block.size != null) strings.fileSize(_block.size!), ].join(' · '); return Column( @@ -144,7 +146,7 @@ class _AttachesEditorState extends State { TextButton.icon( onPressed: _picking ? null : () => _pick(picker), icon: const Icon(Icons.attach_file, size: 18), - label: const Text('Choose file'), + label: Text(strings.chooseFile), ), if (_picking) const LinearProgressIndicator(), if (_error != null) @@ -163,8 +165,8 @@ class _AttachesEditorState extends State { onChanged: _setUrl, keyboardType: TextInputType.url, autocorrect: false, - decoration: const InputDecoration( - labelText: 'File URL', + decoration: InputDecoration( + labelText: strings.fileUrl, hintText: 'https://...', isDense: true, ), @@ -180,7 +182,7 @@ class _AttachesEditorState extends State { TextField( controller: _titleController, onChanged: _setTitle, - decoration: const InputDecoration(labelText: 'Title', isDense: true), + decoration: InputDecoration(labelText: strings.title, isDense: true), ), ], ); diff --git a/lib/src/presentation/blocks/attaches/attaches_renderer.dart b/lib/src/presentation/blocks/attaches/attaches_renderer.dart index 441f541..8d32982 100644 --- a/lib/src/presentation/blocks/attaches/attaches_renderer.dart +++ b/lib/src/presentation/blocks/attaches/attaches_renderer.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/attaches_block.dart'; import '../../widgets/editor_link_scope.dart'; import '../base_block_renderer.dart'; +import '../../widgets/editor_config_scope.dart'; class AttachesRenderer extends BlockRenderer { const AttachesRenderer( @@ -10,8 +11,9 @@ class AttachesRenderer extends BlockRenderer { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); final displayName = - block.title ?? block.name ?? 'Download file'; + block.title ?? block.name ?? strings.downloadFile; final ext = block.extension?.toUpperCase(); return InkWell( diff --git a/lib/src/presentation/blocks/checklist/checklist_editor.dart b/lib/src/presentation/blocks/checklist/checklist_editor.dart index 65ed6fc..513ed3c 100644 --- a/lib/src/presentation/blocks/checklist/checklist_editor.dart +++ b/lib/src/presentation/blocks/checklist/checklist_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/checklist_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; class ChecklistEditor extends BlockEditor { const ChecklistEditor({super.key, required super.block, required super.onChanged}); @@ -59,6 +60,7 @@ class _ChecklistEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -76,8 +78,8 @@ class _ChecklistEditorState extends State { _items[i] = _items[i].copyWith(text: v); _notify(); }, - decoration: const InputDecoration( - hintText: 'List item...', + decoration: InputDecoration( + hintText: strings.checklistItemHint, border: InputBorder.none, ), ), @@ -91,7 +93,7 @@ class _ChecklistEditorState extends State { TextButton.icon( onPressed: _addItem, icon: const Icon(Icons.add, size: 16), - label: const Text('Add item'), + label: Text(strings.addItem), ), ], ); diff --git a/lib/src/presentation/blocks/code/code_editor.dart b/lib/src/presentation/blocks/code/code_editor.dart index c0ffc48..a9cb560 100644 --- a/lib/src/presentation/blocks/code/code_editor.dart +++ b/lib/src/presentation/blocks/code/code_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/code_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; class CodeEditor extends BlockEditor { const CodeEditor({super.key, required super.block, required super.onChanged}); @@ -27,6 +28,7 @@ class _CodeEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Container( width: double.infinity, decoration: BoxDecoration( @@ -44,9 +46,9 @@ class _CodeEditorState extends State { color: Color(0xFFD4D4D4), height: 1.5, ), - decoration: const InputDecoration( - hintText: 'Enter code...', - hintStyle: TextStyle(color: Colors.white30), + decoration: InputDecoration( + hintText: strings.codeHint, + hintStyle: const TextStyle(color: Colors.white30), border: InputBorder.none, ), ), diff --git a/lib/src/presentation/blocks/code/code_renderer.dart b/lib/src/presentation/blocks/code/code_renderer.dart index 3c6e8c8..7ee5e39 100644 --- a/lib/src/presentation/blocks/code/code_renderer.dart +++ b/lib/src/presentation/blocks/code/code_renderer.dart @@ -3,12 +3,14 @@ import 'package:flutter/services.dart'; import '../../../domain/entities/blocks/code_block.dart'; import '../base_block_renderer.dart'; +import '../../widgets/editor_config_scope.dart'; class CodeRenderer extends BlockRenderer { const CodeRenderer({super.key, required super.block, super.styleConfig}); @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Container( width: double.infinity, decoration: BoxDecoration( @@ -35,7 +37,7 @@ class CodeRenderer extends BlockRenderer { right: 6, child: IconButton( icon: const Icon(Icons.copy, size: 16, color: Colors.white54), - tooltip: 'Copy', + tooltip: strings.copy, onPressed: () => Clipboard.setData(ClipboardData(text: block.code)), padding: EdgeInsets.zero, constraints: const BoxConstraints(), diff --git a/lib/src/presentation/blocks/embed/embed_editor.dart b/lib/src/presentation/blocks/embed/embed_editor.dart index 90db7b6..ed1d629 100644 --- a/lib/src/presentation/blocks/embed/embed_editor.dart +++ b/lib/src/presentation/blocks/embed/embed_editor.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../../data/utils/embed_services.dart'; import '../../../domain/entities/blocks/embed_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; /// Edits an embed block: the link to the content and its caption. /// @@ -86,6 +87,7 @@ class _EmbedEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); final recognized = _block.service.isNotEmpty; return Column( @@ -96,8 +98,8 @@ class _EmbedEditorState extends State { onChanged: _setSource, keyboardType: TextInputType.url, autocorrect: false, - decoration: const InputDecoration( - labelText: 'Embed link', + decoration: InputDecoration( + labelText: strings.embedLink, hintText: 'https://www.youtube.com/watch?v=...', isDense: true, ), @@ -107,8 +109,8 @@ class _EmbedEditorState extends State { padding: const EdgeInsets.only(top: 4), child: Text( recognized - ? 'Service: ${_block.service}' - : 'This link is not from a supported service.', + ? strings.embedService(_block.service) + : strings.embedUnsupported, style: TextStyle( fontSize: 12, color: recognized @@ -120,8 +122,8 @@ class _EmbedEditorState extends State { TextField( controller: _captionController, onChanged: _setCaption, - decoration: const InputDecoration( - labelText: 'Caption', + decoration: InputDecoration( + labelText: strings.caption, isDense: true, ), ), diff --git a/lib/src/presentation/blocks/embed/embed_renderer.dart b/lib/src/presentation/blocks/embed/embed_renderer.dart index c49b503..b0d2523 100644 --- a/lib/src/presentation/blocks/embed/embed_renderer.dart +++ b/lib/src/presentation/blocks/embed/embed_renderer.dart @@ -5,12 +5,14 @@ import '../../../domain/entities/blocks/embed_block.dart'; import '../../widgets/editor_link_scope.dart'; import '../../widgets/inline_html.dart'; import '../base_block_renderer.dart'; +import '../../widgets/editor_config_scope.dart'; class EmbedRenderer extends BlockRenderer { const EmbedRenderer({super.key, required super.block, super.styleConfig}); @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return InkWell( onTap: block.source.isNotEmpty ? () => EditorLinkScope.open(context, block.source) @@ -44,7 +46,7 @@ class EmbedRenderer extends BlockRenderer { Text( block.service.isNotEmpty ? _capitalise(block.service) - : 'Embedded content', + : strings.embeddedContent, style: TextStyle( fontWeight: FontWeight.w600, fontSize: 13, diff --git a/lib/src/presentation/blocks/header/header_editor.dart b/lib/src/presentation/blocks/header/header_editor.dart index 1067a0b..e15c3d5 100644 --- a/lib/src/presentation/blocks/header/header_editor.dart +++ b/lib/src/presentation/blocks/header/header_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/header_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; class HeaderEditor extends BlockEditor { const HeaderEditor({ @@ -54,6 +55,7 @@ class _HeaderEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); final fontSize = switch (_level) { 1 => 32.0, 2 => 24.0, @@ -71,7 +73,7 @@ class _HeaderEditorState extends State { Padding( padding: const EdgeInsets.only(top: 12, right: 8), child: Tooltip( - message: 'Heading level', + message: strings.headingLevel, child: DropdownButton( // A document can carry a level outside H1–H6; show the // nearest one rather than failing to build. @@ -81,7 +83,7 @@ class _HeaderEditorState extends State { underline: const SizedBox.shrink(), items: [ for (var level = _minLevel; level <= _maxLevel; level++) - DropdownMenuItem(value: level, child: Text('H$level')), + DropdownMenuItem(value: level, child: Text(strings.headingLabel(level))), ], ), ), @@ -95,7 +97,7 @@ class _HeaderEditorState extends State { fontWeight: _level <= 3 ? FontWeight.bold : FontWeight.w500, ), decoration: InputDecoration( - hintText: 'Heading $_level', + hintText: strings.heading(_level), border: InputBorder.none, ), maxLines: null, diff --git a/lib/src/presentation/blocks/image/image_editor.dart b/lib/src/presentation/blocks/image/image_editor.dart index 5979201..9c2ba62 100644 --- a/lib/src/presentation/blocks/image/image_editor.dart +++ b/lib/src/presentation/blocks/image/image_editor.dart @@ -76,13 +76,14 @@ class _ImageEditorState extends State { Future _pickImage(ImageSource source) async { final uploader = EditorConfigScope.maybeOf(context)?.imageUploader; + final strings = EditorConfigScope.stringsOf(context); setState(() => _error = null); final XFile? file; try { file = await _picker.pickImage(source: source); } on PlatformException { - if (mounted) setState(() => _error = 'Could not open the image.'); + if (mounted) setState(() => _error = strings.imagePickFailed); return; } if (file == null || !mounted) return; @@ -108,7 +109,7 @@ class _ImageEditorState extends State { } catch (_) { // The uploader is app code and may throw anything. The block keeps the // image it had. - if (mounted) setState(() => _error = 'Upload failed. Try again.'); + if (mounted) setState(() => _error = strings.imageUploadFailed); } finally { if (mounted) setState(() => _uploading = false); } @@ -121,6 +122,7 @@ class _ImageEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -132,13 +134,13 @@ class _ImageEditorState extends State { onPressed: _uploading ? null : () => _pickImage(ImageSource.camera), icon: const Icon(Icons.camera_alt_outlined), - label: const Text('Camera'), + label: Text(strings.camera), ), TextButton.icon( onPressed: _uploading ? null : () => _pickImage(ImageSource.gallery), icon: const Icon(Icons.photo_library_outlined), - label: const Text('Gallery'), + label: Text(strings.gallery), ), ], ), @@ -158,8 +160,8 @@ class _ImageEditorState extends State { onChanged: (value) => _setImage(value.trim()), keyboardType: TextInputType.url, autocorrect: false, - decoration: const InputDecoration( - labelText: 'Image URL', + decoration: InputDecoration( + labelText: strings.imageUrl, hintText: 'https://...', isDense: true, ), @@ -167,8 +169,8 @@ class _ImageEditorState extends State { TextField( controller: _captionController, onChanged: (value) => _update(_block.copyWith(caption: value)), - decoration: const InputDecoration( - labelText: 'Caption', + decoration: InputDecoration( + labelText: strings.caption, isDense: true, ), ), @@ -177,18 +179,18 @@ class _ImageEditorState extends State { spacing: 8, children: [ FilterChip( - label: const Text('Border'), + label: Text(strings.imageBorder), selected: _block.withBorder, onSelected: (value) => _update(_block.copyWith(withBorder: value)), ), FilterChip( - label: const Text('Stretch'), + label: Text(strings.imageStretch), selected: _block.stretched, onSelected: (value) => _update(_block.copyWith(stretched: value)), ), FilterChip( - label: const Text('Background'), + label: Text(strings.imageBackground), selected: _block.withBackground, onSelected: (value) => _update(_block.copyWith(withBackground: value)), diff --git a/lib/src/presentation/blocks/link_tool/link_tool_editor.dart b/lib/src/presentation/blocks/link_tool/link_tool_editor.dart index f73ea4e..8b65021 100644 --- a/lib/src/presentation/blocks/link_tool/link_tool_editor.dart +++ b/lib/src/presentation/blocks/link_tool/link_tool_editor.dart @@ -103,6 +103,7 @@ class _LinkToolEditorState extends State { Future _fetchPreview(LinkPreviewFetcher fetch) async { final link = _linkController.text.trim(); if (link.isEmpty) return; + final strings = EditorConfigScope.stringsOf(context); setState(() { _fetching = true; @@ -112,7 +113,7 @@ class _LinkToolEditorState extends State { final meta = await fetch(link); if (!mounted) return; if (meta == null) { - setState(() => _error = 'No preview available for this link.'); + setState(() => _error = strings.noPreview); return; } _titleController.text = meta.title ?? ''; @@ -123,7 +124,7 @@ class _LinkToolEditorState extends State { } catch (_) { // The fetcher is app code and may throw anything. The fields keep what // they had. - if (mounted) setState(() => _error = 'Could not fetch the preview.'); + if (mounted) setState(() => _error = strings.previewFailed); } finally { if (mounted) setState(() => _fetching = false); } @@ -131,6 +132,7 @@ class _LinkToolEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); final fetcher = EditorConfigScope.maybeOf(context)?.linkPreviewFetcher; return Column( @@ -141,8 +143,8 @@ class _LinkToolEditorState extends State { onChanged: (_) => _notify(), keyboardType: TextInputType.url, autocorrect: false, - decoration: const InputDecoration( - labelText: 'Link', + decoration: InputDecoration( + labelText: strings.linkUrl, hintText: 'https://...', isDense: true, ), @@ -151,7 +153,7 @@ class _LinkToolEditorState extends State { TextButton.icon( onPressed: _fetching ? null : () => _fetchPreview(fetcher), icon: const Icon(Icons.travel_explore, size: 18), - label: const Text('Fetch preview'), + label: Text(strings.fetchPreview), ), if (_fetching) const LinearProgressIndicator(), if (_error != null) @@ -168,14 +170,14 @@ class _LinkToolEditorState extends State { TextField( controller: _titleController, onChanged: (_) => _notify(), - decoration: const InputDecoration(labelText: 'Title', isDense: true), + decoration: InputDecoration(labelText: strings.title, isDense: true), ), TextField( controller: _descriptionController, onChanged: (_) => _notify(), maxLines: null, - decoration: const InputDecoration( - labelText: 'Description', + decoration: InputDecoration( + labelText: strings.description, isDense: true, ), ), @@ -184,8 +186,8 @@ class _LinkToolEditorState extends State { onChanged: (_) => _notify(), keyboardType: TextInputType.url, autocorrect: false, - decoration: const InputDecoration( - labelText: 'Preview image URL', + decoration: InputDecoration( + labelText: strings.previewImageUrl, isDense: true, ), ), diff --git a/lib/src/presentation/blocks/list/list_editor.dart b/lib/src/presentation/blocks/list/list_editor.dart index dcd104a..25948ae 100644 --- a/lib/src/presentation/blocks/list/list_editor.dart +++ b/lib/src/presentation/blocks/list/list_editor.dart @@ -2,8 +2,10 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../domain/entities/blocks/list_block.dart'; +import '../../config/editor_strings.dart'; import '../../utils/list_counter_formatter.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; class ListEditor extends BlockEditor { const ListEditor({super.key, required super.block, required super.onChanged}); @@ -41,14 +43,6 @@ class _ListEditorState extends State { ListStyle.checklist, ]; - static const _counterTypeLabels = { - ListCounterType.numeric: 'Numeric', - ListCounterType.lowerRoman: 'Lower Roman', - ListCounterType.upperRoman: 'Upper Roman', - ListCounterType.lowerAlpha: 'Lower Alpha', - ListCounterType.upperAlpha: 'Upper Alpha', - }; - static const double _indentPerLevel = 16; late List<_Row> _rows; @@ -267,12 +261,13 @@ class _ListEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); final markers = _style == ListStyle.ordered ? _orderedMarkers() : null; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - _buildSettings(), + _buildSettings(strings), for (var i = 0; i < _rows.length; i++) Padding( padding: EdgeInsets.only(left: _rows[i].depth * _indentPerLevel), @@ -292,17 +287,17 @@ class _ListEditorState extends State { ), _RowButton( icon: Icons.format_indent_decrease, - tooltip: 'Outdent', + tooltip: strings.outdent, onPressed: _canOutdent(i) ? () => _shift(i, -1) : null, ), _RowButton( icon: Icons.format_indent_increase, - tooltip: 'Indent', + tooltip: strings.indent, onPressed: _canIndent(i) ? () => _shift(i, 1) : null, ), _RowButton( icon: Icons.remove_circle_outline, - tooltip: 'Remove item', + tooltip: strings.removeItem, onPressed: _canRemove(i) ? () => _removeItem(i) : null, ), ], @@ -311,14 +306,22 @@ class _ListEditorState extends State { TextButton.icon( onPressed: _addItem, icon: const Icon(Icons.add, size: 16), - label: const Text('Add item'), + label: Text(strings.addItem), ), ], ); } /// Style selector, plus the numbering options when the list is ordered. - Widget _buildSettings() { + Widget _buildSettings(EditorStrings strings) { + final counterTypeLabels = { + ListCounterType.numeric: strings.counterNumeric, + ListCounterType.lowerRoman: strings.counterLowerRoman, + ListCounterType.upperRoman: strings.counterUpperRoman, + ListCounterType.lowerAlpha: strings.counterLowerAlpha, + ListCounterType.upperAlpha: strings.counterUpperAlpha, + }; + return SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( @@ -328,18 +331,18 @@ class _ListEditorState extends State { onPressed: (index) => _setStyle(_styles[index]), constraints: const BoxConstraints(minHeight: 36, minWidth: 44), borderRadius: BorderRadius.circular(4), - children: const [ + children: [ Tooltip( - message: 'Unordered', - child: Icon(Icons.format_list_bulleted, size: 18), + message: strings.listUnordered, + child: const Icon(Icons.format_list_bulleted, size: 18), ), Tooltip( - message: 'Ordered', - child: Icon(Icons.format_list_numbered, size: 18), + message: strings.listOrdered, + child: const Icon(Icons.format_list_numbered, size: 18), ), Tooltip( - message: 'Checklist', - child: Icon(Icons.checklist, size: 18), + message: strings.listChecklist, + child: const Icon(Icons.checklist, size: 18), ), ], ), @@ -352,8 +355,8 @@ class _ListEditorState extends State { onChanged: _setStart, keyboardType: TextInputType.number, inputFormatters: [FilteringTextInputFormatter.digitsOnly], - decoration: const InputDecoration( - labelText: 'Start with', + decoration: InputDecoration( + labelText: strings.startWith, hintText: '1', isDense: true, ), @@ -366,7 +369,7 @@ class _ListEditorState extends State { isDense: true, underline: const SizedBox.shrink(), items: [ - for (final entry in _counterTypeLabels.entries) + for (final entry in counterTypeLabels.entries) DropdownMenuItem(value: entry.key, child: Text(entry.value)), ], ), diff --git a/lib/src/presentation/blocks/paragraph/paragraph_editor.dart b/lib/src/presentation/blocks/paragraph/paragraph_editor.dart index 8bdf0b0..b4f854b 100644 --- a/lib/src/presentation/blocks/paragraph/paragraph_editor.dart +++ b/lib/src/presentation/blocks/paragraph/paragraph_editor.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/paragraph_block.dart'; +import '../../config/editor_strings.dart'; +import '../../widgets/editor_config_scope.dart'; import '../base_block_editor.dart'; class ParagraphEditor extends BlockEditor { @@ -186,10 +188,13 @@ class _ParagraphEditorState extends State { if (!selection.isValid) return; final html = _textController.text; final anchor = _anchorAt(html, selection.start); + // The dialog is built outside this editor's subtree, so it is handed the + // texts rather than looking them up itself. + final strings = EditorConfigScope.stringsOf(context); final choice = await showDialog<_LinkChoice>( context: context, - builder: (_) => _LinkDialog(initialUrl: anchor?.href), + builder: (_) => _LinkDialog(initialUrl: anchor?.href, strings: strings), ); if (!mounted || choice == null) return; @@ -225,19 +230,25 @@ class _ParagraphEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); + return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ if (_showFormatBar) - _InlineFormatBar(onFormat: _applyFormat, onLink: _editLink), + _InlineFormatBar( + strings: strings, + onFormat: _applyFormat, + onLink: _editLink, + ), TextField( controller: _textController, focusNode: _focusNode, onChanged: _onTextChanged, - decoration: const InputDecoration( - hintText: 'Write something...', + decoration: InputDecoration( + hintText: strings.paragraphHint, border: InputBorder.none, ), maxLines: null, @@ -250,10 +261,15 @@ class _ParagraphEditorState extends State { } class _InlineFormatBar extends StatelessWidget { + final EditorStrings strings; final void Function(String openTag, String closeTag) onFormat; final VoidCallback onLink; - const _InlineFormatBar({required this.onFormat, required this.onLink}); + const _InlineFormatBar({ + required this.strings, + required this.onFormat, + required this.onLink, + }); @override Widget build(BuildContext context) { @@ -262,45 +278,45 @@ class _InlineFormatBar extends StatelessWidget { child: Row( children: [ _FormatButton( - label: 'B', + label: strings.boldLabel, bold: true, - tooltip: 'Bold', + tooltip: strings.bold, onTap: () => onFormat('', ''), ), _FormatButton( - label: 'I', + label: strings.italicLabel, italic: true, - tooltip: 'Italic', + tooltip: strings.italic, onTap: () => onFormat('', ''), ), _FormatButton( - label: 'U', + label: strings.underlineLabel, underline: true, - tooltip: 'Underline', + tooltip: strings.underline, onTap: () => onFormat('', ''), ), _FormatButton( - label: 'S', + label: strings.strikethroughLabel, strikethrough: true, - tooltip: 'Strikethrough', + tooltip: strings.strikethrough, onTap: () => onFormat('', ''), ), _FormatButton( label: '', monospace: true, - tooltip: 'Inline code', + tooltip: strings.inlineCode, onTap: () => onFormat('', ''), ), _FormatButton( - label: 'mark', + label: strings.highlightLabel, highlight: true, - tooltip: 'Highlight', + tooltip: strings.highlight, onTap: () => onFormat('', ''), ), _FormatButton( - label: 'link', + label: strings.linkLabel, underline: true, - tooltip: 'Link', + tooltip: strings.link, onTap: onLink, ), ], @@ -314,8 +330,9 @@ class _InlineFormatBar extends StatelessWidget { class _LinkDialog extends StatefulWidget { /// The current target when an existing link is being edited. final String? initialUrl; + final EditorStrings strings; - const _LinkDialog({this.initialUrl}); + const _LinkDialog({this.initialUrl, required this.strings}); @override State<_LinkDialog> createState() => _LinkDialogState(); @@ -341,16 +358,18 @@ class _LinkDialogState extends State<_LinkDialog> { @override Widget build(BuildContext context) { + final strings = widget.strings; + return AlertDialog( - title: Text(_editing ? 'Edit link' : 'Add link'), + title: Text(_editing ? strings.editLinkTitle : strings.addLinkTitle), content: TextField( controller: _controller, autofocus: true, keyboardType: TextInputType.url, autocorrect: false, onSubmitted: (_) => _save(), - decoration: const InputDecoration( - labelText: 'Link address', + decoration: InputDecoration( + labelText: strings.linkAddress, hintText: 'https://...', ), ), @@ -359,13 +378,13 @@ class _LinkDialogState extends State<_LinkDialog> { TextButton( onPressed: () => Navigator.pop(context, const _LinkChoice.remove()), - child: const Text('Remove link'), + child: Text(strings.removeLink), ), TextButton( onPressed: () => Navigator.pop(context), - child: const Text('Cancel'), + child: Text(strings.cancel), ), - TextButton(onPressed: _save, child: const Text('Save')), + TextButton(onPressed: _save, child: Text(strings.save)), ], ); } diff --git a/lib/src/presentation/blocks/quote/quote_editor.dart b/lib/src/presentation/blocks/quote/quote_editor.dart index b396803..49a6808 100644 --- a/lib/src/presentation/blocks/quote/quote_editor.dart +++ b/lib/src/presentation/blocks/quote/quote_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/quote_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; class QuoteEditor extends BlockEditor { const QuoteEditor({super.key, required super.block, required super.onChanged}); @@ -38,6 +39,7 @@ class _QuoteEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), decoration: BoxDecoration( @@ -56,16 +58,16 @@ class _QuoteEditorState extends State { onChanged: (_) => _notify(), maxLines: null, style: const TextStyle(fontStyle: FontStyle.italic), - decoration: const InputDecoration( - hintText: 'Quote text...', + decoration: InputDecoration( + hintText: strings.quoteHint, border: InputBorder.none, ), ), TextField( controller: _captionController, onChanged: (_) => _notify(), - decoration: const InputDecoration( - hintText: 'Caption (optional)', + decoration: InputDecoration( + hintText: strings.quoteCaptionHint, border: InputBorder.none, isDense: true, ), @@ -73,13 +75,20 @@ class _QuoteEditorState extends State { ), Row( children: [ - const Text('Align:', style: TextStyle(fontSize: 12)), + Text(strings.align, style: const TextStyle(fontSize: 12)), const SizedBox(width: 8), for (final a in QuoteAlignment.values) Padding( padding: const EdgeInsets.only(right: 4), child: ChoiceChip( - label: Text(a.name, style: const TextStyle(fontSize: 11)), + label: Text( + switch (a) { + QuoteAlignment.left => strings.alignLeft, + QuoteAlignment.center => strings.alignCenter, + QuoteAlignment.right => strings.alignRight, + }, + style: const TextStyle(fontSize: 11), + ), selected: _alignment == a, onSelected: (_) => setState(() { _alignment = a; diff --git a/lib/src/presentation/blocks/raw/raw_editor.dart b/lib/src/presentation/blocks/raw/raw_editor.dart index 71bd2fb..eee769c 100644 --- a/lib/src/presentation/blocks/raw/raw_editor.dart +++ b/lib/src/presentation/blocks/raw/raw_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/raw_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; /// Edits the HTML source of a raw block. class RawEditor extends BlockEditor { @@ -36,6 +37,7 @@ class _RawEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return TextField( controller: _controller, onChanged: (value) => widget.onChanged(RawBlock(html: value)), @@ -44,11 +46,11 @@ class _RawEditorState extends State { autocorrect: false, enableSuggestions: false, style: const TextStyle(fontFamily: 'monospace', fontSize: 13), - decoration: const InputDecoration( - labelText: 'Raw HTML', + decoration: InputDecoration( + labelText: strings.rawHtml, hintText: '
...
', alignLabelWithHint: true, - border: OutlineInputBorder(), + border: const OutlineInputBorder(), ), ); } diff --git a/lib/src/presentation/blocks/table/table_editor.dart b/lib/src/presentation/blocks/table/table_editor.dart index 758c060..20ec7dc 100644 --- a/lib/src/presentation/blocks/table/table_editor.dart +++ b/lib/src/presentation/blocks/table/table_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/table_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; class TableEditor extends BlockEditor { const TableEditor({super.key, required super.block, required super.onChanged}); @@ -96,6 +97,7 @@ class _TableEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -108,7 +110,7 @@ class _TableEditorState extends State { _notify(); }, ), - const Text('First row is header'), + Text(strings.firstRowIsHeader), ], ), SingleChildScrollView( @@ -145,7 +147,7 @@ class _TableEditorState extends State { IconButton( icon: const Icon(Icons.remove_circle_outline, size: 16), onPressed: () => _removeRow(r), - tooltip: 'Remove row', + tooltip: strings.removeRow, ), ], ), @@ -160,7 +162,7 @@ class _TableEditorState extends State { icon: const Icon(Icons.remove_circle_outline, size: 16), onPressed: () => _removeColumn(c), - tooltip: 'Remove column', + tooltip: strings.removeColumn, ), ), ), @@ -174,12 +176,12 @@ class _TableEditorState extends State { TextButton.icon( onPressed: _addRow, icon: const Icon(Icons.add, size: 16), - label: const Text('Row'), + label: Text(strings.addRow), ), TextButton.icon( onPressed: _addColumn, icon: const Icon(Icons.add, size: 16), - label: const Text('Column'), + label: Text(strings.addColumn), ), ], ), diff --git a/lib/src/presentation/blocks/warning/warning_editor.dart b/lib/src/presentation/blocks/warning/warning_editor.dart index 20863f4..93f7d46 100644 --- a/lib/src/presentation/blocks/warning/warning_editor.dart +++ b/lib/src/presentation/blocks/warning/warning_editor.dart @@ -2,6 +2,7 @@ import 'package:flutter/material.dart'; import '../../../domain/entities/blocks/warning_block.dart'; import '../base_block_editor.dart'; +import '../../widgets/editor_config_scope.dart'; class WarningEditor extends BlockEditor { const WarningEditor({super.key, required super.block, required super.onChanged}); @@ -35,6 +36,7 @@ class _WarningEditorState extends State { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Container( padding: const EdgeInsets.all(12), decoration: BoxDecoration( @@ -57,8 +59,8 @@ class _WarningEditorState extends State { controller: _titleController, onChanged: (_) => _notify(), style: const TextStyle(fontWeight: FontWeight.bold), - decoration: const InputDecoration( - hintText: 'Warning title', + decoration: InputDecoration( + hintText: strings.warningTitleHint, border: InputBorder.none, isDense: true, ), @@ -67,8 +69,8 @@ class _WarningEditorState extends State { controller: _messageController, onChanged: (_) => _notify(), maxLines: null, - decoration: const InputDecoration( - hintText: 'Warning message...', + decoration: InputDecoration( + hintText: strings.warningMessageHint, border: InputBorder.none, isDense: true, ), diff --git a/lib/src/presentation/config/editor_config.dart b/lib/src/presentation/config/editor_config.dart index b393370..35985be 100644 --- a/lib/src/presentation/config/editor_config.dart +++ b/lib/src/presentation/config/editor_config.dart @@ -3,6 +3,7 @@ import '../../domain/entities/style_config.dart'; import '../registry/block_renderer_registry.dart'; import '../widgets/editor_link_scope.dart'; import 'block_editor_hooks.dart'; +import 'editor_strings.dart'; import 'editor_toolbar_item.dart'; import 'image_uploader.dart'; @@ -62,6 +63,11 @@ class EditorConfig { /// it an attachment is given as a URL. final AttachmentPicker? attachmentPicker; + /// The text of every label, tooltip, hint and message the editor and the + /// viewer show. Defaults to English; pass your own [EditorStrings] to + /// translate or reword them. + final EditorStrings strings; + EditorConfig({ BlockTypeRegistry? typeRegistry, BlockRendererRegistry? rendererRegistry, @@ -72,6 +78,7 @@ class EditorConfig { this.imageUploader, this.linkPreviewFetcher, this.attachmentPicker, + this.strings = const EditorStrings(), }) : typeRegistry = typeRegistry ?? BlockTypeRegistry(), rendererRegistry = rendererRegistry ?? BlockRendererRegistry(); } diff --git a/lib/src/presentation/config/editor_strings.dart b/lib/src/presentation/config/editor_strings.dart new file mode 100644 index 0000000..16747c4 --- /dev/null +++ b/lib/src/presentation/config/editor_strings.dart @@ -0,0 +1,335 @@ +/// Every piece of text the editor and the viewer show on their own: button +/// labels, tooltips, field labels, hints and messages. +/// +/// The defaults are English. To translate the package, or to reword a label, +/// pass an instance with the texts you want to `EditorConfig.strings`; anything +/// you leave out keeps its default: +/// +/// ```dart +/// EditorConfig( +/// strings: EditorStrings( +/// paragraph: 'Párrafo', +/// addItem: 'Agregar elemento', +/// heading: (level) => 'Encabezado $level', +/// ), +/// ) +/// ``` +/// +/// Texts that include a value (a heading level, a file size) are functions. +class EditorStrings { + const EditorStrings({ + // Toolbar + this.paragraph = 'Paragraph', + this.paragraphLabel = 'T', + this.heading = _heading, + this.headingLabel = _headingLabel, + this.quote = 'Quote', + this.code = 'Code', + this.unorderedList = 'Unordered list', + this.orderedList = 'Ordered list', + this.checklist = 'Checklist', + this.legacyChecklist = 'Checklist (legacy)', + this.table = 'Table', + this.delimiter = 'Delimiter', + this.warning = 'Warning', + this.image = 'Image', + this.embed = 'Embed', + this.linkPreview = 'Link preview', + this.attachment = 'Attachment', + this.rawHtml = 'Raw HTML', + this.hyperlink = 'Hyperlink', + this.undo = 'Undo', + this.redo = 'Redo', + this.removeLastBlock = 'Remove last block', + this.addHyperlinkTitle = 'Add hyperlink', + this.hyperlinkTitleHint = 'Link title', + // Shared actions and field labels + this.add = 'Add', + this.cancel = 'Cancel', + this.save = 'Save', + this.caption = 'Caption', + this.title = 'Title', + this.addItem = 'Add item', + // Block controls + this.moveUp = 'Move up', + this.moveDown = 'Move down', + this.deleteBlock = 'Delete block', + this.unsupportedBlock = _unsupportedBlock, + // Paragraph + this.paragraphHint = 'Write something...', + this.bold = 'Bold', + this.boldLabel = 'B', + this.italic = 'Italic', + this.italicLabel = 'I', + this.underline = 'Underline', + this.underlineLabel = 'U', + this.strikethrough = 'Strikethrough', + this.strikethroughLabel = 'S', + this.inlineCode = 'Inline code', + this.highlight = 'Highlight', + this.highlightLabel = 'mark', + this.link = 'Link', + this.linkLabel = 'link', + this.addLinkTitle = 'Add link', + this.editLinkTitle = 'Edit link', + this.linkAddress = 'Link address', + this.removeLink = 'Remove link', + // Header + this.headingLevel = 'Heading level', + // List + this.listUnordered = 'Unordered', + this.listOrdered = 'Ordered', + this.listChecklist = 'Checklist', + this.startWith = 'Start with', + this.counterNumeric = 'Numeric', + this.counterLowerRoman = 'Lower Roman', + this.counterUpperRoman = 'Upper Roman', + this.counterLowerAlpha = 'Lower Alpha', + this.counterUpperAlpha = 'Upper Alpha', + this.outdent = 'Outdent', + this.indent = 'Indent', + this.removeItem = 'Remove item', + this.checklistItemHint = 'List item...', + // Quote + this.quoteHint = 'Quote text...', + this.quoteCaptionHint = 'Caption (optional)', + this.align = 'Align:', + this.alignLeft = 'left', + this.alignCenter = 'center', + this.alignRight = 'right', + // Code + this.codeHint = 'Enter code...', + this.copy = 'Copy', + // Warning + this.warningTitleHint = 'Warning title', + this.warningMessageHint = 'Warning message...', + // Table + this.firstRowIsHeader = 'First row is header', + this.removeRow = 'Remove row', + this.removeColumn = 'Remove column', + this.addRow = 'Row', + this.addColumn = 'Column', + // Image + this.camera = 'Camera', + this.gallery = 'Gallery', + this.imageUrl = 'Image URL', + this.imageBorder = 'Border', + this.imageStretch = 'Stretch', + this.imageBackground = 'Background', + this.imagePickFailed = 'Could not open the image.', + this.imageUploadFailed = 'Upload failed. Try again.', + // Embed + this.embedLink = 'Embed link', + this.embedService = _embedService, + this.embedUnsupported = 'This link is not from a supported service.', + this.embeddedContent = 'Embedded content', + // Link preview + this.linkUrl = 'Link', + this.fetchPreview = 'Fetch preview', + this.description = 'Description', + this.previewImageUrl = 'Preview image URL', + this.noPreview = 'No preview available for this link.', + this.previewFailed = 'Could not fetch the preview.', + // Attachment + this.chooseFile = 'Choose file', + this.fileUrl = 'File URL', + this.fileSize = _fileSize, + this.attachFailed = 'Could not attach the file.', + this.downloadFile = 'Download file', + }); + + static String _heading(int level) => 'Heading $level'; + static String _headingLabel(int level) => 'H$level'; + static String _unsupportedBlock(String type) => '[Unsupported block: $type]'; + static String _embedService(String service) => 'Service: $service'; + static String _fileSize(int bytes) => '$bytes bytes'; + + // --- Toolbar: tooltips of the buttons that add a block --------------------- + + final String paragraph; + + /// Text of the paragraph button, which has no icon. + final String paragraphLabel; + + /// Tooltip of a heading button, and the hint of an empty heading. + final String Function(int level) heading; + + /// Text of a heading button and of the entries of the level selector. + final String Function(int level) headingLabel; + final String quote; + final String code; + final String unorderedList; + final String orderedList; + + /// The checklist stored as a list block (`@editorjs/list` 2.x). + final String checklist; + + /// The checklist stored as the older `checklist` block. + final String legacyChecklist; + final String table; + final String delimiter; + final String warning; + final String image; + final String embed; + final String linkPreview; + final String attachment; + + /// Tooltip of the raw HTML button and label of the raw HTML field. + final String rawHtml; + final String hyperlink; + final String undo; + final String redo; + final String removeLastBlock; + + /// Title of the dialog the hyperlink button opens. + final String addHyperlinkTitle; + final String hyperlinkTitleHint; + + // --- Shared actions and field labels --------------------------------------- + + final String add; + final String cancel; + final String save; + + /// Label of the caption field of image and embed blocks. + final String caption; + + /// Label of the title field of link and attachment blocks. + final String title; + + /// Button that appends an item to a list or a checklist. + final String addItem; + + // --- Controls beside every block ------------------------------------------- + + final String moveUp; + final String moveDown; + final String deleteBlock; + + /// Placeholder shown for a block the editor has no editor for. + final String Function(String type) unsupportedBlock; + + // --- Paragraph -------------------------------------------------------------- + + final String paragraphHint; + + /// Tooltips of the format buttons, each followed by the short text shown on + /// the button itself. + final String bold; + final String boldLabel; + final String italic; + final String italicLabel; + final String underline; + final String underlineLabel; + final String strikethrough; + final String strikethroughLabel; + final String inlineCode; + final String highlight; + final String highlightLabel; + final String link; + final String linkLabel; + + /// Titles of the link dialog, for a new and for an existing link. + final String addLinkTitle; + final String editLinkTitle; + final String linkAddress; + final String removeLink; + + // --- Header ----------------------------------------------------------------- + + /// Tooltip of the level selector. + final String headingLevel; + + // --- List ------------------------------------------------------------------- + + /// Tooltips of the style selector. + final String listUnordered; + final String listOrdered; + final String listChecklist; + final String startWith; + final String counterNumeric; + final String counterLowerRoman; + final String counterUpperRoman; + final String counterLowerAlpha; + final String counterUpperAlpha; + final String outdent; + final String indent; + final String removeItem; + + /// Hint of an empty item of the older checklist block. + final String checklistItemHint; + + // --- Quote ------------------------------------------------------------------ + + final String quoteHint; + final String quoteCaptionHint; + final String align; + final String alignLeft; + final String alignCenter; + final String alignRight; + + // --- Code ------------------------------------------------------------------- + + final String codeHint; + + /// Tooltip of the copy button on a code block in the viewer. + final String copy; + + // --- Warning ---------------------------------------------------------------- + + final String warningTitleHint; + final String warningMessageHint; + + // --- Table ------------------------------------------------------------------ + + final String firstRowIsHeader; + final String removeRow; + final String removeColumn; + + /// Buttons that add a row and a column; shown next to a plus icon. + final String addRow; + final String addColumn; + + // --- Image ------------------------------------------------------------------ + + final String camera; + final String gallery; + final String imageUrl; + final String imageBorder; + final String imageStretch; + final String imageBackground; + final String imagePickFailed; + final String imageUploadFailed; + + // --- Embed ------------------------------------------------------------------ + + final String embedLink; + + /// Line naming the service a link was recognized as. + final String Function(String service) embedService; + final String embedUnsupported; + + /// Heading of an embed card in the viewer when the service is unknown. + final String embeddedContent; + + // --- Link preview ----------------------------------------------------------- + + /// Label of the link field of a link block. + final String linkUrl; + final String fetchPreview; + final String description; + final String previewImageUrl; + final String noPreview; + final String previewFailed; + + // --- Attachment ------------------------------------------------------------- + + final String chooseFile; + final String fileUrl; + final String Function(int bytes) fileSize; + final String attachFailed; + + /// Text of an attachment card in the viewer when the file has no title or + /// name. + final String downloadFile; +} diff --git a/lib/src/presentation/widgets/editor_config_scope.dart b/lib/src/presentation/widgets/editor_config_scope.dart index 32c2eb0..4168b18 100644 --- a/lib/src/presentation/widgets/editor_config_scope.dart +++ b/lib/src/presentation/widgets/editor_config_scope.dart @@ -1,11 +1,12 @@ import 'package:flutter/widgets.dart'; import '../config/editor_config.dart'; +import '../config/editor_strings.dart'; -/// Makes the [EditorConfig] of the surrounding `EditorJSEditor` available to -/// the block editors below it. +/// Makes the [EditorConfig] of the surrounding `EditorJSEditor` or +/// `EditorJSView` available to the block widgets below it. /// -/// Block editors are built by the registry from a block and a callback, so +/// Block editors and renderers are built by the registry from a block, so /// they cannot receive configuration as arguments. They read it from here. class EditorConfigScope extends InheritedWidget { final EditorConfig config; @@ -16,11 +17,16 @@ class EditorConfigScope extends InheritedWidget { required super.child, }); - /// The configuration of the surrounding editor, or `null` when a block - /// editor is used on its own. + /// The configuration of the surrounding editor or viewer, or `null` when a + /// block widget is used on its own. static EditorConfig? maybeOf(BuildContext context) => context.getInheritedWidgetOfExactType()?.config; + /// The texts to show: those of the surrounding configuration, or the + /// English defaults when a block widget is used on its own. + static EditorStrings stringsOf(BuildContext context) => + maybeOf(context)?.strings ?? const EditorStrings(); + @override bool updateShouldNotify(EditorConfigScope oldWidget) => config != oldWidget.config; diff --git a/lib/src/presentation/widgets/editorjs_editor.dart b/lib/src/presentation/widgets/editorjs_editor.dart index f61430d..4e6e279 100644 --- a/lib/src/presentation/widgets/editorjs_editor.dart +++ b/lib/src/presentation/widgets/editorjs_editor.dart @@ -122,6 +122,7 @@ class _BlockWrap extends StatelessWidget { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -131,17 +132,17 @@ class _BlockWrap extends StatelessWidget { children: [ _BlockControlButton( icon: Icons.arrow_upward, - tooltip: 'Move up', + tooltip: strings.moveUp, onTap: onMoveUp, ), _BlockControlButton( icon: Icons.arrow_downward, - tooltip: 'Move down', + tooltip: strings.moveDown, onTap: onMoveDown, ), _BlockControlButton( icon: Icons.close, - tooltip: 'Delete block', + tooltip: strings.deleteBlock, onTap: onDelete, color: Colors.red.shade300, ), @@ -198,7 +199,7 @@ class _UnknownBlockWidget extends StatelessWidget { return Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: Text( - '[Unsupported block: $type]', + EditorConfigScope.stringsOf(context).unsupportedBlock(type), style: TextStyle( color: Colors.grey.shade500, fontStyle: FontStyle.italic, diff --git a/lib/src/presentation/widgets/editorjs_toolbar.dart b/lib/src/presentation/widgets/editorjs_toolbar.dart index df99eb7..80f3548 100644 --- a/lib/src/presentation/widgets/editorjs_toolbar.dart +++ b/lib/src/presentation/widgets/editorjs_toolbar.dart @@ -14,9 +14,11 @@ import '../../domain/entities/blocks/quote_block.dart'; import '../../domain/entities/blocks/raw_block.dart'; import '../../domain/entities/blocks/table_block.dart'; import '../../domain/entities/blocks/warning_block.dart'; +import '../config/editor_strings.dart'; import '../config/editor_toolbar_item.dart'; import '../controller/editor_controller.dart'; import '../registry/block_renderer_registry.dart'; +import 'editor_config_scope.dart'; /// Toolbar for [EditorJSEditor]. /// @@ -38,6 +40,8 @@ class EditorJSToolbar extends StatelessWidget { @override Widget build(BuildContext context) { + final strings = EditorConfigScope.stringsOf(context); + return SafeArea( child: Container( decoration: BoxDecoration( @@ -48,7 +52,7 @@ class EditorJSToolbar extends StatelessWidget { scrollDirection: Axis.horizontal, child: Row( children: [ - for (final item in items) _buildButton(context, item), + for (final item in items) _buildButton(context, item, strings), ], ), ), @@ -56,34 +60,38 @@ class EditorJSToolbar extends StatelessWidget { ); } - Widget _buildButton(BuildContext context, EditorToolbarItem item) { + Widget _buildButton( + BuildContext context, + EditorToolbarItem item, + EditorStrings strings, + ) { return switch (item) { // --- Text blocks --- EditorToolbarItem.paragraph => _ToolbarButton( - label: 'T', - tooltip: 'Paragraph', + label: strings.paragraphLabel, + tooltip: strings.paragraph, onTap: () => controller.addBlock(const ParagraphBlock(html: '')), ), - EditorToolbarItem.heading1 => _headingButton(1), - EditorToolbarItem.heading2 => _headingButton(2), - EditorToolbarItem.heading3 => _headingButton(3), - EditorToolbarItem.heading4 => _headingButton(4), - EditorToolbarItem.heading5 => _headingButton(5), - EditorToolbarItem.heading6 => _headingButton(6), + EditorToolbarItem.heading1 => _headingButton(1, strings), + EditorToolbarItem.heading2 => _headingButton(2, strings), + EditorToolbarItem.heading3 => _headingButton(3, strings), + EditorToolbarItem.heading4 => _headingButton(4, strings), + EditorToolbarItem.heading5 => _headingButton(5, strings), + EditorToolbarItem.heading6 => _headingButton(6, strings), EditorToolbarItem.quote => _ToolbarButton( icon: Icons.format_quote, - tooltip: 'Quote', + tooltip: strings.quote, onTap: () => controller.addBlock(const QuoteBlock(text: '')), ), EditorToolbarItem.code => _ToolbarButton( icon: Icons.code, - tooltip: 'Code', + tooltip: strings.code, onTap: () => controller.addBlock(const CodeBlock(code: '')), ), // --- Lists --- EditorToolbarItem.unorderedList => _ToolbarButton( icon: Icons.format_list_bulleted, - tooltip: 'Unordered list', + tooltip: strings.unorderedList, onTap: () => controller.addBlock( const ListBlock( style: ListStyle.unordered, @@ -93,7 +101,7 @@ class EditorJSToolbar extends StatelessWidget { ), EditorToolbarItem.orderedList => _ToolbarButton( icon: Icons.format_list_numbered, - tooltip: 'Ordered list', + tooltip: strings.orderedList, onTap: () => controller.addBlock( const ListBlock( style: ListStyle.ordered, @@ -106,7 +114,7 @@ class EditorJSToolbar extends StatelessWidget { // `@editorjs/list` 2.x stores a checklist as a list block … EditorToolbarItem.checklist => _ToolbarButton( icon: Icons.checklist, - tooltip: 'Checklist', + tooltip: strings.checklist, onTap: () => controller.addBlock( const ListBlock( style: ListStyle.checklist, @@ -117,7 +125,7 @@ class EditorJSToolbar extends StatelessWidget { // … while the older `@editorjs/checklist` tool has its own block. EditorToolbarItem.legacyChecklist => _ToolbarButton( icon: Icons.check_box_outlined, - tooltip: 'Checklist (legacy)', + tooltip: strings.legacyChecklist, onTap: () => controller.addBlock( const ChecklistBlock( items: [ChecklistItem(text: '')], @@ -127,7 +135,7 @@ class EditorJSToolbar extends StatelessWidget { // --- Structural --- EditorToolbarItem.table => _ToolbarButton( icon: Icons.table_chart_outlined, - tooltip: 'Table', + tooltip: strings.table, onTap: () => controller.addBlock( const TableBlock( content: [ @@ -139,62 +147,62 @@ class EditorJSToolbar extends StatelessWidget { ), EditorToolbarItem.delimiter => _ToolbarButton( icon: Icons.horizontal_rule, - tooltip: 'Delimiter', + tooltip: strings.delimiter, onTap: () => controller.addBlock(const DelimiterBlock()), ), EditorToolbarItem.warning => _ToolbarButton( icon: Icons.warning_amber_outlined, - tooltip: 'Warning', + tooltip: strings.warning, onTap: () => controller.addBlock(const WarningBlock(title: '', message: '')), ), // --- Media --- EditorToolbarItem.image => _ToolbarButton( icon: Icons.image_outlined, - tooltip: 'Image', + tooltip: strings.image, onTap: () => controller.addBlock(const ImageBlock(url: '')), ), EditorToolbarItem.embed => _ToolbarButton( icon: Icons.smart_display_outlined, - tooltip: 'Embed', + tooltip: strings.embed, onTap: () => controller.addBlock( const EmbedBlock(service: '', source: '', embed: ''), ), ), EditorToolbarItem.linkPreview => _ToolbarButton( icon: Icons.add_link, - tooltip: 'Link preview', + tooltip: strings.linkPreview, onTap: () => controller.addBlock(const LinkToolBlock(link: '')), ), EditorToolbarItem.attachment => _ToolbarButton( icon: Icons.attach_file, - tooltip: 'Attachment', + tooltip: strings.attachment, onTap: () => controller.addBlock(const AttachesBlock(url: '')), ), EditorToolbarItem.rawHtml => _ToolbarButton( icon: Icons.html, - tooltip: 'Raw HTML', + tooltip: strings.rawHtml, onTap: () => controller.addBlock(const RawBlock(html: '')), ), EditorToolbarItem.hyperlink => _ToolbarButton( icon: Icons.link, - tooltip: 'Hyperlink', - onTap: () => _showHyperlinkDialog(context), + tooltip: strings.hyperlink, + onTap: () => _showHyperlinkDialog(context, strings), ), // --- Actions --- EditorToolbarItem.undo => _ToolbarButton( icon: Icons.undo, - tooltip: 'Undo', + tooltip: strings.undo, onTap: controller.canUndo ? controller.undo : null, ), EditorToolbarItem.redo => _ToolbarButton( icon: Icons.redo, - tooltip: 'Redo', + tooltip: strings.redo, onTap: controller.canRedo ? controller.redo : null, ), EditorToolbarItem.removeLastBlock => _ToolbarButton( icon: Icons.delete_outline, - tooltip: 'Remove last block', + tooltip: strings.removeLastBlock, onTap: controller.blockCount > 0 ? () => controller.removeBlock(controller.blockCount - 1) : null, @@ -202,26 +210,28 @@ class EditorJSToolbar extends StatelessWidget { }; } - Widget _headingButton(int level) => _ToolbarButton( - label: 'H$level', - tooltip: 'Heading $level', + Widget _headingButton(int level, EditorStrings strings) => _ToolbarButton( + label: strings.headingLabel(level), + tooltip: strings.heading(level), onTap: () => controller.addBlock(HeaderBlock(text: '', level: level)), ); - void _showHyperlinkDialog(BuildContext context) { + void _showHyperlinkDialog(BuildContext context, EditorStrings strings) { final titleController = TextEditingController(); final urlController = TextEditingController(); showDialog( context: context, builder: (ctx) => AlertDialog( - title: const Text('Add hyperlink'), + title: Text(strings.addHyperlinkTitle), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( controller: titleController, - decoration: const InputDecoration(hintText: 'Link title'), + decoration: InputDecoration( + hintText: strings.hyperlinkTitleHint, + ), ), const SizedBox(height: 8), TextField( @@ -234,7 +244,7 @@ class EditorJSToolbar extends StatelessWidget { actions: [ TextButton( onPressed: () => Navigator.pop(ctx), - child: const Text('Cancel'), + child: Text(strings.cancel), ), TextButton( onPressed: () { @@ -247,7 +257,7 @@ class EditorJSToolbar extends StatelessWidget { } Navigator.pop(ctx); }, - child: const Text('Add'), + child: Text(strings.add), ), ], ), diff --git a/lib/src/presentation/widgets/editorjs_view.dart b/lib/src/presentation/widgets/editorjs_view.dart index 128b27b..7374fba 100644 --- a/lib/src/presentation/widgets/editorjs_view.dart +++ b/lib/src/presentation/widgets/editorjs_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../data/datasources/json_document_source.dart'; import '../../domain/usecases/parse_document.dart'; import '../config/editor_config.dart'; +import 'editor_config_scope.dart'; import 'editor_link_scope.dart'; /// Read-only viewer for EditorJS JSON content. @@ -34,17 +35,20 @@ class EditorJSView extends StatelessWidget { config.rendererRegistry.buildRenderer(block, config.styleConfig), ].nonNulls; - return EditorLinkScope( - onLinkTap: config.onLinkTap, - allowedSchemes: config.allowedLinkSchemes, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - for (final widget in rendered) ...[ - widget, - const SizedBox(height: 8), + return EditorConfigScope( + config: config, + child: EditorLinkScope( + onLinkTap: config.onLinkTap, + allowedSchemes: config.allowedLinkSchemes, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final widget in rendered) ...[ + widget, + const SizedBox(height: 8), + ], ], - ], + ), ), ); } diff --git a/test/widget/localization_test.dart b/test/widget/localization_test.dart new file mode 100644 index 0000000..b4d4918 --- /dev/null +++ b/test/widget/localization_test.dart @@ -0,0 +1,384 @@ +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:editorjs_flutter/src/presentation/blocks/paragraph/paragraph_editor.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Every text replaced by a recognisable "translation": the English default +/// with a § in front. Anything on screen without the § was not looked up. +final _marked = EditorStrings( + paragraph: '§Paragraph', + paragraphLabel: '§T', + heading: (level) => '§Heading $level', + headingLabel: (level) => '§H$level', + quote: '§Quote', + code: '§Code', + unorderedList: '§Unordered list', + orderedList: '§Ordered list', + checklist: '§Checklist', + legacyChecklist: '§Checklist (legacy)', + table: '§Table', + delimiter: '§Delimiter', + warning: '§Warning', + image: '§Image', + embed: '§Embed', + linkPreview: '§Link preview', + attachment: '§Attachment', + rawHtml: '§Raw HTML', + hyperlink: '§Hyperlink', + undo: '§Undo', + redo: '§Redo', + removeLastBlock: '§Remove last block', + addHyperlinkTitle: '§Add hyperlink', + hyperlinkTitleHint: '§Link title', + add: '§Add', + cancel: '§Cancel', + save: '§Save', + caption: '§Caption', + title: '§Title', + addItem: '§Add item', + moveUp: '§Move up', + moveDown: '§Move down', + deleteBlock: '§Delete block', + unsupportedBlock: (type) => '§Unsupported $type', + paragraphHint: '§Write something...', + bold: '§Bold', + boldLabel: '§B', + italic: '§Italic', + italicLabel: '§I', + underline: '§Underline', + underlineLabel: '§U', + strikethrough: '§Strikethrough', + strikethroughLabel: '§S', + inlineCode: '§Inline code', + highlight: '§Highlight', + highlightLabel: '§mark', + link: '§Link', + linkLabel: '§link', + addLinkTitle: '§Add link', + editLinkTitle: '§Edit link', + linkAddress: '§Link address', + removeLink: '§Remove link', + headingLevel: '§Heading level', + listUnordered: '§Unordered', + listOrdered: '§Ordered', + listChecklist: '§Checklist', + startWith: '§Start with', + counterNumeric: '§Numeric', + counterLowerRoman: '§Lower Roman', + counterUpperRoman: '§Upper Roman', + counterLowerAlpha: '§Lower Alpha', + counterUpperAlpha: '§Upper Alpha', + outdent: '§Outdent', + indent: '§Indent', + removeItem: '§Remove item', + checklistItemHint: '§List item...', + quoteHint: '§Quote text...', + quoteCaptionHint: '§Caption (optional)', + align: '§Align:', + alignLeft: '§left', + alignCenter: '§center', + alignRight: '§right', + codeHint: '§Enter code...', + copy: '§Copy', + warningTitleHint: '§Warning title', + warningMessageHint: '§Warning message...', + firstRowIsHeader: '§First row is header', + removeRow: '§Remove row', + removeColumn: '§Remove column', + addRow: '§Row', + addColumn: '§Column', + camera: '§Camera', + gallery: '§Gallery', + imageUrl: '§Image URL', + imageBorder: '§Border', + imageStretch: '§Stretch', + imageBackground: '§Background', + imagePickFailed: '§Could not open the image.', + imageUploadFailed: '§Upload failed. Try again.', + embedLink: '§Embed link', + embedService: (service) => '§Service $service', + embedUnsupported: '§This link is not from a supported service.', + embeddedContent: '§Embedded content', + linkUrl: '§Link', + fetchPreview: '§Fetch preview', + description: '§Description', + previewImageUrl: '§Preview image URL', + noPreview: '§No preview available for this link.', + previewFailed: '§Could not fetch the preview.', + chooseFile: '§Choose file', + fileUrl: '§File URL', + fileSize: (bytes) => '§$bytes bytes', + attachFailed: '§Could not attach the file.', + downloadFile: '§Download file', +); + +/// Text the widgets show that is not language: URL and markup examples and +/// the symbol on the inline-code button. +const _notLanguage = { + 'https://...', + 'https://www.youtube.com/watch?v=...', + '
...
', + '', +}; + +/// A document with one block of every type the editor can edit. +const _everyBlock = '{"blocks":[' + '{"type":"header","data":{"text":"","level":2}},' + '{"type":"paragraph","data":{"text":""}},' + '{"type":"list","data":{"style":"ordered","meta":{},"items":' + '[{"content":"","meta":{},"items":[]}]}},' + '{"type":"checklist","data":{"items":[{"text":"","checked":false}]}},' + '{"type":"quote","data":{"text":"","caption":"","alignment":"left"}},' + '{"type":"code","data":{"code":""}},' + '{"type":"warning","data":{"title":"","message":""}},' + '{"type":"table","data":{"withHeadings":false,"content":[[""]]}},' + '{"type":"delimiter","data":{}},' + '{"type":"image","data":{"file":{"url":""},"caption":""}},' + '{"type":"embed","data":{"service":"coub",' + '"source":"https://coub.com/view/1","embed":"e"}},' + '{"type":"linkTool","data":{"link":""}},' + '{"type":"attaches","data":{"file":{"url":"","size":10}}},' + '{"type":"raw","data":{"html":""}},' + '{"type":"mystery","data":{}}' + ']}'; + +/// Every piece of text the widget tree currently shows to the user: plain +/// text, tooltips, and the labels and hints of text fields. +Set _visibleTexts(WidgetTester tester) { + final texts = {}; + for (final widget in tester.allWidgets) { + if (widget is Text && widget.data != null) texts.add(widget.data!); + if (widget is Tooltip && widget.message != null) texts.add(widget.message!); + if (widget is TextField) { + texts.addAll([ + widget.decoration?.labelText, + widget.decoration?.hintText, + ].nonNulls); + } + } + return texts; +} + +/// The visible texts that are words but did not come from [_marked]. +Iterable _untranslated(WidgetTester tester) => + _visibleTexts(tester).where((text) => + !text.startsWith('§') && + !_notLanguage.contains(text) && + RegExp(r'[A-Za-z]{2,}').hasMatch(text)); + +Widget _editor(EditorController controller, {EditorStrings? strings}) => + MaterialApp( + home: Scaffold( + body: EditorJSEditor( + controller: controller, + config: EditorConfig( + strings: strings ?? const EditorStrings(), + // Configured so that the buttons they add are on screen too. + linkPreviewFetcher: (_) async => null, + attachmentPicker: () async => null, + ), + ), + ), + ); + +void main() { + /// Tall and wide enough that every block and toolbar button is built. + Future useLargeSurface(WidgetTester tester) async { + await tester.binding.setSurfaceSize(const Size(2400, 6000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + } + + group('defaults', () { + test('are English', () { + const strings = EditorStrings(); + expect(strings.paragraph, 'Paragraph'); + expect(strings.addItem, 'Add item'); + expect(strings.heading(3), 'Heading 3'); + expect(strings.headingLabel(3), 'H3'); + expect(strings.unsupportedBlock('x'), '[Unsupported block: x]'); + expect(strings.embedService('vimeo'), 'Service: vimeo'); + expect(strings.fileSize(2048), '2048 bytes'); + }); + + test('a partial translation keeps the rest', () { + const strings = EditorStrings(paragraph: 'Párrafo'); + expect(strings.paragraph, 'Párrafo'); + expect(strings.quote, 'Quote'); + }); + + test('EditorConfig uses the defaults unless told otherwise', () { + expect(EditorConfig().strings.undo, 'Undo'); + }); + + testWidgets('the editor shows them', (tester) async { + await useLargeSurface(tester); + await tester.pumpWidget(_editor(EditorController.fromJson(_everyBlock))); + await tester.pumpAndSettle(); + + final visible = _visibleTexts(tester); + for (final text in [ + 'Paragraph', + 'Heading 2', + 'Add item', + 'Start with', + 'First row is header', + 'Camera', + 'Fetch preview', + 'Choose file', + 'Raw HTML', + 'Move up', + '[Unsupported block: mystery]', + ]) { + expect(visible, contains(text)); + } + }); + }); + + group('with translated strings', () { + testWidgets('no editor or toolbar text is left untranslated', + (tester) async { + await useLargeSurface(tester); + await tester.pumpWidget(_editor( + EditorController.fromJson(_everyBlock), + strings: _marked, + )); + await tester.pumpAndSettle(); + + expect(_untranslated(tester), isEmpty); + + // Spot checks that the scan really sees each kind of text. + final visible = _visibleTexts(tester); + expect(visible, contains('§Paragraph')); // toolbar tooltip + expect(visible, contains('§T')); // toolbar label + expect(visible, contains('§Heading 2')); // function, used as a hint + expect(visible, contains('§H2')); // function, level selector + expect(visible, contains('§Lower Roman')); // dropdown entry + expect(visible, contains('§Service coub')); // function with a value + expect(visible, contains('§10 bytes')); + expect(visible, contains('§Unsupported mystery')); + expect(visible, contains('§Caption')); // field label + expect(visible, contains('§left')); // quote alignment chip + }); + + testWidgets('the paragraph format bar and its link dialog', + (tester) async { + await tester.pumpWidget(_editor( + EditorController(initialBlocks: const [ParagraphBlock(html: 'Text')]), + strings: _marked, + )); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(ParagraphEditor)); + await tester.pump(); + expect(find.byTooltip('§Bold'), findsOneWidget); + expect(find.text('§mark'), findsOneWidget); + + await tester.tap(find.byTooltip('§Link')); + await tester.pumpAndSettle(); + expect(find.text('§Add link'), findsOneWidget); + expect(find.text('§Link address'), findsOneWidget); + expect(find.text('§Cancel'), findsOneWidget); + expect(find.text('§Save'), findsOneWidget); + expect(_untranslated(tester), isEmpty); + }); + + testWidgets('the link dialog of an existing link', (tester) async { + await tester.pumpWidget(_editor( + EditorController( + initialBlocks: const [ + ParagraphBlock(html: 'a'), + ], + ), + strings: _marked, + )); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(ParagraphEditor)); + await tester.pump(); + tester + .widget(find.descendant( + of: find.byType(ParagraphEditor), + matching: find.byType(TextField), + )) + .controller! + .selection = const TextSelection.collapsed(offset: 5); + await tester.pump(); + + await tester.tap(find.byTooltip('§Link')); + await tester.pumpAndSettle(); + expect(find.text('§Edit link'), findsOneWidget); + expect(find.text('§Remove link'), findsOneWidget); + }); + + testWidgets('the toolbar hyperlink dialog', (tester) async { + await useLargeSurface(tester); + await tester.pumpWidget(_editor(EditorController(), strings: _marked)); + await tester.pumpAndSettle(); + + await tester.tap(find.byTooltip('§Hyperlink')); + await tester.pumpAndSettle(); + expect(find.text('§Add hyperlink'), findsOneWidget); + expect(find.text('§Link title'), findsOneWidget); + expect(find.text('§Add'), findsOneWidget); + expect(find.text('§Cancel'), findsOneWidget); + }); + + testWidgets('error and status messages', (tester) async { + await useLargeSurface(tester); + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: EditorJSEditor( + controller: EditorController.fromJson('{"blocks":[' + '{"type":"linkTool","data":{"link":"https://x.example"}},' + '{"type":"attaches","data":{"file":{"url":""}}},' + '{"type":"embed","data":{"service":"",' + '"source":"https://unknown.example","embed":""}}' + ']}'), + config: EditorConfig( + strings: _marked, + linkPreviewFetcher: (_) async => null, + attachmentPicker: () async => throw StateError('no'), + ), + ), + ), + )); + await tester.pumpAndSettle(); + + expect( + find.text('§This link is not from a supported service.'), + findsOneWidget, + ); + + await tester.tap(find.text('§Fetch preview')); + await tester.pumpAndSettle(); + expect(find.text('§No preview available for this link.'), findsOneWidget); + + await tester.tap(find.text('§Choose file')); + await tester.pumpAndSettle(); + expect(find.text('§Could not attach the file.'), findsOneWidget); + }); + + testWidgets('the viewer', (tester) async { + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: EditorJSView( + config: EditorConfig(strings: _marked), + jsonData: '{"blocks":[' + '{"type":"code","data":{"code":"x"}},' + '{"type":"embed","data":{"service":"",' + '"source":"https://x.example","embed":""}},' + '{"type":"attaches","data":{"file":{"url":"https://x/f"}}}' + ']}', + ), + ), + ), + )); + await tester.pumpAndSettle(); + + expect(find.byTooltip('§Copy'), findsOneWidget); + expect(find.text('§Embedded content'), findsOneWidget); + expect(find.text('§Download file'), findsOneWidget); + }); + }); +} From 00004c76121a2628f755b95194239989db3a4839 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 10:10:34 -0600 Subject: [PATCH 15/16] Bundle Spanish and French translations and document adding more EditorTranslations exposes complete Spanish and French EditorStrings (es, fr) and forLanguage(code), which accepts a language code or a locale tag and falls back to English. Each language is one file under config/translations. translations_test reads those files and fails when one misses a text, has an unknown one, or is not registered. The README explains how to use a bundled language, reword single texts, add a translation in an app, and contribute one to the package. Co-Authored-By: Claude --- CHANGELOG.md | 3 +- CLAUDE.md | 4 +- README.md | 61 ++++++- lib/editorjs_flutter.dart | 1 + .../translations/editor_strings_es.dart | 132 ++++++++++++++ .../translations/editor_strings_fr.dart | 132 ++++++++++++++ .../translations/editor_translations.dart | 46 +++++ test/unit/translations_test.dart | 172 ++++++++++++++++++ 8 files changed, 541 insertions(+), 10 deletions(-) create mode 100644 lib/src/presentation/config/translations/editor_strings_es.dart create mode 100644 lib/src/presentation/config/translations/editor_strings_fr.dart create mode 100644 lib/src/presentation/config/translations/editor_translations.dart create mode 100644 test/unit/translations_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index ec4c140..c2e0097 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,7 @@ ### Translatable text * **Every label, tooltip, hint and message can be translated or reworded.** New `EditorConfig.strings` takes an `EditorStrings`, which holds all 104 texts the editor and the viewer show on their own, with English defaults; override only the ones you need. Texts that include a value (a heading level, a file size) are functions. Until now all text was hard-coded in English. +* **Spanish and French are bundled.** `EditorTranslations.es` and `EditorTranslations.fr` are complete translations; `EditorTranslations.forLanguage(code)` picks one from a language code or locale tag and falls back to English. The README explains how to add another language, in an app or in the package. ### Parser hardening * A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. @@ -52,7 +53,7 @@ * Lists are always written in the list 2.x shape: `ListBlock.toJson()` adds a root `meta`, and `ListItem.toJson()` adds a per-item `meta`. ### Tests -* Added `test/unit/lossless_roundtrip_test.dart`, `editor_controller_metadata_test.dart`, `json_reader_test.dart`, `list_v2_test.dart` and `embed_services_test.dart`; and `test/widget/unknown_block_test.dart`, `list_v2_test.dart`, `viewer_fidelity_test.dart`, `header_level_test.dart`, `toolbar_items_test.dart`, `image_editor_test.dart`, `nested_list_editor_test.dart`, `media_block_editors_test.dart`, `paragraph_link_test.dart` and `localization_test.dart` (458 tests in total, 95 % line coverage). +* Added `test/unit/lossless_roundtrip_test.dart`, `editor_controller_metadata_test.dart`, `json_reader_test.dart`, `list_v2_test.dart`, `embed_services_test.dart` and `translations_test.dart`; and `test/widget/unknown_block_test.dart`, `list_v2_test.dart`, `viewer_fidelity_test.dart`, `header_level_test.dart`, `toolbar_items_test.dart`, `image_editor_test.dart`, `nested_list_editor_test.dart`, `media_block_editors_test.dart`, `paragraph_link_test.dart` and `localization_test.dart` (469 tests in total, 95 % line coverage). --- diff --git a/CLAUDE.md b/CLAUDE.md index c717787..d12e2f4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -132,7 +132,7 @@ final config = EditorConfig( - **Widgets**: `EditorJSView`, `EditorJSEditor`, `EditorLinkScope` (lets custom renderers open links through `EditorConfig.onLinkTap`) - **Controller**: `EditorController` -- **Config**: `EditorConfig`, `EditorToolbarItem`, `ImageUploader` / `PickedImage` / `UploadedImage`, `LinkPreviewFetcher`, `AttachmentPicker`, `EditorStrings` +- **Config**: `EditorConfig`, `EditorToolbarItem`, `ImageUploader` / `PickedImage` / `UploadedImage`, `LinkPreviewFetcher`, `AttachmentPicker`, `EditorStrings`, `EditorTranslations` (bundled `es` and `fr`) - **Registries**: `BlockTypeRegistry`, `BlockRendererRegistry` - **Contracts** (for custom block authors): `BlockMapper`, `BlockRenderer`, `BlockEditor`, `BlockEntity`, `BlockDocument`, `BlockMetadata`, `StyleConfig` - **Built-in entities**: `HeaderBlock`, `ParagraphBlock`, `ListBlock`, `DelimiterBlock`, `ImageBlock`, and the other block entities; `UnknownBlock` holds any block the package cannot interpret so it round-trips untouched @@ -172,7 +172,7 @@ When building new features, always work bottom-up: 4. Run `fvm flutter test --coverage` locally and verify the coverage threshold. 5. Follow the Clean Architecture layer rules: no Flutter imports in `domain/`, no direct widget dependencies in `data/`. 6. New block types must be added bottom-up: entity → mapper → renderer → (editor) → register in both registries → export from barrel. -7. No hard-coded user-visible text in widgets. Add a field to `EditorStrings` and read it with `EditorConfigScope.stringsOf(context)`; `test/widget/localization_test.dart` fails when a widget shows text that did not come from there. +7. No hard-coded user-visible text in widgets. Add a field to `EditorStrings` and read it with `EditorConfigScope.stringsOf(context)`; `test/widget/localization_test.dart` fails when a widget shows text that did not come from there. Every new text must also be added to each file in `lib/src/presentation/config/translations/`; `test/unit/translations_test.dart` fails when a bundled translation is incomplete. ## Git Workflow diff --git a/README.md b/README.md index 8833ae9..643566c 100644 --- a/README.md +++ b/README.md @@ -229,21 +229,68 @@ Embed blocks need no setup: paste a link from YouTube, Vimeo, X, Instagram, Code ### Translating the editor -All the text the editor and the viewer show on their own (button labels, tooltips, field labels, hints, messages) comes from `EditorStrings`, in English by default. Pass your own to translate or reword it; anything you leave out keeps its default: +All the text the editor and the viewer show on their own (button labels, tooltips, field labels, hints, messages) comes from an `EditorStrings` object. English is the default, and Spanish and French ship with the package: + +```dart +EditorConfig(strings: EditorTranslations.es) // or EditorTranslations.fr +``` + +To follow the language of the app instead, look the texts up by language code. A language that is not bundled falls back to English: + +```dart +EditorConfig( + strings: EditorTranslations.forLanguage( + Localizations.localeOf(context).languageCode, + ), +) +``` + +The same `EditorConfig` works for `EditorJSView`, which uses a few of these texts too. + +#### Rewording a few texts + +Pass an `EditorStrings` with only the texts you want to change. Everything you leave out stays in English: ```dart EditorConfig( strings: EditorStrings( - paragraph: 'Párrafo', - addItem: 'Agregar elemento', - cancel: 'Cancelar', - save: 'Guardar', - heading: (level) => 'Encabezado $level', + addItem: 'New entry', + removeLastBlock: 'Delete last block', ), ) ``` -Texts that include a value, such as a heading level or a file size, are functions. The same `EditorConfig` works for `EditorJSView`, which uses a few of these texts too. +#### Adding a translation in your app + +1. Copy [`editor_strings_es.dart`](lib/src/presentation/config/translations/editor_strings_es.dart) into your project as a template. It lists every text, grouped by where it appears. +2. Rename the constant and translate each text. Texts that include a value, such as a heading level or a file size, are functions, written at the bottom of the file: + + ```dart + const EditorStrings editorStringsDe = EditorStrings( + paragraph: 'Absatz', + heading: _heading, + addItem: 'Element hinzufügen', + // ... every other text + ); + + String _heading(int level) => 'Überschrift $level'; + ``` + +3. Pass it to the editor, choosing by locale yourself if you support several languages: + + ```dart + EditorConfig(strings: editorStringsDe) + ``` + +A text you leave out is shown in English, and so is any text a later version of the package adds, until you translate it. + +#### Contributing a translation to the package + +1. Copy `editor_strings_es.dart` to `editor_strings_.dart` in [`lib/src/presentation/config/translations/`](lib/src/presentation/config/translations/), using the ISO 639-1 language code, and name the constant `editorStrings`. +2. Translate every text in it. +3. Register it in [`editor_translations.dart`](lib/src/presentation/config/translations/editor_translations.dart): add a `static const` for the language and an entry in `byLanguageCode`. +4. Run `fvm flutter test test/unit/translations_test.dart`. It fails if the file misses a text, contains one that does not exist, or is not registered. +5. Add the language to this section and to `CHANGELOG.md`. ### Pre-loading existing content into the editor diff --git a/lib/editorjs_flutter.dart b/lib/editorjs_flutter.dart index 74af085..1d96629 100644 --- a/lib/editorjs_flutter.dart +++ b/lib/editorjs_flutter.dart @@ -10,6 +10,7 @@ export 'src/presentation/controller/editor_controller.dart'; export 'src/presentation/config/block_editor_hooks.dart'; export 'src/presentation/config/editor_config.dart'; export 'src/presentation/config/editor_strings.dart'; +export 'src/presentation/config/translations/editor_translations.dart'; export 'src/presentation/config/editor_toolbar_item.dart'; export 'src/presentation/config/image_uploader.dart'; diff --git a/lib/src/presentation/config/translations/editor_strings_es.dart b/lib/src/presentation/config/translations/editor_strings_es.dart new file mode 100644 index 0000000..ec285bb --- /dev/null +++ b/lib/src/presentation/config/translations/editor_strings_es.dart @@ -0,0 +1,132 @@ +import '../editor_strings.dart'; + +/// Spanish texts for the editor and the viewer. +/// +/// Use it through `EditorTranslations`. To add a language, copy this file, +/// translate every text, and register the result in `EditorTranslations`. +const EditorStrings editorStringsEs = EditorStrings( + // Toolbar + paragraph: 'Párrafo', + paragraphLabel: 'T', + heading: _heading, + headingLabel: _headingLabel, + quote: 'Cita', + code: 'Código', + unorderedList: 'Lista con viñetas', + orderedList: 'Lista numerada', + checklist: 'Lista de verificación', + legacyChecklist: 'Lista de verificación (anterior)', + table: 'Tabla', + delimiter: 'Separador', + warning: 'Advertencia', + image: 'Imagen', + embed: 'Contenido incrustado', + linkPreview: 'Vista previa de enlace', + attachment: 'Archivo adjunto', + rawHtml: 'HTML sin procesar', + hyperlink: 'Hipervínculo', + undo: 'Deshacer', + redo: 'Rehacer', + removeLastBlock: 'Eliminar el último bloque', + addHyperlinkTitle: 'Agregar hipervínculo', + hyperlinkTitleHint: 'Título del enlace', + // Shared actions and field labels + add: 'Agregar', + cancel: 'Cancelar', + save: 'Guardar', + caption: 'Leyenda', + title: 'Título', + addItem: 'Agregar elemento', + // Block controls + moveUp: 'Mover arriba', + moveDown: 'Mover abajo', + deleteBlock: 'Eliminar bloque', + unsupportedBlock: _unsupportedBlock, + // Paragraph + paragraphHint: 'Escribe algo...', + bold: 'Negrita', + boldLabel: 'N', + italic: 'Cursiva', + italicLabel: 'K', + underline: 'Subrayado', + underlineLabel: 'S', + strikethrough: 'Tachado', + strikethroughLabel: 'T', + inlineCode: 'Código en línea', + highlight: 'Resaltar', + highlightLabel: 'marca', + link: 'Enlace', + linkLabel: 'enlace', + addLinkTitle: 'Agregar enlace', + editLinkTitle: 'Editar enlace', + linkAddress: 'Dirección del enlace', + removeLink: 'Quitar enlace', + // Header + headingLevel: 'Nivel de encabezado', + // List + listUnordered: 'Con viñetas', + listOrdered: 'Numerada', + listChecklist: 'Lista de verificación', + startWith: 'Empezar en', + counterNumeric: 'Números', + counterLowerRoman: 'Romanos en minúscula', + counterUpperRoman: 'Romanos en mayúscula', + counterLowerAlpha: 'Letras minúsculas', + counterUpperAlpha: 'Letras mayúsculas', + outdent: 'Reducir sangría', + indent: 'Aumentar sangría', + removeItem: 'Eliminar elemento', + checklistItemHint: 'Elemento de la lista...', + // Quote + quoteHint: 'Texto de la cita...', + quoteCaptionHint: 'Leyenda (opcional)', + align: 'Alinear:', + alignLeft: 'izquierda', + alignCenter: 'centro', + alignRight: 'derecha', + // Code + codeHint: 'Escribe el código...', + copy: 'Copiar', + // Warning + warningTitleHint: 'Título de la advertencia', + warningMessageHint: 'Mensaje de la advertencia...', + // Table + firstRowIsHeader: 'La primera fila es el encabezado', + removeRow: 'Eliminar fila', + removeColumn: 'Eliminar columna', + addRow: 'Fila', + addColumn: 'Columna', + // Image + camera: 'Cámara', + gallery: 'Galería', + imageUrl: 'URL de la imagen', + imageBorder: 'Borde', + imageStretch: 'Estirar', + imageBackground: 'Fondo', + imagePickFailed: 'No se pudo abrir la imagen.', + imageUploadFailed: 'No se pudo subir la imagen. Inténtalo de nuevo.', + // Embed + embedLink: 'Enlace del contenido', + embedService: _embedService, + embedUnsupported: 'Este enlace no es de un servicio compatible.', + embeddedContent: 'Contenido incrustado', + // Link preview + linkUrl: 'Enlace', + fetchPreview: 'Obtener vista previa', + description: 'Descripción', + previewImageUrl: 'URL de la imagen de vista previa', + noPreview: 'No hay vista previa disponible para este enlace.', + previewFailed: 'No se pudo obtener la vista previa.', + // Attachment + chooseFile: 'Elegir archivo', + fileUrl: 'URL del archivo', + fileSize: _fileSize, + attachFailed: 'No se pudo adjuntar el archivo.', + downloadFile: 'Descargar archivo', +); + +String _heading(int level) => 'Encabezado $level'; +String _headingLabel(int level) => 'H$level'; +String _unsupportedBlock(String type) => '[Bloque no compatible: $type]'; +String _embedService(String service) => 'Servicio: $service'; +String _fileSize(int bytes) => '$bytes bytes'; diff --git a/lib/src/presentation/config/translations/editor_strings_fr.dart b/lib/src/presentation/config/translations/editor_strings_fr.dart new file mode 100644 index 0000000..b6fd05f --- /dev/null +++ b/lib/src/presentation/config/translations/editor_strings_fr.dart @@ -0,0 +1,132 @@ +import '../editor_strings.dart'; + +/// French texts for the editor and the viewer. +/// +/// Use it through `EditorTranslations`. To add a language, copy this file, +/// translate every text, and register the result in `EditorTranslations`. +const EditorStrings editorStringsFr = EditorStrings( + // Toolbar + paragraph: 'Paragraphe', + paragraphLabel: 'T', + heading: _heading, + headingLabel: _headingLabel, + quote: 'Citation', + code: 'Code', + unorderedList: 'Liste à puces', + orderedList: 'Liste numérotée', + checklist: 'Liste de tâches', + legacyChecklist: 'Liste de tâches (ancienne)', + table: 'Tableau', + delimiter: 'Séparateur', + warning: 'Avertissement', + image: 'Image', + embed: 'Contenu intégré', + linkPreview: 'Aperçu de lien', + attachment: 'Pièce jointe', + rawHtml: 'HTML brut', + hyperlink: 'Lien hypertexte', + undo: 'Annuler', + redo: 'Rétablir', + removeLastBlock: 'Supprimer le dernier bloc', + addHyperlinkTitle: 'Ajouter un lien hypertexte', + hyperlinkTitleHint: 'Titre du lien', + // Shared actions and field labels + add: 'Ajouter', + cancel: 'Annuler', + save: 'Enregistrer', + caption: 'Légende', + title: 'Titre', + addItem: 'Ajouter un élément', + // Block controls + moveUp: 'Monter', + moveDown: 'Descendre', + deleteBlock: 'Supprimer le bloc', + unsupportedBlock: _unsupportedBlock, + // Paragraph + paragraphHint: 'Écrivez quelque chose...', + bold: 'Gras', + boldLabel: 'G', + italic: 'Italique', + italicLabel: 'I', + underline: 'Souligné', + underlineLabel: 'S', + strikethrough: 'Barré', + strikethroughLabel: 'B', + inlineCode: 'Code en ligne', + highlight: 'Surligner', + highlightLabel: 'marque', + link: 'Lien', + linkLabel: 'lien', + addLinkTitle: 'Ajouter un lien', + editLinkTitle: 'Modifier le lien', + linkAddress: 'Adresse du lien', + removeLink: 'Supprimer le lien', + // Header + headingLevel: 'Niveau de titre', + // List + listUnordered: 'À puces', + listOrdered: 'Numérotée', + listChecklist: 'Liste de tâches', + startWith: 'Commencer à', + counterNumeric: 'Chiffres', + counterLowerRoman: 'Romains minuscules', + counterUpperRoman: 'Romains majuscules', + counterLowerAlpha: 'Lettres minuscules', + counterUpperAlpha: 'Lettres majuscules', + outdent: 'Diminuer le retrait', + indent: 'Augmenter le retrait', + removeItem: "Supprimer l'élément", + checklistItemHint: 'Élément de la liste...', + // Quote + quoteHint: 'Texte de la citation...', + quoteCaptionHint: 'Légende (facultatif)', + align: 'Aligner :', + alignLeft: 'gauche', + alignCenter: 'centre', + alignRight: 'droite', + // Code + codeHint: 'Saisissez le code...', + copy: 'Copier', + // Warning + warningTitleHint: "Titre de l'avertissement", + warningMessageHint: "Message de l'avertissement...", + // Table + firstRowIsHeader: "La première ligne est l'en-tête", + removeRow: 'Supprimer la ligne', + removeColumn: 'Supprimer la colonne', + addRow: 'Ligne', + addColumn: 'Colonne', + // Image + camera: 'Appareil photo', + gallery: 'Galerie', + imageUrl: "URL de l'image", + imageBorder: 'Bordure', + imageStretch: 'Étirer', + imageBackground: 'Arrière-plan', + imagePickFailed: "Impossible d'ouvrir l'image.", + imageUploadFailed: "Échec de l'envoi. Réessayez.", + // Embed + embedLink: 'Lien du contenu', + embedService: _embedService, + embedUnsupported: "Ce lien ne provient pas d'un service pris en charge.", + embeddedContent: 'Contenu intégré', + // Link preview + linkUrl: 'Lien', + fetchPreview: "Récupérer l'aperçu", + description: 'Description', + previewImageUrl: "URL de l'image d'aperçu", + noPreview: 'Aucun aperçu disponible pour ce lien.', + previewFailed: "Impossible de récupérer l'aperçu.", + // Attachment + chooseFile: 'Choisir un fichier', + fileUrl: 'URL du fichier', + fileSize: _fileSize, + attachFailed: 'Impossible de joindre le fichier.', + downloadFile: 'Télécharger le fichier', +); + +String _heading(int level) => 'Titre $level'; +String _headingLabel(int level) => 'H$level'; +String _unsupportedBlock(String type) => '[Bloc non pris en charge : $type]'; +String _embedService(String service) => 'Service : $service'; +String _fileSize(int bytes) => '$bytes octets'; diff --git a/lib/src/presentation/config/translations/editor_translations.dart b/lib/src/presentation/config/translations/editor_translations.dart new file mode 100644 index 0000000..dbfd83d --- /dev/null +++ b/lib/src/presentation/config/translations/editor_translations.dart @@ -0,0 +1,46 @@ +import '../editor_strings.dart'; +import 'editor_strings_es.dart'; +import 'editor_strings_fr.dart'; + +/// The translations of the editor and viewer texts that ship with the package. +/// +/// ```dart +/// EditorConfig(strings: EditorTranslations.es) +/// +/// // Or follow the language of the app: +/// EditorConfig( +/// strings: EditorTranslations.forLanguage( +/// Localizations.localeOf(context).languageCode, +/// ), +/// ) +/// ``` +class EditorTranslations { + EditorTranslations._(); + + /// English, the default. + static const EditorStrings en = EditorStrings(); + + /// Spanish. + static const EditorStrings es = editorStringsEs; + + /// French. + static const EditorStrings fr = editorStringsFr; + + /// Every bundled translation by its ISO 639-1 language code. + static const Map byLanguageCode = { + 'en': en, + 'es': es, + 'fr': fr, + }; + + /// Returns the texts for [languageCode], or English when the language is + /// not bundled. + /// + /// Accepts a bare code (`es`) as well as a full locale tag (`es-MX`, + /// `fr_CA`); only the language part is used. + static EditorStrings forLanguage(String? languageCode) { + final language = + (languageCode ?? '').split(RegExp('[-_]')).first.toLowerCase(); + return byLanguageCode[language] ?? en; + } +} diff --git a/test/unit/translations_test.dart b/test/unit/translations_test.dart new file mode 100644 index 0000000..46cdef2 --- /dev/null +++ b/test/unit/translations_test.dart @@ -0,0 +1,172 @@ +import 'dart:io'; + +import 'package:editorjs_flutter/editorjs_flutter.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _configDir = 'lib/src/presentation/config'; + +/// The name of every text of [EditorStrings], read from its constructor. +Set _stringNames() { + final source = File('$_configDir/editor_strings.dart').readAsStringSync(); + final constructor = source.substring( + source.indexOf('const EditorStrings({'), + source.indexOf('});'), + ); + return RegExp(r'this\.(\w+) =') + .allMatches(constructor) + .map((m) => m.group(1)!) + .toSet(); +} + +/// The bundled translation files by language code. +Map _translationFiles() => { + for (final file in Directory('$_configDir/translations') + .listSync() + .whereType()) + if (RegExp(r'editor_strings_(\w+)\.dart$').firstMatch(file.path) + case final match?) + match.group(1)!: file, + }; + +/// The texts a translation file passes to the [EditorStrings] constructor. +Set _translatedNames(File file) { + final source = file.readAsStringSync(); + final arguments = source.substring( + source.indexOf('= EditorStrings('), + source.indexOf(');'), + ); + return RegExp(r'^ (\w+):', multiLine: true) + .allMatches(arguments) + .map((m) => m.group(1)!) + .toSet(); +} + +void main() { + group('bundled translation files', () { + final names = _stringNames(); + final files = _translationFiles(); + + test('Spanish and French are bundled', () { + expect(files.keys, containsAll(['es', 'fr'])); + expect(names.length, greaterThan(100)); + }); + + for (final entry in files.entries) { + test('${entry.key} translates every text and nothing else', () { + final translated = _translatedNames(entry.value); + expect( + names.difference(translated), + isEmpty, + reason: 'texts missing from ${entry.value.path}', + ); + expect( + translated.difference(names), + isEmpty, + reason: 'unknown texts in ${entry.value.path}', + ); + }); + + test('${entry.key} is registered in EditorTranslations', () { + expect(EditorTranslations.byLanguageCode, contains(entry.key)); + }); + } + }); + + group('EditorTranslations', () { + test('exposes each language', () { + expect(EditorTranslations.en.paragraph, 'Paragraph'); + expect(EditorTranslations.es.paragraph, 'Párrafo'); + expect(EditorTranslations.fr.paragraph, 'Paragraphe'); + expect(EditorTranslations.byLanguageCode.keys, ['en', 'es', 'fr']); + }); + + test('texts with a value include it', () { + expect(EditorTranslations.es.heading(2), 'Encabezado 2'); + expect(EditorTranslations.fr.heading(2), 'Titre 2'); + expect(EditorTranslations.es.headingLabel(3), 'H3'); + expect(EditorTranslations.es.fileSize(10), '10 bytes'); + expect(EditorTranslations.fr.fileSize(10), '10 octets'); + expect(EditorTranslations.es.embedService('vimeo'), 'Servicio: vimeo'); + expect(EditorTranslations.fr.embedService('vimeo'), 'Service : vimeo'); + expect( + EditorTranslations.es.unsupportedBlock('x'), + '[Bloque no compatible: x]', + ); + expect( + EditorTranslations.fr.unsupportedBlock('x'), + '[Bloc non pris en charge : x]', + ); + }); + + test('forLanguage accepts codes and locale tags, in any case', () { + expect(EditorTranslations.forLanguage('es'), same(EditorTranslations.es)); + expect( + EditorTranslations.forLanguage('es-MX'), + same(EditorTranslations.es), + ); + expect( + EditorTranslations.forLanguage('FR_ca'), + same(EditorTranslations.fr), + ); + expect(EditorTranslations.forLanguage('en'), same(EditorTranslations.en)); + }); + + test('forLanguage falls back to English', () { + for (final code in ['de', 'pt-BR', '', null]) { + expect( + EditorTranslations.forLanguage(code), + same(EditorTranslations.en), + reason: '$code', + ); + } + }); + }); + + group('in the editor', () { + const document = '{"blocks":[' + '{"type":"list","data":{"style":"ordered","meta":{},"items":' + '[{"content":"","meta":{},"items":[]}]}},' + '{"type":"image","data":{"file":{"url":""},"caption":""}}' + ']}'; + + Future pumpEditor(WidgetTester tester, EditorStrings strings) async { + await tester.binding.setSurfaceSize(const Size(2400, 2000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget(MaterialApp( + home: Scaffold( + body: EditorJSEditor( + controller: EditorController.fromJson(document), + config: EditorConfig(strings: strings), + ), + ), + )); + await tester.pumpAndSettle(); + } + + testWidgets('Spanish', (tester) async { + await pumpEditor(tester, EditorTranslations.es); + expect(find.byTooltip('Párrafo'), findsOneWidget); + expect(find.byTooltip('Encabezado 2'), findsOneWidget); + expect(find.text('Agregar elemento'), findsOneWidget); + expect(find.text('Empezar en'), findsOneWidget); + expect(find.text('Cámara'), findsOneWidget); + expect(find.byTooltip('Deshacer'), findsOneWidget); + // None of the English defaults they replace is left. + expect(find.byTooltip('Paragraph'), findsNothing); + expect(find.text('Add item'), findsNothing); + expect(find.text('Camera'), findsNothing); + }); + + testWidgets('French', (tester) async { + await pumpEditor(tester, EditorTranslations.fr); + expect(find.byTooltip('Paragraphe'), findsOneWidget); + expect(find.byTooltip('Titre 2'), findsOneWidget); + expect(find.text('Ajouter un élément'), findsOneWidget); + expect(find.text('Commencer à'), findsOneWidget); + expect(find.text('Appareil photo'), findsOneWidget); + expect(find.byTooltip('Rétablir'), findsOneWidget); + expect(find.text('Add item'), findsNothing); + }); + }); +} From 79e41c5daabcdc4b9c781dc2624af9d79dbe3ebd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marco=20Rami=CC=81rez?= Date: Tue, 10 Nov 2026 11:35:37 -0600 Subject: [PATCH 16/16] Release 1.0.0 Set the version to 1.0.0 and turn the unreleased changelog section into the 1.0.0 entry. Fixes found while preparing the release: - Cap html below 0.15.7. flutter_html 3.0.0 calls a function that html 0.15.7 removed, so an app resolving to it failed to compile. - Depend on flutter_html ^3.0.0 instead of ^3.0.0-beta.2. - Declare Flutter 3.27 / Dart 3.6 as the minimum; the quote renderer already needed it. Also run CI for develop, and describe git flow in CLAUDE.md and the README. Co-Authored-By: Claude --- .github/workflows/ci.yml | 4 ++-- CHANGELOG.md | 11 ++++++++++- CLAUDE.md | 32 +++++++++++++++++++++++--------- README.md | 14 +++++++++----- example/pubspec.lock | 2 +- pubspec.lock | 2 +- pubspec.yaml | 12 ++++++++---- 7 files changed, 54 insertions(+), 23 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e0ed498..1a4c123 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -2,9 +2,9 @@ name: CI on: push: - branches: [master] + branches: [master, develop] pull_request: - branches: [master] + branches: [master, develop] jobs: test: diff --git a/CHANGELOG.md b/CHANGELOG.md index c2e0097..a659d18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -## [Unreleased] — towards 1.0.0 +## [1.0.0] - 2026-11-10 — EditorJS 2.31 parity ### Lossless round-trip with current EditorJS (2.31) * **Block ids and tunes are preserved.** `id` and `tunes` are read into the new `BlockDocument.metadata` (`BlockMetadata`) and written back on serialize. `EditorController.blockIds` now holds the EditorJS ids (kept from the document, generated in EditorJS's own 10-character format for new blocks) and the new `EditorController.blockTunes` exposes each block's tunes. Both follow their block through update, move and undo/redo. @@ -36,6 +36,15 @@ * **Every label, tooltip, hint and message can be translated or reworded.** New `EditorConfig.strings` takes an `EditorStrings`, which holds all 104 texts the editor and the viewer show on their own, with English defaults; override only the ones you need. Texts that include a value (a heading level, a file size) are functions. Until now all text was hard-coded in English. * **Spanish and French are bundled.** `EditorTranslations.es` and `EditorTranslations.fr` are complete translations; `EditorTranslations.forLanguage(code)` picks one from a language code or locale tag and falls back to English. The README explains how to add another language, in an app or in the package. +### Requirements and dependencies +* **The minimum is now declared as Flutter 3.27 (Dart 3.6).** Earlier releases declared Flutter 3.10 but already used `Color.withValues`, which arrived in 3.27, so on an older Flutter the package installed and then failed to compile. Nothing changes for apps that could build it. +* **`html` is capped below 0.15.7.** `html` 0.15.7 removed a function that `flutter_html` 3.0.0 calls, so an app that resolved to it failed to compile. The package now depends on `html: ">=0.15.5 <0.15.7"` until `flutter_html` supports the newer version. An app that needs `html` 0.15.7 or later for another package will get a version conflict. +* `flutter_html`: `^3.0.0-beta.2` → `^3.0.0`. The pre-release versions are no longer accepted. + +### CI and workflow +* CI also runs on pushes and pull requests to `develop`. +* `CLAUDE.md` and the README describe the git flow the project uses: work branches from `develop`, releases from `release/` into `master`. + ### Parser hardening * A field of the wrong type no longer throws out of `EditorJSView` / `EditorController.fromJson`. Every built-in mapper now reads through tolerant helpers; previously `linkTool.meta: []`, a non-string list `style`, a non-string paragraph `text` and a non-integer document `time` each raised a `TypeError`. * `time` accepts integers, doubles and numeric strings; header `level` accepts doubles. diff --git a/CLAUDE.md b/CLAUDE.md index d12e2f4..ffe3ff6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ fvm flutter test test/editorjs_flutter_test.dart ## Architecture -The package follows **Clean Architecture** with three strict layers. Dependencies only flow inward (presentation → data → domain). No new external dependencies — only `flutter_html`, `image_picker`, `url_launcher`, and Flutter's built-in `ChangeNotifier`. +The package follows **Clean Architecture** with three strict layers. Dependencies only flow inward (presentation → data → domain). No new external dependencies — only `flutter_html`, `image_picker`, `url_launcher`, and Flutter's built-in `ChangeNotifier`. (`html` is listed in `pubspec.yaml` only to cap the version `flutter_html` resolves to; the package does not import it.) ``` lib/src/ @@ -176,27 +176,33 @@ When building new features, always work bottom-up: ## Git Workflow -**This repo has branch protection. Direct commits to `master` are not allowed.** +**This repo follows git flow. Direct commits to `master` or `develop` are not allowed.** + +- `master` holds released versions only. +- `develop` is the integration branch: every feature, fix and chore is merged here first. +- `release/` is cut from `develop` when a version is ready, and is merged into `master`. ### Before starting any coding task -1. Ensure `master` is up to date and create a new branch: +1. Ensure `develop` is up to date and create a new branch from it: ```bash - git checkout master + git checkout develop git pull git checkout -b / ``` + Always branch from `develop`, never from another work branch: one branch and one PR per task. 2. Use these branch name prefixes: - `feat/` — new feature or block type - `fix/` — bug fix - `refactor/` — internal restructuring with no behaviour change - `chore/` — dependency bumps, tooling, docs + - `release/` — release branch, named after the version (`release/1.0.0`) ### Before finishing any coding task 1. Run `fvm flutter analyze` — must report **no issues** before marking work done. 2. Generate a `PR_DESCRIPTION.md` file at the repo root (see template below). -3. All changes go to `master` via Pull Request only — never push directly. +3. All changes go to `develop` via Pull Request only — never push directly. Only a release branch is merged into `master`. 4. Delete `PR_DESCRIPTION.md` after the PR is merged. ### PR_DESCRIPTION.md template @@ -227,15 +233,23 @@ When building new features, always work bottom-up: - [ ] Demo app tested manually on at least one platform ``` +### Releasing + +1. Cut `release/` from `develop`. +2. On that branch, set the version in `pubspec.yaml`, turn the `[Unreleased]` section of `CHANGELOG.md` into the entry for the version, and update the version references in `README.md` and in this file. Apart from that, only fixes found while preparing the release go on this branch. +3. Open a PR from the release branch into `master`. CI must pass. +4. After the merge, merge `master` back into `develop`. + --- ## Versioning -Current version: `0.5.0` (in `pubspec.yaml`). +Current version: `1.0.0` (in `pubspec.yaml`). -When making changes, always update `CHANGELOG.md` with a new entry at the top following the existing format: -- Bump the patch version for bug fixes -- Bump the minor version for new features or breaking API changes +The package follows semantic versioning. When making changes, add a note to the `## [Unreleased]` section at the top of `CHANGELOG.md` (create it if it is missing), following the existing format. Do not change the version on a work branch; it is set on the release branch: +- Patch version for bug fixes +- Minor version for new features +- Major version for breaking changes to the public API - Keep `pubspec.yaml` version in sync with `CHANGELOG.md` ## Known Issues / Backlog diff --git a/README.md b/README.md index 643566c..7db4c25 100644 --- a/README.md +++ b/README.md @@ -6,10 +6,12 @@ A viewer and editor compatible with the [EditorJS](https://editorjs.io/) JSON sc [![CI](https://github.com/DEV1-Softworks/editorjs-flutter/actions/workflows/ci.yml/badge.svg)](https://github.com/DEV1-Softworks/editorjs-flutter/actions/workflows/ci.yml) [![codecov](https://codecov.io/gh/DEV1-Softworks/editorjs-flutter/branch/master/graph/badge.svg)](https://codecov.io/gh/DEV1-Softworks/editorjs-flutter) -# DISCLAIMER -This package is in active development (pre-1.0). The public API is stable and the Clean Architecture foundation is solid, but some editor features are still being refined. Suitable for early production use with the understanding that minor API changes may occur in future minor versions. +# Status +Version 1.0 is the first stable release. It reads and writes the JSON of EditorJS 2.31, including the `@editorjs/list` 2.x format, and saving a document keeps everything that was loaded: block ids, tunes, and blocks from plugins this package does not know. -Requires **Flutter 3.10+** and **Dart 3.0+**. +From 1.0 on the package follows [semantic versioning](https://dart.dev/tools/pub/versioning): the public API changes incompatibly only in a new major version. + +Requires **Flutter 3.27+** (Dart 3.6+). # Installation @@ -17,11 +19,13 @@ Add the following to your `pubspec.yaml` dependencies: ```yaml dependencies: - editorjs_flutter: ^0.5.0-beta.1 + editorjs_flutter: ^1.0.0 ``` Then run `flutter pub get`. +The package limits `html` to versions below 0.15.7, because `flutter_html` 3.0.0 does not compile with 0.15.7. If `pub get` reports a conflict on `html`, another of your dependencies requires the newer version. + # Usage ## Viewer @@ -347,7 +351,7 @@ AI tools (including Claude Code) are permitted to assist with contributions to t The following rules apply when using Claude Code (`claude` CLI) on this repository: -1. **Branch before coding.** Claude Code must create and checkout a new branch from `master` before writing any code. Branch names must follow the `feat/`, `fix/`, `refactor/`, or `chore/` prefix convention. Direct commits to `master` are never allowed. +1. **Branch before coding.** Claude Code must create and checkout a new branch from `develop` before writing any code, one branch per task and never on top of another work branch. Branch names must follow the `feat/`, `fix/`, `refactor/`, or `chore/` prefix convention (`release/` for a release). Direct commits to `master` or `develop` are never allowed. `CLAUDE.md` describes the full workflow. 2. **Generate a PR description before finishing.** At the end of every coding session, Claude Code must produce a `PR_DESCRIPTION.md` file at the repo root summarising the changes (title, type of change, summary, breaking changes, migration notes, test plan checklist). This file is ephemeral — delete it after the PR is merged. 3. **No autonomous commits.** Claude Code must never commit or push changes without explicit human instruction. Every commit requires a human to review the diff and approve it first. 4. **No force pushes.** Claude Code must never run `git push --force` or any destructive git operation (`reset --hard`, `branch -D`, etc.) without explicit human confirmation. diff --git a/example/pubspec.lock b/example/pubspec.lock index 5540466..b62d24d 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -47,7 +47,7 @@ packages: path: ".." relative: true source: path - version: "0.5.0" + version: "1.0.0" file_selector_linux: dependency: transitive description: diff --git a/pubspec.lock b/pubspec.lock index c9d0db1..49a7caa 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -145,7 +145,7 @@ packages: source: sdk version: "0.0.0" html: - dependency: transitive + dependency: "direct main" description: name: html sha256: "6d1264f2dffa1b1101c25a91dff0dc2daee4c18e87cd8538729773c073dbf602" diff --git a/pubspec.yaml b/pubspec.yaml index fe31eb9..b3f5c77 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: editorjs_flutter description: "Flutter viewer and editor widgets for the EditorJS JSON schema. Supports 14 built-in block types with a Clean Architecture extension point for custom blocks." -version: 0.5.0-beta.1 +version: 1.0.0 homepage: https://labs.dev1.mx/editorjs-flutter repository: https://github.com/DEV1-Softworks/editorjs-flutter issue_tracker: https://github.com/DEV1-Softworks/editorjs-flutter/issues @@ -11,13 +11,17 @@ topics: - content environment: - sdk: ">=3.0.0 <4.0.0" - flutter: ">=3.10.0" + sdk: ">=3.6.0 <4.0.0" + flutter: ">=3.27.0" dependencies: flutter: sdk: flutter - flutter_html: ^3.0.0-beta.2 + flutter_html: ^3.0.0 + # Not used directly. flutter_html 3.0.0 calls a function that html 0.15.7 + # removed, so an app that resolves to 0.15.7 fails to compile. Remove this + # cap once flutter_html supports it. + html: ">=0.15.5 <0.15.7" image_picker: ^1.0.0 url_launcher: ^6.2.0