feat: richtextfield

Signed-off-by: bggRGjQaUbCoE <githubaccount56556@proton.me>
This commit is contained in:
bggRGjQaUbCoE
2025-06-27 12:02:32 +08:00
parent 721bf2d59f
commit 6f2570c5be
26 changed files with 7154 additions and 870 deletions

View File

@@ -47,7 +47,7 @@
## feat
- [x] 动态/评论@用户
- [x] 发布动态/评论支持`富文本编辑`/`表情显示`/`@用户`
- [x] 修改消息设置
- [x] 修改聊天设置
- [x] 展示折叠消息

View File

@@ -0,0 +1,973 @@
/*
* This file is part of PiliPlus
*
* PiliPlus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PiliPlus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PiliPlus. If not, see <https://www.gnu.org/licenses/>.
*/
import 'dart:math';
import 'package:PiliPlus/common/widgets/image/network_img_layer.dart';
import 'package:PiliPlus/models/common/image_type.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
///
/// created by bggRGjQaUbCoE on 2025/6/27
///
enum RichTextType { text, composing, at, emoji }
class Emote {
late String url;
late double width;
late double height;
Emote({
required this.url,
required this.width,
double? height,
}) : height = height ?? width;
}
mixin RichTextTypeMixin {
RichTextType get type;
Emote? get emote;
String? get uid;
String? get rawText;
}
extension TextEditingDeltaExt on TextEditingDelta {
({RichTextType type, String? rawText, Emote? emote, String? uid}) get config {
if (this case RichTextTypeMixin e) {
return (type: e.type, rawText: e.rawText, emote: e.emote, uid: e.uid);
}
return (
type: composing.isValid ? RichTextType.composing : RichTextType.text,
rawText: null,
emote: null,
uid: null
);
}
bool get isText {
if (this case RichTextTypeMixin e) {
return e.type == RichTextType.text;
}
return !composing.isValid;
}
bool get isComposing {
return composing.isValid;
}
}
class RichTextEditingDeltaInsertion extends TextEditingDeltaInsertion
with RichTextTypeMixin {
RichTextEditingDeltaInsertion({
required super.oldText,
required super.textInserted,
required super.insertionOffset,
required super.selection,
required super.composing,
RichTextType? type,
this.emote,
this.uid,
this.rawText,
}) {
this.type = type ??
(composing.isValid ? RichTextType.composing : RichTextType.text);
}
@override
late final RichTextType type;
@override
final Emote? emote;
@override
final String? uid;
@override
final String? rawText;
}
class RichTextEditingDeltaReplacement extends TextEditingDeltaReplacement
with RichTextTypeMixin {
RichTextEditingDeltaReplacement({
required super.oldText,
required super.replacementText,
required super.replacedRange,
required super.selection,
required super.composing,
RichTextType? type,
this.emote,
this.uid,
this.rawText,
}) {
this.type = type ??
(composing.isValid ? RichTextType.composing : RichTextType.text);
}
@override
late final RichTextType type;
@override
final Emote? emote;
@override
final String? uid;
@override
final String? rawText;
}
class RichTextItem {
late RichTextType type;
late String text;
String? _rawText;
late TextRange range;
Emote? emote;
String? uid;
String get rawText => _rawText ?? text;
bool get isText => type == RichTextType.text;
bool get isComposing => type == RichTextType.composing;
bool get isRich => type == RichTextType.at || type == RichTextType.emoji;
RichTextItem({
this.type = RichTextType.text,
required this.text,
String? rawText,
required this.range,
this.emote,
this.uid,
}) {
_rawText = rawText;
}
RichTextItem.fromStart(
this.text, {
String? rawText,
this.type = RichTextType.text,
this.emote,
this.uid,
}) {
range = TextRange(start: 0, end: text.length);
_rawText = rawText;
}
List<RichTextItem>? onInsert(
TextEditingDeltaInsertion delta,
RichTextEditingController controller,
) {
final int insertionOffset = delta.insertionOffset;
if (range.end < insertionOffset) {
return null;
}
if (insertionOffset == 0 && range.start == 0) {
final insertedLength = delta.textInserted.length;
controller.newSelection = TextSelection.collapsed(offset: insertedLength);
if (isText && delta.isText) {
text = delta.textInserted + text;
range = TextRange(start: range.start, end: range.start + text.length);
return null;
}
range = TextRange(
start: range.start + insertedLength,
end: range.end + insertedLength,
);
final config = delta.config;
final insertedItem = RichTextItem.fromStart(
delta.textInserted,
rawText: config.rawText,
type: config.type,
emote: config.emote,
uid: config.uid,
);
return [insertedItem];
}
if (range.start >= insertionOffset) {
final int insertedLength = delta.textInserted.length;
range = TextRange(
start: range.start + insertedLength,
end: range.end + insertedLength,
);
return null;
}
if (range.end == insertionOffset) {
final end = insertionOffset + delta.textInserted.length;
controller.newSelection = TextSelection.collapsed(offset: end);
if ((isText && delta.isText) || (isComposing && delta.isComposing)) {
text += delta.textInserted;
range = TextRange(start: range.start, end: end);
return null;
}
final config = delta.config;
final insertedItem = RichTextItem(
type: config.type,
emote: config.emote,
uid: config.uid,
text: delta.textInserted,
rawText: config.rawText,
range: TextRange(start: insertionOffset, end: end),
);
return [insertedItem];
}
if (isText &&
range.start < insertionOffset &&
range.end > insertionOffset) {
final leadingText = text.substring(0, insertionOffset - range.start);
final trailingString = text.substring(leadingText.length);
final insertEnd = insertionOffset + delta.textInserted.length;
controller.newSelection = TextSelection.collapsed(offset: insertEnd);
if (delta.isText) {
text = leadingText + delta.textInserted + trailingString;
range = TextRange(
start: range.start,
end: range.start + text.length,
);
return null;
}
final config = delta.config;
final insertedItem = RichTextItem(
type: config.type,
emote: config.emote,
uid: config.uid,
text: delta.textInserted,
rawText: config.rawText,
range: TextRange(start: insertionOffset, end: insertEnd),
);
final trailItem = RichTextItem(
text: trailingString,
range: TextRange(
start: insertEnd,
end: insertEnd + trailingString.length,
),
);
text = leadingText;
range = TextRange(
start: range.start,
end: range.start + leadingText.length,
);
return [insertedItem, trailItem];
}
return null;
}
({bool remove, bool cal})? onDelete(
TextEditingDeltaDeletion delta,
RichTextEditingController controller,
int? delLength,
) {
final deletedRange = delta.deletedRange;
if (range.end <= deletedRange.start) {
return null;
}
if (range.start >= deletedRange.end) {
final length = delLength ?? delta.textDeleted.length;
range = TextRange(
start: range.start - length,
end: range.end - length,
);
return null;
}
if (range.start < deletedRange.start && range.end > deletedRange.end) {
if (isRich) {
controller.newSelection = TextSelection.collapsed(offset: range.start);
return (remove: true, cal: true);
}
text = text.replaceRange(
deletedRange.start - range.start,
deletedRange.end - range.start,
'',
);
range = TextRange(start: range.start, end: range.start + text.length);
controller.newSelection =
TextSelection.collapsed(offset: deletedRange.start);
return null;
}
if (range.start >= deletedRange.start && range.end <= deletedRange.end) {
if (range.start == deletedRange.start) {
controller.newSelection = TextSelection.collapsed(offset: range.start);
}
return (remove: true, cal: false);
}
if (range.start < deletedRange.start && range.end <= deletedRange.end) {
if (isRich) {
controller.newSelection = TextSelection.collapsed(offset: range.start);
return (remove: true, cal: true);
}
text = text.replaceRange(
text.length - (range.end - deletedRange.start),
null,
'',
);
range = TextRange(
start: range.start,
end: deletedRange.start,
);
controller.newSelection =
TextSelection.collapsed(offset: deletedRange.start);
return null;
}
if (range.start >= deletedRange.start && range.end > deletedRange.end) {
final start = min(deletedRange.start, range.start);
controller.newSelection = TextSelection.collapsed(offset: start);
if (isRich) {
return (remove: true, cal: true);
}
text = text.substring(deletedRange.end - range.start);
range = TextRange(
start: start,
end: start + text.length,
);
return null;
}
return null;
}
({bool remove, List<RichTextItem>? toAdd})? onReplace(
TextEditingDeltaReplacement delta,
RichTextEditingController controller,
) {
final replacedRange = delta.replacedRange;
if (range.end <= replacedRange.start) {
return null;
}
if (range.start >= replacedRange.end) {
final before = replacedRange.end - replacedRange.start;
final after = delta.replacementText.length;
final length = after - before;
range = TextRange(
start: range.start + length,
end: range.end + length,
);
return null;
}
if (range.start < replacedRange.start && range.end > replacedRange.end) {
if (isText) {
if (delta.isText) {
text = text.replaceRange(
replacedRange.start - range.start,
replacedRange.end - range.start,
delta.replacementText,
);
final end = range.start + text.length;
range = TextRange(start: range.start, end: end);
controller.newSelection = TextSelection.collapsed(
offset: replacedRange.start + delta.replacementText.length);
return null;
} else {
final leadingText =
text.substring(0, replacedRange.start - range.start);
final trailString = text.substring(replacedRange.end - range.start);
final insertEnd = replacedRange.start + delta.replacementText.length;
controller.newSelection = TextSelection.collapsed(offset: insertEnd);
final config = delta.config;
final insertedItem = RichTextItem(
type: config.type,
emote: config.emote,
uid: config.uid,
text: delta.replacementText,
rawText: config.rawText,
range: TextRange(
start: replacedRange.start,
end: insertEnd,
),
);
final trailItem = RichTextItem(
text: trailString,
range: TextRange(
start: insertEnd,
end: insertEnd + trailString.length,
),
);
text = leadingText;
range = TextRange(
start: range.start,
end: range.start + leadingText.length,
);
return (
remove: false,
toAdd: [insertedItem, trailItem],
);
}
}
final config = delta.config;
text = delta.replacementText;
type = config.type;
emote = config.emote;
uid = config.uid;
final end = range.start + text.length;
range = TextRange(start: range.start, end: end);
controller.newSelection = TextSelection.collapsed(offset: end);
return null;
}
if (range.start >= replacedRange.start && range.end <= replacedRange.end) {
if (range.start == replacedRange.start) {
text = delta.replacementText;
final config = delta.config;
_rawText = config.rawText;
type = config.type;
emote = config.emote;
uid = config.uid;
final end = range.start + text.length;
range = TextRange(start: range.start, end: end);
controller.newSelection = TextSelection.collapsed(offset: end);
return (remove: false, toAdd: null);
}
return (remove: true, toAdd: null);
}
if (range.start < replacedRange.start && range.end <= replacedRange.end) {
if (isText) {
if (delta.isText) {
text = text.replaceRange(
text.length - (range.end - replacedRange.start),
null,
delta.replacementText,
);
final end = range.start + text.length;
range = TextRange(start: range.start, end: end);
controller.newSelection = TextSelection.collapsed(offset: end);
return null;
} else {
text = text.replaceRange(
text.length - (range.end - replacedRange.start),
null,
'',
);
range = TextRange(start: range.start, end: range.start + text.length);
final end = replacedRange.start + delta.replacementText.length;
final config = delta.config;
final insertedItem = RichTextItem(
text: delta.replacementText,
rawText: config.rawText,
type: config.type,
emote: config.emote,
uid: config.uid,
range: TextRange(start: replacedRange.start, end: end),
);
controller.newSelection = TextSelection.collapsed(offset: end);
return (remove: false, toAdd: [insertedItem]);
}
}
text = delta.replacementText;
final config = delta.config;
type = config.type;
emote = config.emote;
uid = config.uid;
final end = range.start + text.length;
range = TextRange(start: range.start, end: end);
controller.newSelection = TextSelection.collapsed(offset: end);
return null;
}
if (range.start >= replacedRange.start && range.end > replacedRange.end) {
if (range.start > replacedRange.start) {
if (isText) {
text = text.substring(replacedRange.end - range.start);
final start = replacedRange.start + delta.replacementText.length;
range = TextRange(start: start, end: start + text.length);
return null;
}
return (remove: true, toAdd: null);
}
if (isText) {
if (delta.isText) {
text = text.replaceRange(
0,
replacedRange.end - range.start,
delta.replacementText,
);
final end = range.start + text.length;
range = TextRange(start: range.start, end: end);
controller.newSelection = TextSelection.collapsed(offset: end);
return null;
} else {
final end = range.start + delta.replacementText.length;
final config = delta.config;
final insertedItem = RichTextItem(
text: delta.replacementText,
rawText: config.rawText,
type: config.type,
emote: config.emote,
uid: config.uid,
range: TextRange(start: range.start, end: end),
);
controller.newSelection = TextSelection.collapsed(offset: end);
text = text.substring(replacedRange.end - range.start);
range = TextRange(start: end, end: end + text.length);
return (remove: true, toAdd: [insertedItem]);
}
}
text = delta.replacementText;
final config = delta.config;
type = config.type;
emote = config.emote;
uid = config.uid;
final end = range.start + text.length;
range = TextRange(start: range.start, end: end);
controller.newSelection = TextSelection.collapsed(offset: end);
return null;
}
return null;
}
@override
String toString() {
return '\ntype: [${type.name}],'
'text: [$text],'
'rawText: [$_rawText],'
'\nrange: [$range]\n';
}
}
class RichTextEditingController extends TextEditingController {
RichTextEditingController({
List<RichTextItem>? items,
this.onMention,
}) : super(
text: items != null && items.isNotEmpty
? (StringBuffer()..writeAll(items.map((e) => e.text))).toString()
: null,
) {
if (items != null && items.isNotEmpty) {
this.items.addAll(items);
}
}
final VoidCallback? onMention;
TextSelection newSelection = const TextSelection.collapsed(offset: 0);
final List<RichTextItem> items = <RichTextItem>[];
String get plainText {
if (items.isEmpty) {
return '';
}
final buffer = StringBuffer();
for (var e in items) {
buffer.write(e.text);
}
return buffer.toString();
}
String get rawText {
if (items.isEmpty) {
return '';
}
final buffer = StringBuffer();
for (var e in items) {
if (e.type == RichTextType.at) {
buffer.write(e.text);
} else {
buffer.write(e.rawText);
}
}
return buffer.toString();
}
void syncRichText(TextEditingDelta delta) {
if (text.isEmpty) {
items.clear();
}
int? addIndex;
List<RichTextItem>? toAdd;
int? delLength;
List<RichTextItem>? toDel;
switch (delta) {
case TextEditingDeltaInsertion e:
if (e.textInserted == '@') {
onMention?.call();
}
if (items.isEmpty) {
final config = delta.config;
items.add(
RichTextItem.fromStart(
delta.textInserted,
rawText: config.rawText,
type: config.type,
emote: config.emote,
uid: config.uid,
),
);
newSelection =
TextSelection.collapsed(offset: delta.textInserted.length);
return;
}
for (int index = 0; index < items.length; index++) {
List<RichTextItem>? newItems = items[index].onInsert(e, this);
if (newItems != null) {
addIndex = (e.insertionOffset == 0 && index == 0) ? 0 : index + 1;
toAdd = newItems;
}
}
case TextEditingDeltaDeletion e:
for (int index = 0; index < items.length; index++) {
final item = items[index];
({bool remove, bool cal})? res = item.onDelete(e, this, delLength);
if (res != null) {
if (res.remove) {
(toDel ??= <RichTextItem>[]).add(item);
}
if (res.cal) {
delLength ??= item.text.length;
}
}
}
case TextEditingDeltaReplacement e:
for (int index = 0; index < items.length; index++) {
final item = items[index];
({bool remove, List<RichTextItem>? toAdd})? res =
item.onReplace(e, this);
if (res != null) {
if (res.toAdd != null) {
addIndex = res.remove
? index
: (e.replacedRange.start == 0 && index == 0)
? 0
: index + 1;
(toAdd ??= <RichTextItem>[]).addAll(res.toAdd!);
} else if (res.remove) {
(toDel ??= <RichTextItem>[]).add(item);
}
}
}
case TextEditingDeltaNonTextUpdate e:
newSelection = e.selection;
if (newSelection.isCollapsed) {
final newPos = dragOffset(newSelection.base);
newSelection = newSelection.copyWith(
baseOffset: newPos.offset, extentOffset: newPos.offset);
} else {
final isNormalized =
newSelection.baseOffset < newSelection.extentOffset;
var startOffset = newSelection.start;
var endOffset = newSelection.end;
final newOffset = longPressOffset(startOffset, endOffset);
startOffset = newOffset.startOffset;
endOffset = newOffset.endOffset;
newSelection = newSelection.copyWith(
baseOffset: isNormalized ? startOffset : endOffset,
extentOffset: isNormalized ? endOffset : startOffset,
);
}
}
if (addIndex != null && toAdd?.isNotEmpty == true) {
items.insertAll(addIndex, toAdd!);
}
if (toDel?.isNotEmpty == true) {
for (var item in toDel!) {
items.remove(item);
}
}
}
TextStyle? composingStyle;
TextStyle? richStyle;
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
required bool withComposing,
}) {
assert(
!value.composing.isValid || !withComposing || value.isComposingRangeValid,
);
final bool composingRegionOutOfRange =
!value.isComposingRangeValid || !withComposing;
// if (composingRegionOutOfRange) {
// return TextSpan(style: style, text: text);
// }
// debugPrint('$items,,\n$selection');
return TextSpan(
style: style,
children: items.map((e) {
switch (e.type) {
case RichTextType.text:
return TextSpan(text: e.text);
case RichTextType.composing:
composingStyle ??= style?.merge(
const TextStyle(decoration: TextDecoration.underline)) ??
const TextStyle(decoration: TextDecoration.underline);
if (composingRegionOutOfRange) {
e.type = RichTextType.text;
}
return TextSpan(
text: e.text,
style: composingRegionOutOfRange ? null : composingStyle,
);
case RichTextType.at:
richStyle ??= (style ?? const TextStyle())
.copyWith(color: Theme.of(context).colorScheme.primary);
return TextSpan(
text: e.text,
style: richStyle,
);
case RichTextType.emoji:
final emote = e.emote;
if (emote != null) {
return WidgetSpan(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 2),
child: NetworkImgLayer(
src: emote.url,
width: 22, // emote.width,
height: 22, // emote.height,
type: ImageType.emote,
boxFit: BoxFit.contain,
),
),
);
}
return TextSpan(text: e.text);
}
}).toList(),
);
// final TextStyle composingStyle =
// style?.merge(const TextStyle(decoration: TextDecoration.underline)) ??
// const TextStyle(decoration: TextDecoration.underline);
// return TextSpan(
// style: style,
// children: <TextSpan>[
// TextSpan(text: value.composing.textBefore(value.text)),
// TextSpan(
// style: composingStyle,
// text: value.composing.textInside(value.text)),
// TextSpan(text: value.composing.textAfter(value.text)),
// ],
// );
}
@override
void clear() {
items.clear();
super.clear();
}
@override
void dispose() {
items.clear();
super.dispose();
}
TextPosition dragOffset(TextPosition position) {
final offset = position.offset;
for (var e in items) {
final range = e.range;
if (offset >= range.end) {
continue;
}
if (offset <= range.start) {
break;
}
if (e.isRich) {
if (offset * 2 > range.start + range.end) {
return TextPosition(offset: range.end);
} else {
return TextPosition(offset: range.start);
}
}
}
return position;
}
int tapOffset(
int offset, {
required TextPainter textPainter,
required Offset localPos,
required Offset lastTapDownPosition,
}) {
for (var e in items) {
final range = e.range;
if (offset >= range.end) {
continue;
}
if (offset < range.start) {
break;
}
// emoji tap
if (offset == range.start) {
if (e.emote != null) {
final cloestOffset = textPainter.getClosestGlyphForOffset(localPos);
if (cloestOffset != null) {
final offsetRect = cloestOffset.graphemeClusterLayoutBounds;
final offsetRange = cloestOffset.graphemeClusterCodeUnitRange;
if (lastTapDownPosition.dx > offsetRect.right) {
return offsetRange.end;
} else {
return offsetRange.start;
}
}
}
} else {
if (e.isRich) {
if (offset * 2 > range.start + range.end) {
return range.end;
} else {
return range.start;
}
}
}
}
return offset;
}
({int startOffset, int endOffset}) longPressOffset(
int startOffset,
int endOffset,
) {
for (var e in items) {
final range = e.range;
if (startOffset >= range.end) {
continue;
}
if (endOffset <= range.start) {
break;
}
late final cal = range.start + range.end;
if (startOffset > range.start && startOffset < range.end) {
if (e.isRich) {
if (startOffset * 2 > cal) {
startOffset = range.end;
} else {
startOffset = range.start;
}
}
}
if (endOffset > range.start && endOffset < range.end) {
if (e.isRich) {
if (endOffset * 2 > cal) {
endOffset = range.end;
} else {
endOffset = range.start;
}
}
}
}
return (startOffset: startOffset, endOffset: endOffset);
}
TextSelection keyboardOffset(TextSelection newSelection) {
final offset = newSelection.baseOffset;
for (var e in items) {
final range = e.range;
if (offset >= range.end) {
continue;
}
if (offset <= range.start) {
break;
}
if (offset > range.start && offset < range.end) {
if (e.isRich) {
if (offset < value.selection.baseOffset) {
return newSelection.copyWith(
baseOffset: range.start, extentOffset: range.start);
} else {
return newSelection.copyWith(
baseOffset: range.end, extentOffset: range.end);
}
}
}
}
return newSelection;
}
TextSelection keyboardOffsets(TextSelection newSelection) {
final startOffset = newSelection.start;
final endOffset = newSelection.end;
final isNormalized = newSelection.baseOffset < newSelection.extentOffset;
for (var e in items) {
final range = e.range;
if (startOffset >= range.end) {
continue;
}
if (endOffset <= range.start) {
break;
}
if (isNormalized) {
if (startOffset <= range.start &&
endOffset > range.start &&
endOffset < range.end) {
if (e.isRich) {
if (endOffset < selection.extentOffset) {
return newSelection.copyWith(
baseOffset: startOffset,
extentOffset: range.start,
);
} else {
return newSelection.copyWith(
baseOffset: startOffset,
extentOffset: range.end,
);
}
}
}
} else {
if (startOffset < range.end && startOffset > range.start) {
if (e.isRich) {
if (startOffset > selection.extentOffset) {
return newSelection.copyWith(
baseOffset: endOffset,
extentOffset: range.end,
);
} else {
return newSelection.copyWith(
baseOffset: endOffset,
extentOffset: range.start,
);
}
}
}
}
}
return newSelection;
}
}

View File

@@ -7,6 +7,7 @@ library;
import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle;
import 'package:PiliPlus/common/widgets/text_field/controller.dart';
import 'package:PiliPlus/common/widgets/text_field/cupertino/cupertino_adaptive_text_selection_toolbar.dart';
import 'package:PiliPlus/common/widgets/text_field/cupertino/cupertino_spell_check_suggestions_toolbar.dart';
import 'package:PiliPlus/common/widgets/text_field/editable_text.dart';
@@ -23,7 +24,8 @@ import 'package:flutter/cupertino.dart'
CupertinoSpellCheckSuggestionsToolbar,
CupertinoAdaptiveTextSelectionToolbar,
TextSelectionGestureDetectorBuilderDelegate,
TextSelectionGestureDetectorBuilder;
TextSelectionGestureDetectorBuilder,
TextSelectionOverlay;
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
@@ -114,11 +116,11 @@ enum OverlayVisibilityMode {
class _CupertinoTextFieldSelectionGestureDetectorBuilder
extends TextSelectionGestureDetectorBuilder {
_CupertinoTextFieldSelectionGestureDetectorBuilder(
{required _CupertinoTextFieldState state})
{required _CupertinoRichTextFieldState state})
: _state = state,
super(delegate: state);
final _CupertinoTextFieldState _state;
final _CupertinoRichTextFieldState _state;
@override
void onSingleTapUp(TapDragUpDetails details) {
@@ -162,7 +164,7 @@ class _CupertinoTextFieldSelectionGestureDetectorBuilder
/// {@macro flutter.widgets.EditableText.onChanged}
///
/// {@tool dartpad}
/// This example shows how to set the initial value of the [CupertinoTextField] using
/// This example shows how to set the initial value of the [CupertinoRichTextField] using
/// a [controller] that already contains some text.
///
/// ** See code in examples/api/lib/cupertino/text_field/cupertino_text_field.0.dart **
@@ -177,18 +179,18 @@ class _CupertinoTextFieldSelectionGestureDetectorBuilder
///
/// {@macro flutter.material.textfield.wantKeepAlive}
///
/// Remember to call [TextEditingController.dispose] when it is no longer
/// Remember to call [RichTextEditingController.dispose] when it is no longer
/// needed. This will ensure we discard any resources used by the object.
///
/// {@macro flutter.widgets.editableText.showCaretOnScreen}
///
/// ## Scrolling Considerations
///
/// If this [CupertinoTextField] is not a descendant of [Scaffold] and is being
/// If this [CupertinoRichTextField] is not a descendant of [Scaffold] and is being
/// used within a [Scrollable] or nested [Scrollable]s, consider placing a
/// [ScrollNotificationObserver] above the root [Scrollable] that contains this
/// [CupertinoTextField] to ensure proper scroll coordination for
/// [CupertinoTextField] and its components like [TextSelectionOverlay].
/// [CupertinoRichTextField] to ensure proper scroll coordination for
/// [CupertinoRichTextField] and its components like [TextSelectionOverlay].
///
/// See also:
///
@@ -197,12 +199,12 @@ class _CupertinoTextFieldSelectionGestureDetectorBuilder
/// Design UI conventions.
/// * [EditableText], which is the raw text editing control at the heart of a
/// [TextField].
/// * Learn how to use a [TextEditingController] in one of our [cookbook recipes](https://docs.flutter.dev/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller).
/// * Learn how to use a [RichTextEditingController] in one of our [cookbook recipes](https://docs.flutter.dev/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller).
/// * <https://developer.apple.com/design/human-interface-guidelines/ios/controls/text-fields/>
class CupertinoTextField extends StatefulWidget {
class CupertinoRichTextField extends StatefulWidget {
/// Creates an iOS-style text field.
///
/// To provide a prefilled text entry, pass in a [TextEditingController] with
/// To provide a prefilled text entry, pass in a [RichTextEditingController] with
/// an initial value to the [controller] parameter.
///
/// To provide a hint placeholder text that appears when the text entry is
@@ -238,10 +240,10 @@ class CupertinoTextField extends StatefulWidget {
/// * [expands], to allow the widget to size itself to its parent's height.
/// * [maxLength], which discusses the precise meaning of "number of
/// characters" and how it may differ from the intuitive meaning.
const CupertinoTextField({
const CupertinoRichTextField({
super.key,
this.groupId = EditableText,
this.controller,
required this.controller,
this.focusNode,
this.undoController,
this.decoration = _kDefaultRoundedBorderDecoration,
@@ -354,7 +356,7 @@ class CupertinoTextField extends StatefulWidget {
/// Creates a borderless iOS-style text field.
///
/// To provide a prefilled text entry, pass in a [TextEditingController] with
/// To provide a prefilled text entry, pass in a [RichTextEditingController] with
/// an initial value to the [controller] parameter.
///
/// To provide a hint placeholder text that appears when the text entry is
@@ -382,10 +384,10 @@ class CupertinoTextField extends StatefulWidget {
/// * [expands], to allow the widget to size itself to its parent's height.
/// * [maxLength], which discusses the precise meaning of "number of
/// characters" and how it may differ from the intuitive meaning.
const CupertinoTextField.borderless({
const CupertinoRichTextField.borderless({
super.key,
this.groupId = EditableText,
this.controller,
required this.controller,
this.focusNode,
this.undoController,
this.decoration,
@@ -497,8 +499,8 @@ class CupertinoTextField extends StatefulWidget {
/// Controls the text being edited.
///
/// If null, this widget will create its own [TextEditingController].
final TextEditingController? controller;
/// If null, this widget will create its own [RichTextEditingController].
final RichTextEditingController controller;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
@@ -567,7 +569,7 @@ class CupertinoTextField extends StatefulWidget {
/// Show an iOS-style clear button to clear the current text entry.
///
/// Can be made to appear depending on various text states of the
/// [TextEditingController].
/// [RichTextEditingController].
///
/// Will only appear if no [suffix] widget is appearing.
///
@@ -882,11 +884,11 @@ class CupertinoTextField extends StatefulWidget {
///
/// See also:
/// * [spellCheckConfiguration], where this is typically specified for
/// [CupertinoTextField].
/// [CupertinoRichTextField].
/// * [SpellCheckConfiguration.spellCheckSuggestionsToolbarBuilder], the
/// parameter for which this is the default value for [CupertinoTextField].
/// parameter for which this is the default value for [CupertinoRichTextField].
/// * [TextField.defaultSpellCheckSuggestionsToolbarBuilder], which is like
/// this but specifies the default for [CupertinoTextField].
/// this but specifies the default for [CupertinoRichTextField].
@visibleForTesting
static Widget defaultSpellCheckSuggestionsToolbarBuilder(
BuildContext context,
@@ -900,13 +902,13 @@ class CupertinoTextField extends StatefulWidget {
final UndoHistoryController? undoController;
@override
State<CupertinoTextField> createState() => _CupertinoTextFieldState();
State<CupertinoRichTextField> createState() => _CupertinoRichTextFieldState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
DiagnosticsProperty<TextEditingController>('controller', controller,
DiagnosticsProperty<RichTextEditingController>('controller', controller,
defaultValue: null),
);
properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode,
@@ -1111,24 +1113,24 @@ class CupertinoTextField extends StatefulWidget {
return configuration.copyWith(
misspelledTextStyle: configuration.misspelledTextStyle ??
CupertinoTextField.cupertinoMisspelledTextStyle,
CupertinoRichTextField.cupertinoMisspelledTextStyle,
misspelledSelectionColor: configuration.misspelledSelectionColor ??
CupertinoTextField.kMisspelledSelectionColor,
CupertinoRichTextField.kMisspelledSelectionColor,
spellCheckSuggestionsToolbarBuilder:
configuration.spellCheckSuggestionsToolbarBuilder ??
CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder,
CupertinoRichTextField.defaultSpellCheckSuggestionsToolbarBuilder,
);
}
}
class _CupertinoTextFieldState extends State<CupertinoTextField>
with RestorationMixin, AutomaticKeepAliveClientMixin<CupertinoTextField>
class _CupertinoRichTextFieldState extends State<CupertinoRichTextField>
with RestorationMixin, AutomaticKeepAliveClientMixin<CupertinoRichTextField>
implements TextSelectionGestureDetectorBuilderDelegate, AutofillClient {
final GlobalKey _clearGlobalKey = GlobalKey();
RestorableTextEditingController? _controller;
TextEditingController get _effectiveController =>
widget.controller ?? _controller!.value;
// RestorableRichTextEditingController? _controller;
RichTextEditingController get _effectiveController => widget.controller;
// widget.controller ?? _controller!.value;
FocusNode? _focusNode;
FocusNode get _effectiveFocusNode =>
@@ -1162,23 +1164,23 @@ class _CupertinoTextFieldState extends State<CupertinoTextField>
_CupertinoTextFieldSelectionGestureDetectorBuilder(
state: this,
);
if (widget.controller == null) {
_createLocalController();
}
// if (widget.controller == null) {
// _createLocalController();
// }
_effectiveFocusNode.canRequestFocus = widget.enabled;
_effectiveFocusNode.addListener(_handleFocusChanged);
}
@override
void didUpdateWidget(CupertinoTextField oldWidget) {
void didUpdateWidget(CupertinoRichTextField oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller == null && oldWidget.controller != null) {
_createLocalController(oldWidget.controller!.value);
} else if (widget.controller != null && oldWidget.controller == null) {
unregisterFromRestoration(_controller!);
_controller!.dispose();
_controller = null;
}
// if (widget.controller == null && oldWidget.controller != null) {
// _createLocalController(oldWidget.controller!.value);
// } else if (widget.controller != null && oldWidget.controller == null) {
// unregisterFromRestoration(_controller!);
// _controller!.dispose();
// _controller = null;
// }
if (widget.focusNode != oldWidget.focusNode) {
(oldWidget.focusNode ?? _focusNode)?.removeListener(_handleFocusChanged);
@@ -1189,26 +1191,26 @@ class _CupertinoTextFieldState extends State<CupertinoTextField>
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
if (_controller != null) {
_registerController();
}
// if (_controller != null) {
// _registerController();
// }
}
void _registerController() {
assert(_controller != null);
registerForRestoration(_controller!, 'controller');
_controller!.value.addListener(updateKeepAlive);
}
// void _registerController() {
// assert(_controller != null);
// registerForRestoration(_controller!, 'controller');
// _controller!.value.addListener(updateKeepAlive);
// }
void _createLocalController([TextEditingValue? value]) {
assert(_controller == null);
_controller = value == null
? RestorableTextEditingController()
: RestorableTextEditingController.fromValue(value);
if (!restorePending) {
_registerController();
}
}
// void _createLocalController([TextEditingValue? value]) {
// assert(_controller == null);
// _controller = value == null
// ? RestorableRichTextEditingController()
// : RestorableRichTextEditingController.fromValue(value);
// if (!restorePending) {
// _registerController();
// }
// }
@override
String? get restorationId => widget.restorationId;
@@ -1217,7 +1219,7 @@ class _CupertinoTextFieldState extends State<CupertinoTextField>
void dispose() {
_effectiveFocusNode.removeListener(_handleFocusChanged);
_focusNode?.dispose();
_controller?.dispose();
// _controller?.dispose();
super.dispose();
}
@@ -1297,7 +1299,7 @@ class _CupertinoTextFieldState extends State<CupertinoTextField>
}
@override
bool get wantKeepAlive => _controller?.value.text.isNotEmpty ?? false;
bool get wantKeepAlive => _effectiveController.value.text.isNotEmpty;
static bool _shouldShowAttachment({
required OverlayVisibilityMode attachment,
@@ -1489,7 +1491,7 @@ class _CupertinoTextFieldState extends State<CupertinoTextField>
Widget build(BuildContext context) {
super.build(context); // See AutomaticKeepAliveClientMixin.
assert(debugCheckHasDirectionality(context));
final TextEditingController controller = _effectiveController;
final RichTextEditingController controller = _effectiveController;
TextSelectionControls? textSelectionControls = widget.selectionControls;
VoidCallback? handleDidGainAccessibilityFocus;
@@ -1608,7 +1610,7 @@ class _CupertinoTextFieldState extends State<CupertinoTextField>
// ensure that configuration uses Cupertino text style for misspelled words
// unless a custom style is specified.
final SpellCheckConfiguration spellCheckConfiguration =
CupertinoTextField.inferIOSSpellCheckConfiguration(
CupertinoRichTextField.inferIOSSpellCheckConfiguration(
widget.spellCheckConfiguration);
final Widget paddedEditable = Padding(
@@ -1643,7 +1645,7 @@ class _CupertinoTextFieldState extends State<CupertinoTextField>
minLines: widget.minLines,
expands: widget.expands,
magnifierConfiguration: widget.magnifierConfiguration ??
CupertinoTextField._iosMagnifierConfiguration,
CupertinoRichTextField._iosMagnifierConfiguration,
// Only show the selection highlight when the text field is focused.
selectionColor:
_effectiveFocusNode.hasFocus ? selectionColor : null,

File diff suppressed because it is too large Load Diff

View File

@@ -21,12 +21,20 @@ import 'dart:math' as math;
import 'dart:ui' as ui hide TextStyle;
import 'dart:ui';
import 'package:PiliPlus/common/widgets/text_field/controller.dart';
import 'package:PiliPlus/common/widgets/text_field/editable.dart';
import 'package:PiliPlus/common/widgets/text_field/spell_check.dart';
import 'package:PiliPlus/common/widgets/text_field/text_selection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'
hide SpellCheckConfiguration, buildTextSpanWithSpellCheckSuggestions;
import 'package:flutter/rendering.dart';
hide
SpellCheckConfiguration,
buildTextSpanWithSpellCheckSuggestions,
TextSelectionOverlay,
TextSelectionGestureDetectorBuilder;
import 'package:flutter/rendering.dart'
hide RenderEditable, VerticalCaretMovementRun;
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
@@ -124,7 +132,7 @@ class _RenderCompositionCallback extends RenderProxyBox {
/// A controller for an editable text field.
///
/// Whenever the user modifies a text field with an associated
/// [TextEditingController], the text field updates [value] and the controller
/// [RichTextEditingController], the text field updates [value] and the controller
/// notifies its listeners. Listeners can then read the [text] and [selection]
/// properties to learn what the user has typed or how the selection has been
/// updated.
@@ -132,7 +140,7 @@ class _RenderCompositionCallback extends RenderProxyBox {
/// Similarly, if you modify the [text] or [selection] properties, the text
/// field will be notified and will update itself appropriately.
///
/// A [TextEditingController] can also be used to provide an initial value for a
/// A [RichTextEditingController] can also be used to provide an initial value for a
/// text field. If you build a text field with a controller that already has
/// [text], the text field will use that text as its initial value.
///
@@ -150,11 +158,11 @@ class _RenderCompositionCallback extends RenderProxyBox {
/// controller's [value] instead. Setting [text] will clear the selection
/// and composing range.
///
/// Remember to [dispose] of the [TextEditingController] when it is no longer
/// Remember to [dispose] of the [RichTextEditingController] when it is no longer
/// needed. This will ensure we discard any resources used by the object.
///
/// {@tool dartpad}
/// This example creates a [TextField] with a [TextEditingController] whose
/// This example creates a [TextField] with a [RichTextEditingController] whose
/// change listener forces the entered text to be lower case and keeps the
/// cursor at the end of the input.
///
@@ -164,10 +172,10 @@ class _RenderCompositionCallback extends RenderProxyBox {
/// See also:
///
/// * [TextField], which is a Material Design text field that can be controlled
/// with a [TextEditingController].
/// with a [RichTextEditingController].
/// * [EditableText], which is a raw region of editable text that can be
/// controlled with a [TextEditingController].
/// * Learn how to use a [TextEditingController] in one of our [cookbook recipes](https://docs.flutter.dev/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller).
/// controlled with a [RichTextEditingController].
/// * Learn how to use a [RichTextEditingController] in one of our [cookbook recipes](https://docs.flutter.dev/cookbook/forms/text-field-changes#2-use-a-texteditingcontroller).
// A time-value pair that represents a key frame in an animation.
class _KeyFrame {
@@ -273,7 +281,7 @@ class _DiscreteKeyFrameSimulation extends Simulation {
///
/// * The [inputFormatters] will be first applied to the user input.
///
/// * The [controller]'s [TextEditingController.value] will be updated with the
/// * The [controller]'s [RichTextEditingController.value] will be updated with the
/// formatted result, and the [controller]'s listeners will be notified.
///
/// * The [onChanged] callback, if specified, will be called last.
@@ -371,8 +379,8 @@ class _DiscreteKeyFrameSimulation extends Simulation {
/// | **Intent Class** | **Default Behavior** |
/// | :-------------------------------------- | :--------------------------------------------------- |
/// | [DoNothingAndStopPropagationTextIntent] | Does nothing in the input field, and prevents the key event from further propagating in the widget tree. |
/// | [ReplaceTextIntent] | Replaces the current [TextEditingValue] in the input field's [TextEditingController], and triggers all related user callbacks and [TextInputFormatter]s. |
/// | [UpdateSelectionIntent] | Updates the current selection in the input field's [TextEditingController], and triggers the [onSelectionChanged] callback. |
/// | [ReplaceTextIntent] | Replaces the current [TextEditingValue] in the input field's [RichTextEditingController], and triggers all related user callbacks and [TextInputFormatter]s. |
/// | [UpdateSelectionIntent] | Updates the current selection in the input field's [RichTextEditingController], and triggers the [onSelectionChanged] callback. |
/// | [CopySelectionTextIntent] | Copies or cuts the selected text into the clipboard |
/// | [PasteTextIntent] | Inserts the current text in the clipboard after the caret location, or replaces the selected text if the selection is not collapsed. |
///
@@ -573,8 +581,6 @@ class EditableText extends StatefulWidget {
this.spellCheckConfiguration,
this.magnifierConfiguration = TextMagnifierConfiguration.disabled,
this.undoController,
this.onDelAtUser,
this.onMention,
}) : assert(obscuringCharacter.length == 1),
smartDashesType = smartDashesType ??
(obscureText ? SmartDashesType.disabled : SmartDashesType.enabled),
@@ -634,12 +640,8 @@ class EditableText extends StatefulWidget {
: inputFormatters,
showCursor = showCursor ?? !readOnly;
final VoidCallback? onMention;
final ValueChanged<String>? onDelAtUser;
/// Controls the text being edited.
final TextEditingController controller;
final RichTextEditingController controller;
/// Controls whether this widget has keyboard focus.
final FocusNode focusNode;
@@ -1068,7 +1070,7 @@ class EditableText extends StatefulWidget {
///
/// To be notified of all changes to the TextField's text, cursor,
/// and selection, one can add a listener to its [controller] with
/// [TextEditingController.addListener].
/// [RichTextEditingController.addListener].
///
/// [onChanged] is called before [onSubmitted] when user indicates completion
/// of editing, such as when pressing the "done" button on the keyboard. That
@@ -1104,7 +1106,7 @@ class EditableText extends StatefulWidget {
/// runs and can validate and change ("format") the input value.
/// * [onEditingComplete], [onSubmitted], [onSelectionChanged]:
/// which are more specialized input change notifications.
/// * [TextEditingController], which implements the [Listenable] interface
/// * [RichTextEditingController], which implements the [Listenable] interface
/// and notifies its listeners on [TextEditingValue] changes.
final ValueChanged<String>? onChanged;
@@ -1268,7 +1270,7 @@ class EditableText extends StatefulWidget {
///
/// See also:
///
/// * [TextEditingController], which implements the [Listenable] interface
/// * [RichTextEditingController], which implements the [Listenable] interface
/// and notifies its listeners on [TextEditingValue] changes.
/// {@endtemplate}
final List<TextInputFormatter>? inputFormatters;
@@ -1572,7 +1574,7 @@ class EditableText extends StatefulWidget {
///
/// Persisting and restoring the content of the [EditableText] is the
/// responsibility of the owner of the [controller], who may use a
/// [RestorableTextEditingController] for that purpose.
/// [RestorableRichTextEditingController] for that purpose.
///
/// See also:
///
@@ -1955,8 +1957,8 @@ class EditableText extends StatefulWidget {
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
DiagnosticsProperty<TextEditingController>('controller', controller));
properties.add(DiagnosticsProperty<RichTextEditingController>(
'controller', controller));
properties.add(DiagnosticsProperty<FocusNode>('focusNode', focusNode));
properties.add(DiagnosticsProperty<bool>('obscureText', obscureText,
defaultValue: false));
@@ -2373,7 +2375,8 @@ class EditableTextState extends State<EditableText>
if (selection.isCollapsed || widget.obscureText) {
return;
}
final String text = textEditingValue.text;
// TODO copy
String text = textEditingValue.text;
Clipboard.setData(ClipboardData(text: selection.textInside(text)));
if (cause == SelectionChangedCause.toolbar) {
bringIntoView(textEditingValue.selection.extent);
@@ -2388,6 +2391,7 @@ class EditableTextState extends State<EditableText>
case TargetPlatform.android:
case TargetPlatform.fuchsia:
// Collapse the selection and hide the toolbar and handles.
userUpdateTextEditingValue(
TextEditingValue(
text: textEditingValue.text,
@@ -2455,13 +2459,37 @@ class EditableTextState extends State<EditableText>
final TextSelection selection = textEditingValue.selection;
final int lastSelectionIndex =
math.max(selection.baseOffset, selection.extentOffset);
final TextEditingValue collapsedTextEditingValue =
textEditingValue.copyWith(
selection: TextSelection.collapsed(offset: lastSelectionIndex),
// final TextEditingValue collapsedTextEditingValue =
// textEditingValue.copyWith(
// selection: TextSelection.collapsed(offset: lastSelectionIndex),
// );
// final newValue = collapsedTextEditingValue.replaced(selection, text);
widget.controller.syncRichText(
selection.isCollapsed
? TextEditingDeltaInsertion(
oldText: textEditingValue.text,
textInserted: text,
insertionOffset: selection.baseOffset,
selection: TextSelection.collapsed(offset: lastSelectionIndex),
composing: TextRange.empty,
)
: TextEditingDeltaReplacement(
oldText: textEditingValue.text,
replacementText: text,
replacedRange: selection,
selection: TextSelection.collapsed(offset: lastSelectionIndex),
composing: TextRange.empty,
),
);
userUpdateTextEditingValue(
collapsedTextEditingValue.replaced(selection, text), cause);
final newValue = _value.copyWith(
text: widget.controller.plainText,
selection: widget.controller.newSelection,
);
userUpdateTextEditingValue(newValue, cause);
if (cause == SelectionChangedCause.toolbar) {
// Schedule a call to bringIntoView() after renderEditable updates.
SchedulerBinding.instance.addPostFrameCallback((_) {
@@ -2481,6 +2509,7 @@ class EditableTextState extends State<EditableText>
// selecting it.
return;
}
userUpdateTextEditingValue(
textEditingValue.copyWith(
selection: TextSelection(
@@ -3165,7 +3194,7 @@ class EditableTextState extends State<EditableText>
// everything else.
value = _value.copyWith(selection: value.selection);
}
_lastKnownRemoteTextEditingValue = value;
_lastKnownRemoteTextEditingValue = _value;
if (value == _value) {
// This is possible, for example, when the numeric keyboard is input,
@@ -3257,47 +3286,25 @@ class EditableTextState extends State<EditableText>
}
}
static final _atUserRegex = RegExp(r'@[\u4e00-\u9fa5a-zA-Z\d_-]+ $');
@override
void updateEditingValueWithDeltas(List<TextEditingDelta> textEditingDeltas) {
var last = textEditingDeltas.lastOrNull;
if (last case TextEditingDeltaInsertion e) {
if (e.textInserted == '@') {
widget.onMention?.call();
}
} else if (last case TextEditingDeltaDeletion e) {
if (e.textDeleted == ' ') {
final selection = _value.selection;
if (selection.isCollapsed) {
final text = _value.text;
final offset = selection.baseOffset;
RegExpMatch? match =
_atUserRegex.firstMatch(text.substring(0, offset));
if (match != null) {
userUpdateTextEditingValue(
TextEditingDeltaDeletion(
oldText: e.oldText,
deletedRange: TextRange(start: match.start, end: match.end),
selection: TextSelection.collapsed(offset: match.start),
composing: e.composing,
).apply(_value),
SelectionChangedCause.keyboard,
);
widget.onDelAtUser?.call(match.group(0)!.trim());
return;
}
}
}
}
TextEditingValue value = _value;
for (final TextEditingDelta delta in textEditingDeltas) {
value = delta.apply(value);
widget.controller.syncRichText(delta);
}
updateEditingValue(value);
final newValue = _value.copyWith(
text: widget.controller.plainText,
selection: widget.controller.newSelection,
composing: textEditingDeltas.lastOrNull?.composing,
);
updateEditingValue(newValue);
// TextEditingValue value = _value;
// for (final TextEditingDelta delta in textEditingDeltas) {
// value = delta.apply(value);
// }
// updateEditingValue(value);
}
@override
@@ -3388,6 +3395,10 @@ class EditableTextState extends State<EditableText>
renderEditable
.localToGlobal(_lastBoundedOffset! + _floatingCursorOffset),
);
// bggRGjQaUbCoE ios single long press
_lastTextPosition = widget.controller.dragOffset(_lastTextPosition!);
renderEditable.setFloatingCursor(
point.state, _lastBoundedOffset!, _lastTextPosition!);
case FloatingCursorDragState.End:
@@ -4005,6 +4016,7 @@ class EditableTextState extends State<EditableText>
final EditableTextContextMenuBuilder? contextMenuBuilder =
widget.contextMenuBuilder;
final TextSelectionOverlay selectionOverlay = TextSelectionOverlay(
controller: widget.controller,
clipboardStatus: clipboardStatus,
context: context,
value: _value,
@@ -4248,6 +4260,15 @@ class EditableTextState extends State<EditableText>
final bool textCommitted =
!oldValue.composing.isCollapsed && value.composing.isCollapsed;
final bool selectionChanged = oldValue.selection != value.selection;
// if (!textChanged && selectionChanged) {
// value = value.copyWith(
// selection: widget.controller.updateSelection(
// oldSelection: _value.selection,
// newSelection: value.selection,
// cause: cause,
// ),
// );
// }
if (textChanged || textCommitted) {
// Only apply input formatters if the text has changed (including uncommitted
@@ -5144,10 +5165,34 @@ class EditableTextState extends State<EditableText>
void _replaceText(ReplaceTextIntent intent) {
final TextEditingValue oldValue = _value;
final TextEditingValue newValue = intent.currentTextEditingValue.replaced(
intent.replacementRange,
intent.replacementText,
// final TextEditingValue newValue = intent.currentTextEditingValue.replaced(
// intent.replacementRange,
// intent.replacementText,
// );
widget.controller.syncRichText(
intent.replacementText.isEmpty
? TextEditingDeltaDeletion(
oldText: oldValue.text,
deletedRange: intent.replacementRange,
selection: TextSelection.collapsed(
offset: intent.replacementRange.start),
composing: TextRange.empty,
)
: TextEditingDeltaReplacement(
oldText: oldValue.text,
replacementText: intent.replacementText,
replacedRange: intent.replacementRange,
selection: TextSelection.collapsed(
offset: intent.replacementRange.start),
composing: TextRange.empty,
),
);
final newValue = oldValue.copyWith(
text: widget.controller.plainText,
selection: widget.controller.newSelection,
);
userUpdateTextEditingValue(newValue, intent.cause);
// If there's no change in text and selection (e.g. when selecting and
@@ -5258,6 +5303,7 @@ class EditableTextState extends State<EditableText>
}
bringIntoView(nextSelection.extent);
userUpdateTextEditingValue(
_value.copyWith(selection: nextSelection),
SelectionChangedCause.keyboard,
@@ -5275,8 +5321,17 @@ class EditableTextState extends State<EditableText>
);
bringIntoView(intent.newSelection.extent);
// bggRGjQaUbCoE keyboard
TextSelection newSelection = intent.newSelection;
if (newSelection.isCollapsed) {
newSelection = widget.controller.keyboardOffset(newSelection);
} else {
newSelection = widget.controller.keyboardOffsets(newSelection);
}
userUpdateTextEditingValue(
intent.currentTextEditingValue.copyWith(selection: intent.newSelection),
intent.currentTextEditingValue.copyWith(selection: newSelection),
intent.cause,
);
}
@@ -5358,8 +5413,6 @@ class EditableTextState extends State<EditableText>
this,
_characterBoundary,
_moveBeyondTextBoundary,
atUserRegex: _atUserRegex,
onDelAtUser: widget.onDelAtUser,
),
),
DeleteToNextWordBoundaryIntent: _makeOverridable(
@@ -5623,6 +5676,7 @@ class EditableTextState extends State<EditableText>
child: SizeChangedLayoutNotifier(
child: _Editable(
key: _editableKey,
controller: widget.controller,
startHandleLayerLink: _startHandleLayerLink,
endHandleLayerLink: _endHandleLayerLink,
inlineSpan: buildTextSpan(),
@@ -5823,6 +5877,7 @@ class _Editable extends MultiChildRenderObjectWidget {
this.promptRectRange,
this.promptRectColor,
required this.clipBehavior,
required this.controller,
}) : super(
children: WidgetSpan.extractFromInlineSpan(inlineSpan, textScaler));
@@ -5864,10 +5919,12 @@ class _Editable extends MultiChildRenderObjectWidget {
final TextRange? promptRectRange;
final Color? promptRectColor;
final Clip clipBehavior;
final RichTextEditingController controller;
@override
RenderEditable createRenderObject(BuildContext context) {
return RenderEditable(
controller: controller,
text: inlineSpan,
cursorColor: cursorColor,
startHandleLayerLink: startHandleLayerLink,
@@ -6200,16 +6257,12 @@ class _DeleteTextAction<T extends DirectionalTextEditingIntent>
_DeleteTextAction(
this.state,
this.getTextBoundary,
this._applyTextBoundary, {
this.atUserRegex,
this.onDelAtUser,
});
this._applyTextBoundary,
);
final EditableTextState state;
final TextBoundary Function() getTextBoundary;
final _ApplyTextBoundary _applyTextBoundary;
final RegExp? atUserRegex;
final ValueChanged<String>? onDelAtUser;
void _hideToolbarIfTextChanged(ReplaceTextIntent intent) {
if (state._selectionOverlay == null ||
@@ -6255,28 +6308,6 @@ class _DeleteTextAction<T extends DirectionalTextEditingIntent>
return Actions.invoke(context!, replaceTextIntent);
}
final value = state._value;
final text = value.text;
if (!intent.forward) {
if (text.isNotEmpty && selection.baseOffset != 0) {
String subText = text.substring(0, selection.baseOffset);
RegExpMatch? match = atUserRegex?.firstMatch(subText);
if (match != null) {
onDelAtUser?.call(match.group(0)!.trim());
final range = TextRange(start: match.start, end: match.end);
final ReplaceTextIntent replaceTextIntent = ReplaceTextIntent(
value,
'',
range,
SelectionChangedCause.keyboard,
);
_hideToolbarIfTextChanged(replaceTextIntent);
return Actions.invoke(context!, replaceTextIntent);
}
}
}
final int target =
_applyTextBoundary(selection.base, intent.forward, getTextBoundary())
.offset;
@@ -6284,14 +6315,14 @@ class _DeleteTextAction<T extends DirectionalTextEditingIntent>
final TextRange rangeToDelete = TextSelection(
baseOffset: intent.forward
? atomicBoundary.getLeadingTextBoundaryAt(selection.baseOffset) ??
text.length
state._value.text.length
: atomicBoundary
.getTrailingTextBoundaryAt(selection.baseOffset - 1) ??
0,
extentOffset: target,
);
final ReplaceTextIntent replaceTextIntent = ReplaceTextIntent(
value,
state._value,
'',
rangeToDelete,
SelectionChangedCause.keyboard,

View File

@@ -14,6 +14,7 @@ library;
import 'dart:ui' as ui show BoxHeightStyle, BoxWidthStyle;
import 'package:PiliPlus/common/widgets/text_field/adaptive_text_selection_toolbar.dart';
import 'package:PiliPlus/common/widgets/text_field/controller.dart';
import 'package:PiliPlus/common/widgets/text_field/cupertino/cupertino_spell_check_suggestions_toolbar.dart';
import 'package:PiliPlus/common/widgets/text_field/cupertino/cupertino_text_field.dart';
import 'package:PiliPlus/common/widgets/text_field/editable_text.dart';
@@ -32,7 +33,8 @@ import 'package:flutter/cupertino.dart'
buildTextSpanWithSpellCheckSuggestions,
CupertinoTextField,
TextSelectionGestureDetectorBuilderDelegate,
TextSelectionGestureDetectorBuilder;
TextSelectionGestureDetectorBuilder,
TextSelectionOverlay;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'
@@ -46,7 +48,8 @@ import 'package:flutter/material.dart'
EditableTextContextMenuBuilder,
buildTextSpanWithSpellCheckSuggestions,
TextSelectionGestureDetectorBuilderDelegate,
TextSelectionGestureDetectorBuilder;
TextSelectionGestureDetectorBuilder,
TextSelectionOverlay;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
@@ -62,7 +65,7 @@ export 'package:flutter/services.dart'
// late BuildContext context;
// late FocusNode myFocusNode;
/// Signature for the [TextField.buildCounter] callback.
/// Signature for the [RichTextField.buildCounter] callback.
typedef InputCounterWidgetBuilder = Widget? Function(
/// The build context for the TextField.
BuildContext context, {
@@ -79,11 +82,12 @@ typedef InputCounterWidgetBuilder = Widget? Function(
class _TextFieldSelectionGestureDetectorBuilder
extends TextSelectionGestureDetectorBuilder {
_TextFieldSelectionGestureDetectorBuilder({required _TextFieldState state})
_TextFieldSelectionGestureDetectorBuilder(
{required _RichTextFieldState state})
: _state = state,
super(delegate: state);
final _TextFieldState _state;
final _RichTextFieldState _state;
@override
bool get onUserTapAlwaysCalled => _state.widget.onTapAlwaysCalled;
@@ -119,7 +123,7 @@ class _TextFieldSelectionGestureDetectorBuilder
/// If [decoration] is non-null (which is the default), the text field requires
/// one of its ancestors to be a [Material] widget.
///
/// To integrate the [TextField] into a [Form] with other [FormField] widgets,
/// To integrate the [RichTextField] into a [Form] with other [FormField] widgets,
/// consider using [TextFormField].
///
/// {@template flutter.material.textfield.wantKeepAlive}
@@ -129,7 +133,7 @@ class _TextFieldSelectionGestureDetectorBuilder
/// disposed.
/// {@endtemplate}
///
/// Remember to call [TextEditingController.dispose] on the [TextEditingController]
/// Remember to call [RichTextEditingController.dispose] on the [RichTextEditingController]
/// when it is no longer needed. This will ensure we discard any resources used
/// by the object.
///
@@ -141,7 +145,7 @@ class _TextFieldSelectionGestureDetectorBuilder
/// ## Obscured Input
///
/// {@tool dartpad}
/// This example shows how to create a [TextField] that will obscure input. The
/// This example shows how to create a [RichTextField] that will obscure input. The
/// [InputDecoration] surrounds the field in a border using [OutlineInputBorder]
/// and adds a label.
///
@@ -173,7 +177,7 @@ class _TextFieldSelectionGestureDetectorBuilder
/// callback.
///
/// Keep in mind you can also always read the current string from a TextField's
/// [TextEditingController] using [TextEditingController.text].
/// [RichTextEditingController] using [RichTextEditingController.text].
///
/// ## Handling emojis and other complex characters
/// {@macro flutter.widgets.EditableText.onChanged}
@@ -196,10 +200,10 @@ class _TextFieldSelectionGestureDetectorBuilder
///
/// ## Scrolling Considerations
///
/// If this [TextField] is not a descendant of [Scaffold] and is being used
/// If this [RichTextField] is not a descendant of [Scaffold] and is being used
/// within a [Scrollable] or nested [Scrollable]s, consider placing a
/// [ScrollNotificationObserver] above the root [Scrollable] that contains this
/// [TextField] to ensure proper scroll coordination for [TextField] and its
/// [RichTextField] to ensure proper scroll coordination for [RichTextField] and its
/// components like [TextSelectionOverlay].
///
/// See also:
@@ -208,7 +212,7 @@ class _TextFieldSelectionGestureDetectorBuilder
/// * [InputDecorator], which shows the labels and other visual elements that
/// surround the actual text editing widget.
/// * [EditableText], which is the raw text editing control at the heart of a
/// [TextField]. The [EditableText] widget is rarely used directly unless
/// [RichTextField]. The [EditableText] widget is rarely used directly unless
/// you are implementing an entirely different design language, such as
/// Cupertino.
/// * <https://material.io/design/components/text-fields.html>
@@ -216,7 +220,7 @@ class _TextFieldSelectionGestureDetectorBuilder
/// * Cookbook: [Handle changes to a text field](https://docs.flutter.dev/cookbook/forms/text-field-changes)
/// * Cookbook: [Retrieve the value of a text field](https://docs.flutter.dev/cookbook/forms/retrieve-input)
/// * Cookbook: [Focus and text fields](https://docs.flutter.dev/cookbook/forms/focus)
class TextField extends StatefulWidget {
class RichTextField extends StatefulWidget {
/// Creates a Material Design text field.
///
/// If [decoration] is non-null (which is the default), the text field requires
@@ -236,7 +240,7 @@ class TextField extends StatefulWidget {
/// field showing how many characters have been entered. If the value is
/// set to a positive integer it will also display the maximum allowed
/// number of characters to be entered. If the value is set to
/// [TextField.noMaxLength] then only the current length is displayed.
/// [RichTextField.noMaxLength] then only the current length is displayed.
///
/// After [maxLength] characters have been input, additional input
/// is ignored, unless [maxLengthEnforcement] is set to
@@ -261,10 +265,10 @@ class TextField extends StatefulWidget {
///
/// * [maxLength], which discusses the precise meaning of "number of
/// characters" and how it may differ from the intuitive meaning.
const TextField({
const RichTextField({
super.key,
this.groupId = EditableText,
this.controller,
required this.controller,
this.focusNode,
this.undoController,
this.decoration = const InputDecoration(),
@@ -340,8 +344,6 @@ class TextField extends StatefulWidget {
this.canRequestFocus = true,
this.spellCheckConfiguration,
this.magnifierConfiguration,
this.onDelAtUser,
this.onMention,
}) : assert(obscuringCharacter.length == 1),
smartDashesType = smartDashesType ??
(obscureText ? SmartDashesType.disabled : SmartDashesType.enabled),
@@ -360,7 +362,7 @@ class TextField extends StatefulWidget {
assert(!obscureText || maxLines == 1,
'Obscured fields cannot be multiline.'),
assert(maxLength == null ||
maxLength == TextField.noMaxLength ||
maxLength == RichTextField.noMaxLength ||
maxLength > 0),
// Assert the following instead of setting it directly to avoid surprising the user by silently changing the value they set.
assert(
@@ -374,10 +376,6 @@ class TextField extends StatefulWidget {
enableInteractiveSelection =
enableInteractiveSelection ?? (!readOnly || !obscureText);
final VoidCallback? onMention;
final ValueChanged<String>? onDelAtUser;
/// The configuration for the magnifier of this text field.
///
/// By default, builds a [CupertinoTextMagnifier] on iOS and [TextMagnifier]
@@ -398,8 +396,8 @@ class TextField extends StatefulWidget {
/// Controls the text being edited.
///
/// If null, this widget will create its own [TextEditingController].
final TextEditingController? controller;
/// If null, this widget will create its own [RichTextEditingController].
final RichTextEditingController controller;
/// Defines the keyboard focus for this widget.
///
@@ -570,7 +568,7 @@ class TextField extends StatefulWidget {
/// If set, a character counter will be displayed below the
/// field showing how many characters have been entered. If set to a number
/// greater than 0, it will also display the maximum number allowed. If set
/// to [TextField.noMaxLength] then only the current character count is displayed.
/// to [RichTextField.noMaxLength] then only the current character count is displayed.
///
/// After [maxLength] characters have been input, additional input
/// is ignored, unless [maxLengthEnforcement] is set to
@@ -579,9 +577,9 @@ class TextField extends StatefulWidget {
/// The text field enforces the length with a [LengthLimitingTextInputFormatter],
/// which is evaluated after the supplied [inputFormatters], if any.
///
/// This value must be either null, [TextField.noMaxLength], or greater than 0.
/// This value must be either null, [RichTextField.noMaxLength], or greater than 0.
/// If null (the default) then there is no limit to the number of characters
/// that can be entered. If set to [TextField.noMaxLength], then no limit will
/// that can be entered. If set to [RichTextField.noMaxLength], then no limit will
/// be enforced, but the number of characters entered will still be displayed.
///
/// Whitespace characters (e.g. newline, space, tab) are included in the
@@ -740,7 +738,7 @@ class TextField extends StatefulWidget {
///
/// {@tool dartpad}
/// This example shows how to use a `TextFieldTapRegion` to wrap a set of
/// "spinner" buttons that increment and decrement a value in the [TextField]
/// "spinner" buttons that increment and decrement a value in the [RichTextField]
/// without causing the text field to lose keyboard focus.
///
/// This example includes a generic `SpinnerField<T>` class that you can copy
@@ -770,7 +768,7 @@ class TextField extends StatefulWidget {
///
/// If this property is null, [WidgetStateMouseCursor.textable] will be used.
///
/// The [mouseCursor] is the only property of [TextField] that controls the
/// The [mouseCursor] is the only property of [RichTextField] that controls the
/// appearance of the mouse pointer. All other properties related to "cursor"
/// stand for the text cursor, which is usually a blinking vertical line at
/// the editing position.
@@ -903,7 +901,7 @@ class TextField extends StatefulWidget {
/// See also:
/// * [SpellCheckConfiguration.misspelledTextStyle], the style configured to
/// mark misspelled words with.
/// * [CupertinoTextField.cupertinoMisspelledTextStyle], the style configured
/// * [CupertinoRichTextField.cupertinoMisspelledTextStyle], the style configured
/// to mark misspelled words with in the Cupertino style.
static const TextStyle materialMisspelledTextStyle = TextStyle(
decoration: TextDecoration.underline,
@@ -911,18 +909,18 @@ class TextField extends StatefulWidget {
decorationStyle: TextDecorationStyle.wavy,
);
/// Default builder for [TextField]'s spell check suggestions toolbar.
/// Default builder for [RichTextField]'s spell check suggestions toolbar.
///
/// On Apple platforms, builds an iOS-style toolbar. Everywhere else, builds
/// an Android-style toolbar.
///
/// See also:
/// * [spellCheckConfiguration], where this is typically specified for
/// [TextField].
/// [RichTextField].
/// * [SpellCheckConfiguration.spellCheckSuggestionsToolbarBuilder], the
/// parameter for which this is the default value for [TextField].
/// * [CupertinoTextField.defaultSpellCheckSuggestionsToolbarBuilder], which
/// is like this but specifies the default for [CupertinoTextField].
/// parameter for which this is the default value for [RichTextField].
/// * [CupertinoRichTextField.defaultSpellCheckSuggestionsToolbarBuilder], which
/// is like this but specifies the default for [CupertinoRichTextField].
@visibleForTesting
static Widget defaultSpellCheckSuggestionsToolbarBuilder(
BuildContext context,
@@ -955,22 +953,22 @@ class TextField extends StatefulWidget {
}
return configuration.copyWith(
misspelledTextStyle: configuration.misspelledTextStyle ??
TextField.materialMisspelledTextStyle,
RichTextField.materialMisspelledTextStyle,
spellCheckSuggestionsToolbarBuilder:
configuration.spellCheckSuggestionsToolbarBuilder ??
TextField.defaultSpellCheckSuggestionsToolbarBuilder,
RichTextField.defaultSpellCheckSuggestionsToolbarBuilder,
);
}
@override
State<TextField> createState() => _TextFieldState();
State<RichTextField> createState() => _RichTextFieldState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
..add(
DiagnosticsProperty<TextEditingController>('controller', controller,
DiagnosticsProperty<RichTextEditingController>('controller', controller,
defaultValue: null),
)
..add(DiagnosticsProperty<FocusNode>('focusNode', focusNode,
@@ -1152,12 +1150,12 @@ class TextField extends StatefulWidget {
}
}
class _TextFieldState extends State<TextField>
class _RichTextFieldState extends State<RichTextField>
with RestorationMixin
implements TextSelectionGestureDetectorBuilderDelegate, AutofillClient {
RestorableTextEditingController? _controller;
TextEditingController get _effectiveController =>
widget.controller ?? _controller!.value;
// RestorableRichTextEditingController? _controller;
RichTextEditingController get _effectiveController => widget.controller;
// widget.controller ?? _controller!.value;
FocusNode? _focusNode;
FocusNode get _effectiveFocusNode =>
@@ -1199,11 +1197,13 @@ class _TextFieldState extends State<TextField>
bool get _hasIntrinsicError =>
widget.maxLength != null &&
widget.maxLength! > 0 &&
(widget.controller == null
? !restorePending &&
_effectiveController.value.text.characters.length >
widget.maxLength!
: _effectiveController.value.text.characters.length >
(
// widget.controller == null
// ? !restorePending &&
// _effectiveController.value.text.characters.length >
// widget.maxLength!
// :
_effectiveController.value.text.characters.length >
widget.maxLength!);
bool get _hasError =>
@@ -1295,9 +1295,9 @@ class _TextFieldState extends State<TextField>
super.initState();
_selectionGestureDetectorBuilder =
_TextFieldSelectionGestureDetectorBuilder(state: this);
if (widget.controller == null) {
_createLocalController();
}
// if (widget.controller == null) {
// _createLocalController();
// }
_effectiveFocusNode.canRequestFocus = widget.canRequestFocus && _isEnabled;
_effectiveFocusNode.addListener(_handleFocusChanged);
_initStatesController();
@@ -1319,15 +1319,15 @@ class _TextFieldState extends State<TextField>
}
@override
void didUpdateWidget(TextField oldWidget) {
void didUpdateWidget(RichTextField oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller == null && oldWidget.controller != null) {
_createLocalController(oldWidget.controller!.value);
} else if (widget.controller != null && oldWidget.controller == null) {
unregisterFromRestoration(_controller!);
_controller!.dispose();
_controller = null;
}
// if (widget.controller == null && oldWidget.controller != null) {
// _createLocalController(oldWidget.controller!.value);
// } else if (widget.controller != null && oldWidget.controller == null) {
// unregisterFromRestoration(_controller!);
// _controller!.dispose();
// _controller = null;
// }
if (widget.focusNode != oldWidget.focusNode) {
(oldWidget.focusNode ?? _focusNode)?.removeListener(_handleFocusChanged);
@@ -1345,11 +1345,11 @@ class _TextFieldState extends State<TextField>
}
if (widget.statesController == oldWidget.statesController) {
_statesController.update(MaterialState.disabled, !_isEnabled);
_statesController.update(MaterialState.hovered, _isHovering);
_statesController.update(
MaterialState.focused, _effectiveFocusNode.hasFocus);
_statesController.update(MaterialState.error, _hasError);
_statesController
..update(MaterialState.disabled, !_isEnabled)
..update(MaterialState.hovered, _isHovering)
..update(MaterialState.focused, _effectiveFocusNode.hasFocus)
..update(MaterialState.error, _hasError);
} else {
oldWidget.statesController?.removeListener(_handleStatesControllerChange);
if (widget.statesController != null) {
@@ -1362,25 +1362,25 @@ class _TextFieldState extends State<TextField>
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
if (_controller != null) {
_registerController();
}
// if (_controller != null) {
// _registerController();
// }
}
void _registerController() {
assert(_controller != null);
registerForRestoration(_controller!, 'controller');
}
// void _registerController() {
// assert(_controller != null);
// registerForRestoration(_controller!, 'controller');
// }
void _createLocalController([TextEditingValue? value]) {
assert(_controller == null);
_controller = value == null
? RestorableTextEditingController()
: RestorableTextEditingController.fromValue(value);
if (!restorePending) {
_registerController();
}
}
// void _createLocalController([TextEditingValue? value]) {
// assert(_controller == null);
// _controller = value == null
// ? RestorableRichTextEditingController()
// : RestorableRichTextEditingController.fromValue(value);
// if (!restorePending) {
// _registerController();
// }
// }
@override
String? get restorationId => widget.restorationId;
@@ -1389,7 +1389,7 @@ class _TextFieldState extends State<TextField>
void dispose() {
_effectiveFocusNode.removeListener(_handleFocusChanged);
_focusNode?.dispose();
_controller?.dispose();
// _controller?.dispose();
_statesController.removeListener(_handleStatesControllerChange);
_internalStatesController?.dispose();
super.dispose();
@@ -1582,7 +1582,7 @@ class _TextFieldState extends State<TextField>
).merge(providedStyle);
final Brightness keyboardAppearance =
widget.keyboardAppearance ?? theme.brightness;
final TextEditingController controller = _effectiveController;
final RichTextEditingController controller = _effectiveController;
final FocusNode focusNode = _effectiveFocusNode;
final List<TextInputFormatter> formatters = <TextInputFormatter>[
...?widget.inputFormatters,
@@ -1601,14 +1601,15 @@ class _TextFieldState extends State<TextField>
case TargetPlatform.iOS:
case TargetPlatform.macOS:
spellCheckConfiguration =
CupertinoTextField.inferIOSSpellCheckConfiguration(
CupertinoRichTextField.inferIOSSpellCheckConfiguration(
widget.spellCheckConfiguration,
);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
spellCheckConfiguration = TextField.inferAndroidSpellCheckConfiguration(
spellCheckConfiguration =
RichTextField.inferAndroidSpellCheckConfiguration(
widget.spellCheckConfiguration,
);
}
@@ -1804,8 +1805,6 @@ class _TextFieldState extends State<TextField>
spellCheckConfiguration: spellCheckConfiguration,
magnifierConfiguration: widget.magnifierConfiguration ??
TextMagnifier.adaptiveMagnifierConfiguration,
onDelAtUser: widget.onDelAtUser,
onMention: widget.onMention,
),
),
);

File diff suppressed because it is too large Load Diff

View File

@@ -510,7 +510,7 @@ class VideoHttp {
int? parent,
List? pictures,
bool? syncToDynamic,
Map? atNameToMid,
Map<String, int>? atNameToMid,
}) async {
if (message == '') {
return {'status': false, 'msg': '请输入评论内容'};
@@ -521,7 +521,7 @@ class VideoHttp {
if (root != null && root != 0) 'root': root,
if (parent != null && parent != 0) 'parent': parent,
'message': message,
if (atNameToMid != null)
if (atNameToMid?.isNotEmpty == true)
'at_name_to_mid': jsonEncode(atNameToMid), // {"name":uid}
if (pictures != null) 'pictures': jsonEncode(pictures),
if (syncToDynamic == true) 'sync_to_dynamic': 1,

View File

@@ -1,506 +0,0 @@
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:PiliPlus/common/widgets/button/icon_button.dart';
import 'package:PiliPlus/http/msg.dart';
import 'package:PiliPlus/models/common/image_preview_type.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/models_new/dynamic/dyn_mention/item.dart';
import 'package:PiliPlus/models_new/emote/emote.dart';
import 'package:PiliPlus/models_new/live/live_emote/emoticon.dart';
import 'package:PiliPlus/models_new/upload_bfs/data.dart';
import 'package:PiliPlus/pages/dynamics_mention/view.dart';
import 'package:PiliPlus/utils/extension.dart';
import 'package:PiliPlus/utils/feed_back.dart';
import 'package:chat_bottom_container/chat_bottom_container.dart';
import 'package:dio/dio.dart';
import 'package:easy_debounce/easy_throttle.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
abstract class CommonPublishPage extends StatefulWidget {
const CommonPublishPage({
super.key,
this.initialValue,
this.mentions,
this.imageLengthLimit,
this.onSave,
this.autofocus = true,
});
final String? initialValue;
final List<MentionItem>? mentions;
final int? imageLengthLimit;
final ValueChanged<({String text, List<MentionItem>? mentions})>? onSave;
final bool autofocus;
}
abstract class CommonPublishPageState<T extends CommonPublishPage>
extends State<T> with WidgetsBindingObserver {
late final focusNode = FocusNode();
late final controller = ChatBottomPanelContainerController<PanelType>();
late final editController = TextEditingController(text: widget.initialValue);
Rx<PanelType> panelType = PanelType.none.obs;
late final RxBool readOnly = false.obs;
late final RxBool enablePublish = false.obs;
late final imagePicker = ImagePicker();
late final RxList<String> pathList = <String>[].obs;
int get limit => widget.imageLengthLimit ?? 9;
List<MentionItem>? mentions;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
mentions = widget.mentions;
if (widget.initialValue?.trim().isNotEmpty == true) {
enablePublish.value = true;
}
if (widget.autofocus) {
Future.delayed(const Duration(milliseconds: 300)).whenComplete(() {
if (mounted) {
focusNode.requestFocus();
}
});
}
}
@override
void dispose() {
focusNode.dispose();
editController.dispose();
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
Future<void> _requestFocus() async {
await Future.delayed(const Duration(microseconds: 200));
focusNode.requestFocus();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
if (mounted &&
widget.autofocus &&
panelType.value == PanelType.keyboard) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (focusNode.hasFocus) {
focusNode.unfocus();
_requestFocus();
} else {
_requestFocus();
}
});
}
} else if (state == AppLifecycleState.paused) {
controller.keepChatPanel();
if (focusNode.hasFocus) {
focusNode.unfocus();
}
}
}
void updatePanelType(PanelType type) {
final isSwitchToKeyboard = PanelType.keyboard == type;
final isSwitchToEmojiPanel = PanelType.emoji == type;
bool isUpdated = false;
switch (type) {
case PanelType.keyboard:
updateInputView(isReadOnly: false);
break;
case PanelType.emoji:
isUpdated = updateInputView(isReadOnly: true);
break;
default:
break;
}
void updatePanelTypeFunc() {
controller.updatePanelType(
isSwitchToKeyboard
? ChatBottomPanelType.keyboard
: ChatBottomPanelType.other,
data: type,
forceHandleFocus: isSwitchToEmojiPanel
? ChatBottomHandleFocus.requestFocus
: ChatBottomHandleFocus.none,
);
}
if (isUpdated) {
// Waiting for the input view to update.
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
updatePanelTypeFunc();
});
} else {
updatePanelTypeFunc();
}
}
Future<void> hidePanel() async {
if (focusNode.hasFocus) {
await Future.delayed(const Duration(milliseconds: 100));
focusNode.unfocus();
}
updateInputView(isReadOnly: false);
if (ChatBottomPanelType.none == controller.currentPanelType) return;
controller.updatePanelType(ChatBottomPanelType.none);
}
bool updateInputView({
required bool isReadOnly,
}) {
if (readOnly.value != isReadOnly) {
readOnly.value = isReadOnly;
return true;
}
return false;
}
Future<void> onPublish() async {
feedBack();
List<Map<String, dynamic>>? pictures;
if (pathList.isNotEmpty) {
SmartDialog.showLoading(msg: '正在上传图片...');
final cancelToken = CancelToken();
try {
pictures = await Future.wait<Map<String, dynamic>>(
pathList.map((path) async {
Map result = await MsgHttp.uploadBfs(
path: path,
category: 'daily',
biz: 'new_dyn',
cancelToken: cancelToken,
);
if (!result['status']) throw HttpException(result['msg']);
UploadBfsResData data = result['data'];
return {
'img_width': data.imageWidth,
'img_height': data.imageHeight,
'img_size': data.imgSize,
'img_src': data.imageUrl,
};
}).toList(),
eagerError: true);
SmartDialog.dismiss();
} on HttpException catch (e) {
cancelToken.cancel();
SmartDialog.dismiss();
SmartDialog.showToast(e.message);
return;
}
}
onCustomPublish(message: editController.text, pictures: pictures);
}
Future<void> onCustomPublish({required String message, List? pictures});
void onChooseEmote(dynamic emote) {
if (emote is Emote) {
onInsertText(emote.text!);
} else if (emote is Emoticon) {
onInsertText(emote.emoji!);
}
}
Widget? get customPanel => null;
Widget buildEmojiPickerPanel() {
double height = context.isTablet ? 300 : 170;
final keyboardHeight = controller.keyboardHeight;
if (keyboardHeight != 0) {
height = max(height, keyboardHeight);
}
return SizedBox(
height: height,
child: customPanel,
);
}
Widget buildPanelContainer([Color? panelBgColor]) {
return ChatBottomPanelContainer<PanelType>(
controller: controller,
inputFocusNode: focusNode,
otherPanelWidget: (type) {
if (type == null) return const SizedBox.shrink();
switch (type) {
case PanelType.emoji:
return buildEmojiPickerPanel();
default:
return const SizedBox.shrink();
}
},
onPanelTypeChange: (panelType, data) {
// if (kDebugMode) debugPrint('panelType: $panelType');
switch (panelType) {
case ChatBottomPanelType.none:
this.panelType.value = PanelType.none;
break;
case ChatBottomPanelType.keyboard:
this.panelType.value = PanelType.keyboard;
break;
case ChatBottomPanelType.other:
if (data == null) return;
switch (data) {
case PanelType.emoji:
this.panelType.value = PanelType.emoji;
break;
default:
this.panelType.value = PanelType.none;
break;
}
break;
}
},
panelBgColor: panelBgColor ?? Theme.of(context).colorScheme.surface,
);
}
Widget buildImage(int index, double height) {
final color =
Theme.of(context).colorScheme.secondaryContainer.withValues(alpha: 0.5);
void onClear() {
pathList.removeAt(index);
if (pathList.isEmpty && editController.text.trim().isEmpty) {
enablePublish.value = false;
}
}
return Stack(
clipBehavior: Clip.none,
children: [
GestureDetector(
onTap: () {
controller.keepChatPanel();
context.imageView(
imgList: pathList
.map((path) => SourceModel(
url: path,
sourceType: SourceType.fileImage,
))
.toList(),
initialPage: index,
);
},
onLongPress: onClear,
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4)),
child: Image(
height: height,
fit: BoxFit.fitHeight,
filterQuality: FilterQuality.low,
image: FileImage(File(pathList[index])),
),
),
),
Positioned(
top: 34,
right: 5,
child: iconButton(
context: context,
icon: Icons.edit,
onPressed: () => onCropImage(index),
size: 24,
iconSize: 14,
bgColor: color,
),
),
Positioned(
top: 5,
right: 5,
child: iconButton(
context: context,
icon: Icons.clear,
onPressed: onClear,
size: 24,
iconSize: 14,
bgColor: color,
),
),
],
);
}
Future<void> onCropImage(int index) async {
final theme = Theme.of(context);
CroppedFile? croppedFile = await ImageCropper().cropImage(
sourcePath: pathList[index],
uiSettings: [
AndroidUiSettings(
toolbarTitle: '裁剪',
toolbarColor: theme.colorScheme.secondaryContainer,
toolbarWidgetColor: theme.colorScheme.onSecondaryContainer,
),
IOSUiSettings(
title: '裁剪',
),
],
);
if (croppedFile != null) {
pathList[index] = croppedFile.path;
}
}
void onPickImage([VoidCallback? callback]) {
EasyThrottle.throttle('imagePicker', const Duration(milliseconds: 500),
() async {
try {
List<XFile> pickedFiles = await imagePicker.pickMultiImage(
limit: limit,
imageQuality: 100,
);
if (pickedFiles.isNotEmpty) {
for (int i = 0; i < pickedFiles.length; i++) {
if (pathList.length == limit) {
SmartDialog.showToast('最多选择$limit张图片');
break;
} else {
pathList.add(pickedFiles[i].path);
}
}
callback?.call();
}
} catch (e) {
SmartDialog.showToast(e.toString());
}
});
}
List<Map<String, dynamic>>? getRichContent() {
if (mentions.isNullOrEmpty) {
return null;
}
List<Map<String, dynamic>> content = [];
void addPlainText(String text) {
content.add({
"raw_text": text,
"type": 1,
"biz_id": "",
});
}
final pattern = RegExp(
mentions!.toSet().map((e) => RegExp.escape('@${e.name!}')).join('|'));
editController.text.splitMapJoin(
pattern,
onMatch: (Match match) {
final name = match.group(0)!;
final item =
mentions!.firstWhereOrNull((e) => e.name == name.substring(1));
if (item != null) {
content.add({
"raw_text": name,
"type": 2,
"biz_id": item.uid,
});
} else {
addPlainText(name);
}
return '';
},
onNonMatch: (String text) {
addPlainText(text);
return '';
},
);
return content;
}
double _mentionOffset = 0;
void onMention([bool fromClick = false]) {
controller.keepChatPanel();
DynMentionPanel.onDynMention(
context,
offset: _mentionOffset,
callback: (offset) => _mentionOffset = offset,
).then((MentionItem? res) {
if (res != null) {
(mentions ??= <MentionItem>[]).add(res);
String atName = '${fromClick ? '@' : ''}${res.name} ';
onInsertText(atName);
}
});
}
void onInsertText(String text) {
if (text.isEmpty) {
return;
}
enablePublish.value = true;
final oldValue = editController.value;
final selection = oldValue.selection;
if (selection.isValid) {
TextEditingDelta delta;
if (selection.isCollapsed) {
delta = TextEditingDeltaInsertion(
oldText: oldValue.text,
textInserted: text,
insertionOffset: selection.start,
selection: TextSelection.collapsed(
offset: selection.start + text.length,
),
composing: TextRange.empty,
);
} else {
delta = TextEditingDeltaReplacement(
oldText: oldValue.text,
replacementText: text,
replacedRange: selection,
selection: TextSelection.collapsed(
offset: selection.start + text.length,
),
composing: TextRange.empty,
);
}
final newValue = delta.apply(oldValue);
if (oldValue == newValue) {
return;
}
editController.value = newValue;
} else {
editController.value = TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: text.length),
);
}
widget.onSave?.call((text: editController.text, mentions: mentions));
}
void onDelAtUser(String name) {
mentions!.removeFirstWhere((e) => e.name == name);
}
void onChanged(String value) {
bool isEmpty = value.trim().isEmpty;
if (isEmpty) {
enablePublish.value = false;
mentions?.clear();
} else {
enablePublish.value = true;
}
widget.onSave?.call((text: value, mentions: mentions));
}
}

View File

@@ -0,0 +1,256 @@
import 'dart:async';
import 'dart:io';
import 'dart:math' show max;
import 'package:PiliPlus/http/msg.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/models_new/upload_bfs/data.dart';
import 'package:PiliPlus/utils/feed_back.dart';
import 'package:chat_bottom_container/chat_bottom_container.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
abstract class CommonPublishPage<T> extends StatefulWidget {
const CommonPublishPage({
super.key,
this.initialValue,
this.imageLengthLimit,
this.onSave,
this.autofocus = true,
});
final String? initialValue;
final int? imageLengthLimit;
final ValueChanged<T>? onSave;
final bool autofocus;
}
abstract class CommonPublishPageState<T extends CommonPublishPage>
extends State<T> with WidgetsBindingObserver {
late final focusNode = FocusNode();
late final controller = ChatBottomPanelContainerController<PanelType>();
TextEditingController get editController;
Rx<PanelType> panelType = PanelType.none.obs;
late final RxBool readOnly = false.obs;
late final RxBool enablePublish = false.obs;
late final imagePicker = ImagePicker();
late final RxList<String> pathList = <String>[].obs;
int get limit => widget.imageLengthLimit ?? 9;
bool? hasPub;
void initPubState();
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
initPubState();
if (widget.autofocus) {
Future.delayed(const Duration(milliseconds: 300)).whenComplete(() {
if (mounted) {
focusNode.requestFocus();
}
});
}
}
@override
void dispose() {
if (hasPub != true) {
onSave();
}
focusNode.dispose();
editController.dispose();
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
Future<void> _requestFocus() async {
await Future.delayed(const Duration(microseconds: 200));
focusNode.requestFocus();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
if (mounted &&
widget.autofocus &&
panelType.value == PanelType.keyboard) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (focusNode.hasFocus) {
focusNode.unfocus();
_requestFocus();
} else {
_requestFocus();
}
});
}
} else if (state == AppLifecycleState.paused) {
controller.keepChatPanel();
if (focusNode.hasFocus) {
focusNode.unfocus();
}
}
}
void updatePanelType(PanelType type) {
final isSwitchToKeyboard = PanelType.keyboard == type;
final isSwitchToEmojiPanel = PanelType.emoji == type;
bool isUpdated = false;
switch (type) {
case PanelType.keyboard:
updateInputView(isReadOnly: false);
break;
case PanelType.emoji:
isUpdated = updateInputView(isReadOnly: true);
break;
default:
break;
}
void updatePanelTypeFunc() {
controller.updatePanelType(
isSwitchToKeyboard
? ChatBottomPanelType.keyboard
: ChatBottomPanelType.other,
data: type,
forceHandleFocus: isSwitchToEmojiPanel
? ChatBottomHandleFocus.requestFocus
: ChatBottomHandleFocus.none,
);
}
if (isUpdated) {
// Waiting for the input view to update.
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
updatePanelTypeFunc();
});
} else {
updatePanelTypeFunc();
}
}
Future<void> hidePanel() async {
if (focusNode.hasFocus) {
await Future.delayed(const Duration(milliseconds: 100));
focusNode.unfocus();
}
updateInputView(isReadOnly: false);
if (ChatBottomPanelType.none == controller.currentPanelType) return;
controller.updatePanelType(ChatBottomPanelType.none);
}
bool updateInputView({
required bool isReadOnly,
}) {
if (readOnly.value != isReadOnly) {
readOnly.value = isReadOnly;
return true;
}
return false;
}
Widget buildEmojiPickerPanel() {
double height = context.isTablet ? 300 : 170;
final keyboardHeight = controller.keyboardHeight;
if (keyboardHeight != 0) {
height = max(height, keyboardHeight);
}
return SizedBox(
height: height,
child: customPanel,
);
}
Widget buildPanelContainer([Color? panelBgColor]) {
return ChatBottomPanelContainer<PanelType>(
controller: controller,
inputFocusNode: focusNode,
otherPanelWidget: (type) {
if (type == null) return const SizedBox.shrink();
switch (type) {
case PanelType.emoji:
return buildEmojiPickerPanel();
default:
return const SizedBox.shrink();
}
},
onPanelTypeChange: (panelType, data) {
// if (kDebugMode) debugPrint('panelType: $panelType');
switch (panelType) {
case ChatBottomPanelType.none:
this.panelType.value = PanelType.none;
break;
case ChatBottomPanelType.keyboard:
this.panelType.value = PanelType.keyboard;
break;
case ChatBottomPanelType.other:
if (data == null) return;
switch (data) {
case PanelType.emoji:
this.panelType.value = PanelType.emoji;
break;
default:
this.panelType.value = PanelType.none;
break;
}
break;
}
},
panelBgColor: panelBgColor ?? Theme.of(context).colorScheme.surface,
);
}
Future<void> onPublish() async {
feedBack();
List<Map<String, dynamic>>? pictures;
if (pathList.isNotEmpty) {
SmartDialog.showLoading(msg: '正在上传图片...');
final cancelToken = CancelToken();
try {
pictures = await Future.wait<Map<String, dynamic>>(
pathList.map((path) async {
Map result = await MsgHttp.uploadBfs(
path: path,
category: 'daily',
biz: 'new_dyn',
cancelToken: cancelToken,
);
if (!result['status']) throw HttpException(result['msg']);
UploadBfsResData data = result['data'];
return {
'img_width': data.imageWidth,
'img_height': data.imageHeight,
'img_size': data.imgSize,
'img_src': data.imageUrl,
};
}).toList(),
eagerError: true);
SmartDialog.dismiss();
} on HttpException catch (e) {
cancelToken.cancel();
SmartDialog.dismiss();
SmartDialog.showToast(e.message);
return;
}
}
onCustomPublish(pictures: pictures);
}
Future<void> onCustomPublish({List? pictures});
Widget? get customPanel => null;
void onChanged(String value) {
enablePublish.value = value.trim().isNotEmpty;
}
void onSave() {}
}

View File

@@ -0,0 +1,342 @@
import 'dart:io';
import 'package:PiliPlus/common/widgets/button/icon_button.dart';
import 'package:PiliPlus/common/widgets/text_field/controller.dart';
import 'package:PiliPlus/models/common/image_preview_type.dart';
import 'package:PiliPlus/models_new/dynamic/dyn_mention/item.dart';
import 'package:PiliPlus/models_new/emote/emote.dart' as e;
import 'package:PiliPlus/models_new/live/live_emote/emoticon.dart';
import 'package:PiliPlus/pages/common/publish/common_publish_page.dart';
import 'package:PiliPlus/pages/dynamics_mention/view.dart';
import 'package:PiliPlus/utils/extension.dart';
import 'package:easy_debounce/easy_throttle.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:image_picker/image_picker.dart';
abstract class CommonRichTextPubPage
extends CommonPublishPage<List<RichTextItem>> {
const CommonRichTextPubPage({
super.key,
this.items,
super.onSave,
super.autofocus,
super.imageLengthLimit,
});
final List<RichTextItem>? items;
}
abstract class CommonRichTextPubPageState<T extends CommonRichTextPubPage>
extends CommonPublishPageState<T> {
bool? hasPub;
@override
late final RichTextEditingController editController =
RichTextEditingController(
items: widget.items,
onMention: onMention,
);
@override
void initPubState() {
if (editController.rawText.trim().isNotEmpty) {
enablePublish.value = true;
}
}
@override
void didChangeDependencies() {
editController.richStyle = null;
super.didChangeDependencies();
}
Widget buildImage(int index, double height) {
final color =
Theme.of(context).colorScheme.secondaryContainer.withValues(alpha: 0.5);
void onClear() {
pathList.removeAt(index);
if (pathList.isEmpty && editController.rawText.trim().isEmpty) {
enablePublish.value = false;
}
}
return Stack(
clipBehavior: Clip.none,
children: [
GestureDetector(
onTap: () {
controller.keepChatPanel();
context.imageView(
imgList: pathList
.map((path) => SourceModel(
url: path,
sourceType: SourceType.fileImage,
))
.toList(),
initialPage: index,
);
},
onLongPress: onClear,
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4)),
child: Image(
height: height,
fit: BoxFit.fitHeight,
filterQuality: FilterQuality.low,
image: FileImage(File(pathList[index])),
),
),
),
Positioned(
top: 34,
right: 5,
child: iconButton(
context: context,
icon: Icons.edit,
onPressed: () => onCropImage(index),
size: 24,
iconSize: 14,
bgColor: color,
),
),
Positioned(
top: 5,
right: 5,
child: iconButton(
context: context,
icon: Icons.clear,
onPressed: onClear,
size: 24,
iconSize: 14,
bgColor: color,
),
),
],
);
}
Future<void> onCropImage(int index) async {
final theme = Theme.of(context);
CroppedFile? croppedFile = await ImageCropper().cropImage(
sourcePath: pathList[index],
uiSettings: [
AndroidUiSettings(
toolbarTitle: '裁剪',
toolbarColor: theme.colorScheme.secondaryContainer,
toolbarWidgetColor: theme.colorScheme.onSecondaryContainer,
),
IOSUiSettings(
title: '裁剪',
),
],
);
if (croppedFile != null) {
pathList[index] = croppedFile.path;
}
}
void onPickImage([VoidCallback? callback]) {
EasyThrottle.throttle('imagePicker', const Duration(milliseconds: 500),
() async {
try {
List<XFile> pickedFiles = await imagePicker.pickMultiImage(
limit: limit,
imageQuality: 100,
);
if (pickedFiles.isNotEmpty) {
for (int i = 0; i < pickedFiles.length; i++) {
if (pathList.length == limit) {
SmartDialog.showToast('最多选择$limit张图片');
break;
} else {
pathList.add(pickedFiles[i].path);
}
}
callback?.call();
}
} catch (e) {
SmartDialog.showToast(e.toString());
}
});
}
void onChooseEmote(dynamic emote, double? width, double? height) {
if (emote is e.Emote) {
final isTextEmote = width == null;
onInsertText(
isTextEmote ? emote.text! : '\uFFFC',
RichTextType.emoji,
rawText: emote.text!,
emote: isTextEmote
? null
: Emote(
url: emote.url!,
width: width,
height: height,
),
);
} else if (emote is Emoticon) {
onInsertText(
'\uFFFC',
RichTextType.emoji,
rawText: emote.emoji!,
emote: Emote(
url: emote.url!,
width: width!,
height: height,
),
);
}
}
List<Map<String, dynamic>>? getRichContent() {
if (editController.items.isEmpty) return null;
return editController.items.map((e) {
return switch (e.type) {
RichTextType.text || RichTextType.composing => <String, dynamic>{
"raw_text": e.text,
"type": 1,
"biz_id": "",
},
RichTextType.at => <String, dynamic>{
"raw_text": '@${e.rawText}',
"type": 2,
"biz_id": e.uid,
},
RichTextType.emoji => <String, dynamic>{
"raw_text": e.rawText,
"type": 9,
"biz_id": "",
},
};
}).toList();
}
double _mentionOffset = 0;
void onMention([bool fromClick = false]) {
controller.keepChatPanel();
DynMentionPanel.onDynMention(
context,
offset: _mentionOffset,
callback: (offset) => _mentionOffset = offset,
).then((MentionItem? res) {
if (res != null) {
onInsertText(
'@${res.name} ',
RichTextType.at,
rawText: res.name,
uid: res.uid,
fromClick: fromClick,
);
}
});
}
void onInsertText(
String text,
RichTextType type, {
String? rawText,
Emote? emote,
String? uid,
bool? fromClick,
}) {
if (text.isEmpty) {
return;
}
enablePublish.value = true;
var oldValue = editController.value;
final selection = oldValue.selection;
if (selection.isValid) {
TextEditingDelta delta;
if (selection.isCollapsed) {
if (type == RichTextType.at && fromClick == false) {
delta = RichTextEditingDeltaReplacement(
oldText: oldValue.text,
replacementText: text,
replacedRange:
TextRange(start: selection.start - 1, end: selection.end),
selection: TextSelection.collapsed(
offset: selection.start - 1 + text.length,
),
composing: TextRange.empty,
rawText: rawText,
type: type,
emote: emote,
uid: uid,
);
} else {
delta = RichTextEditingDeltaInsertion(
oldText: oldValue.text,
textInserted: text,
insertionOffset: selection.start,
selection: TextSelection.collapsed(
offset: selection.start + text.length,
),
composing: TextRange.empty,
rawText: rawText,
type: type,
emote: emote,
uid: uid,
);
}
} else {
delta = RichTextEditingDeltaReplacement(
oldText: oldValue.text,
replacementText: text,
replacedRange: selection,
selection: TextSelection.collapsed(
offset: selection.start + text.length,
),
composing: TextRange.empty,
rawText: rawText,
type: type,
emote: emote,
uid: uid,
);
}
final newValue = delta.apply(oldValue);
if (oldValue == newValue) {
return;
}
editController
..value = newValue
..syncRichText(delta);
} else {
editController.value = TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: text.length),
);
editController.items
..clear()
..add(
RichTextItem(
type: type,
text: text,
rawText: rawText,
range: TextRange(
start: 0,
end: text.length,
),
emote: emote,
uid: uid,
),
);
}
}
@override
void onSave() {
widget.onSave?.call(editController.items);
}
}

View File

@@ -0,0 +1,29 @@
import 'package:PiliPlus/pages/common/publish/common_publish_page.dart';
import 'package:flutter/material.dart';
abstract class CommonTextPubPage extends CommonPublishPage<String> {
const CommonTextPubPage({
super.key,
super.initialValue,
super.onSave,
});
}
abstract class CommonTextPubPageState<T extends CommonTextPubPage>
extends CommonPublishPageState<T> {
@override
late final TextEditingController editController =
TextEditingController(text: widget.initialValue);
@override
void initPubState() {
if (widget.initialValue?.trim().isNotEmpty == true) {
enablePublish.value = true;
}
}
@override
void onSave() {
widget.onSave?.call(editController.text);
}
}

View File

@@ -1,10 +1,10 @@
import 'package:PiliPlus/common/widgets/text_field/controller.dart';
import 'package:PiliPlus/grpc/bilibili/main/community/reply/v1.pb.dart'
show MainListReply, ReplyInfo, SubjectControl, Mode;
import 'package:PiliPlus/grpc/bilibili/pagination.pb.dart';
import 'package:PiliPlus/http/loading_state.dart';
import 'package:PiliPlus/http/reply.dart';
import 'package:PiliPlus/models/common/reply/reply_sort_type.dart';
import 'package:PiliPlus/models_new/dynamic/dyn_mention/item.dart';
import 'package:PiliPlus/pages/common/common_list_controller.dart';
import 'package:PiliPlus/pages/video/reply_new/view.dart';
import 'package:PiliPlus/services/account_service.dart';
@@ -25,8 +25,7 @@ abstract class ReplyController<R> extends CommonListController<R, ReplyInfo> {
late Rx<ReplySortType> sortType;
late Rx<Mode> mode;
late final savedReplies =
<Object, ({String text, List<MentionItem>? mentions})?>{};
late final savedReplies = <Object, List<RichTextItem>?>{};
AccountService accountService = Get.find<AccountService>();
@@ -127,16 +126,20 @@ abstract class ReplyController<R> extends CommonListController<R, ReplyInfo> {
.push(
GetDialogRoute(
pageBuilder: (buildContext, animation, secondaryAnimation) {
final saved = savedReplies[key];
return ReplyPage(
oid: oid ?? replyItem!.oid.toInt(),
root: oid != null ? 0 : replyItem!.id.toInt(),
parent: oid != null ? 0 : replyItem!.id.toInt(),
replyType: replyItem?.type.toInt() ?? replyType!,
replyItem: replyItem,
initialValue: saved?.text,
mentions: saved?.mentions,
onSave: (reply) => savedReplies[key] = reply,
items: savedReplies[key],
onSave: (reply) {
if (reply.isEmpty) {
savedReplies.remove(key);
} else {
savedReplies[key] = reply.toList();
}
},
hint: hint,
);
},
@@ -238,4 +241,10 @@ abstract class ReplyController<R> extends CommonListController<R, ReplyInfo> {
SmartDialog.showToast(res['msg']);
}
}
@override
void onClose() {
savedReplies.clear();
super.onClose();
}
}

View File

@@ -5,13 +5,12 @@ import 'package:PiliPlus/common/widgets/custom_icon.dart';
import 'package:PiliPlus/common/widgets/draggable_sheet/draggable_scrollable_sheet_dyn.dart'
as dyn_sheet;
import 'package:PiliPlus/common/widgets/pair.dart';
import 'package:PiliPlus/common/widgets/text_field/text_field.dart'
as text_field;
import 'package:PiliPlus/common/widgets/text_field/text_field.dart';
import 'package:PiliPlus/http/dynamics.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/models/common/reply/reply_option_type.dart';
import 'package:PiliPlus/models_new/dynamic/dyn_topic_top/topic_item.dart';
import 'package:PiliPlus/pages/common/common_publish_page.dart';
import 'package:PiliPlus/pages/common/publish/common_rich_text_pub_page.dart';
import 'package:PiliPlus/pages/dynamics_mention/controller.dart';
import 'package:PiliPlus/pages/dynamics_select_topic/controller.dart';
import 'package:PiliPlus/pages/dynamics_select_topic/view.dart';
@@ -26,7 +25,7 @@ import 'package:flutter/services.dart' show LengthLimitingTextInputFormatter;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
class CreateDynPanel extends CommonPublishPage {
class CreateDynPanel extends CommonRichTextPubPage {
const CreateDynPanel({
super.key,
super.imageLengthLimit = 18,
@@ -60,7 +59,7 @@ class CreateDynPanel extends CommonPublishPage {
);
}
class _CreateDynPanelState extends CommonPublishPageState<CreateDynPanel> {
class _CreateDynPanelState extends CommonRichTextPubPageState<CreateDynPanel> {
final RxBool _isPrivate = false.obs;
final Rx<DateTime?> _publishTime = Rx<DateTime?>(null);
final Rx<ReplyOptionType> _replyOption = ReplyOptionType.allow.obs;
@@ -550,6 +549,12 @@ class _CreateDynPanelState extends CommonPublishPageState<CreateDynPanel> {
tooltip: '@',
selected: false,
),
// if (kDebugMode)
// ToolbarIconButton(
// onPressed: editController.clear,
// icon: const Icon(Icons.clear, size: 22),
// selected: false,
// ),
],
),
);
@@ -563,13 +568,12 @@ class _CreateDynPanelState extends CommonPublishPageState<CreateDynPanel> {
}
},
child: Obx(
() => text_field.TextField(
() => RichTextField(
controller: editController,
minLines: 4,
maxLines: null,
focusNode: focusNode,
readOnly: readOnly.value,
onDelAtUser: onDelAtUser,
onChanged: onChanged,
decoration: InputDecoration(
hintText: '说点什么吧',
@@ -580,8 +584,7 @@ class _CreateDynPanelState extends CommonPublishPageState<CreateDynPanel> {
),
contentPadding: EdgeInsets.zero,
),
inputFormatters: [LengthLimitingTextInputFormatter(1000)],
onMention: onMention,
// inputFormatters: [LengthLimitingTextInputFormatter(1000)],
),
),
),
@@ -591,14 +594,13 @@ class _CreateDynPanelState extends CommonPublishPageState<CreateDynPanel> {
Widget? get customPanel => EmotePanel(onChoose: onChooseEmote);
@override
Future<void> onCustomPublish(
{required String message, List? pictures}) async {
Future<void> onCustomPublish({List? pictures}) async {
SmartDialog.showLoading(msg: '正在发布');
List<Map<String, dynamic>>? extraContent = getRichContent();
final hasMention = extraContent != null;
final hasRichText = extraContent != null;
var result = await DynamicsHttp.createDynamic(
mid: Accounts.main.mid,
rawText: hasMention ? null : editController.text,
rawText: hasRichText ? null : editController.text,
pics: pictures,
publishTime: _publishTime.value != null
? _publishTime.value!.millisecondsSinceEpoch ~/ 1000
@@ -611,13 +613,14 @@ class _CreateDynPanelState extends CommonPublishPageState<CreateDynPanel> {
);
SmartDialog.dismiss();
if (result['status']) {
hasPub = true;
Get.back();
SmartDialog.showToast('发布成功');
var id = result['data']?['dyn_id'];
RequestUtils.insertCreatedDyn(id);
RequestUtils.checkCreatedDyn(
id: id,
dynText: editController.text,
dynText: editController.rawText,
);
} else {
SmartDialog.showToast(result['msg']);
@@ -637,4 +640,7 @@ class _CreateDynPanelState extends CommonPublishPageState<CreateDynPanel> {
}
});
}
@override
void onSave() {}
}

View File

@@ -6,18 +6,17 @@ import 'package:PiliPlus/common/widgets/text_field/text_field.dart';
import 'package:PiliPlus/http/dynamics.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/models/dynamics/result.dart';
import 'package:PiliPlus/pages/common/common_publish_page.dart';
import 'package:PiliPlus/pages/common/publish/common_rich_text_pub_page.dart';
import 'package:PiliPlus/pages/dynamics_mention/controller.dart';
import 'package:PiliPlus/pages/emote/controller.dart';
import 'package:PiliPlus/pages/emote/view.dart';
import 'package:PiliPlus/utils/accounts.dart';
import 'package:PiliPlus/utils/request_utils.dart';
import 'package:flutter/material.dart' hide DraggableScrollableSheet, TextField;
import 'package:flutter/services.dart' show LengthLimitingTextInputFormatter;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
class RepostPanel extends CommonPublishPage {
class RepostPanel extends CommonRichTextPubPage {
const RepostPanel({
super.key,
this.item,
@@ -48,7 +47,7 @@ class RepostPanel extends CommonPublishPage {
State<RepostPanel> createState() => _RepostPanelState();
}
class _RepostPanelState extends CommonPublishPageState<RepostPanel> {
class _RepostPanelState extends CommonRichTextPubPageState<RepostPanel> {
late bool _isMax = widget.isMax ?? false;
bool? _isExpanded;
@@ -225,7 +224,7 @@ class _RepostPanelState extends CommonPublishPageState<RepostPanel> {
}
},
child: Obx(
() => TextField(
() => RichTextField(
controller: editController,
minLines: 4,
maxLines: null,
@@ -240,9 +239,7 @@ class _RepostPanelState extends CommonPublishPageState<RepostPanel> {
),
contentPadding: const EdgeInsets.symmetric(vertical: 10),
),
inputFormatters: [LengthLimitingTextInputFormatter(1000)],
onMention: onMention,
onDelAtUser: onDelAtUser,
// inputFormatters: [LengthLimitingTextInputFormatter(1000)],
),
),
),
@@ -376,7 +373,7 @@ class _RepostPanelState extends CommonPublishPageState<RepostPanel> {
@override
Widget? get customPanel => EmotePanel(onChoose: onChooseEmote);
List<Map<String, dynamic>>? extraContent(DynamicItemModel item) {
List<Map<String, dynamic>>? getRepostContent(DynamicItemModel item) {
try {
return [
{"raw_text": "//", "type": 1, "biz_id": ""},
@@ -416,26 +413,26 @@ class _RepostPanelState extends CommonPublishPageState<RepostPanel> {
}
@override
Future<void> onCustomPublish(
{required String message, List? pictures}) async {
Future<void> onCustomPublish({List? pictures}) async {
SmartDialog.showLoading();
List<Map<String, dynamic>>? content = getRichContent();
final hasMention = content != null;
List<Map<String, dynamic>>? richContent = getRichContent();
final hasRichText = richContent != null;
List<Map<String, dynamic>>? repostContent =
widget.item?.orig != null ? extraContent(widget.item!) : null;
if (hasMention && repostContent != null) {
content.addAll(repostContent);
widget.item?.orig != null ? getRepostContent(widget.item!) : null;
if (hasRichText && repostContent != null) {
richContent.addAll(repostContent);
}
var result = await DynamicsHttp.createDynamic(
mid: Accounts.main.mid,
dynIdStr: widget.item?.idStr ?? widget.dynIdStr,
rid: widget.rid,
dynType: widget.dynType,
rawText: hasMention ? null : editController.text,
extraContent: content ?? repostContent,
rawText: hasRichText ? null : editController.text,
extraContent: richContent ?? repostContent,
);
SmartDialog.dismiss();
if (result['status']) {
hasPub = true;
Get.back();
SmartDialog.showToast('转发成功');
widget.callback?.call();
@@ -443,10 +440,13 @@ class _RepostPanelState extends CommonPublishPageState<RepostPanel> {
RequestUtils.insertCreatedDyn(id);
RequestUtils.checkCreatedDyn(
id: id,
dynText: editController.text,
dynText: editController.rawText,
);
} else {
SmartDialog.showToast(result['msg']);
}
}
@override
void onSave() {}
}

View File

@@ -11,7 +11,8 @@ import 'package:flutter/material.dart';
import 'package:get/get.dart';
class EmotePanel extends StatefulWidget {
final ValueChanged<Emote> onChoose;
final Function(Emote emote, double? width, double? height) onChoose;
const EmotePanel({super.key, required this.onChoose});
@override
@@ -46,18 +47,17 @@ class _EmotePanelState extends State<EmotePanel>
controller: _emotePanelController.tabController,
children: response!.map(
(e) {
int size = e.emote!.first.meta!.size!;
int type = e.type!;
double size = e.emote!.first.meta!.size == 1 ? 40 : 60;
bool isTextEmote = e.type == 4;
return GridView.builder(
padding: const EdgeInsets.only(
left: 12, right: 12, bottom: 12),
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent:
type == 4 ? 100 : (size == 1 ? 40 : 60),
maxCrossAxisExtent: isTextEmote ? 100 : size,
crossAxisSpacing: 8,
mainAxisSpacing: 8,
mainAxisExtent: size == 1 ? 40 : 60,
mainAxisExtent: size,
),
itemCount: e.emote!.length,
itemBuilder: (context, index) {
@@ -67,10 +67,17 @@ class _EmotePanelState extends State<EmotePanel>
child: InkWell(
borderRadius:
const BorderRadius.all(Radius.circular(8)),
onTap: () => widget.onChoose(item),
onTap: () => widget.onChoose(
item,
isTextEmote
? null
: e.emote!.first.meta!.size == 1
? 24
: 42,
null),
child: Padding(
padding: const EdgeInsets.all(6),
child: type == 4
child: isTextEmote
? Center(
child: Text(
item.text!,
@@ -80,8 +87,8 @@ class _EmotePanelState extends State<EmotePanel>
)
: NetworkImgLayer(
src: item.url!,
width: size * 38,
height: size * 38,
width: size,
height: size,
semanticsLabel: item.text!,
type: ImageType.emote,
boxFit: BoxFit.contain,

View File

@@ -14,7 +14,7 @@ import 'package:get/get.dart';
class LiveEmotePanel extends StatefulWidget {
final int roomId;
final ValueChanged<Emoticon> onChoose;
final Function(Emoticon emote, double? width, double? height) onChoose;
final ValueChanged<Emoticon> onSendEmoticonUnique;
const LiveEmotePanel({
super.key,
@@ -61,6 +61,8 @@ class _LiveEmotePanelState extends State<LiveEmotePanel>
max(1, item.emoticons!.first.width! / 80);
double heightFac =
max(1, item.emoticons!.first.height! / 80);
final width = widthFac * 38;
final height = heightFac * 38;
return GridView.builder(
padding: const EdgeInsets.only(
left: 12, right: 12, bottom: 12),
@@ -81,7 +83,7 @@ class _LiveEmotePanelState extends State<LiveEmotePanel>
const BorderRadius.all(Radius.circular(8)),
onTap: () {
if (item.pkgType == 3) {
widget.onChoose(e);
widget.onChoose(e, width, height);
} else {
widget.onSendEmoticonUnique(e);
}
@@ -91,8 +93,8 @@ class _LiveEmotePanelState extends State<LiveEmotePanel>
child: NetworkImgLayer(
boxFit: BoxFit.contain,
src: e.url!,
width: widthFac * 38,
height: heightFac * 38,
width: width,
height: height,
type: ImageType.emote,
quality: item.pkgType == 3 ? null : 80,
),

View File

@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:PiliPlus/common/widgets/text_field/controller.dart';
import 'package:PiliPlus/http/constants.dart';
import 'package:PiliPlus/http/live.dart';
import 'package:PiliPlus/http/video.dart';
@@ -48,7 +49,7 @@ class LiveRoomController extends GetxController {
late List<({int code, String desc})> acceptQnList = [];
RxString currentQnDesc = ''.obs;
String? savedDanmaku;
List<RichTextItem>? savedDanmaku;
AccountService accountService = Get.find<AccountService>();
@@ -233,6 +234,8 @@ class LiveRoomController extends GetxController {
@override
void onClose() {
savedDanmaku?.clear();
savedDanmaku = null;
scrollController
..removeListener(listener)
..dispose();

View File

@@ -1,24 +1,24 @@
import 'dart:async';
import 'package:PiliPlus/common/widgets/button/toolbar_icon_button.dart';
import 'package:PiliPlus/common/widgets/text_field/text_field.dart';
import 'package:PiliPlus/http/live.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/pages/common/common_publish_page.dart';
import 'package:PiliPlus/pages/common/publish/common_rich_text_pub_page.dart';
import 'package:PiliPlus/pages/live_emote/controller.dart';
import 'package:PiliPlus/pages/live_emote/view.dart';
import 'package:PiliPlus/pages/live_room/controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show LengthLimitingTextInputFormatter;
import 'package:flutter/material.dart' hide TextField;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart' hide MultipartFile;
class LiveSendDmPanel extends CommonPublishPage {
class LiveSendDmPanel extends CommonRichTextPubPage {
final bool fromEmote;
final LiveRoomController liveRoomController;
const LiveSendDmPanel({
super.key,
super.initialValue,
super.items,
super.onSave,
this.fromEmote = false,
required this.liveRoomController,
@@ -28,7 +28,7 @@ class LiveSendDmPanel extends CommonPublishPage {
State<LiveSendDmPanel> createState() => _ReplyPageState();
}
class _ReplyPageState extends CommonPublishPageState<LiveSendDmPanel> {
class _ReplyPageState extends CommonRichTextPubPageState<LiveSendDmPanel> {
LiveRoomController get liveRoomController => widget.liveRoomController;
@override
@@ -101,7 +101,7 @@ class _ReplyPageState extends CommonPublishPageState<LiveSendDmPanel> {
}
},
child: Obx(
() => TextField(
() => RichTextField(
controller: editController,
minLines: 1,
maxLines: 2,
@@ -115,7 +115,7 @@ class _ReplyPageState extends CommonPublishPageState<LiveSendDmPanel> {
hintStyle: TextStyle(fontSize: 14),
),
style: theme.textTheme.bodyLarge,
inputFormatters: [LengthLimitingTextInputFormatter(20)],
// inputFormatters: [LengthLimitingTextInputFormatter(20)],
),
),
),
@@ -176,20 +176,23 @@ class _ReplyPageState extends CommonPublishPageState<LiveSendDmPanel> {
@override
Future<void> onCustomPublish({
required String message,
String? message,
List? pictures,
int? dmType,
emoticonOptions,
}) async {
final res = await LiveHttp.sendLiveMsg(
roomId: liveRoomController.roomId,
msg: message,
msg: message ?? editController.rawText,
dmType: dmType,
emoticonOptions: emoticonOptions,
);
if (res['status']) {
hasPub = true;
Get.back();
liveRoomController.savedDanmaku = null;
liveRoomController
..savedDanmaku?.clear()
..savedDanmaku = null;
SmartDialog.showToast('发送成功');
} else {
SmartDialog.showToast(res['msg']);

View File

@@ -606,8 +606,16 @@ class _LiveRoomPageState extends State<LiveRoomPage>
return LiveSendDmPanel(
fromEmote: fromEmote,
liveRoomController: _liveRoomController,
initialValue: _liveRoomController.savedDanmaku,
onSave: (msg) => _liveRoomController.savedDanmaku = msg.text,
items: _liveRoomController.savedDanmaku,
onSave: (msg) {
if (msg.isEmpty) {
_liveRoomController
..savedDanmaku?.clear()
..savedDanmaku = null;
} else {
_liveRoomController.savedDanmaku = msg.toList();
}
},
);
},
transitionDuration: const Duration(milliseconds: 500),

View File

@@ -945,7 +945,7 @@ class VideoDetailController extends GetxController
bvid: bvid,
progress: plPlayerController.position.value.inMilliseconds,
initialValue: savedDanmaku,
onSave: (danmaku) => savedDanmaku = danmaku.text,
onSave: (danmaku) => savedDanmaku = danmaku,
callback: (danmakuModel) {
savedDanmaku = null;
plPlayerController.danmakuController?.addDanmaku(danmakuModel);

View File

@@ -1,13 +1,15 @@
import 'dart:async';
import 'package:PiliPlus/common/widgets/button/toolbar_icon_button.dart';
import 'package:PiliPlus/common/widgets/text_field/controller.dart'
show RichTextType;
import 'package:PiliPlus/common/widgets/text_field/text_field.dart';
import 'package:PiliPlus/grpc/bilibili/main/community/reply/v1.pb.dart'
show ReplyInfo;
import 'package:PiliPlus/http/video.dart';
import 'package:PiliPlus/main.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/pages/common/common_publish_page.dart';
import 'package:PiliPlus/pages/common/publish/common_rich_text_pub_page.dart';
import 'package:PiliPlus/pages/dynamics_mention/controller.dart';
import 'package:PiliPlus/pages/emote/view.dart';
import 'package:PiliPlus/utils/storage_pref.dart';
@@ -15,7 +17,7 @@ import 'package:flutter/material.dart' hide TextField;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
class ReplyPage extends CommonPublishPage {
class ReplyPage extends CommonRichTextPubPage {
final int oid;
final int root;
final int parent;
@@ -25,8 +27,7 @@ class ReplyPage extends CommonPublishPage {
const ReplyPage({
super.key,
super.initialValue,
super.mentions,
super.items,
super.imageLengthLimit,
super.onSave,
required this.oid,
@@ -41,7 +42,7 @@ class ReplyPage extends CommonPublishPage {
State<ReplyPage> createState() => _ReplyPageState();
}
class _ReplyPageState extends CommonPublishPageState<ReplyPage> {
class _ReplyPageState extends CommonRichTextPubPageState<ReplyPage> {
final RxBool _syncToDynamic = false.obs;
Widget get child => SafeArea(
@@ -137,7 +138,7 @@ class _ReplyPageState extends CommonPublishPageState<ReplyPage> {
}
},
child: Obx(
() => TextField(
() => RichTextField(
controller: editController,
minLines: 4,
maxLines: 8,
@@ -151,8 +152,6 @@ class _ReplyPageState extends CommonPublishPageState<ReplyPage> {
hintStyle: const TextStyle(fontSize: 14),
),
style: themeData.textTheme.bodyLarge,
onMention: onMention,
onDelAtUser: onDelAtUser,
),
),
),
@@ -265,8 +264,12 @@ class _ReplyPageState extends CommonPublishPageState<ReplyPage> {
}
@override
Future<void> onCustomPublish(
{required String message, List? pictures}) async {
Future<void> onCustomPublish({List? pictures}) async {
Map<String, int> atNameToMid = {
for (var e in editController.items)
if (e.type == RichTextType.at) e.rawText: int.parse(e.uid!),
};
String message = editController.rawText;
var result = await VideoHttp.replyAdd(
type: widget.replyType,
oid: widget.oid,
@@ -275,13 +278,12 @@ class _ReplyPageState extends CommonPublishPageState<ReplyPage> {
message: widget.replyItem != null && widget.replyItem!.root != 0
? ' 回复 @${widget.replyItem!.member.name} : $message'
: message,
atNameToMid: mentions?.isNotEmpty == true
? {for (var e in mentions!) e.name: e.uid}
: null,
atNameToMid: atNameToMid,
pictures: pictures,
syncToDynamic: _syncToDynamic.value,
);
if (result['status']) {
hasPub = true;
SmartDialog.showToast(result['data']['success_toast']);
Get.back(result: result['data']['reply']);
} else {

View File

@@ -149,16 +149,20 @@ class VideoReplyReplyController extends ReplyController
.push(
GetDialogRoute(
pageBuilder: (buildContext, animation, secondaryAnimation) {
final saved = savedReplies[key];
return ReplyPage(
oid: oid,
root: root,
parent: root,
replyType: this.replyType,
replyItem: replyItem,
initialValue: saved?.text,
mentions: saved?.mentions,
onSave: (reply) => savedReplies[key] = reply,
items: savedReplies[key],
onSave: (reply) {
if (reply.isEmpty) {
savedReplies.remove(key);
} else {
savedReplies[key] = reply.toList();
}
},
);
},
transitionDuration: const Duration(milliseconds: 500),

View File

@@ -5,7 +5,7 @@ import 'package:PiliPlus/http/danmaku.dart';
import 'package:PiliPlus/main.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/models/user/info.dart';
import 'package:PiliPlus/pages/common/common_publish_page.dart';
import 'package:PiliPlus/pages/common/publish/common_text_pub_page.dart';
import 'package:PiliPlus/pages/setting/slide_color_picker.dart';
import 'package:PiliPlus/utils/storage.dart';
import 'package:canvas_danmaku/models/danmaku_content_item.dart';
@@ -14,7 +14,7 @@ import 'package:flutter/services.dart' show LengthLimitingTextInputFormatter;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
class SendDanmakuPanel extends CommonPublishPage {
class SendDanmakuPanel extends CommonTextPubPage {
// video
final dynamic cid;
final dynamic bvid;
@@ -44,7 +44,7 @@ class SendDanmakuPanel extends CommonPublishPage {
State<SendDanmakuPanel> createState() => _SendDanmakuPanelState();
}
class _SendDanmakuPanelState extends CommonPublishPageState<SendDanmakuPanel> {
class _SendDanmakuPanelState extends CommonTextPubPageState<SendDanmakuPanel> {
late final RxInt _mode;
late final RxInt _fontsize;
late final Rx<Color> _color;
@@ -448,8 +448,7 @@ class _SendDanmakuPanelState extends CommonPublishPageState<SendDanmakuPanel> {
}
@override
Future<void> onCustomPublish(
{required String message, List? pictures}) async {
Future<void> onCustomPublish({List? pictures}) async {
SmartDialog.showLoading(msg: '发送中...');
bool isColorful = _color.value == Colors.transparent;
final res = await DanmakuHttp.shootDanmaku(
@@ -464,6 +463,7 @@ class _SendDanmakuPanelState extends CommonPublishPageState<SendDanmakuPanel> {
);
SmartDialog.dismiss();
if (res['status']) {
hasPub = true;
Get.back();
SmartDialog.showToast('发送成功');
widget.callback(

View File

@@ -65,12 +65,13 @@ class WhisperDetailController extends CommonListController<RspSessionMsg, Msg> {
}
Future<void> sendMsg({
required String message,
String? message,
Map? picMsg,
required VoidCallback onClearText,
int? msgType,
int? index,
}) async {
assert((message != null) ^ (picMsg != null));
feedBack();
SmartDialog.dismiss();
if (!accountService.isLogin.value) {
@@ -81,7 +82,7 @@ class WhisperDetailController extends CommonListController<RspSessionMsg, Msg> {
senderUid: accountService.mid,
receiverId: mid!,
content:
msgType == 5 ? message : jsonEncode(picMsg ?? {"content": message}),
msgType == 5 ? message! : jsonEncode(picMsg ?? {"content": message!}),
msgType: MsgType.values[msgType ?? (picMsg != null ? 2 : 1)],
);
SmartDialog.dismiss();

View File

@@ -3,13 +3,14 @@ import 'dart:async';
import 'package:PiliPlus/common/widgets/image/network_img_layer.dart';
import 'package:PiliPlus/common/widgets/loading_widget/loading_widget.dart';
import 'package:PiliPlus/common/widgets/refresh_indicator.dart';
import 'package:PiliPlus/common/widgets/text_field/text_field.dart';
import 'package:PiliPlus/grpc/bilibili/im/type.pb.dart' show Msg;
import 'package:PiliPlus/http/loading_state.dart';
import 'package:PiliPlus/http/msg.dart';
import 'package:PiliPlus/models/common/image_type.dart';
import 'package:PiliPlus/models/common/publish_panel_type.dart';
import 'package:PiliPlus/models_new/upload_bfs/data.dart';
import 'package:PiliPlus/pages/common/common_publish_page.dart';
import 'package:PiliPlus/pages/common/publish/common_rich_text_pub_page.dart';
import 'package:PiliPlus/pages/emote/view.dart';
import 'package:PiliPlus/pages/whisper_detail/controller.dart';
import 'package:PiliPlus/pages/whisper_detail/widget/chat_item.dart';
@@ -17,14 +18,13 @@ import 'package:PiliPlus/pages/whisper_link_setting/view.dart';
import 'package:PiliPlus/utils/extension.dart';
import 'package:PiliPlus/utils/feed_back.dart';
import 'package:PiliPlus/utils/utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show LengthLimitingTextInputFormatter;
import 'package:flutter/material.dart' hide TextField;
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mime/mime.dart';
class WhisperDetailPage extends CommonPublishPage {
class WhisperDetailPage extends CommonRichTextPubPage {
const WhisperDetailPage({
super.key,
super.autofocus = false,
@@ -35,7 +35,7 @@ class WhisperDetailPage extends CommonPublishPage {
}
class _WhisperDetailPageState
extends CommonPublishPageState<WhisperDetailPage> {
extends CommonRichTextPubPageState<WhisperDetailPage> {
final _whisperDetailController = Get.put(
WhisperDetailController(),
tag: Utils.makeHeroTag(Get.parameters['talkerId']),
@@ -239,7 +239,7 @@ class _WhisperDetailPageState
}
},
child: Obx(
() => TextField(
() => RichTextField(
readOnly: readOnly.value,
focusNode: focusNode,
controller: editController,
@@ -258,7 +258,7 @@ class _WhisperDetailPageState
),
contentPadding: const EdgeInsets.all(10),
),
inputFormatters: [LengthLimitingTextInputFormatter(500)],
// inputFormatters: [LengthLimitingTextInputFormatter(500)],
),
),
),
@@ -269,7 +269,7 @@ class _WhisperDetailPageState
onPressed: () async {
if (enablePublish.value) {
_whisperDetailController.sendMsg(
message: editController.text,
message: editController.rawText,
onClearText: editController.clear,
);
} else {
@@ -301,7 +301,6 @@ class _WhisperDetailPageState
SmartDialog.showLoading(msg: '正在发送');
await _whisperDetailController.sendMsg(
picMsg: picMsg,
message: editController.text,
onClearText: editController.clear,
);
} else {
@@ -331,7 +330,13 @@ class _WhisperDetailPageState
Widget? get customPanel => EmotePanel(onChoose: onChooseEmote);
@override
Future<void> onCustomPublish({required String message, List? pictures}) {
Future<void> onCustomPublish({List? pictures}) {
throw UnimplementedError();
}
@override
void onMention([bool fromClick = false]) {}
@override
void onSave() {}
}