The comment module is widely used in image-text and video applications. It consists of an editing area, a friend list, a common emoji list, and an emoji panel (as shown in the figure below). It allows users to type texts, add emojis, mention friends, and select images. This module is generally displayed in the form of a dialog box that directly pops up on image-text and video pages, or above the comment list. This document provides guidance on your development from the following aspects by focusing on the relatively complex scenario where the dialog box pops up above the comment list:

The following table lists the module names used in this document.
Module Name | No. in Figure 1 |
|---|---|
Comment list | 1 |
Friend list | 2 |
Editing area | 3 |
Common emoji list | 4 |
Soft keyboard | 5 |
Emoji panel | 6 |
References:
After trying the CustomDialog, bindSheet, and Navigation Dialog (dialog box type in Page Display Mode) solutions, it is found that the custom dialog box and semi-modal dialog box have certain specifications and may cause some unavoidable issues. Therefore, the Navigation Dialog solution (dialog box type in Page Display Mode) is chosen to implement the comment dialog box. The following describes the advantages and disadvantages of the three solutions.
Advantages:
Disadvantages:
The display effect of PromptAction.openCustomDialog is the same as that of the custom dialog box.

Advantages:
Disadvantages:

Advantages:
Disadvantages:
Navigation Dialog (dialog box type in Page Display Mode) is at lower z-index hierarchy. If you use this solution, the comment module will be displayed under other dialog box modules that use CustomDialog and bindSheet, such as the comment list. Therefore, the other modules should also use Navigation Dialog (dialog box type in Page Display Mode )to implement unified hierarchy control by the navigation stack.
In the editing area, users can type texts, add emojis, and mention friends. When it comes to components that offer both interactive text editing and mixed image and text layouts, RichEditor stands out as the ideal option. To implement the adding of emojis, you can use RichEditorController.addImageSpan. To implement the mentioning of friends, you can use either RichEditorController.addTextSpan or RichEditorController.addBuilderSpan. After the following analysis and comparison of the two methods, addBuilderSpan is used.
In the following content, the content added to the editing area using addTextSpan, addImageSpan, and addBuilderSpan is named textSpan, imageSpan, and builderSpan, respectively.
Tap the message button on a video page to display the comment list, and tap the comment button on the comment list page to display the comment module.

You can set the mode attribute of Navigation to NavigationMode.Stack. To display the dialog box in full screen, Navigation should be the outermost component.
// features/home/src/main/ets/view/Home.ets
build() {
Navigation(this.navDialogPageInfos) {
// ...
}
.hideTitleBar(true)
.mode(NavigationMode.Stack)
.navDestination(this.NavDialogPageMap)
} Wrap the dialog module by using NavDestination. Set the mode property of NavDestination to NavDestinationMode.DIALOG and expandSafeArea to [SafeAreaType.KEYBOARD], so that the dialog box does not need to avoid the soft keyboard, resolving the issues with CustomDialog. In addition, add a mask through the navigation stack so that users can tap the mask to close the dialog box. You can also encapsulate the dialog box module into a component. The comment list and comment module can call this component without concerning their interaction, but only the content to display.
// features/home/src/main/ets/view/NavigationDialog.ets
@Component
export struct NavigationDialog {
@Consume navDialogPageInfos: NavPathStack;
@Prop alignContent: Alignment = Alignment.Bottom;
@Prop maskBackgroundColor: ResourceColor
@Builder
DefaultContentBuilder() {}
@BuilderParam
contentBuilderParam: () => void = this.DefaultContentBuilder
onClose = () => {
this.navDialogPageInfos.pop();
}
build() {
NavDestination() {
Stack() {
Column()
.height('100%')
.width('100%')
.backgroundColor(this.maskBackgroundColor)
.onClick(this.onClose)
this.contentBuilderParam()
}
.height('100%')
.alignContent(this.alignContent)
}
.mode(NavDestinationMode.DIALOG)
.hideTitleBar(true)
.expandSafeArea([SafeAreaType.KEYBOARD])
}
} Use the navigation stack to open or close the dialog box. The dialog box hierarchy is determined by the stack sequence.
After users touch the emoji icon button, the soft keyboard is switched to the emoji panel, and the button is switched from the emoji icon to the keyboard icon. After users touch the keyboard icon button, the emoji panel is switched to the soft keyboard, and the button is switched from the keyboard icon to the emoji icon.

In this document, a custom keyboard is used to control the switching between the soft keyboard and emoji panel. You can set RichEditor.customKeyboard to the EmojiKeyboard component's constructor to display the emoji panel. Setting this property to undefined will display the default soft keyboard. In this way, when the soft keyboard is switched to the emoji panel, the focus of the richEditor does not need to be manually processed.
// features/home/src/main/ets/view/CommentKeyboard.ets
RichEditor({ controller: this.richEditorController })
.customKeyboard(this.isEmojiKeyboardVisible ? this.EmojiKeyboard() : undefined)
// ... To ensure that the overall comment module height remains unchanged during the switching, you must obtain the soft keyboard height to calculate and manually set the emoji panel height. The soft keyboard height may be manually changed. Therefore, you need to use the keyboardHeightChange event to listen for soft keyboard height changes. If the height is greater than 0, update the state variable that records the soft keyboard height. Note that this listening event must be canceled before the component is destroyed.
aboutToAppear(): void {
window.getLastWindow(this.getUIContext().getHostContext()).then(win => {
this.addKeyboardHeightListener(win);
}).catch((err: BusinessError) => {
Logger.error(TAG,
`getLastWindow Failed. Code:${err.code}, message:${err.message}`);
});
}
aboutToDisappear(): void {
window.getLastWindow(this.getUIContext().getHostContext()).then(win => {
this.removeKeyboardHeightListener(win);
}).catch((err: BusinessError) => {
Logger.error(TAG,
`getLastWindow Failed. Code:${err.code}, message:${err.message}`);
});
}
getResourceString(resource: Resource): string {
try {
return this.getUIContext().getHostContext()!.resourceManager.getStringSync(resource.id);
} catch (exception) {
Logger.error(TAG,
`getLastWindow Failed. Code:${exception.code}, message:${exception.message}`);
return '';
}
}
addKeyboardHeightListener(win: window.Window) {
win.on('keyboardHeightChange', height => {
Logger.info(TAG, 'keyboard height has changed', this.getUIContext().px2vp(height));
if (height !== 0) {
this.keyboardHeight = this.getUIContext().px2vp(height);
return;
}
// ...
});
}
removeKeyboardHeightListener(win: window.Window) {
win.off('keyboardHeightChange');
} As shown in Figure 1, the emoji panel height is equal to the emoji list height plus the soft keyboard height. As the dialog box does not avoid the soft keyboard and the custom keyboard, when the soft keyboard is used, a placeholder element is required to push up the area above the soft keyboard, with its height set to the soft keyboard height. Similarly, when the emoji panel is used, the placeholder height should be the emoji panel height (which is the common emoji list height plus the soft keyboard height).
Adaptation code for the comment dialog box height:
// features/home/src/main/ets/view/CommentKeyboard.ets
build() {
NavigationDialog({ maskBackgroundColor: 'rgba(0, 0, 0, 0.1)' }) {
Column() {
this.AtFriendList()
this.ToolBar()
Divider()
if (!this.isEmojiKeyboardVisible) {
this.FrequentEmojiList()
}
Column()
.height(
this.isEmojiKeyboardVisible ?
this.keyboardHeight + this.frequentEmojiListHeight :
this.keyboardHeight
)
}
.backgroundColor(Color.White)
}
} Adaptation code for the emoji panel height:
// features/home/src/main/ets/view/CommentKeyboard.ets
@Builder
EmojiKeyboard() {
Grid() {
ForEach(this.getEmojiIcons(), (icon: Resource) => {
GridItem() {
Image(icon)
.width(45)
.onClick(() => {
this.onEmojiClick(icon)
})
}
})
}
.width('100%')
.height(this.keyboardHeight + this.frequentEmojiListHeight)
// ...
} In the editing area, users can type texts, add emojis, mention friends, and select images. The following provides effect diagrams and code explanation to describe how to develop these functions.
Tap an emoji in the common emoji list above the soft keyboard, or switch to the emoji panel and tap an emoji, to add the emoji after the cursor in the editing area.

You can use RichEditorController.addImageSpan for adding emojis in the editing area. Note that the offset property must be set to the current cursor position, which can be obtained through RichEditorController.getCaretOffset. In this way, the emoji is added following the current cursor, rather than at the end of the content (default behavior). Similar adding operations in the following sections comply with this rule.
// features/home/src/main/ets/view/CommentKeyboard.ets
onEmojiClick: (icon: Resource) => void = icon => {
this.richEditorController.addImageSpan(icon, {
offset: this.richEditorController.getCaretOffset(),
imageStyle: { size: [20, 20] }
});
// ...
} Tap the @ button in the editing area or type the @ symbol on the soft keyboard, to display the friend list, and tap a friend's avatar in the list to mention the friend in the editing area.

You can use RichEditorController.addTextSpan for adding the @ symbol and displaying the friend list. In addition, you need to listen for the RichEditor.aboutToIMEInput event, which is triggered before the content is typed. You can obtain the content to be typed in the callback. Typing the @ symbol has the same effect as tapping the @ button, which facilitates subsequent processing of some details.
// features/home/src/main/ets/view/CommentKeyboard.ets
onAtButtonClick: (event?: ClickEvent) => void = event => {
const controller = this.richEditorController;
this.isAtFriendListVisible = true;
controller.addTextSpan('@', { offset: controller.getCaretOffset() });
} When users tap a friend's avatar in the friend list, RichEditorController.getSpans can be called to obtain the span before the cursor. If the span is @, delete it, and use RichEditorController.addBuilderSpan to add @[friend nickname] as a whole to the editing area.
// features/home/src/main/ets/view/CommentKeyboard.ets
onAtFriendClick: (friend: User) => void = friend => {
const controller = this.richEditorController;
const offset = controller.getCaretOffset();
const range: RichEditorRange = { start: offset - 1, end: offset };
const span = controller.getSpans(range);
if (offset !== 0 && (span[0] as RichEditorTextSpanResult).value === '@') {
controller.deleteSpans(range);
}
controller.addBuilderSpan(() => this.AtSpan(friend.nickname), {
offset: controller.getCaretOffset()
});
this.setBuilderSpans(controller, friend);
}
@Builder
AtSpan(nickname: string) {
Text(`@${nickname}`)
.fontColor(0xFF133667)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
} Tap the delete button on the soft keyboard. If the content to be deleted before the cursor is a builderSpan (@friend) and is not selected, the content is selected for deletion. Otherwise, the content before the cursor is directly deleted. Any content that is selected will be deleted as a whole.

Listen for the RichEditor.aboutToDelete event. You can return false in the callback to prevent the default deletion behavior in the editing area. When you delete the builderSpan (@friend) for the first time, use RichEditorController.setSelection to select the entire content, and the selected content will be deleted from the RichEditor by default when the delete button is tapped again.
// features/home/src/main/ets/view/CommentKeyboard.ets
aboutToDelete: (value: RichEditorDeleteValue) => boolean = value => {
const controller = this.richEditorController;
const span = value.richEditorDeleteSpans[0];
if (span && this.isBuilderSpan(span)) {
if (this.hasSelection(controller)) {
this.deleteBuilderSpan();
return true;
}
controller.setSelection(value.offset, value.offset + 1);
return false;
}
return true;
} Type texts, add emojis, and mention friends in the editing area, tap the send button, obtain the content in the editing area, and display the content and friend's information in a dialog box.

You can use RichEditorController.getSpans to obtain all content in the editing area. In the return value of getSpans, the obtained content is of the RichEditorTextSpanResult or RichEditorImageSpanResult type. The following table lists the mapping between the text, emoji, and @friend and the two types.
Definition | Editing Area Content | Adding Mode | Return Value Type of getSpans |
|---|---|---|---|
textSpan | Consecutive text | Keyboard input or RichEditorController.addTextSpan | |
imageSpan | Images | ||
builderSpan | @[friend nickname] |
The textSpan can be obtained through RichEditorTextSpanResult.value. The imageSpan can be obtained through RichEditorImageSpanResult.valueResourceStr. However, the builderSpan cannot be obtained through RichEditorImageSpanResult. You need to manually maintain the builderSpan when tapping an avatar to add @friend.
// features/home/src/main/ets/view/CommentKeyboard.ets
onAtFriendClick: (friend: User) => void = friend => {
// ...
this.setBuilderSpans(controller, friend);
} Different types of content in the editing area need to be expressed in a unified data structure for easier data transmission and storage. The data structure needs to record the content in the editing area and carry additional information, for example, user information related to @friends. Here RichEditorSpan is used. (Flexibly adjust the attribute fields in actual development as required.)
// features/home/src/main/ets/view/CommentKeyboard.ets
export interface RichEditorSpan {
value?: string
resourceValue?: ResourceStr
type: 'text' | 'image' | 'builder'
data?: User | ImageInfo
} When you use the builderSpans array of the RichEditorSpan[] type to maintain the builderSpans when mentioning friends, ensure that the sequence of each builderSpan in the array is the same as that in the actual content. When you add a builderSpan, calculate the number of builderSpans before the cursor to determine the builderSpan position in the builderSpans array, and put the friend information to be carried to the data attribute.
setBuilderSpans(controller: RichEditorController, friend: User) {
const builderSpan: RichEditorSpan = {
value: `@${friend.nickname}`,
data: friend,
type: 'builder'
};
const range: RichEditorRange = { end: controller.getCaretOffset() };
const index = this.getBuilderSpanCount(controller, range) - 1;
this.builderSpans.splice(index, 0, builderSpan);
}
getBuilderSpanCount(controller: RichEditorController, range: RichEditorRange) {
return controller.getSpans(range).reduce((count: number, span) => {
return this.isBuilderSpan(span) ? count + 1 : count;
}, 0);
} When a comment is sent, express the obtained content in the richEditorSpans array of the RichEditorSpan[] type. Use getSpans to obtain all content. If textSpan is used, use the value attribute to output the text content and set RichEditorSpan.type to text. If imageSpan is used, use the valueResourceStr attribute to obtain the image and set RichEditorSpan.type to image. If builderSpan is used, obtain the content from the builderSpans array and add it to richEditorSpans in sequence.
// features/home/src/main/ets/view/CommentKeyboard.ets
onSendComment: () => void = () => {
let builderSpanIndex = 0;
let richEditorSpan: RichEditorSpan;
const richEditorSpans: RichEditorSpan[] = [];
this.richEditorController.getSpans().forEach((span, index) => {
const textSpan = span as RichEditorTextSpanResult;
const imageSpan = span as RichEditorImageSpanResult;
if (textSpan.value) {
richEditorSpan = { value: textSpan.value, type: 'text' };
} else if (this.isBuilderSpan(span)) {
richEditorSpan = this.builderSpans[builderSpanIndex];
builderSpanIndex += 1;
} else {
richEditorSpan = { resourceValue: imageSpan.valueResourceStr, type: 'image' };
}
richEditorSpans.push(richEditorSpan);
});
// ...
} The generated richEditorSpans data structure is as follows:
[
{
"value": "@friend 1",
"data": {
"id": "0",
"avatar": {
"id": 16777268,
"type": 20000,
"params": [],
"bundleName": "com.example.commentreply",
"moduleName": "default"
},
"nickname": "Friend 1"
},
"type": "builder"
},
{
"value": "Hello",
"type": "text"
},
{
"resourceValue": "resource:///emoji_3.png",
"type": "image"
}
] To display comments, the system traverses richEditorSpans and processes the display logic of text, emojis, and @friends based on the type attribute. You can determine the specific display mode as required.
// features/home/src/main/ets/view/CommentSendDialog.ets
Column() {
Text($r('app.string.send_title'))
.margin({ bottom: 20 })
Flex({ wrap: FlexWrap.Wrap }) {
ForEach(this.getComment(), (richEditorSpan: RichEditorSpan) => {
if (richEditorSpan.type === 'text') {
Text(richEditorSpan.value)
} else if (richEditorSpan.type === 'image') {
Image(richEditorSpan.resourceValue)
.width(20)
} else {
Text(`${richEditorSpan.value}(`)
.fontColor(0xFF133667)
Text(`id:${(richEditorSpan.data as User).id}; avatar:`)
Image((richEditorSpan.data as User).avatar)
.width(20)
Text(')')
}
}, (richEditorSpan: RichEditorSpan) => JSON.stringify(richEditorSpan))
}
} Tap the image button to open the system album and select a local image to upload. This function is relatively independent and is not described in this document. For details, see the following samples.