diff --git a/README.md b/README.md index 65cec03..3e8da5c 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ | Package | Use it for | |---|---| | [`val_highlight`](val_highlight/) | The engine, in pure Dart: 55 languages plus a generic fallback, flat tokens, incremental updates, language detection, 8 themes, VS Code theme import and HTML output. Runs on the VM, in Flutter and on the web. | -| [`val_highlight_flutter`](val_highlight_flutter/) | Flutter widgets: `CodeView` to show code, `CodeField` to edit it, `HighlightTextController`, and `CodeTheme` for app-wide defaults. | +| [`val_highlight_flutter`](val_highlight_flutter/) | Flutter widgets: `CodeView` to show code, `HighlightTextController` for any text field, and `CodeTheme` for app-wide defaults, in any app; and `CodeField`, an editor built on `material_ui`. | A `val_highlight_jaspr` package is planned, built on the same engine. @@ -99,7 +99,7 @@ pin. ## Built by Val -`val_highlight` is part of [Val](https://useval.io), the live visual layer +`val_highlight` is part of [Val](https://useval.ai), the live visual layer for AI agents. ## 💬 Community diff --git a/docs/api/_code-field.mdx b/docs/api/_code-field.mdx index 4fef5b7..78da8c4 100644 --- a/docs/api/_code-field.mdx +++ b/docs/api/_code-field.mdx @@ -22,10 +22,14 @@ the text's own layout, so wrapped lines line up. Laying out a text field is proportional to its styled runs, so for documents longer than `styleAllBelow` lines only the visible lines, plus -`margin` lines on each side, are colored. The window follows scrolling +`styleMargin` lines on each side, are colored. The window follows scrolling (of the field itself or of an enclosing scroll view) and is computed from the laid-out text, so wrapped lines are handled exactly. +The field is built on `material_ui`'s `TextField`, so it needs a +`material_ui` `MaterialApp` (or `Material`) above it. Code is always +laid out left to right, even in a right-to-left app. + ```dart const CodeField({ Key? key, @@ -42,13 +46,13 @@ const CodeField({ ScrollController? scrollController, TextAlignVertical? textAlignVertical, int styleAllBelow = 300, - int margin = 150, + int styleMargin = 150, String indent = ' ', CodeEditing editing = const CodeEditing(), Map? shortcuts, List? inputFormatters, UndoHistoryController? undoController, - bool lineNumbers = false, + bool? lineNumbers, int firstLineNumber = 1, TextStyle? gutterStyle, Set highlightedLines = const {}, @@ -76,13 +80,13 @@ Creates a code editor. | `scrollController` | `ScrollController?` | | Scroll controller for the field's own scrolling. | | `textAlignVertical` | `TextAlignVertical?` | | Vertical alignment of the text. | | `styleAllBelow` | `int` | `300` | Documents with at most this many lines are colored in full. | -| `margin` | `int` | `150` | Lines colored beyond each edge of the visible area. | +| `styleMargin` | `int` | `150` | Lines colored beyond each edge of the visible area, once the document is longer than `styleAllBelow` lines. | | `indent` | `String` | `' '` | Text inserted by Tab and removed by Shift+Tab, such as two spaces or `'\t'`. Enter keeps the current line's indentation, adding one level after an opening `{`, `[`, `(` or `:`. | | `editing` | `CodeEditing` | `const CodeEditing()` | What typing, Enter and Backspace do beyond inserting text. Use `CodeEditing.none` for a plain text field. | | `shortcuts` | `Map?` | | Keys and the intents they send. Defaults to `defaultShortcuts`; pass `const {}` for none, so Tab moves focus as in other fields. | -| `inputFormatters` | `List?` | | Formatters applied after the editing behavior, such as a length limit. | +| `inputFormatters` | `List?` | | Formatters applied after the editing behavior, such as a length limit. Edits made by shortcuts, such as Tab, go through them too. | | `undoController` | `UndoHistoryController?` | | Controls the field's undo history, as in `TextField.undoController`. Every edit the field makes itself — an auto-closed pair, a toggled comment, an indent — is a single undo step. | -| `lineNumbers` | `bool` | `false` | Whether to show line numbers in a gutter. | +| `lineNumbers` | `bool?` | | Whether to show line numbers in a gutter. Defaults to `CodeThemeData.lineNumbers`, or `false`. | | `firstLineNumber` | `int` | `1` | Number shown for the first line. | | `gutterStyle` | `TextStyle?` | | Style of the line numbers. Defaults to the code style in a faded text color. | | `highlightedLines` | `Set` | `const {}` | Line numbers, as shown in the gutter, to highlight. | diff --git a/docs/api/_code-view.mdx b/docs/api/_code-view.mdx index c4c747f..7c8c17b 100644 --- a/docs/api/_code-view.mdx +++ b/docs/api/_code-view.mdx @@ -8,11 +8,15 @@ Shows syntax-highlighted code. CodeView(source, language: dartLanguage) ``` -Everything else is optional. The theme follows the app's brightness -(see `CodeTheme` for app-wide defaults). Results are cached, and inputs -above `CodeHighlighter.isolateThreshold` are highlighted in a background +Everything else is optional. The theme follows the brightness (see +`CodeTheme` for app-wide defaults). Results are cached, and inputs above +`CodeHighlighter.isolateThreshold` are highlighted in a background isolate while plain text is shown. +Code is always laid out left to right, even in a right-to-left app. To +let people select and copy it, put it — or the page around it — inside +a `SelectionArea`; line numbers are never selected. + Short code renders as one text block. Code with more than `virtualizeAbove` lines, placed where its height is bounded, renders one row per line in a lazy list, so only visible lines are laid out. @@ -25,14 +29,13 @@ const CodeView( List detectLanguages = const [], Grammar fallbackLanguage = genericLanguage, ValTheme? theme, - TextStyle? textStyle, + TextStyle? style, EdgeInsetsGeometry? padding, bool? lineNumbers, int firstLineNumber = 1, Set highlightedLines = const {}, Color? highlightColor, bool wrap = false, - bool selectable = true, CodeHighlighter? highlighter, int virtualizeAbove = 1000, CodeGutterBuilder? gutterBuilder, @@ -53,20 +56,19 @@ Creates a code view. | `fallbackLanguage` | `Grammar` | `genericLanguage` | Language used when `language` is `null` and detection finds nothing. Defaults to `genericLanguage`, which highlights what most languages share. Use `plainTextLanguage` for no highlighting. | | `detectLanguages` | `List` | `const []` | Candidates for detection when `language` is `null`. | | `theme` | `ValTheme?` | | Color theme. Defaults to `CodeTheme` or the built-in light/dark theme. | -| `textStyle` | `TextStyle?` | | Text style merged over the default monospace style. | -| `padding` | `EdgeInsetsGeometry?` | | Padding inside the background. Defaults to `CodeTheme.padding`, or 16 on every side. | -| `lineNumbers` | `bool?` | | Whether to show line numbers. Defaults to `CodeTheme.lineNumbers`, or `false`. | +| `style` | `TextStyle?` | | Text style merged over the default code style (`CodeTheme.textStyleOf`). | +| `padding` | `EdgeInsetsGeometry?` | | Padding inside the background. Defaults to `CodeThemeData.padding`, or 16 on every side. | +| `lineNumbers` | `bool?` | | Whether to show line numbers. Defaults to `CodeThemeData.lineNumbers`, or `false`. | | `firstLineNumber` | `int` | `1` | Number shown for the first line. | | `highlightedLines` | `Set` | `const {}` | Line numbers (as shown in the gutter) to highlight. | | `highlightColor` | `Color?` | | Background for `highlightedLines`. | | `wrap` | `bool` | `false` | Whether long lines wrap. When `false`, code scrolls horizontally. | -| `selectable` | `bool` | `true` | Whether the code can be selected and copied. | | `highlighter` | `CodeHighlighter?` | | Highlighter to use. Defaults to `CodeHighlighter.shared`. | | `virtualizeAbove` | `int` | `1000` | Line count above which rows are built lazily. | | `gutterBuilder` | `CodeGutterBuilder?` | | Custom gutter cells. | | `lineBuilder` | `CodeLineBuilder?` | | Custom rows. Setting this always renders one row per line. | | `header` | `Widget?` | | A widget shown above the code, such as a title or copy button. | -| `scrollController` | `ScrollController?` | | Vertical scroll controller for the lazy list. | +| `scrollController` | `ScrollController?` | | Vertical scroll controller for the lazy list. Only attached while the code is laid out lazily (see `virtualizeAbove`). | | `onTokenTap` | `ValueChanged?` | | Called when a token is tapped, such as an identifier to jump to. Whitespace is not tappable. | | `spanBuilder` | `CodeSpanBuilder?` | | Builds each token's span, for hover effects, links, tooltips or custom styling. Takes priority over `onTokenTap`. | @@ -99,27 +101,47 @@ Creates a token. |---|---|---| | `scope` | `String?` | Innermost scope, or `null` for plain text. | +### `CodeLineDetails` + +One line of a `CodeView`, as passed to `CodeView.gutterBuilder` and +`CodeView.lineBuilder`. + +```dart +const CodeLineDetails({ + required int line, + required int lineNumber, + required bool highlighted, +}) +``` + +Creates the details of a line. + +| Field | Type | Default | Description | +|---|---|---|---| +| `line` | `int` | *required* | Zero-based index of the line in the code. | +| `lineNumber` | `int` | *required* | Number shown in the gutter: `line` plus `CodeView.firstLineNumber`. | +| `highlighted` | `bool` | *required* | Whether `lineNumber` is in `CodeView.highlightedLines`. | + ### `CodeGutterBuilder` -Builds the gutter cell for `lineNumber`. Return a fixed-width widget so -rows stay aligned. +Builds the gutter cell for `line`. Return a fixed-width widget so rows +stay aligned. ```dart typedef CodeGutterBuilder = Widget Function( BuildContext context, - int lineNumber, - bool highlighted, + CodeLineDetails line, ) ``` ### `CodeLineBuilder` -Wraps the row for zero-based `line`. `child` is the default row. +Wraps the row for `line`. `child` is the default row. ```dart typedef CodeLineBuilder = Widget Function( BuildContext context, - int line, + CodeLineDetails line, Widget child, ) ``` diff --git a/docs/api/_highlighting.mdx b/docs/api/_highlighting.mdx index 3350b75..26f8839 100644 --- a/docs/api/_highlighting.mdx +++ b/docs/api/_highlighting.mdx @@ -78,6 +78,7 @@ cached per stack id stay valid; later results may only add stacks. | `tokenAt(int offset)` | `int` | Index of the token covering `offset`, or `tokenCount` if `offset` is at or past the end. | | `lineCount` | `int` | Number of lines. Empty code has one empty line, and a trailing `\n` starts a final empty line. | | `lineStart(int line)` | `int` | Start offset of line `line`. | +| `lineAt(int offset)` | `int` | The line holding `offset`. An offset at a line break belongs to the line the break ends; offsets before the start or past the end belong to the first or last line. | | `lineEnd(int line)` | `int` | End offset of line `line`, excluding its `\n` or `\r\n`. | | `forEachSegment(…)` | `void` | Calls `segment` for each piece of line `line`, in order, with the piece's offsets and scope stack. Pieces never include the line break. | | `isStringOrCommentAt(int offset)` | `bool` | Whether the character at `offset` is inside a string, comment or regular expression. Interpolations inside strings count as code. | diff --git a/docs/api/_libraries.mdx b/docs/api/_libraries.mdx index fd6bb5c..316bc0b 100644 --- a/docs/api/_libraries.mdx +++ b/docs/api/_libraries.mdx @@ -6,6 +6,7 @@ | `package:val_highlight/languages/all.dart` | Every built-in language, for apps that want them all. | | `package:val_highlight/themes/all.dart` | Every built-in theme. | | `package:val_highlight/val_highlight.dart` | Fast, light, fully customizable syntax highlighting in pure Dart. | +| `package:val_highlight_flutter/material.dart` | `CodeField`, a code editor built on `material_ui`'s `TextField`: everything in `val_highlight_flutter.dart`, plus the editor. | | `package:val_highlight_flutter/val_highlight_flutter.dart` | Flutter widgets for `val_highlight`. |
@@ -49,6 +50,22 @@ in `advanced.dart`.
+
+package:val_highlight_flutter/material.dart: more + +```dart +import 'package:val_highlight_flutter/material.dart'; +import 'package:val_highlight/languages/dart.dart'; + +CodeField(controller: HighlightTextController(language: dartLanguage)) +``` + +The field needs a `material_ui` `MaterialApp` (or `Material`) above it. +In an app with another design system, give your own text field a +`HighlightTextController` and a `CodeEditingFormatter` instead. + +
+
package:val_highlight_flutter/val_highlight_flutter.dart: more @@ -59,8 +76,12 @@ import 'package:val_highlight/languages/dart.dart'; CodeView(source, language: dartLanguage) ``` -This library re-exports `package:val_highlight/val_highlight.dart`, so -one import covers the core API. Languages and themes are separate -imports under `package:val_highlight/languages/` and `themes/`. +This library needs only Flutter's widgets layer, so it works in any app, +whatever its design system. The code editor, `CodeField`, is built on +`material_ui` and is in `package:val_highlight_flutter/material.dart`. + +It re-exports `package:val_highlight/val_highlight.dart`, so one import +covers the core API. Languages and themes are separate imports under +`package:val_highlight/languages/` and `themes/`.
diff --git a/docs/api/_text-field.mdx b/docs/api/_text-field.mdx index c94aac1..331c831 100644 --- a/docs/api/_text-field.mdx +++ b/docs/api/_text-field.mdx @@ -10,7 +10,9 @@ TextField(controller: controller, maxLines: null, style: monospace); ``` Edits are highlighted incrementally: only the lines an edit can affect -are re-scanned, so typing stays fast in large documents. +are re-scanned, so typing stays fast in large documents. A plain +`TextField` still lays out and colors its whole text on every change; +for long text use `CodeField`, which colors only the lines on screen. ```dart HighlightTextController({ @@ -23,26 +25,16 @@ HighlightTextController({ Creates a controller for `language`. -`theme` defaults to `CodeTheme` or the built-in theme for the app's -brightness. `registry` resolves languages named inside the text, such -as Markdown code fences. +`theme` defaults to `CodeTheme`'s theme for the current brightness. +`registry` resolves languages named inside the text, such as Markdown +code fences. | Member | Type | Description | |---|---|---| -| `window` | `({int first, int last})?` | Zero-based lines to color, or `null` for all of them. *Settable.* | | `language` | `Grammar` | The language of the text. Setting it re-highlights everything. *Settable.* | -| `theme` | `ValTheme?` | The theme, or `null` to follow the app. *Settable.* | +| `theme` | `ValTheme?` | The theme, or `null` to follow `CodeTheme`. *Settable.* | | `result` | `HighlightResult` | The highlight result for the current text. | -
-window: more - -Laying out a text field with many thousands of styled runs is slow, so -for large documents only the visible lines, plus a margin, need -colors. `CodeField` sets this automatically as you scroll. - -
- ### `CodeEditingFormatter` Applies `CodeEditing` to text typed into a field driven by a @@ -64,6 +56,10 @@ with hardware keyboards, on-screen keyboards and voice input. Text being composed by an input method is never changed. Each change it makes is a single edit, so one undo reverts it. +What it needs to remember between edits, such as which closers it +inserted, is kept on the `controller`, so creating a new formatter in +each build is fine. + ```dart CodeEditingFormatter({ required HighlightTextController controller, diff --git a/docs/api/_themes.mdx b/docs/api/_themes.mdx index 877b31a..f6780ab 100644 --- a/docs/api/_themes.mdx +++ b/docs/api/_themes.mdx @@ -106,20 +106,69 @@ Creates a style. ### `CodeTheme` -App-wide defaults for code widgets, set once on `ThemeData.extensions`. +Sets `CodeThemeData` for the code widgets below it. + +It works in any app, whatever its design system. Put one above your +app's content, for example in `MaterialApp.builder`, so it can follow +the app's own brightness: ```dart MaterialApp( - theme: ThemeData(extensions: [CodeTheme(light: myTheme)]), + builder: (context, child) => CodeTheme( + data: CodeThemeData( + light: sepiaTheme, + dark: dimTheme, + brightness: Theme.of(context).brightness, + ), + child: child!, + ), ) ``` -Anything set directly on a widget wins over these defaults. +Without a `CodeTheme`, the widgets use `lightTheme` or `darkTheme` by +the platform's brightness. ```dart const CodeTheme({ + Key? key, + required CodeThemeData data, + required Widget child, +}) +``` + +Provides `data` to the code widgets in `child`. + +| Field | Type | Default | Description | +|---|---|---|---| +| `data` | `CodeThemeData` | *required* | The defaults. | + +| Member | Type | Description | +|---|---|---| +| `static maybeOf(BuildContext context)` | `CodeThemeData?` | The nearest `CodeThemeData`, if any. | +| `static of(BuildContext context)` | `CodeThemeData` | The nearest `CodeThemeData`, or the default one. | +| `static brightnessOf(BuildContext context)` | `Brightness` | The brightness the code widgets use: `CodeThemeData.brightness`, or the platform's. | +| `static resolve(BuildContext context, [ValTheme? override])` | `ValTheme` | The `ValTheme` to use: `override` if given, otherwise the default for `brightnessOf`. | +| `static textStyleOf(BuildContext context, [TextStyle? override])` | `TextStyle` | The default code text style: monospace, merged with `CodeThemeData.textStyle` and then `override`. | + +
+static textStyleOf: more + +Letter and word spacing are fixed at zero so an app-wide text theme +cannot stretch code or its line numbers. + +
+ +### `CodeThemeData` + +App-wide defaults for the code widgets, provided by a `CodeTheme`. + +Anything set directly on a widget wins over these defaults. + +```dart +const CodeThemeData({ ValTheme? light, ValTheme? dark, + Brightness? brightness, TextStyle? textStyle, EdgeInsetsGeometry? padding, bool? lineNumbers, @@ -130,26 +179,26 @@ Creates code defaults. | Field | Type | Description | |---|---|---| -| `light` | `ValTheme?` | Theme used when the app is light. Defaults to `lightTheme`. | -| `dark` | `ValTheme?` | Theme used when the app is dark. Defaults to `darkTheme`. | +| `light` | `ValTheme?` | Theme used when `brightness` is light. Defaults to `lightTheme`. | +| `dark` | `ValTheme?` | Theme used when `brightness` is dark. Defaults to `darkTheme`. | +| `brightness` | `Brightness?` | Whether to use `light` or `dark`. Defaults to the platform's brightness, from `MediaQuery`. Set it from your app's theme when the app does not follow the platform: | | `textStyle` | `TextStyle?` | Base text style for code, merged over the default monospace style. | -| `padding` | `EdgeInsetsGeometry?` | Padding around code blocks. | -| `lineNumbers` | `bool?` | Whether code blocks show line numbers. | - -| Member | Type | Description | -|---|---|---| -| `static maybeOf(BuildContext context)` | `CodeTheme?` | The nearest `CodeTheme`, if any. | -| `static resolve(BuildContext context, [ValTheme? override])` | `ValTheme` | The `ValTheme` to use: `override` if given, otherwise the app default for the current brightness. | -| `static textStyleOf(BuildContext context, [TextStyle? override])` | `TextStyle` | The default code text style: monospace, merged with `CodeTheme` and then `override`. | +| `padding` | `EdgeInsetsGeometry?` | Padding around code in `CodeView`. | +| `lineNumbers` | `bool?` | Whether `CodeView` and `CodeField` show line numbers. |
-static textStyleOf: more +brightness: more -Letter and word spacing are fixed at zero so an app-wide text theme -cannot stretch code or its line numbers. +```dart +CodeThemeData(brightness: Theme.of(context).brightness) +```
+| Member | Type | Description | +|---|---|---| +| `copyWith({…})` | `CodeThemeData` | Returns a copy with the given fields replaced. | + ### `allThemes` Every built-in theme. diff --git a/docs/components/code-field.mdx b/docs/components/code-field.mdx index 8f33a60..0aefaec 100644 --- a/docs/components/code-field.mdx +++ b/docs/components/code-field.mdx @@ -20,11 +20,24 @@ highlighted, and the parenthesis before the caret and its match are marked. ## Usage -`CodeField` is a multi-line `TextField` for code. Its text, language and theme -live in a `HighlightTextController`: create it once, change -`controller.language` or `controller.theme` whenever you like, and dispose it -with the widget that owns it. `controller.result` is the current -`HighlightResult`. +```dart +import 'package:val_highlight/languages/dart.dart'; +import 'package:val_highlight_flutter/material.dart'; + +CodeField(controller: controller) +``` + +`CodeField` is a multi-line `TextField` for code, built on `material_ui`, so +it comes from `package:val_highlight_flutter/material.dart` and needs a +`material_ui` `MaterialApp` above it. In an app with another design system, +give your own text field a `HighlightTextController` and a +`CodeEditingFormatter`; see [highlighted TextField](/docs/components/text-field/). + +Its text, language and theme live in a `HighlightTextController`: create it +once, change `controller.language` or `controller.theme` whenever you like, +and dispose it with the widget that owns it. `controller.result` is the +current `HighlightResult`. Code is always laid out left to right, even in a +right-to-left app. `CodeField` paints no background, so paint the theme's behind it, as the example does. `CodeTheme.resolve(context, controller.theme)` returns the @@ -104,8 +117,8 @@ CodeField( ) ``` -The gutter, the line bands and the bracket marks are painted from the text's -own layout, so they line up with wrapped lines, only visible lines are +`lineNumbers` defaults to `CodeTheme`'s, or off. The gutter, the line bands +and the bracket marks are painted from the text's own layout, so they line up with wrapped lines, only visible lines are painted, and they follow the text when a font finishes loading late. The gutter has room for at least two digits and widens when the line count gains one. `firstLineNumber`, `gutterStyle`, `highlightColor`, `currentLineColor` @@ -122,7 +135,9 @@ Each shortcut sends an intent: `IndentCodeIntent` (Tab), `OutdentCodeIntent` CodeField(controller: controller, shortcuts: const {}) ``` -To change what an intent does, put an `Actions` widget above the field: +Edits made by shortcuts go through the field's `inputFormatters`, the same +as typed text. To change what an intent does, put an `Actions` widget above +the field: ```dart Actions( @@ -159,8 +174,8 @@ is one undo step. Flutter lays out a text field's whole text on every change, and styled runs make that slower. So for a document of more than `styleAllBelow` lines (300 -by default), `CodeField` colors only the visible lines plus `margin` lines -on each side (150 by default), and the rest is plain text. The colored +by default), `CodeField` colors only the visible lines plus `styleMargin` +lines on each side (150 by default), and the rest is plain text. The colored window follows scrolling — the field's own, or that of a scroll view around it. Moving the window lays the whole field out again, so while you scroll it moves only when the visible lines come close to its edge, and it is centered diff --git a/docs/components/code-view.mdx b/docs/components/code-view.mdx index b3d6018..14061ec 100644 --- a/docs/components/code-view.mdx +++ b/docs/components/code-view.mdx @@ -31,9 +31,17 @@ CodeView(source, language: dartLanguage) ``` Give it the source and a language; every other parameter is optional. With -the defaults, the theme follows the app's brightness, the code is selectable, -long lines scroll sideways, and the code sits in 16 pixels of the theme's -background color. +the defaults, the theme follows the platform's brightness (or a +[`CodeTheme`](/docs/themes/#app-wide-defaults)), long lines scroll sideways, +and the code sits in 16 pixels of the theme's background color. Code is +always laid out left to right, even in a right-to-left app. + +To let people select and copy the code, put it — or the page around it — +in a `SelectionArea`: + +```dart +SelectionArea(child: CodeView(source, language: dartLanguage)) +``` ## Examples @@ -52,28 +60,34 @@ background color. longer file, and `highlightedLines` takes the numbers as shown in the gutter. Without `highlightColor`, highlighted lines get a translucent band: black at 8% opacity in a light theme, white at 13% in a dark one. Line numbers are -never selected, so copying the code never copies them. +never selected, so copying the code never copies them, and screen readers +skip them. -To draw the gutter yourself, pass a `gutterBuilder`. It gets the line number -as shown and whether that line is highlighted, and is only used while -`lineNumbers` is on. Return a fixed-width widget so the rows stay aligned: +To draw the gutter yourself, pass a `gutterBuilder`. It gets a +`CodeLineDetails` — the zero-based `line`, its `lineNumber` as shown, and +whether it is `highlighted` — and is only used while `lineNumbers` is on. +Return a fixed-width widget so the rows stay aligned: ```dart CodeView( source, language: dartLanguage, lineNumbers: true, - gutterBuilder: (context, lineNumber, highlighted) => SizedBox( + gutterBuilder: (context, line) => SizedBox( width: 32, child: Text( - '$lineNumber', + '${line.lineNumber}', textAlign: TextAlign.right, - style: TextStyle(fontWeight: highlighted ? FontWeight.bold : null), + style: TextStyle(fontWeight: line.highlighted ? FontWeight.bold : null), ), ), ) ``` +`lineBuilder` wraps each row the same way, with the row as `child` — for a +gesture detector per line, say. Setting it lays the code out one row per +line. + :::note Placed where its height is bounded, such as in an `Expanded`, a `CodeView` with line numbers fills that height, its background included. Without line @@ -237,9 +251,9 @@ CodeHighlighter.shared.preload([dartLanguage, kotlinLanguage, jsonLanguage]); ## Themes and text style `theme` picks a `ValTheme` for one view; without it, `CodeView` follows -`CodeTheme` and the app's brightness. `textStyle` is merged over the default -code style — `monospace` at 14 pixels with a line height of 1.5 — for -example to set a font family. See [Themes](/docs/themes/). +`CodeTheme` and the brightness. `style` is merged over the default code +style — `monospace` at 14 pixels with a line height of 1.5 — for example to +set a font family. See [Themes](/docs/themes/). ## API reference diff --git a/docs/components/index.mdx b/docs/components/index.mdx index 4a61bfe..b0bd640 100644 --- a/docs/components/index.mdx +++ b/docs/components/index.mdx @@ -42,7 +42,12 @@ in a light Material 3 app, so the picture and the code always agree. The generator draws `monospace` with JetBrains Mono, and turns off its ligatures so `=>` shows as typed. -The widgets take their app-wide defaults — the light and dark themes, the -code text style, and for `CodeView` its padding and line numbers — from a -`CodeTheme` set once on your `ThemeData`. See +The widgets take their app-wide defaults — the light and dark themes and +which one to use, the code text style, line numbers, and `CodeView`'s +padding — from a `CodeTheme` above them. See [Themes](/docs/themes/#app-wide-defaults). + +`CodeView`, `HighlightTextController` and the rendering functions need only +Flutter's widgets layer. `CodeField` is built on `material_ui` and comes from +`package:val_highlight_flutter/material.dart`; see +[which library to import](/docs/getting-started/#which-library-to-import). diff --git a/docs/components/text-field.mdx b/docs/components/text-field.mdx index a47587a..5a1ef15 100644 --- a/docs/components/text-field.mdx +++ b/docs/components/text-field.mdx @@ -33,7 +33,7 @@ final controller = HighlightTextController( |---|---| | `language` | Required. The grammar to highlight with. Set `controller.language` later to switch; the text is highlighted again. | | `text` | The initial text. | -| `theme` | A `ValTheme`. Without one, the controller follows `CodeTheme` and the app's brightness. Settable as `controller.theme`. | +| `theme` | A `ValTheme`. Without one, the controller follows `CodeTheme` and the brightness. Settable as `controller.theme`. | | `registry` | A `LanguageRegistry` that resolves languages named inside the text, such as Markdown code fences. | Give the field a monospace style: `CodeTheme.textStyleOf(context)` is the one @@ -44,7 +44,9 @@ the package's widgets use. `CodeEditingFormatter` brings `CodeField`'s typing to a plain `TextField`: brackets and quotes that close themselves, typing over a selection to wrap it, and Enter that keeps the indentation. Add it to `inputFormatters`, as the -example does. It takes `editing` and `indent`, like `CodeField`. +example does. It takes `editing` and `indent`, like `CodeField`. What it +remembers between edits is kept on the controller, so creating it in +`build`, as the example does, is fine. Keys are `CodeField`'s own: a plain `TextField` gets no Tab, Shift+Tab or Ctrl+/ shortcuts, no bracket marks and no line numbers. When you need those, @@ -53,12 +55,9 @@ use [CodeField](/docs/components/code-field/). ## Long text A plain `TextField` colors the whole text, and Flutter lays all of it out on -every change. For long text, use `CodeField`, which colors only the lines on -screen, or set `controller.window` to the zero-based lines to color: - -```dart -controller.window = (first: 0, last: 199); -``` +every change, which gets slow after a few hundred lines. For long text, use +[`CodeField`](/docs/components/code-field/#large-documents), which colors +only the lines on screen. ## API reference diff --git a/docs/engine/highlighting.mdx b/docs/engine/highlighting.mdx index acdebad..d3c3cc4 100644 --- a/docs/engine/highlighting.mdx +++ b/docs/engine/highlighting.mdx @@ -69,8 +69,9 @@ for (var line = 0; line < result.lineCount; line++) { `forEachSegment` calls back with the pieces of one line, cut where a token crosses the line break, and never includes the break itself. `lineStart` and -`lineEnd` give a line's offsets; `lineEnd` excludes the `\n` or `\r\n`. Empty -source has one empty line, and a trailing `\n` starts a final empty line. +`lineEnd` give a line's offsets; `lineEnd` excludes the `\n` or `\r\n`, and +`lineAt(offset)` finds the line holding an offset. Empty source has one +empty line, and a trailing `\n` starts a final empty line. ## Questions an editor asks diff --git a/docs/getting-started.mdx b/docs/getting-started.mdx index 1b14d5c..d0c90c9 100644 --- a/docs/getting-started.mdx +++ b/docs/getting-started.mdx @@ -16,13 +16,19 @@ a static site generator. Coming from a 0.x version? See ```bash -flutter pub add val_highlight_flutter val_highlight material_ui +flutter pub add val_highlight_flutter val_highlight ``` A Flutter app lists `val_highlight` too, because languages and themes are imported from `package:val_highlight/…`, and Dart's recommended lints (`depend_on_referenced_packages`) flag imports from a package you don't -depend on. `material_ui` is explained [below](#use-material_ui-in-your-app). +depend on. + +The examples on these pages build their apps with +[`material_ui`](https://pub.dev/packages/material_ui), Flutter's Material +library as a package (`flutter pub add material_ui`). Apart from +`CodeField`, the widgets work the same with `package:flutter/material.dart` +or any other design system. ```bash @@ -47,32 +53,21 @@ dart pub add val_highlight -`CodeView` takes the source and a language; everything else is optional. Its -theme follows the app's brightness — `lightTheme` in a light app, `darkTheme` -in a dark one — the code can be selected and copied, and long lines scroll -sideways. [CodeView](/docs/components/code-view/) shows the rest; to let -people edit code, see [CodeField](/docs/components/code-field/). - -### Use material_ui in your app - -`val_highlight_flutter` is built on -[`material_ui`](https://pub.dev/packages/material_ui), Flutter's Material -library published as a package, rather than on -`package:flutter/material.dart`. The two libraries have separate `Theme`, -`Material` and localizations widgets, so build your app with `material_ui`: +`CodeView` takes the source and a language; everything else is optional. +Its theme follows the platform's brightness — `lightTheme` in light mode, +`darkTheme` in dark mode — and long lines scroll sideways. To follow your +app's own light and dark mode instead, add a `CodeTheme`; see +[app-wide defaults](/docs/themes/#app-wide-defaults). To let people select +and copy the code, put it — or the page around it — in a `SelectionArea`. +[CodeView](/docs/components/code-view/) shows the rest; to let people edit +code, see [CodeField](/docs/components/code-field/). -```dart -import 'package:material_ui/material_ui.dart'; -``` +### Which library to import -:::caution -Under a `MaterialApp` from `package:flutter/material.dart`, the widgets can't -see your app's theme: `CodeView` stays light in a dark app and, while -`selectable` is on (the default), fails with "No MaterialLocalizations -found". `CodeField` fails with "No Material widget found". And `CodeTheme` -can't be added to that library's `ThemeData`, because it is a `material_ui` -theme extension. -::: +| Import | Use it for | +|---|---| +| `package:val_highlight_flutter/val_highlight_flutter.dart` | `CodeView`, `HighlightTextController`, `CodeTheme` and the rest. Built on Flutter's widgets layer only, so it works in any app: `package:flutter/material.dart`, [`material_ui`](https://pub.dev/packages/material_ui), Cupertino or your own design system. | +| `package:val_highlight_flutter/material.dart` | All of the above, plus `CodeField`, an editor built on `material_ui`'s `TextField`. It needs a `material_ui` `MaterialApp` above it. In other apps, give your own text field a `HighlightTextController`; see [highlighted TextField](/docs/components/text-field/). | ## Render HTML in Dart @@ -112,7 +107,8 @@ a stylesheet, write inline styles instead — see | Import | Gives you | |---|---| -| `package:val_highlight_flutter/val_highlight_flutter.dart` | The Flutter widgets, plus everything in `val_highlight.dart`. | +| `package:val_highlight_flutter/val_highlight_flutter.dart` | The Flutter widgets except `CodeField`, plus everything in `val_highlight.dart`. | +| `package:val_highlight_flutter/material.dart` | Everything in `val_highlight_flutter.dart`, plus `CodeField`. | | `package:val_highlight/val_highlight.dart` | The engine: `Highlighter`, `HighlightResult`, `IncrementalHighlighter`, `HtmlRenderer`, `LanguageRegistry`, `LanguageDetector`, `ValTheme`, `Style`, `Scopes`, `EditingSyntax` and more. | | `package:val_highlight/advanced.dart` | The engine plus the rules and building blocks for [writing a grammar](/docs/customize/writing-a-grammar/). | | `package:val_highlight/languages/.dart` | One language, such as `languages/kotlin.dart` for `kotlinLanguage`. [Every language](/docs/languages/) lists its file. | diff --git a/docs/index.mdx b/docs/index.mdx index 6f7353a..bf420a0 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -19,10 +19,10 @@ companion package adds Flutter widgets to show code and to edit it. | Package | Use it for | |---|---| | [`val_highlight`](https://pub.dev/packages/val_highlight) | The engine. 55 languages plus a generic fallback and plain text, flat tokens, incremental updates, language detection, 8 themes, VS Code theme import and HTML output. No Flutter dependency. | -| [`val_highlight_flutter`](https://pub.dev/packages/val_highlight_flutter) | Flutter widgets: `CodeView` to show code, `CodeField` to edit it, `HighlightTextController` for any `TextField`, and `CodeTheme` for app-wide defaults. Re-exports the core API of `val_highlight`. | +| [`val_highlight_flutter`](https://pub.dev/packages/val_highlight_flutter) | Flutter widgets: `CodeView` to show code, `HighlightTextController` for any text field, and `CodeTheme` for app-wide defaults, which work in any app; and `CodeField`, an editor built on `material_ui`. Re-exports the core API of `val_highlight`. | ```bash -flutter pub add val_highlight_flutter val_highlight material_ui +flutter pub add val_highlight_flutter val_highlight ``` Then follow [Getting started](/docs/getting-started/). @@ -69,8 +69,9 @@ JetBrains Mono stands in for the platform's monospace font. ## What is in the box - **[CodeView](/docs/components/code-view/)** — read-only code with line - numbers, highlighted lines, wrapping or horizontal scrolling, selection that - never copies line numbers, a header slot, tappable tokens and custom spans. + numbers, highlighted lines, wrapping or horizontal scrolling, a header + slot, tappable tokens and custom spans. Inside a `SelectionArea` the code + can be selected, and line numbers never are. Long files render lazily; large inputs are highlighted in a background isolate. - **[CodeField](/docs/components/code-field/)** — an editor: brackets and diff --git a/docs/reference/platforms.mdx b/docs/reference/platforms.mdx index afbfbaa..b7af4b6 100644 --- a/docs/reference/platforms.mdx +++ b/docs/reference/platforms.mdx @@ -17,7 +17,8 @@ to native code, compiled to JavaScript, and compiled to WebAssembly. So it works in Flutter on Android, iOS, macOS, Windows, Linux and the web, on servers, and in command-line tools. `val_highlight_flutter` draws with ordinary Flutter text, with no platform code, so it runs wherever Flutter -does. +does. Its main library needs only Flutter's widgets layer; `CodeField`, in +`package:val_highlight_flutter/material.dart`, needs `material_ui`. The engine's tests run on the Dart VM and again compiled to JavaScript, and the two give the same tokens for every language. The widget tests run with diff --git a/docs/reference/troubleshooting.mdx b/docs/reference/troubleshooting.mdx index fa9a8aa..f8581c0 100644 --- a/docs/reference/troubleshooting.mdx +++ b/docs/reference/troubleshooting.mdx @@ -3,6 +3,36 @@ title: Troubleshooting description: Common problems with val_highlight and val_highlight_flutter, what causes them, and how to fix them. --- +## The code widgets don't follow my app's dark mode + +They follow the platform's brightness unless a `CodeTheme` says otherwise. +Set it from your app's theme in `MaterialApp.builder` (or your app's +equivalent): + +```dart +MaterialApp( + builder: (context, child) => CodeTheme( + data: CodeThemeData(brightness: Theme.of(context).brightness), + child: child!, + ), +) +``` + +See [app-wide defaults](/docs/themes/#app-wide-defaults). + +## The code in a `CodeView` can't be selected + +Selection belongs to the app: put the view, or the page around it, in a +`SelectionArea`. Line numbers are never selected. + +## `CodeField` throws "No Material widget found" + +`CodeField` is built on `material_ui`'s `TextField`, which needs a +`material_ui` `MaterialApp` or `Material` above it. An app built on +`package:flutter/material.dart` or another design system can give its own +text field a `HighlightTextController` and a `CodeEditingFormatter`; see +[highlighted TextField](/docs/components/text-field/). + ## Code inside Markdown fences is not highlighted Markdown looks up the language named on each fence in a registry, and the diff --git a/docs/themes.mdx b/docs/themes.mdx index 0863245..e6d0517 100644 --- a/docs/themes.mdx +++ b/docs/themes.mdx @@ -30,7 +30,7 @@ styles the same scopes as `lightTheme`; and `dark` matches the background. ## In Flutter By default, `CodeView`, `CodeField` and `HighlightTextController` use -`lightTheme` in a light app and `darkTheme` in a dark one. Pick a theme for +`lightTheme` or `darkTheme` by the platform's brightness. Pick a theme for one widget with `theme`, or for an editor with the controller's `theme`: ```dart @@ -44,44 +44,42 @@ final controller = HighlightTextController( ### App-wide defaults -Add a `CodeTheme` to your `ThemeData.extensions` to set defaults once. -Anything set on a widget wins. +Put a `CodeTheme` above your app's content to set defaults once. Anything +set on a widget wins. In `MaterialApp.builder` it sits below the app's +theme, so it can follow the app's own light and dark mode: ```dart -const codeTheme = CodeTheme( - light: sepiaTheme, - dark: dimTheme, - textStyle: TextStyle(fontFamily: 'JetBrains Mono'), - lineNumbers: true, -); - MaterialApp( - theme: ThemeData(extensions: const [codeTheme]), - darkTheme: ThemeData( - brightness: Brightness.dark, - extensions: const [codeTheme], + theme: ThemeData(), + darkTheme: ThemeData(brightness: Brightness.dark), + builder: (context, child) => CodeTheme( + data: CodeThemeData( + light: sepiaTheme, + dark: dimTheme, + brightness: Theme.of(context).brightness, + textStyle: const TextStyle(fontFamily: 'JetBrains Mono'), + lineNumbers: true, + ), + child: child!, ), home: const MyHome(), ) ``` -`CodeTheme` is read from the `ThemeData` in effect, so add it to both -`theme` and `darkTheme` when you set both. `padding` and `lineNumbers` apply -to `CodeView`; the themes and `textStyle` to every widget. A font family only -applies if your app bundles the font or the platform has it. +`brightness` picks `light` or `dark`; without it, the platform's brightness +does. `padding` applies to `CodeView`, `lineNumbers` to `CodeView` and +`CodeField`, and the themes and `textStyle` to every widget. A font family +only applies if your app bundles the font or the platform has it. +`CodeTheme` is a plain inherited widget, so it works the same in a +`CupertinoApp`, a `WidgetsApp` or anywhere in the tree. `CodeTheme.resolve(context)` returns the `ValTheme` a widget would use, for -painting a matching background. The default code text style is the +painting a matching background, and `CodeTheme.brightnessOf(context)` the +brightness it picked it by. The default code text style is the `monospace` family — with Menlo, Consolas, Roboto Mono and Courier New as fallbacks — at 14 pixels and a line height of 1.5, with letter and word spacing fixed at zero so an app-wide text theme can't stretch the code. -:::note -`CodeTheme` is a `ThemeExtension` from `material_ui`: add it to a -`material_ui` `ThemeData`. See -[Getting started](/docs/getting-started/#use-material_ui-in-your-app). -::: - ## Adjust a theme `extend` returns a new theme: `root` is merged over the current root style, diff --git a/docs/upgrading.mdx b/docs/upgrading.mdx index e4a0842..b4980d1 100644 --- a/docs/upgrading.mdx +++ b/docs/upgrading.mdx @@ -1,26 +1,32 @@ --- title: Upgrading to 1.0 -description: What changed between 0.x and 1.0 of val_highlight, and how to update your code for each breaking change. +description: What changed between 0.x and 1.0 of val_highlight and val_highlight_flutter, and how to update your code for each breaking change. --- -1.0 is the first stable release: from here on, breaking changes only come -with a new major version (see [versions](/docs/reference/platforms/#versions)). -Code that only highlights — with `Highlighter`, `allLanguagesRegistry()` -and the built-in themes — needs no changes. The changes below affect code -that builds a registry with a fallback, reads detection results, writes its -own grammar blocks, or used the engine's internal buffers. - -Update the constraints: +1.0 is the first stable release of both packages: from here on, breaking +changes only come with a new major version (see +[versions](/docs/reference/platforms/#versions)). Update both constraints +together, since `val_highlight_flutter` 1.0 needs `val_highlight` 1.0: ```yaml dependencies: val_highlight: ^1.0.0 + val_highlight_flutter: ^1.0.0 ``` -The full list, including fixes, is in the -[changelog](https://github.com/useval/highlight/blob/main/val_highlight/CHANGELOG.md). +In the engine, code that only highlights — with `Highlighter`, +`allLanguagesRegistry()` and the built-in themes — needs no changes. In the +widgets, the biggest change is that they no longer depend on Material: see +[val_highlight_flutter](#val_highlight_flutter) below. + +The full lists, including fixes, are in the changelogs of +[`val_highlight`](https://github.com/useval/highlight/blob/main/val_highlight/CHANGELOG.md) +and +[`val_highlight_flutter`](https://github.com/useval/highlight/blob/main/val_highlight_flutter/CHANGELOG.md). + +## val_highlight -## Registry fallback is named +### Registry fallback is named `LanguageRegistry` takes the fallback by name, and its list of languages is required: @@ -37,7 +43,7 @@ LanguageRegistry(const []); `LanguageRegistry(allLanguages)` and `allLanguagesRegistry()` are unchanged. -## Detection reasons are an enum +### Detection reasons are an enum `Detection.reason` is a `DetectionReason` instead of a string: @@ -51,7 +57,7 @@ if (detection?.reason == DetectionReason.fileName) … The values are `fileName`, `shebang` and `content`. -## Grammar building blocks +### Grammar building blocks `Operators` takes its characters as a required argument, and `Annotation` and `Preprocessor` take every argument by name: @@ -87,7 +93,7 @@ final class Pragma extends BlockRule { … } `cCommonRules`. If you built on them, copy the lists you need into your grammar. -## Engine internals are private +### Engine internals are private These were for the engine's own use and are gone: @@ -97,7 +103,7 @@ These were for the engine's own use and are gone: | `ScopeTable()`, `nameId`, `push` | Nothing: a result's `ScopeTable` is read-only. | | Setting `IncrementalHighlighter.lastRescannedLines` | It is read-only. | -## Behavior changes +### Behavior changes These compile unchanged but can give different results: @@ -118,3 +124,104 @@ These compile unchanged but can give different results: - **Delimiters longer than 1,024 characters**, such as a code fence of thousands of backticks, are plain text. They used to throw `GrammarException`. + +## val_highlight_flutter + +### Import CodeField from material.dart + +`CodeView`, `HighlightTextController`, `CodeTheme` and the rest now need only +Flutter's widgets layer, so they work in any app. `CodeField` is built on +`material_ui` and moved to its own library, which also exports everything +else: + +```dart +// 0.x +import 'package:val_highlight_flutter/val_highlight_flutter.dart'; + +// 1.0, where you use CodeField +import 'package:val_highlight_flutter/material.dart'; +``` + +### CodeTheme is a widget + +`CodeTheme` used to be a `ThemeExtension` on `ThemeData`. It is now an +inherited widget holding a `CodeThemeData`, and the brightness it picks the +light or dark theme by is the platform's unless you set it. To follow your +app's light and dark mode, put it in `MaterialApp.builder`: + +```dart +// 0.x +MaterialApp( + theme: ThemeData(extensions: const [CodeTheme(light: sepiaTheme)]), +) + +// 1.0 +MaterialApp( + builder: (context, child) => CodeTheme( + data: CodeThemeData( + light: sepiaTheme, + brightness: Theme.of(context).brightness, + ), + child: child!, + ), +) +``` + +`CodeTheme.maybeOf(context)` and `CodeTheme.of(context)` return the +`CodeThemeData`. `CodeTheme.resolve` and `CodeTheme.textStyleOf` are +unchanged. + +### CodeView + +- **Selection is the app's.** `CodeView` no longer wraps itself in a + `SelectionArea`, and `selectable` is gone. Put the view, or the page, in + a `SelectionArea` to let people select and copy code: + + ```dart + // 0.x + CodeView(source, language: dartLanguage) + + // 1.0, selectable + SelectionArea(child: CodeView(source, language: dartLanguage)) + ``` + +- **`textStyle` is `style`**, as on `CodeField` and `Text`. +- **Builders take a `CodeLineDetails`** with the line's zero-based `line`, + its `lineNumber` as shown, and whether it is `highlighted`: + + ```dart + // 0.x + gutterBuilder: (context, lineNumber, highlighted) => … + lineBuilder: (context, line, child) => … + + // 1.0 + gutterBuilder: (context, line) => … line.lineNumber … line.highlighted … + lineBuilder: (context, line, child) => … line.line … + ``` + +### CodeField and HighlightTextController + +- **`margin` is `styleMargin`**, beside `styleAllBelow`. +- **`lineNumbers` follows `CodeTheme`** when you don't set it, as on + `CodeView`. +- **`HighlightTextController.window` is gone.** It was for coloring part of + a long text in a plain `TextField`; use `CodeField`, which does that + itself. +- **`CodeEditingFormatter.editing` and `indent` are final.** Create a new + formatter to change them; it keeps its state on the controller, so + creating one in `build` is fine. + +### Final classes + +`CodeToken`, `CodeEditing`, `CodeHighlighter`, `CodeEditingFormatter`, +`CodeThemeData` and the three intents are `final`: they can no longer be +extended or implemented. + +### Behavior changes + +- Code is laid out left to right in `CodeView` and `CodeField`, even in a + right-to-left app. +- Edits made by `CodeField` shortcuts, such as Tab, go through its + `inputFormatters`. +- `CodeView` rows grow with the text scale, and screen readers skip its line + numbers. diff --git a/screenshots/code-view.png b/screenshots/code-view.png index 510aa1f..8d1daed 100644 Binary files a/screenshots/code-view.png and b/screenshots/code-view.png differ diff --git a/val_highlight/CHANGELOG.md b/val_highlight/CHANGELOG.md index 046c9f7..62f9ea0 100644 --- a/val_highlight/CHANGELOG.md +++ b/val_highlight/CHANGELOG.md @@ -29,6 +29,10 @@ major version. * `HighlightResult.matchingBracket` uses the language's `EditingSyntax.brackets` unless `brackets` is given. +### Added + +* `HighlightResult.lineAt`, the line holding an offset. + ### Fixed * Highlighting time no longer grows with the square of the input on long diff --git a/val_highlight/lib/src/incremental.dart b/val_highlight/lib/src/incremental.dart index 2491265..9fb942c 100644 --- a/val_highlight/lib/src/incremental.dart +++ b/val_highlight/lib/src/incremental.dart @@ -91,7 +91,7 @@ final class IncrementalHighlighter { // Resume one line before the line holding the first change, because a // rule's lookahead may have read across the line break. Grammars whose // lookahead reaches further name the lines it never crosses. - var line = _lineOf(old, prefix) - 1; + var line = old.lineAt(prefix) - 1; if (line < 0) line = 0; final restart = _restartLine; while (line > 0 && @@ -207,7 +207,7 @@ final class IncrementalHighlighter { final oldEditEnd = old.code.length - suffix; final newEditEnd = text.length - suffix; // Old lines starting at or before `prefix` are unchanged. - final keep = _lineOf(old, prefix) + 1; + final keep = old.lineAt(prefix) + 1; // Old lines starting after the edited range survive, shifted. var after = keep; while (after < old.lineCount && old.lineStart(after) <= oldEditEnd) { @@ -231,18 +231,4 @@ final class IncrementalHighlighter { } return starts; } - - static int _lineOf(HighlightResult result, int offset) { - var low = 0; - var high = result.lineCount - 1; - while (low < high) { - final mid = (low + high + 1) >> 1; - if (result.lineStart(mid) <= offset) { - low = mid; - } else { - high = mid - 1; - } - } - return low; - } } diff --git a/val_highlight/lib/src/result.dart b/val_highlight/lib/src/result.dart index 98941da..71a1dba 100644 --- a/val_highlight/lib/src/result.dart +++ b/val_highlight/lib/src/result.dart @@ -87,6 +87,24 @@ final class HighlightResult { /// Start offset of line [line]. int lineStart(int line) => _lineStarts[line]; + /// The line holding [offset]. An offset at a line break belongs to the + /// line the break ends; offsets before the start or past the end belong + /// to the first or last line. + int lineAt(int offset) { + final starts = _lineStarts; + var low = 0; + var high = starts.length - 1; + while (low < high) { + final mid = (low + high + 1) >> 1; + if (starts[mid] <= offset) { + low = mid; + } else { + high = mid - 1; + } + } + return low; + } + /// End offset of line [line], excluding its `\n` or `\r\n`. int lineEnd(int line) { var end = line + 1 < _lineStarts.length diff --git a/val_highlight/test/lines_and_detect_test.dart b/val_highlight/test/lines_and_detect_test.dart index 352d6a1..1a9d6a5 100644 --- a/val_highlight/test/lines_and_detect_test.dart +++ b/val_highlight/test/lines_and_detect_test.dart @@ -34,6 +34,22 @@ void main() { ]); }); + test('lineAt finds the line holding an offset', () { + final result = const Highlighter().highlight( + 'ab\r\ncd\n\nef', + language: plainTextLanguage, + ); + expect( + [for (var i = -1; i <= result.code.length + 1; i++) result.lineAt(i)], + [0, 0, 0, 0, 0, 1, 1, 1, 2, 3, 3, 3, 3], + ); + final empty = const Highlighter().highlight( + '', + language: plainTextLanguage, + ); + expect(empty.lineAt(0), 0); + }); + test('tokenAt finds the covering token', () { final r = highlighter.highlight('x = 1', language: dartLanguage); expect(r.tokenAt(0), 0); diff --git a/val_highlight_flutter/CHANGELOG.md b/val_highlight_flutter/CHANGELOG.md index 1d28a80..a183b29 100644 --- a/val_highlight_flutter/CHANGELOG.md +++ b/val_highlight_flutter/CHANGELOG.md @@ -1,7 +1,52 @@ -## Unreleased +## 1.0.0 +The API is now stable: from here on, breaking changes only come with a new +major version. `docs/upgrading.mdx` shows each change below with before +and after code. + +### Breaking + +* **Material is optional.** The main library needs only Flutter's widgets + layer, so `CodeView`, `HighlightTextController` and `CodeTheme` work in + apps built on `package:flutter/material.dart`, `material_ui`, Cupertino + or anything else. 0.1.2 threw in a `flutter/material.dart` app. + `CodeField`, built on `material_ui`, moved to + `package:val_highlight_flutter/material.dart`, which also exports + everything else. +* **`CodeTheme` is an inherited widget** holding a `CodeThemeData`, instead + of a `ThemeExtension`. It picks the light or dark theme by + `CodeThemeData.brightness`, or the platform's brightness; set it from + your app's theme in `MaterialApp.builder` to follow the app's mode. +* **`CodeView` is selectable inside a `SelectionArea`** you provide; it no + longer adds its own, and `selectable` is gone. +* **`CodeView.textStyle` is `style`**, as on `CodeField`. +* **`gutterBuilder` and `lineBuilder` take a `CodeLineDetails`** (`line`, + `lineNumber`, `highlighted`) instead of positional arguments. +* **`CodeField.margin` is `styleMargin`**, and `CodeField.lineNumbers` + falls back to `CodeThemeData.lineNumbers`. +* **`HighlightTextController.window` is no longer public.** Use `CodeField` + for long text. +* **`CodeEditingFormatter.editing` and `indent` are final.** The formatter + keeps its state on the controller, so creating one in `build` works. +* **Final classes:** `CodeToken`, `CodeEditing`, `CodeHighlighter`, + `CodeEditingFormatter`, `CodeThemeData` and the three intents. * Requires `val_highlight` 1.0.0. +### Fixed + +* `CodeView` rows were cut off at large text scales. +* Code was laid out right to left in a right-to-left app; `CodeView` and + `CodeField` now always lay it out left to right. +* Edits made by `CodeField` shortcuts, such as Tab, skipped + `inputFormatters`. +* Screen readers read `CodeView`'s line numbers. +* A `CodeEditingFormatter` created in `build` lost track of the closers it + inserted, so typing `)` after an auto-closed `(` added a second one. +* A failed background highlight is reported to `FlutterError` instead of + being dropped. +* `CodeField.defaultShortcuts` returns the same map each time, so a + rebuild no longer rebinds the shortcuts. + ## 0.1.2 * Migrated from `package:flutter/material.dart` to `material_ui`. diff --git a/val_highlight_flutter/README.md b/val_highlight_flutter/README.md index 00d67e0..e81c192 100644 --- a/val_highlight_flutter/README.md +++ b/val_highlight_flutter/README.md @@ -32,8 +32,12 @@ every edit re-highlights only what it can affect. - **Native rendering** — plain Flutter text, no WebView and no platform code. Works on Android, iOS, macOS, Windows, Linux and the web. -- **Follows your app** — light and dark themes switch with the app, and - `CodeTheme` sets defaults once for every code block. +- **Any design system** — the main library needs only Flutter's widgets + layer, so it works with `package:flutter/material.dart`, `material_ui`, + Cupertino or your own widgets. `CodeField`, built on `material_ui`, has + its own import. +- **Follows your app** — light and dark themes switch with the brightness, + and `CodeTheme` sets defaults once for every code block. - **Interactive** — tap handlers and custom spans per token, for jump-to-definition, links and tooltips. @@ -55,6 +59,14 @@ This package re-exports the core API of themes are separate imports under `package:val_highlight/languages/` and `package:val_highlight/themes/`, so an app ships only what it uses. +| Import | Gives you | +|---|---| +| `package:val_highlight_flutter/val_highlight_flutter.dart` | `CodeView`, `HighlightTextController`, `CodeTheme` and the rest; needs only Flutter's widgets layer. | +| `package:val_highlight_flutter/material.dart` | All of that, plus `CodeField`, which needs a `material_ui` `MaterialApp`. | + +Upgrading from 0.x? See +[Upgrading to 1.0](https://github.com/useval/highlight/blob/main/docs/upgrading.mdx). + ## 📄 CodeView ```dart @@ -73,8 +85,8 @@ CodeView( `gutterBuilder`. - **Highlighted lines** — `highlightedLines`, `highlightColor`. - **Wrapping** — `wrap: true`, or scroll long lines horizontally. -- **Selection and copying** — on by default (`selectable`); line numbers are - never copied. +- **Selection and copying** — inside a `SelectionArea`; line numbers are + never copied, and screen readers skip them. - **Custom rendering** — `lineBuilder` wraps each row, `header` adds a title bar or copy button, `spanBuilder` replaces any token's span. - **Tappable tokens** — `onTokenTap` receives each token's text, offsets, @@ -91,12 +103,14 @@ CodeView( ## ⌨️ CodeField ```dart +import 'package:val_highlight_flutter/material.dart'; + final controller = HighlightTextController(language: dartLanguage); CodeField(controller: controller, expands: true) ``` -`CodeField` is a `TextField` for code: +`CodeField` is a `material_ui` `TextField` for code: - monospace, no autocorrect or smart quotes; - brackets and quotes close themselves, typing a closer steps over it, and @@ -106,7 +120,7 @@ CodeField(controller: controller, expands: true) or `:`, and moves the closer of `{|}` onto its own line; - Tab and Shift+Tab indent and outdent (`indent` sets the unit); - Ctrl+/ (Cmd+/ on Apple platforms) comments and uncomments lines; -- the bracket at the caret and its match are outlined; +- the bracket at the caret and its match get a background; - each edit re-scans only the lines it can affect. Brackets, quotes and comment markers come from the language @@ -149,16 +163,16 @@ For a plain `TextField`, add get the same typing behavior. Flutter lays out a text field's whole text on every change, and styled runs -make that slower. So for documents over 300 lines, `CodeField` colors only -the visible lines plus a margin, and the colored window follows scrolling. +make that slower. So for documents over 300 lines (`styleAllBelow`), +`CodeField` colors only the visible lines plus `styleMargin` lines on each +side, and the colored window follows scrolling. -`HighlightTextController` also works in a plain `TextField` for short -documents. For long ones, use `CodeField`, or set `controller.window` -yourself. +`HighlightTextController` also works in a plain `TextField`, in any design +system, for short documents. For long ones, use `CodeField`. ## 🎨 Themes -The theme follows the app's brightness: `lightTheme` or `darkTheme` by +The theme follows the platform's brightness: `lightTheme` or `darkTheme` by default. Choose any of the eight built-in themes, a VS Code theme, or your own: @@ -166,19 +180,20 @@ own: CodeView(source, language: dartLanguage, theme: midnightTheme) ``` -Set app-wide defaults once: +Set app-wide defaults once with a `CodeTheme`. In `MaterialApp.builder` it +can follow the app's own light and dark mode: ```dart MaterialApp( - theme: ThemeData( - extensions: [ - CodeTheme( - light: sepiaTheme, - dark: dimTheme, - textStyle: const TextStyle(fontFamily: 'JetBrains Mono'), - lineNumbers: true, - ), - ], + builder: (context, child) => CodeTheme( + data: CodeThemeData( + light: sepiaTheme, + dark: dimTheme, + brightness: Theme.of(context).brightness, + textStyle: const TextStyle(fontFamily: 'JetBrains Mono'), + lineNumbers: true, + ), + child: child!, ), ) ``` @@ -233,7 +248,7 @@ editor, and a large file rendered lazily. ## Built by Val -`val_highlight_flutter` is part of [Val](https://useval.io), the live visual +`val_highlight_flutter` is part of [Val](https://useval.ai), the live visual layer for AI agents. ## 💬 Community diff --git a/val_highlight_flutter/example/integration_test/app_test.dart b/val_highlight_flutter/example/integration_test/app_test.dart index 4c2414a..adf029e 100644 --- a/val_highlight_flutter/example/integration_test/app_test.dart +++ b/val_highlight_flutter/example/integration_test/app_test.dart @@ -3,7 +3,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/material.dart'; import 'package:val_highlight_flutter_example/main.dart'; void main() { diff --git a/val_highlight_flutter/example/integration_test/editor_test.dart b/val_highlight_flutter/example/integration_test/editor_test.dart index bc0f029..232a7d7 100644 --- a/val_highlight_flutter/example/integration_test/editor_test.dart +++ b/val_highlight_flutter/example/integration_test/editor_test.dart @@ -5,7 +5,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:val_highlight/languages/all.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/material.dart'; RenderEditable _editable(WidgetTester tester) { RenderEditable? found; diff --git a/val_highlight_flutter/example/integration_test/frame_timing_test.dart b/val_highlight_flutter/example/integration_test/frame_timing_test.dart index 0fc558a..a28da44 100644 --- a/val_highlight_flutter/example/integration_test/frame_timing_test.dart +++ b/val_highlight_flutter/example/integration_test/frame_timing_test.dart @@ -7,7 +7,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:val_highlight/languages/dart.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/material.dart'; import 'package:val_highlight_flutter_example/samples.g.dart'; String _dartLines(int lines) { diff --git a/val_highlight_flutter/example/lib/main.dart b/val_highlight_flutter/example/lib/main.dart index 03cd908..ef4fe97 100644 --- a/val_highlight_flutter/example/lib/main.dart +++ b/val_highlight_flutter/example/lib/main.dart @@ -2,7 +2,7 @@ import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import 'package:val_highlight/languages/all.dart'; import 'package:val_highlight/themes/all.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/material.dart'; import 'samples.dart'; @@ -32,6 +32,12 @@ class _ExampleAppState extends State { colorSchemeSeed: const Color(0xFFB0226E), brightness: Brightness.dark, ), + // The code widgets follow the app's light/dark mode, not the + // platform's. + builder: (context, child) => CodeTheme( + data: CodeThemeData(brightness: Theme.of(context).brightness), + child: child!, + ), home: DefaultTabController( length: 3, child: Scaffold( @@ -57,7 +63,11 @@ class _ExampleAppState extends State { ), ), body: const TabBarView( - children: [GalleryPage(), EditorPage(), LargeFilePage()], + children: [ + SelectionArea(child: GalleryPage()), + EditorPage(), + SelectionArea(child: LargeFilePage()), + ], ), ), ), diff --git a/val_highlight_flutter/example/pubspec.yaml b/val_highlight_flutter/example/pubspec.yaml index a246f75..212764f 100644 --- a/val_highlight_flutter/example/pubspec.yaml +++ b/val_highlight_flutter/example/pubspec.yaml @@ -13,7 +13,7 @@ dependencies: sdk: flutter material_ui: ^1.0.1 val_highlight: ^1.0.0 - val_highlight_flutter: ^0.1.2 + val_highlight_flutter: ^1.0.0 dev_dependencies: flutter_test: diff --git a/val_highlight_flutter/lib/material.dart b/val_highlight_flutter/lib/material.dart new file mode 100644 index 0000000..00fc6fa --- /dev/null +++ b/val_highlight_flutter/lib/material.dart @@ -0,0 +1,18 @@ +/// `CodeField`, a code editor built on `material_ui`'s `TextField`: everything +/// in `val_highlight_flutter.dart`, plus the editor. +/// +/// ```dart +/// import 'package:val_highlight_flutter/material.dart'; +/// import 'package:val_highlight/languages/dart.dart'; +/// +/// CodeField(controller: HighlightTextController(language: dartLanguage)) +/// ``` +/// +/// The field needs a `material_ui` `MaterialApp` (or `Material`) above it. +/// In an app with another design system, give your own text field a +/// `HighlightTextController` and a `CodeEditingFormatter` instead. +library; + +export 'val_highlight_flutter.dart'; + +export 'src/code_field.dart' show CodeField; diff --git a/val_highlight_flutter/lib/src/code_editing.dart b/val_highlight_flutter/lib/src/code_editing.dart index 9095dc1..b084359 100644 --- a/val_highlight_flutter/lib/src/code_editing.dart +++ b/val_highlight_flutter/lib/src/code_editing.dart @@ -19,7 +19,7 @@ import 'highlight_text_controller.dart'; /// /// Use [CodeEditing.none] to turn every behavior off. @immutable -class CodeEditing { +final class CodeEditing { /// Creates editing behavior. Everything is on by default. const CodeEditing({ this.autoIndent = true, @@ -102,21 +102,21 @@ class CodeEditing { /// Indents the selected lines, or inserts an indent at the caret. Bound to /// Tab in `CodeField`. -class IndentCodeIntent extends Intent { +final class IndentCodeIntent extends Intent { /// Creates an indent intent. const IndentCodeIntent(); } /// Removes one indent from the selected lines. Bound to Shift+Tab in /// `CodeField`. -class OutdentCodeIntent extends Intent { +final class OutdentCodeIntent extends Intent { /// Creates an outdent intent. const OutdentCodeIntent(); } /// Comments or uncomments the selected lines. Bound to Ctrl+/ (Cmd+/ on /// Apple platforms) in `CodeField`. -class ToggleCommentIntent extends Intent { +final class ToggleCommentIntent extends Intent { /// Creates a toggle-comment intent. const ToggleCommentIntent(); } @@ -139,7 +139,11 @@ class ToggleCommentIntent extends Intent { /// with hardware keyboards, on-screen keyboards and voice input. Text being /// composed by an input method is never changed. Each change it makes is a /// single edit, so one undo reverts it. -class CodeEditingFormatter extends TextInputFormatter { +/// +/// What it needs to remember between edits, such as which closers it +/// inserted, is kept on the [controller], so creating a new formatter in +/// each build is fine. +final class CodeEditingFormatter extends TextInputFormatter { /// Creates a formatter for [controller]. CodeEditingFormatter({ required this.controller, @@ -151,15 +155,14 @@ class CodeEditingFormatter extends TextInputFormatter { final HighlightTextController controller; /// The behavior to apply. - CodeEditing editing; + final CodeEditing editing; /// One level of indentation, for Enter. - String indent; + final String indent; // Offsets of closers inserted automatically, in increasing order. Only // these are stepped over or deleted with their opener. - final List _closers = []; - String? _text; + List get _closers => controller.autoClosers; @override TextEditingValue formatEditUpdate( @@ -167,14 +170,16 @@ class CodeEditingFormatter extends TextInputFormatter { TextEditingValue newValue, ) { final value = _format(oldValue, newValue); - _text = value.text; + controller.autoClosersText = value.text; return value; } TextEditingValue _format(TextEditingValue oldValue, TextEditingValue value) { - // Something other than this formatter changed the text: the recorded + // Something other than a formatter changed the text: the recorded // closers may no longer be where they were. - if (!identical(oldValue.text, _text)) _closers.clear(); + if (!identical(oldValue.text, controller.autoClosersText)) { + _closers.clear(); + } final edit = _Edit.between(oldValue, value); if (edit == null) { _closers.clear(); diff --git a/val_highlight_flutter/lib/src/code_field.dart b/val_highlight_flutter/lib/src/code_field.dart index ae8639d..6580562 100644 --- a/val_highlight_flutter/lib/src/code_field.dart +++ b/val_highlight_flutter/lib/src/code_field.dart @@ -10,8 +10,6 @@ import 'code_theme.dart'; import 'editor_decorations.dart'; import 'highlight_text_controller.dart'; -export 'code_editing.dart' show indentText, newlineKeepingIndent, outdentLines; - /// A code editor: a multi-line [TextField] driven by a /// [HighlightTextController], which stays fast on large documents. /// @@ -32,9 +30,13 @@ export 'code_editing.dart' show indentText, newlineKeepingIndent, outdentLines; /// /// Laying out a text field is proportional to its styled runs, so for /// documents longer than [styleAllBelow] lines only the visible lines, plus -/// [margin] lines on each side, are colored. The window follows scrolling +/// [styleMargin] lines on each side, are colored. The window follows scrolling /// (of the field itself or of an enclosing scroll view) and is computed from /// the laid-out text, so wrapped lines are handled exactly. +/// +/// The field is built on `material_ui`'s [TextField], so it needs a +/// `material_ui` `MaterialApp` (or `Material`) above it. Code is always +/// laid out left to right, even in a right-to-left app. class CodeField extends StatefulWidget { /// Creates a code editor. const CodeField({ @@ -55,13 +57,13 @@ class CodeField extends StatefulWidget { this.scrollController, this.textAlignVertical, this.styleAllBelow = 300, - this.margin = 150, + this.styleMargin = 150, this.indent = ' ', this.editing = const CodeEditing(), this.shortcuts, this.inputFormatters, this.undoController, - this.lineNumbers = false, + this.lineNumbers, this.firstLineNumber = 1, this.gutterStyle, this.highlightedLines = const {}, @@ -110,8 +112,9 @@ class CodeField extends StatefulWidget { /// Documents with at most this many lines are colored in full. final int styleAllBelow; - /// Lines colored beyond each edge of the visible area. - final int margin; + /// Lines colored beyond each edge of the visible area, once the document + /// is longer than [styleAllBelow] lines. + final int styleMargin; /// Text inserted by Tab and removed by Shift+Tab, such as two spaces or /// `'\t'`. Enter keeps the current line's indentation, adding one level @@ -127,7 +130,7 @@ class CodeField extends StatefulWidget { final Map? shortcuts; /// Formatters applied after the editing behavior, such as a length - /// limit. + /// limit. Edits made by shortcuts, such as Tab, go through them too. final List? inputFormatters; /// Controls the field's undo history, as in [TextField.undoController]. @@ -135,8 +138,9 @@ class CodeField extends StatefulWidget { /// comment, an indent — is a single undo step. final UndoHistoryController? undoController; - /// Whether to show line numbers in a gutter. - final bool lineNumbers; + /// Whether to show line numbers in a gutter. Defaults to + /// [CodeThemeData.lineNumbers], or `false`. + final bool? lineNumbers; /// Number shown for the first line. final int firstLineNumber; @@ -163,18 +167,25 @@ class CodeField extends StatefulWidget { /// The default [shortcuts]: Tab, Shift+Tab, and Ctrl+/ (Cmd+/ on macOS /// and iOS). - static Map get defaultShortcuts { - final apple = - defaultTargetPlatform == TargetPlatform.macOS || - defaultTargetPlatform == TargetPlatform.iOS; - return { - const SingleActivator(LogicalKeyboardKey.tab): const IndentCodeIntent(), - const SingleActivator(LogicalKeyboardKey.tab, shift: true): - const OutdentCodeIntent(), - SingleActivator(LogicalKeyboardKey.slash, meta: apple, control: !apple): - const ToggleCommentIntent(), - }; - } + static Map get defaultShortcuts => + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS + ? _appleShortcuts + : _shortcuts; + + static const Map _shortcuts = { + SingleActivator(LogicalKeyboardKey.tab): IndentCodeIntent(), + SingleActivator(LogicalKeyboardKey.tab, shift: true): OutdentCodeIntent(), + SingleActivator(LogicalKeyboardKey.slash, control: true): + ToggleCommentIntent(), + }; + + static const Map _appleShortcuts = { + SingleActivator(LogicalKeyboardKey.tab): IndentCodeIntent(), + SingleActivator(LogicalKeyboardKey.tab, shift: true): OutdentCodeIntent(), + SingleActivator(LogicalKeyboardKey.slash, meta: true): + ToggleCommentIntent(), + }; @override State createState() => _CodeFieldState(); @@ -190,6 +201,10 @@ class _CodeFieldState extends State { GutterDigits? _currentDigits; int _digitCount = 0; + // Whether the gutter is shown, as of the last build: the widget's + // setting, or CodeTheme's. + bool _lineNumbers = false; + late final Map> _actions = { IndentCodeIntent: Action.overridable( defaultAction: _EditAction( @@ -258,11 +273,11 @@ class _CodeFieldState extends State { if (!identical(old.controller, widget.controller)) { old.controller.removeListener(_onChanged); widget.controller.addListener(_onChanged); + } + if (!identical(old.controller, widget.controller) || + old.editing != widget.editing || + old.indent != widget.indent) { _formatter = _newFormatter(); - } else { - _formatter - ..editing = widget.editing - ..indent = widget.indent; } } @@ -291,7 +306,7 @@ class _CodeFieldState extends State { void _onChanged() { _schedule(); // The gutter widens when the line count gains a digit. - if (widget.lineNumbers && _digitsFor() != _digitCount) setState(() {}); + if (_lineNumbers && _digitsFor() != _digitCount) setState(() {}); } /// A font finished loading, so the text was laid out again: lay out the @@ -352,22 +367,23 @@ class _CodeFieldState extends State { final bottom = editable .getPositionForPoint(visible.bottomRight - const Offset(1, 1)) .offset; - final firstVisible = _lineOf(result.lineStart, lines, top); - final lastVisible = _lineOf(result.lineStart, lines, bottom); + final firstVisible = result.lineAt(top); + final lastVisible = result.lineAt(bottom); // Moving the window re-lays out the whole field, so keep it while the // visible lines stay clear of its edges; while scrolling, only move it // when they get close. Once scrolling stops, re-center it. final current = controller.window; - final slack = settled ? widget.margin ~/ 2 : widget.margin ~/ 5; + final margin = widget.styleMargin; + final slack = settled ? margin ~/ 2 : margin ~/ 5; if (current != null && (current.first == 0 || firstVisible - current.first >= slack) && (current.last >= lines - 1 || current.last - lastVisible >= slack)) { return; } controller.window = ( - first: math.max(0, firstVisible - widget.margin), - last: math.min(lines - 1, lastVisible + widget.margin), + first: math.max(0, firstVisible - margin), + last: math.min(lines - 1, lastVisible + margin), ); } @@ -380,20 +396,6 @@ class _CodeFieldState extends State { return box.localToGlobal(Offset.zero) & box.size; } - static int _lineOf(int Function(int) lineStart, int lines, int offset) { - var low = 0; - var high = lines - 1; - while (low < high) { - final mid = (low + high + 1) >> 1; - if (lineStart(mid) <= offset) { - low = mid; - } else { - high = mid - 1; - } - } - return low; - } - static RenderEditable? _findEditable(RenderObject? object) { if (object == null) return null; if (object is RenderEditable) return object; @@ -410,12 +412,19 @@ class _CodeFieldState extends State { !value.isComposingRangeValid; } - /// Applies an edit made by a shortcut, as the user's own. + /// Applies an edit made by a shortcut, as the user's own: through + /// [CodeField.inputFormatters], as typed text would go. void _apply(TextEditingValue? edited) { if (edited == null) return; - final changed = edited.text != widget.controller.text; - widget.controller.value = edited; - if (changed) widget.onChanged?.call(edited.text); + final old = widget.controller.value; + var value = edited; + for (final formatter + in widget.inputFormatters ?? const []) { + value = formatter.formatEditUpdate(old, value); + } + final changed = value.text != old.text; + widget.controller.value = value; + if (changed) widget.onChanged?.call(value.text); } /// Enter keeps the indentation. Typed line breaks reach the formatter @@ -449,6 +458,8 @@ class _CodeFieldState extends State { @override Widget build(BuildContext context) { + _lineNumbers = + widget.lineNumbers ?? CodeTheme.maybeOf(context)?.lineNumbers ?? false; _schedule(requestFrame: false); Widget field = Focus( canRequestFocus: false, @@ -462,19 +473,20 @@ class _CodeFieldState extends State { child: field, ); final decorated = - widget.lineNumbers || + _lineNumbers || widget.highlightCurrentLine || widget.highlightedLines.isNotEmpty || widget.editing.matchBrackets; - if (!decorated) return field; - return _decorate(context, field); + if (decorated) field = _decorate(context, field); + return Directionality(textDirection: TextDirection.ltr, child: field); } Widget _decorate(BuildContext context, Widget field) { final theme = CodeTheme.resolve(context, widget.controller.theme); final base = CodeTheme.textStyleOf(context, widget.style); final foreground = theme.root.color == null - ? base.color ?? (theme.dark ? Colors.white : Colors.black) + ? base.color ?? + (theme.dark ? const Color(0xFFFFFFFF) : const Color(0xFF000000)) : Color(theme.root.color!); var gutterWidth = 0.0; @@ -482,7 +494,7 @@ class _CodeFieldState extends State { const leading = 8.0; GutterDigits? digits; GutterDigits? current; - if (widget.lineNumbers) { + if (_lineNumbers) { final scaler = MediaQuery.textScalerOf(context); final style = base .copyWith(color: foreground.withValues(alpha: 0.45)) diff --git a/val_highlight_flutter/lib/src/code_highlighter.dart b/val_highlight_flutter/lib/src/code_highlighter.dart index 4653b18..9f4c74f 100644 --- a/val_highlight_flutter/lib/src/code_highlighter.dart +++ b/val_highlight_flutter/lib/src/code_highlighter.dart @@ -13,7 +13,7 @@ import 'package:val_highlight/val_highlight.dart'; /// ```dart /// final highlighter = CodeHighlighter(registry: allLanguagesRegistry()); /// ``` -class CodeHighlighter { +final class CodeHighlighter { /// Creates a highlighter. CodeHighlighter({ this.registry, diff --git a/val_highlight_flutter/lib/src/code_theme.dart b/val_highlight_flutter/lib/src/code_theme.dart index a2d9655..ac28f8a 100644 --- a/val_highlight_flutter/lib/src/code_theme.dart +++ b/val_highlight_flutter/lib/src/code_theme.dart @@ -1,59 +1,136 @@ -import 'package:material_ui/material_ui.dart'; +import 'package:flutter/widgets.dart'; import 'package:val_highlight/themes/dark.dart'; import 'package:val_highlight/themes/light.dart'; import 'package:val_highlight/val_highlight.dart'; -/// App-wide defaults for code widgets, set once on [ThemeData.extensions]. -/// -/// ```dart -/// MaterialApp( -/// theme: ThemeData(extensions: [CodeTheme(light: myTheme)]), -/// ) -/// ``` +/// App-wide defaults for the code widgets, provided by a [CodeTheme]. /// /// Anything set directly on a widget wins over these defaults. @immutable -class CodeTheme extends ThemeExtension { +final class CodeThemeData { /// Creates code defaults. - const CodeTheme({ + const CodeThemeData({ this.light, this.dark, + this.brightness, this.textStyle, this.padding, this.lineNumbers, }); - /// Theme used when the app is light. Defaults to `lightTheme`. + /// Theme used when [brightness] is light. Defaults to `lightTheme`. final ValTheme? light; - /// Theme used when the app is dark. Defaults to `darkTheme`. + /// Theme used when [brightness] is dark. Defaults to `darkTheme`. final ValTheme? dark; + /// Whether to use [light] or [dark]. Defaults to the platform's + /// brightness, from [MediaQuery]. Set it from your app's theme when the + /// app does not follow the platform: + /// + /// ```dart + /// CodeThemeData(brightness: Theme.of(context).brightness) + /// ``` + final Brightness? brightness; + /// Base text style for code, merged over the default monospace style. final TextStyle? textStyle; - /// Padding around code blocks. + /// Padding around code in `CodeView`. final EdgeInsetsGeometry? padding; - /// Whether code blocks show line numbers. + /// Whether `CodeView` and `CodeField` show line numbers. final bool? lineNumbers; - /// The nearest [CodeTheme], if any. - static CodeTheme? maybeOf(BuildContext context) => - Theme.of(context).extension(); + /// Returns a copy with the given fields replaced. + CodeThemeData copyWith({ + ValTheme? light, + ValTheme? dark, + Brightness? brightness, + TextStyle? textStyle, + EdgeInsetsGeometry? padding, + bool? lineNumbers, + }) { + return CodeThemeData( + light: light ?? this.light, + dark: dark ?? this.dark, + brightness: brightness ?? this.brightness, + textStyle: textStyle ?? this.textStyle, + padding: padding ?? this.padding, + lineNumbers: lineNumbers ?? this.lineNumbers, + ); + } + + @override + bool operator ==(Object other) => + other is CodeThemeData && + other.light == light && + other.dark == dark && + other.brightness == brightness && + other.textStyle == textStyle && + other.padding == padding && + other.lineNumbers == lineNumbers; + + @override + int get hashCode => + Object.hash(light, dark, brightness, textStyle, padding, lineNumbers); +} - /// The [ValTheme] to use: [override] if given, otherwise the app default - /// for the current brightness. +/// Sets [CodeThemeData] for the code widgets below it. +/// +/// It works in any app, whatever its design system. Put one above your +/// app's content, for example in `MaterialApp.builder`, so it can follow +/// the app's own brightness: +/// +/// ```dart +/// MaterialApp( +/// builder: (context, child) => CodeTheme( +/// data: CodeThemeData( +/// light: sepiaTheme, +/// dark: dimTheme, +/// brightness: Theme.of(context).brightness, +/// ), +/// child: child!, +/// ), +/// ) +/// ``` +/// +/// Without a [CodeTheme], the widgets use `lightTheme` or `darkTheme` by +/// the platform's brightness. +class CodeTheme extends InheritedTheme { + /// Provides [data] to the code widgets in [child]. + const CodeTheme({super.key, required this.data, required super.child}); + + /// The defaults. + final CodeThemeData data; + + /// The nearest [CodeThemeData], if any. + static CodeThemeData? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.data; + + /// The nearest [CodeThemeData], or the default one. + static CodeThemeData of(BuildContext context) => + maybeOf(context) ?? const CodeThemeData(); + + /// The brightness the code widgets use: [CodeThemeData.brightness], or + /// the platform's. + static Brightness brightnessOf(BuildContext context) => + maybeOf(context)?.brightness ?? + MediaQuery.maybePlatformBrightnessOf(context) ?? + Brightness.light; + + /// The [ValTheme] to use: [override] if given, otherwise the default for + /// [brightnessOf]. static ValTheme resolve(BuildContext context, [ValTheme? override]) { if (override != null) return override; - final codeTheme = maybeOf(context); - return Theme.of(context).brightness == Brightness.dark - ? codeTheme?.dark ?? darkTheme - : codeTheme?.light ?? lightTheme; + final data = maybeOf(context); + return brightnessOf(context) == Brightness.dark + ? data?.dark ?? darkTheme + : data?.light ?? lightTheme; } - /// The default code text style: monospace, merged with [CodeTheme] and - /// then [override]. + /// The default code text style: monospace, merged with + /// [CodeThemeData.textStyle] and then [override]. /// /// Letter and word spacing are fixed at zero so an app-wide text theme /// cannot stretch code or its line numbers. @@ -69,25 +146,9 @@ class CodeTheme extends ThemeExtension { } @override - CodeTheme copyWith({ - ValTheme? light, - ValTheme? dark, - TextStyle? textStyle, - EdgeInsetsGeometry? padding, - bool? lineNumbers, - }) { - return CodeTheme( - light: light ?? this.light, - dark: dark ?? this.dark, - textStyle: textStyle ?? this.textStyle, - padding: padding ?? this.padding, - lineNumbers: lineNumbers ?? this.lineNumbers, - ); - } + Widget wrap(BuildContext context, Widget child) => + CodeTheme(data: data, child: child); @override - CodeTheme lerp(covariant CodeTheme? other, double t) { - if (other == null) return this; - return t < 0.5 ? this : other; - } + bool updateShouldNotify(CodeTheme oldWidget) => data != oldWidget.data; } diff --git a/val_highlight_flutter/lib/src/code_view.dart b/val_highlight_flutter/lib/src/code_view.dart index 7467237..e1a8ef2 100644 --- a/val_highlight_flutter/lib/src/code_view.dart +++ b/val_highlight_flutter/lib/src/code_view.dart @@ -1,8 +1,9 @@ import 'dart:math' as math; -import 'package:flutter/foundation.dart' show listEquals; +import 'package:flutter/foundation.dart' + show FlutterError, FlutterErrorDetails, listEquals; import 'package:flutter/gestures.dart'; -import 'package:material_ui/material_ui.dart'; +import 'package:flutter/widgets.dart'; import 'package:val_highlight/languages/generic.dart'; import 'package:val_highlight/languages/plaintext.dart'; import 'package:val_highlight/val_highlight.dart'; @@ -12,14 +13,50 @@ import 'code_styles.dart'; import 'code_theme.dart'; import 'spans.dart'; -/// Builds the gutter cell for [lineNumber]. Return a fixed-width widget so -/// rows stay aligned. +/// Builds the gutter cell for [line]. Return a fixed-width widget so rows +/// stay aligned. typedef CodeGutterBuilder = - Widget Function(BuildContext context, int lineNumber, bool highlighted); + Widget Function(BuildContext context, CodeLineDetails line); -/// Wraps the row for zero-based [line]. [child] is the default row. +/// Wraps the row for [line]. [child] is the default row. typedef CodeLineBuilder = - Widget Function(BuildContext context, int line, Widget child); + Widget Function(BuildContext context, CodeLineDetails line, Widget child); + +/// One line of a [CodeView], as passed to [CodeView.gutterBuilder] and +/// [CodeView.lineBuilder]. +@immutable +final class CodeLineDetails { + /// Creates the details of a line. + const CodeLineDetails({ + required this.line, + required this.lineNumber, + required this.highlighted, + }); + + /// Zero-based index of the line in the code. + final int line; + + /// Number shown in the gutter: [line] plus [CodeView.firstLineNumber]. + final int lineNumber; + + /// Whether [lineNumber] is in [CodeView.highlightedLines]. + final bool highlighted; + + @override + bool operator ==(Object other) => + other is CodeLineDetails && + other.line == line && + other.lineNumber == lineNumber && + other.highlighted == highlighted; + + @override + int get hashCode => Object.hash(line, lineNumber, highlighted); + + @override + String toString() => + 'CodeLineDetails(line: $line, lineNumber: $lineNumber, ' + 'highlighted: $highlighted)'; +} /// Builds the span for one [token], replacing the default. [style] is the /// token's themed style (`null` for plain text). Return a [TextSpan] with @@ -34,7 +71,7 @@ typedef CodeSpanBuilder = /// One piece of highlighted code, as passed to [CodeView.onTokenTap] and /// [CodeView.spanBuilder]. Pieces never cross a line break. @immutable -class CodeToken { +final class CodeToken { /// Creates a token. const CodeToken({ required this.text, @@ -72,11 +109,15 @@ class CodeToken { /// CodeView(source, language: dartLanguage) /// ``` /// -/// Everything else is optional. The theme follows the app's brightness -/// (see [CodeTheme] for app-wide defaults). Results are cached, and inputs -/// above [CodeHighlighter.isolateThreshold] are highlighted in a background +/// Everything else is optional. The theme follows the brightness (see +/// [CodeTheme] for app-wide defaults). Results are cached, and inputs above +/// [CodeHighlighter.isolateThreshold] are highlighted in a background /// isolate while plain text is shown. /// +/// Code is always laid out left to right, even in a right-to-left app. To +/// let people select and copy it, put it — or the page around it — inside +/// a `SelectionArea`; line numbers are never selected. +/// /// Short code renders as one text block. Code with more than /// [virtualizeAbove] lines, placed where its height is bounded, renders one /// row per line in a lazy list, so only visible lines are laid out. @@ -89,14 +130,13 @@ class CodeView extends StatefulWidget { this.detectLanguages = const [], this.fallbackLanguage = genericLanguage, this.theme, - this.textStyle, + this.style, this.padding, this.lineNumbers, this.firstLineNumber = 1, this.highlightedLines = const {}, this.highlightColor, this.wrap = false, - this.selectable = true, this.highlighter, this.virtualizeAbove = 1000, this.gutterBuilder, @@ -125,15 +165,16 @@ class CodeView extends StatefulWidget { /// Color theme. Defaults to [CodeTheme] or the built-in light/dark theme. final ValTheme? theme; - /// Text style merged over the default monospace style. - final TextStyle? textStyle; + /// Text style merged over the default code style + /// ([CodeTheme.textStyleOf]). + final TextStyle? style; - /// Padding inside the background. Defaults to [CodeTheme.padding], or 16 - /// on every side. + /// Padding inside the background. Defaults to [CodeThemeData.padding], + /// or 16 on every side. final EdgeInsetsGeometry? padding; - /// Whether to show line numbers. Defaults to [CodeTheme.lineNumbers], or - /// `false`. + /// Whether to show line numbers. Defaults to + /// [CodeThemeData.lineNumbers], or `false`. final bool? lineNumbers; /// Number shown for the first line. @@ -148,9 +189,6 @@ class CodeView extends StatefulWidget { /// Whether long lines wrap. When `false`, code scrolls horizontally. final bool wrap; - /// Whether the code can be selected and copied. - final bool selectable; - /// Highlighter to use. Defaults to [CodeHighlighter.shared]. final CodeHighlighter? highlighter; @@ -166,7 +204,8 @@ class CodeView extends StatefulWidget { /// A widget shown above the code, such as a title or copy button. final Widget? header; - /// Vertical scroll controller for the lazy list. + /// Vertical scroll controller for the lazy list. Only attached while the + /// code is laid out lazily (see [virtualizeAbove]). final ScrollController? scrollController; /// Called when a token is tapped, such as an identifier to jump to. @@ -253,11 +292,28 @@ class _CodeViewState extends State { } _result = highlighter.cached(code, language); if (_result != null) return; - highlighter.highlight(code, language).then((result) { - if (mounted && generation == _generation) { - setState(() => _result = result); - } - }); + highlighter + .highlight(code, language) + .then( + (result) { + if (mounted && generation == _generation) { + setState(() => _result = result); + } + }, + onError: (Object error, StackTrace stack) { + // The code stays plain; report the failure like a build error. + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stack, + library: 'val_highlight_flutter', + context: ErrorDescription( + 'while highlighting code for CodeView', + ), + ), + ); + }, + ); } HighlightResult get _current => @@ -273,15 +329,15 @@ class _CodeViewState extends State { if (_styles?.theme != theme) _styles = CodeStyles(theme); final styles = _styles!; final codeTheme = CodeTheme.maybeOf(context); - final base = styles.rootStyle( - CodeTheme.textStyleOf(context, widget.textStyle), - ); + final base = styles.rootStyle(CodeTheme.textStyleOf(context, widget.style)); final layout = _Layout( result: _current, styles: styles, base: base, strut: StrutStyle.fromTextStyle(base, forceStrutHeight: true), - lineHeight: (base.fontSize ?? 14) * (base.height ?? 1.2), + lineHeight: + MediaQuery.textScalerOf(context).scale(base.fontSize ?? 14) * + (base.height ?? 1.2), lineNumbers: widget.lineNumbers ?? codeTheme?.lineNumbers ?? false, highlightColor: widget.highlightColor ?? @@ -297,11 +353,13 @@ class _CodeViewState extends State { Widget content = Padding( padding: widget.padding ?? codeTheme?.padding ?? const EdgeInsets.all(16), - child: LayoutBuilder( - builder: (context, constraints) => _body(layout, constraints), + child: Directionality( + textDirection: TextDirection.ltr, + child: LayoutBuilder( + builder: (context, constraints) => _body(layout, constraints), + ), ), ); - if (widget.selectable) content = SelectionArea(child: content); if (widget.header != null) { content = Column( mainAxisSize: MainAxisSize.min, @@ -313,7 +371,7 @@ class _CodeViewState extends State { ); } return ColoredBox( - color: background == null ? Colors.transparent : Color(background), + color: Color(background ?? 0x00000000), child: content, ); }, @@ -392,8 +450,8 @@ class _CodeViewState extends State { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ - SelectionContainer.disabled( - child: Column( + _gutter( + Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ for (var line = 0; line < result.lineCount; line++) @@ -441,11 +499,8 @@ class _CodeViewState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (layout.lineNumbers) ...[ - SelectionContainer.disabled( - child: SizedBox( - width: gutterWidth, - child: _gutterCell(layout, line), - ), + _gutter( + SizedBox(width: gutterWidth, child: _gutterCell(layout, line)), ), const SizedBox(width: 16), ], @@ -455,7 +510,8 @@ class _CodeViewState extends State { if (widget.highlightedLines.contains(number)) { child = ColoredBox(color: layout.highlightColor, child: child); } - return widget.lineBuilder?.call(context, line, child) ?? child; + final builder = widget.lineBuilder; + return builder == null ? child : builder(context, _details(line), child); } Widget list; @@ -545,12 +601,24 @@ class _CodeViewState extends State { return spans; } + CodeLineDetails _details(int line) { + final number = widget.firstLineNumber + line; + return CodeLineDetails( + line: line, + lineNumber: number, + highlighted: widget.highlightedLines.contains(number), + ); + } + + /// Line numbers are not part of the code: never selected, and not read + /// out by screen readers. + static Widget _gutter(Widget child) => + SelectionContainer.disabled(child: ExcludeSemantics(child: child)); + Widget _gutterCell(_Layout layout, int line) { final number = widget.firstLineNumber + line; final builder = widget.gutterBuilder; - if (builder != null) { - return builder(context, number, widget.highlightedLines.contains(number)); - } + if (builder != null) return builder(context, _details(line)); // Line numbers never wrap, even if the gutter is a pixel too narrow. return Text( '$number', diff --git a/val_highlight_flutter/lib/src/editor_decorations.dart b/val_highlight_flutter/lib/src/editor_decorations.dart index 2b96f44..48603f2 100644 --- a/val_highlight_flutter/lib/src/editor_decorations.dart +++ b/val_highlight_flutter/lib/src/editor_decorations.dart @@ -238,10 +238,9 @@ class RenderEditorDecorations extends RenderBox { final selection = _config.controller.selection; final caretLine = selection.isValid - ? _lineOf(result, selection.extentOffset) + ? result.lineAt(selection.extentOffset) : -1; - final firstVisible = _lineOf( - result, + final firstVisible = result.lineAt( editable .getPositionForPoint( localToGlobal(Offset(visible.left + 1, visible.top + 1)), @@ -335,18 +334,4 @@ class RenderEditorDecorations extends RenderBox { } return _match; } - - static int _lineOf(HighlightResult result, int offset) { - var low = 0; - var high = result.lineCount - 1; - while (low < high) { - final mid = (low + high + 1) >> 1; - if (result.lineStart(mid) <= offset) { - low = mid; - } else { - high = mid - 1; - } - } - return low; - } } diff --git a/val_highlight_flutter/lib/src/highlight_text_controller.dart b/val_highlight_flutter/lib/src/highlight_text_controller.dart index 60ad610..8951b42 100644 --- a/val_highlight_flutter/lib/src/highlight_text_controller.dart +++ b/val_highlight_flutter/lib/src/highlight_text_controller.dart @@ -13,13 +13,15 @@ import 'spans.dart'; /// ``` /// /// Edits are highlighted incrementally: only the lines an edit can affect -/// are re-scanned, so typing stays fast in large documents. +/// are re-scanned, so typing stays fast in large documents. A plain +/// [TextField] still lays out and colors its whole text on every change; +/// for long text use `CodeField`, which colors only the lines on screen. class HighlightTextController extends TextEditingController { /// Creates a controller for [language]. /// - /// [theme] defaults to [CodeTheme] or the built-in theme for the app's - /// brightness. [registry] resolves languages named inside the text, such - /// as Markdown code fences. + /// [theme] defaults to [CodeTheme]'s theme for the current brightness. + /// [registry] resolves languages named inside the text, such as Markdown + /// code fences. HighlightTextController({ super.text, required Grammar language, @@ -36,17 +38,11 @@ class HighlightTextController extends TextEditingController { CodeStyles? _styles; ({int first, int last})? _window; - /// Zero-based lines to color, or `null` for all of them. - /// - /// Laying out a text field with many thousands of styled runs is slow, so - /// for large documents only the visible lines, plus a margin, need - /// colors. `CodeField` sets this automatically as you scroll. - ({int first, int last})? get window => _window; - set window(({int first, int last})? value) { - if (value == _window) return; - _window = value; - notifyListeners(); - } + // Offsets of closers a CodeEditingFormatter inserted, in increasing + // order, and the text they were recorded for. Kept here rather than in + // the formatter, so a formatter created anew in each build keeps them. + final List _closers = []; + String? _closersText; /// The language of the text. Setting it re-highlights everything. Grammar get language => _document.language; @@ -56,7 +52,7 @@ class HighlightTextController extends TextEditingController { notifyListeners(); } - /// The theme, or `null` to follow the app. + /// The theme, or `null` to follow [CodeTheme]. ValTheme? get theme => _theme; set theme(ValTheme? value) { if (identical(value, _theme)) return; @@ -67,6 +63,12 @@ class HighlightTextController extends TextEditingController { /// The highlight result for the current text. HighlightResult get result => _document.update(text); + void _setWindow(({int first, int last})? value) { + if (value == _window) return; + _window = value; + notifyListeners(); + } + @override TextSpan buildTextSpan({ required BuildContext context, @@ -103,3 +105,19 @@ class HighlightTextController extends TextEditingController { ); } } + +/// State the package's own widgets keep on a [HighlightTextController]. +/// Not exported. +extension HighlightTextControllerInternals on HighlightTextController { + /// Zero-based lines to color, or `null` for all of them. `CodeField` sets + /// this as the field scrolls. + ({int first, int last})? get window => _window; + set window(({int first, int last})? value) => _setWindow(value); + + /// Closers inserted automatically, for `CodeEditingFormatter`. + List get autoClosers => _closers; + + /// The text [autoClosers] were recorded for. + String? get autoClosersText => _closersText; + set autoClosersText(String? value) => _closersText = value; +} diff --git a/val_highlight_flutter/lib/val_highlight_flutter.dart b/val_highlight_flutter/lib/val_highlight_flutter.dart index f3ab08c..436ed95 100644 --- a/val_highlight_flutter/lib/val_highlight_flutter.dart +++ b/val_highlight_flutter/lib/val_highlight_flutter.dart @@ -7,9 +7,13 @@ /// CodeView(source, language: dartLanguage) /// ``` /// -/// This library re-exports `package:val_highlight/val_highlight.dart`, so -/// one import covers the core API. Languages and themes are separate -/// imports under `package:val_highlight/languages/` and `themes/`. +/// This library needs only Flutter's widgets layer, so it works in any app, +/// whatever its design system. The code editor, `CodeField`, is built on +/// `material_ui` and is in `package:val_highlight_flutter/material.dart`. +/// +/// It re-exports `package:val_highlight/val_highlight.dart`, so one import +/// covers the core API. Languages and themes are separate imports under +/// `package:val_highlight/languages/` and `themes/`. library; export 'package:val_highlight/val_highlight.dart'; @@ -22,14 +26,14 @@ export 'src/code_editing.dart' OutdentCodeIntent, ToggleCommentIntent, toggleComment; -export 'src/code_field.dart' show CodeField; export 'src/code_highlighter.dart' show CodeHighlighter; export 'src/code_styles.dart' show CodeStyles, textStyleFromStyle; -export 'src/code_theme.dart' show CodeTheme; +export 'src/code_theme.dart' show CodeTheme, CodeThemeData; export 'src/code_view.dart' show CodeGutterBuilder, CodeLineBuilder, + CodeLineDetails, CodeSpanBuilder, CodeToken, CodeView; diff --git a/val_highlight_flutter/pubspec.yaml b/val_highlight_flutter/pubspec.yaml index d941e8e..82be41a 100644 --- a/val_highlight_flutter/pubspec.yaml +++ b/val_highlight_flutter/pubspec.yaml @@ -1,6 +1,6 @@ name: val_highlight_flutter -description: "Flutter widgets for syntax-highlighted code: CodeView for display and CodeField for editing, with 55 languages, themes and smooth large files." -version: 0.1.2 +description: "Flutter widgets for syntax-highlighted code: CodeView to show it and CodeField to edit it, with 55 languages, themes and smooth large files." +version: 1.0.0 homepage: https://github.com/useval/highlight repository: https://github.com/useval/highlight/tree/main/val_highlight_flutter issue_tracker: https://github.com/useval/highlight/issues diff --git a/val_highlight_flutter/test/code_editing_test.dart b/val_highlight_flutter/test/code_editing_test.dart index 6230ccf..e2703de 100644 --- a/val_highlight_flutter/test/code_editing_test.dart +++ b/val_highlight_flutter/test/code_editing_test.dart @@ -381,4 +381,32 @@ void main() { expect(toggle('a', 0, 5), isNull); }); }); + test( + 'a new formatter for the same controller keeps the auto-closed pair', + () { + final controller = HighlightTextController( + text: 'f', + language: dartLanguage, + )..selection = const TextSelection.collapsed(offset: 1); + TextEditingValue type(String char) { + final value = controller.value; + final at = value.selection.start; + // A new formatter for every edit, as a build method would make. + return controller.value = CodeEditingFormatter(controller: controller) + .formatEditUpdate( + value, + TextEditingValue( + text: value.text.replaceRange(at, at, char), + selection: TextSelection.collapsed(offset: at + 1), + ), + ); + } + + type('('); + expect(controller.text, 'f()'); + type(')'); + expect(controller.text, 'f()'); + expect(controller.selection.baseOffset, 3); + }, + ); } diff --git a/val_highlight_flutter/test/code_field_test.dart b/val_highlight_flutter/test/code_field_test.dart index b867dcc..25ddbef 100644 --- a/val_highlight_flutter/test/code_field_test.dart +++ b/val_highlight_flutter/test/code_field_test.dart @@ -3,9 +3,12 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:val_highlight/languages/dart.dart'; -import 'package:val_highlight_flutter/src/code_field.dart'; +import 'package:val_highlight_flutter/material.dart'; +import 'package:val_highlight_flutter/src/code_editing.dart' + show indentText, newlineKeepingIndent, outdentLines; import 'package:val_highlight_flutter/src/editor_decorations.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/src/highlight_text_controller.dart' + show HighlightTextControllerInternals; String _lines(int n) => List.generate(n, (i) => 'final value$i = compute($i); // $i').join('\n'); @@ -282,6 +285,32 @@ void main() { }); group('shortcuts', () { + testWidgets('shortcut edits go through the input formatters', ( + tester, + ) async { + final controller = await pumpField( + tester, + 'abc', + build: (controller) => CodeField( + controller: controller, + expands: true, + inputFormatters: [LengthLimitingTextInputFormatter(4)], + ), + ); + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pump(); + expect(controller.text.length, lessThanOrEqualTo(4)); + }); + + testWidgets('default shortcuts are the same map every time', ( + tester, + ) async { + expect( + identical(CodeField.defaultShortcuts, CodeField.defaultShortcuts), + isTrue, + ); + }); + testWidgets('Ctrl+/ toggles a comment', (tester) async { final controller = await pumpField(tester, 'a();\nb();', caret: 2); await pressCombo(tester, LogicalKeyboardKey.slash); @@ -376,6 +405,36 @@ void main() { ); }); + testWidgets('CodeTheme can turn line numbers on', (tester) async { + await pumpField( + tester, + 'a\nb', + wrap: (field) => CodeTheme( + data: const CodeThemeData(lineNumbers: true), + child: field, + ), + ); + expect(textLeft(tester), greaterThan(16)); + }); + + testWidgets('code stays left to right in a right-to-left app', ( + tester, + ) async { + await pumpField( + tester, + 'a\nb', + wrap: (field) => + Directionality(textDirection: TextDirection.rtl, child: field), + build: (controller) => + CodeField(controller: controller, expands: true, lineNumbers: true), + ); + final editable = tester + .state(find.byType(EditableText)) + .renderEditable; + expect(editable.textDirection, TextDirection.ltr); + expect(textLeft(tester), greaterThan(16)); + }); + testWidgets('no gutter by default', (tester) async { await pumpField(tester, 'a\nb'); expect(textLeft(tester), 0); diff --git a/val_highlight_flutter/test/code_view_test.dart b/val_highlight_flutter/test/code_view_test.dart index 3b5ff5e..2f3f2b7 100644 --- a/val_highlight_flutter/test/code_view_test.dart +++ b/val_highlight_flutter/test/code_view_test.dart @@ -1,4 +1,5 @@ import 'package:material_ui/material_ui.dart'; +import 'package:flutter/rendering.dart' show RenderParagraph; import 'package:flutter_test/flutter_test.dart'; import 'package:val_highlight/languages/all.dart'; import 'package:val_highlight/themes/dark.dart'; @@ -54,12 +55,11 @@ void main() { expect(_colorOf(tester, ' x '), _c(lightTheme.root.color!)); }); - testWidgets('follows dark brightness', (tester) async { + testWidgets('follows the platform brightness', (tester) async { + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); await tester.pumpWidget( - _app( - const CodeView('final x = 1;', language: dartLanguage), - theme: ThemeData(brightness: Brightness.dark), - ), + _app(const CodeView('final x = 1;', language: dartLanguage)), ); expect( _colorOf(tester, 'final'), @@ -67,28 +67,67 @@ void main() { ); }); - testWidgets('CodeTheme extension and widget theme override', (tester) async { + testWidgets('CodeTheme sets the brightness and the themes', (tester) async { final custom = lightTheme.extend( styles: {Scopes.keyword: const Style(color: 0xFF123456)}, ); await tester.pumpWidget( _app( - const CodeView('final x;', language: dartLanguage), - theme: ThemeData(extensions: [CodeTheme(light: custom)]), + CodeTheme( + data: CodeThemeData(light: custom, brightness: Brightness.light), + child: const CodeView('final x;', language: dartLanguage), + ), ), ); expect(_colorOf(tester, 'final'), const Color(0xFF123456)); await tester.pumpWidget( _app( - const CodeView('final x;', language: dartLanguage, theme: darkTheme), - theme: ThemeData(extensions: [CodeTheme(light: custom)]), + const CodeTheme( + data: CodeThemeData(brightness: Brightness.dark), + child: CodeView('final x;', language: dartLanguage), + ), ), ); expect( _colorOf(tester, 'final'), _c(darkTheme.lookup(Scopes.keyword)!.color!), ); + + await tester.pumpWidget( + _app( + CodeTheme( + data: CodeThemeData(light: custom), + child: const CodeView( + 'final x;', + language: dartLanguage, + theme: darkTheme, + ), + ), + ), + ); + expect( + _colorOf(tester, 'final'), + _c(darkTheme.lookup(Scopes.keyword)!.color!), + ); + }); + + testWidgets('works without any Material ancestor', (tester) async { + await tester.pumpWidget( + WidgetsApp( + color: const Color(0xFFFFFFFF), + builder: (context, _) => const CodeView( + 'final x = 1;\nfinal y = 2;', + language: dartLanguage, + lineNumbers: true, + ), + ), + ); + expect(tester.takeException(), isNull); + expect( + _colorOf(tester, 'final'), + _c(lightTheme.lookup(Scopes.keyword)!.color!), + ); }); testWidgets('line numbers', (tester) async { @@ -119,10 +158,12 @@ void main() { lineNumbers: true, highlightedLines: const {2}, highlightColor: const Color(0xFFFF0000), - gutterBuilder: (context, number, highlighted) => - SizedBox(width: 30, child: Text(highlighted ? '>' : '$number')), + gutterBuilder: (context, line) => SizedBox( + width: 30, + child: Text(line.highlighted ? '>' : '${line.lineNumber}'), + ), lineBuilder: (context, line, child) => - KeyedSubtree(key: ValueKey('line$line'), child: child), + KeyedSubtree(key: ValueKey('line${line.line}'), child: child), ), ), ); @@ -383,4 +424,63 @@ void main() { controller.dispose(); }); }); + testWidgets('rows are tall enough at a large text scale', (tester) async { + final source = List.generate(50, (i) => 'line $i').join('\n'); + await tester.pumpWidget( + MediaQuery( + data: const MediaQueryData(textScaler: TextScaler.linear(2)), + child: _app( + SizedBox( + height: 400, + child: CodeView( + source, + language: plainTextLanguage, + virtualizeAbove: 10, + ), + ), + ), + ), + ); + final row = tester.getSize(find.text('line 0').first); + final text = tester.renderObject( + find.text('line 0').first, + ); + expect(text.textSize.height, lessThanOrEqualTo(row.height + 0.5)); + expect(row.height, closeTo(14 * 2 * 1.5, 0.5)); + }); + + testWidgets('code stays left to right in a right-to-left app', ( + tester, + ) async { + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.rtl, + child: _app(const CodeView('final x = 1;', language: dartLanguage)), + ), + ); + final paragraph = tester.renderObject( + find.descendant( + of: find.byType(CodeView), + matching: find.byType(RichText), + ), + ); + expect(paragraph.textDirection, TextDirection.ltr); + }); + + testWidgets('screen readers skip the line numbers', (tester) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget( + _app( + const CodeView( + 'alpha\nbeta', + language: plainTextLanguage, + lineNumbers: true, + firstLineNumber: 41, + ), + ), + ); + expect(find.bySemanticsLabel(RegExp('41')), findsNothing); + expect(find.bySemanticsLabel(RegExp('alpha')), findsOneWidget); + semantics.dispose(); + }); } diff --git a/val_highlight_flutter/test/docs/api_completeness_test.dart b/val_highlight_flutter/test/docs/api_completeness_test.dart index a1c80a1..a6a61b6 100644 --- a/val_highlight_flutter/test/docs/api_completeness_test.dart +++ b/val_highlight_flutter/test/docs/api_completeness_test.dart @@ -26,6 +26,7 @@ void main() { 'package:val_highlight/themes/dark.dart', 'package:val_highlight/val_highlight.dart', 'package:val_highlight_flutter/val_highlight_flutter.dart', + 'package:val_highlight_flutter/material.dart', ]) { expect(libraries, contains(uri)); } @@ -34,6 +35,8 @@ void main() { for (final id in [ 'CodeView', 'CodeView.new', + 'CodeThemeData.brightness', + 'CodeLineDetails.lineNumber', 'CodeView.code', 'CodeField.defaultShortcuts', 'Grammar.validate', diff --git a/val_highlight_flutter/test/docs/public_api.dart b/val_highlight_flutter/test/docs/public_api.dart index 6ee6d6a..9573643 100644 --- a/val_highlight_flutter/test/docs/public_api.dart +++ b/val_highlight_flutter/test/docs/public_api.dart @@ -237,8 +237,10 @@ List undocumented(List api, Directory docs) { sections[h[1]!] = section.split('{/* Generated by').first; } + // A row documents a symbol when one of its cells is the symbol itself, + // not when a description merely mentions it. bool inTable(String code) => RegExp( - r'^\|.*`' + RegExp.escape(code) + r'`.*\|$', + r'^\|(?:.*\|)?\s*`' + RegExp.escape(code) + r'`\s*\|', multiLine: true, ).hasMatch(ref); diff --git a/val_highlight_flutter/test/docs/snippets_test.dart b/val_highlight_flutter/test/docs/snippets_test.dart index cf94408..8aef84e 100644 --- a/val_highlight_flutter/test/docs/snippets_test.dart +++ b/val_highlight_flutter/test/docs/snippets_test.dart @@ -8,7 +8,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:val_highlight/languages/all.dart'; import 'package:val_highlight/themes/all.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/material.dart'; const source = 'void main() {\n print(1);\n}\n'; @@ -28,15 +28,18 @@ void main() { source, language: dartLanguage, lineNumbers: true, - gutterBuilder: (context, lineNumber, highlighted) => SizedBox( + gutterBuilder: (context, line) => SizedBox( width: 32, child: Text( - '$lineNumber', + '${line.lineNumber}', textAlign: TextAlign.right, - style: TextStyle(fontWeight: highlighted ? FontWeight.bold : null), + style: TextStyle( + fontWeight: line.highlighted ? FontWeight.bold : null, + ), ), ), ), + const SelectionArea(child: CodeView(source, language: dartLanguage)), CodeView( source, language: dartLanguage, @@ -153,7 +156,6 @@ void main() { text: 'SELECT 1;', ); addTearDown(controller.dispose); - controller.window = (first: 0, last: 199); await tester.pumpWidget( _app( TextField( @@ -171,26 +173,32 @@ void main() { theme: sepiaTheme, ); addTearDown(controller.dispose); - const codeTheme = CodeTheme( - light: sepiaTheme, - dark: dimTheme, - textStyle: TextStyle(fontFamily: 'JetBrains Mono'), - lineNumbers: true, - ); - await tester.pumpWidget( - MaterialApp( - theme: ThemeData(extensions: const [codeTheme]), - darkTheme: ThemeData( - brightness: Brightness.dark, - extensions: const [codeTheme], - ), - home: const Scaffold( - body: CodeView(source, language: dartLanguage, theme: midnightTheme), + Widget app(ThemeMode mode) => MaterialApp( + themeMode: mode, + theme: ThemeData(), + darkTheme: ThemeData(brightness: Brightness.dark), + builder: (context, child) => CodeTheme( + data: CodeThemeData( + light: sepiaTheme, + dark: dimTheme, + brightness: Theme.of(context).brightness, + textStyle: const TextStyle(fontFamily: 'JetBrains Mono'), + lineNumbers: true, ), + child: child!, + ), + home: const Scaffold( + body: CodeView(source, language: dartLanguage, theme: midnightTheme), ), ); - final context = tester.element(find.byType(CodeView)); + await tester.pumpWidget(app(ThemeMode.light)); + var context = tester.element(find.byType(CodeView)); expect(CodeTheme.resolve(context), same(sepiaTheme)); + expect(CodeTheme.brightnessOf(context), Brightness.light); + await tester.pumpWidget(app(ThemeMode.dark)); + await tester.pumpAndSettle(); + context = tester.element(find.byType(CodeView)); + expect(CodeTheme.resolve(context), same(dimTheme)); expect(CodeTheme.textStyleOf(context).fontSize, 14); expect(CodeTheme.textStyleOf(context).height, 1.5); diff --git a/val_highlight_flutter/test/flutter_material_test.dart b/val_highlight_flutter/test/flutter_material_test.dart new file mode 100644 index 0000000..5611254 --- /dev/null +++ b/val_highlight_flutter/test/flutter_material_test.dart @@ -0,0 +1,43 @@ +// An app built the way most apps still are, on package:flutter/material.dart +// rather than material_ui. The widgets-layer library must work there. +// ignore_for_file: deprecated_member_use +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:val_highlight/languages/dart.dart'; +import 'package:val_highlight/themes/dark.dart'; +import 'package:val_highlight_flutter/val_highlight_flutter.dart'; + +void main() { + testWidgets( + 'CodeView, a controller and CodeTheme in a flutter/material app', + (tester) async { + final controller = HighlightTextController( + text: 'final x = 1;', + language: dartLanguage, + ); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + theme: ThemeData(brightness: Brightness.dark), + builder: (context, child) => CodeTheme( + data: CodeThemeData(brightness: Theme.of(context).brightness), + child: child!, + ), + home: Scaffold( + body: SelectionArea( + child: Column( + children: [ + const CodeView('void main() {}', language: dartLanguage), + TextField(controller: controller, maxLines: null), + ], + ), + ), + ), + ), + ); + expect(tester.takeException(), isNull); + final context = tester.element(find.byType(CodeView)); + expect(CodeTheme.resolve(context), same(darkTheme)); + }, + ); +} diff --git a/val_highlight_flutter/tool/docs/api_reference.dart b/val_highlight_flutter/tool/docs/api_reference.dart index 68465f5..16ab61b 100644 --- a/val_highlight_flutter/tool/docs/api_reference.dart +++ b/val_highlight_flutter/tool/docs/api_reference.dart @@ -35,6 +35,7 @@ const pages = >{ 'code-view': [ 'CodeView', 'CodeToken', + 'CodeLineDetails', 'CodeGutterBuilder', 'CodeLineBuilder', 'CodeSpanBuilder', @@ -73,7 +74,7 @@ const pages = >{ 'allLanguages', 'allLanguagesRegistry', ], - 'themes': ['ValTheme', 'Style', 'CodeTheme', 'allThemes'], + 'themes': ['ValTheme', 'Style', 'CodeTheme', 'CodeThemeData', 'allThemes'], 'grammar': [ 'Grammar', 'Rule', @@ -652,7 +653,7 @@ String _constructor( List<_Param> params, Map types, ) { - const superTypes = {'key': 'Key?', 'text': 'String?'}; + const superTypes = {'key': 'Key?', 'text': 'String?', 'child': 'Widget'}; final name = header.substring(0, header.indexOf('(')); final lines = []; var group = ''; diff --git a/val_highlight_flutter/tool/screenshots/examples/code_field/editor.dart b/val_highlight_flutter/tool/screenshots/examples/code_field/editor.dart index 94a8edc..20ed955 100644 --- a/val_highlight_flutter/tool/screenshots/examples/code_field/editor.dart +++ b/val_highlight_flutter/tool/screenshots/examples/code_field/editor.dart @@ -1,6 +1,6 @@ import 'package:material_ui/material_ui.dart'; import 'package:val_highlight/languages/python.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/material.dart'; const source = ''' from dataclasses import dataclass diff --git a/val_highlight_flutter/tool/screenshots/generate_test.dart b/val_highlight_flutter/tool/screenshots/generate_test.dart index 065ff90..2559d3f 100644 --- a/val_highlight_flutter/tool/screenshots/generate_test.dart +++ b/val_highlight_flutter/tool/screenshots/generate_test.dart @@ -23,7 +23,7 @@ import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:val_highlight/languages/all.dart'; import 'package:val_highlight/themes/all.dart'; -import 'package:val_highlight_flutter/val_highlight_flutter.dart'; +import 'package:val_highlight_flutter/material.dart'; import 'examples/code_field/editor.dart' as code_field_editor; import 'examples/code_view/basic.dart' as code_view_basic; @@ -480,15 +480,16 @@ class _Preview extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, - theme: ThemeData( - useMaterial3: true, - fontFamily: 'Roboto', - extensions: const [ + theme: ThemeData(useMaterial3: true, fontFamily: 'Roboto'), + builder: (context, child) => CodeTheme( + data: CodeThemeData( + brightness: Theme.of(context).brightness, // JetBrains Mono draws `=>` as an arrow; show the source as typed. - CodeTheme( - textStyle: TextStyle(fontFeatures: [FontFeature.disable('calt')]), + textStyle: const TextStyle( + fontFeatures: [FontFeature.disable('calt')], ), - ], + ), + child: child!, ), home: SingleChildScrollView( child: Align( @@ -583,12 +584,16 @@ class _Showcase extends StatelessWidget { useMaterial3: true, fontFamily: 'Roboto', brightness: theme.dark ? Brightness.dark : Brightness.light, - extensions: const [ + ), + builder: (context, child) => CodeTheme( + data: CodeThemeData( + brightness: Theme.of(context).brightness, // JetBrains Mono draws `=>` as an arrow; show the source as typed. - CodeTheme( - textStyle: TextStyle(fontFeatures: [FontFeature.disable('calt')]), + textStyle: const TextStyle( + fontFeatures: [FontFeature.disable('calt')], ), - ], + ), + child: child!, ), home: Align( alignment: Alignment.topLeft,