TUIInputBar.m 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. //
  2. // TUIInputBar.m
  3. // UIKit
  4. //
  5. // Created by kennethmiao on 2018/9/18.
  6. // Copyright © 2018 Tencent. All rights reserved.
  7. //
  8. #import "TUIInputBar.h"
  9. #import <TIMCommon/TIMDefine.h>
  10. #import <TUICore/TUITool.h>
  11. #import "TUIRecordView.h"
  12. #import <TIMCommon/NSString+TUIEmoji.h>
  13. #import <TIMCommon/NSTimer+TUISafe.h>
  14. #import <TUICore/TUICore.h>
  15. #import <TUICore/TUIDarkModel.h>
  16. #import <TUICore/TUIGlobalization.h>
  17. #import <TUICore/UIView+TUILayout.h>
  18. #import "ReactiveObjC/ReactiveObjC.h"
  19. #import "TUIAudioRecorder.h"
  20. #import "TUIChatConfig.h"
  21. @interface TUIInputBar () <UITextViewDelegate, TUIAudioRecorderDelegate>
  22. @property(nonatomic, strong) TUIRecordView *recordView;
  23. @property(nonatomic, strong) NSDate *recordStartTime;
  24. @property(nonatomic, strong) TUIAudioRecorder *recorder;
  25. @property(nonatomic, assign) BOOL isFocusOn;
  26. @property(nonatomic, strong) NSTimer *sendTypingStatusTimer;
  27. @property(nonatomic, assign) BOOL allowSendTypingStatusByChangeWord;
  28. @property(nonatomic, strong) UIButton *sendButton;
  29. @property(nonatomic, strong) UIView *bgView;
  30. @end
  31. @implementation TUIInputBar
  32. - (id)initWithFrame:(CGRect)frame {
  33. self = [super initWithFrame:frame];
  34. if (self) {
  35. [self setupViews];
  36. [self defaultLayout];
  37. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onThemeChanged) name:TUIDidApplyingThemeChangedNotfication object:nil];
  38. }
  39. return self;
  40. }
  41. - (void)dealloc {
  42. if (_sendTypingStatusTimer) {
  43. [_sendTypingStatusTimer invalidate];
  44. _sendTypingStatusTimer = nil;
  45. }
  46. [[NSNotificationCenter defaultCenter] removeObserver:self];
  47. }
  48. #pragma mark - UI
  49. - (void)setupViews {
  50. self.backgroundColor = TUIChatDynamicColor(@"chat_input_controller_bg_color", @"#EBF0F6");
  51. _lineView = [[UIView alloc] init];
  52. _lineView.backgroundColor = TIMCommonDynamicColor(@"separator_color", @"#FFFFFF");
  53. [self addSubview:_lineView];
  54. _bgView = [[UIView alloc] init];
  55. _bgView.backgroundColor = TUIChatDynamicColor(@"chat_input_bg_color", @"#FFFFFF");
  56. _bgView.layer.cornerRadius = 12.0f;
  57. _bgView.layer.masksToBounds = YES;
  58. [self addSubview:_bgView];
  59. _micButton = [[UIButton alloc] init];
  60. [_micButton addTarget:self action:@selector(onMicButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
  61. [_micButton setImage:TUIChatBundleThemeImage(@"chat_ToolViewInputVoice_img", @"ToolViewInputVoice") forState:UIControlStateNormal];
  62. [_micButton setImage:TUIChatBundleThemeImage(@"chat_ToolViewInputVoiceHL_img", @"ToolViewInputVoiceHL") forState:UIControlStateHighlighted];
  63. [self addSubview:_micButton];
  64. _micButton.hidden = YES;
  65. _faceButton = [[UIButton alloc] init];
  66. [_faceButton addTarget:self action:@selector(onFaceEmojiButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
  67. [_faceButton setImage:TUIChatBundleThemeImage(@"chat_ToolViewEmotion_img", @"ToolViewEmotion_2") forState:UIControlStateNormal];
  68. [_faceButton setImage:TUIChatBundleThemeImage(@"chat_ToolViewEmotionHL_img", @"ToolViewEmotionHL_2") forState:UIControlStateHighlighted];
  69. [self addSubview:_faceButton];
  70. _keyboardButton = [[UIButton alloc] init];
  71. [_keyboardButton addTarget:self action:@selector(onKeyboardButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
  72. [_keyboardButton setImage:TUIChatBundleThemeImage(@"chat_ToolViewKeyboard_img", @"ToolViewKeyboard_2") forState:UIControlStateNormal];
  73. [_keyboardButton setImage:TUIChatBundleThemeImage(@"chat_ToolViewKeyboardHL_img", @"ToolViewKeyboardHL_2") forState:UIControlStateHighlighted];
  74. _keyboardButton.hidden = YES;
  75. [self addSubview:_keyboardButton];
  76. _moreButton = [[UIButton alloc] init];
  77. [_moreButton addTarget:self action:@selector(onMoreButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
  78. [_moreButton setImage:TUIChatBundleThemeImage(@"chat_TypeSelectorBtn_Black_img", @"TypeSelectorBtn_Black_2") forState:UIControlStateNormal];
  79. [_moreButton setImage:TUIChatBundleThemeImage(@"chat_TypeSelectorBtnHL_Black_img", @"TypeSelectorBtnHL_Black_2") forState:UIControlStateHighlighted];
  80. [self addSubview:_moreButton];
  81. _sendButton = [[UIButton alloc] init];
  82. [_sendButton addTarget:self action:@selector(onSendButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
  83. [_sendButton setImage:TUIChatBundleThemeImage(@"chat_icon_new_send_btn_img", @"icon_new_send_btn") forState:UIControlStateNormal];
  84. [_sendButton setImage:TUIChatBundleThemeImage(@"chat_icon_new_send_btn_img", @"icon_new_send_btn") forState:UIControlStateHighlighted];
  85. [self addSubview:_sendButton];
  86. _recordButton = [[UIButton alloc] init];
  87. [_recordButton.titleLabel setFont:[UIFont systemFontOfSize:15.0f]];
  88. [_recordButton addTarget:self action:@selector(onRecordButtonTouchDown:) forControlEvents:UIControlEventTouchDown];
  89. [_recordButton addTarget:self action:@selector(onRecordButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
  90. [_recordButton addTarget:self action:@selector(onRecordButtonTouchCancel:) forControlEvents:UIControlEventTouchUpOutside | UIControlEventTouchCancel];
  91. [_recordButton addTarget:self action:@selector(onRecordButtonTouchDragExit:) forControlEvents:UIControlEventTouchDragExit];
  92. [_recordButton addTarget:self action:@selector(onRecordButtonTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
  93. [_recordButton setTitle:TIMCommonLocalizableString(TUIKitInputHoldToTalk) forState:UIControlStateNormal];
  94. [_recordButton setTitleColor:TUIChatDynamicColor(@"chat_input_text_color", @"#000000") forState:UIControlStateNormal];
  95. _recordButton.hidden = YES;
  96. [self addSubview:_recordButton];
  97. _inputTextView = [[TUIResponderTextView alloc] init];
  98. _inputTextView.delegate = self;
  99. [_inputTextView setFont:kTUIInputNoramlFont];
  100. // _inputTextView.backgroundColor = TUIChatDynamicColor(@"chat_input_bg_color", @"#FFFFFF");
  101. _inputTextView.backgroundColor = [UIColor clearColor];
  102. _inputTextView.textColor = TUIChatDynamicColor(@"chat_input_text_color", @"#000000");
  103. _inputTextView.textAlignment = isRTL()?NSTextAlignmentRight: NSTextAlignmentLeft;
  104. [_inputTextView setReturnKeyType:UIReturnKeySend];
  105. [self addSubview:_inputTextView];
  106. [self applyBorderTheme];
  107. }
  108. - (void)onThemeChanged {
  109. [self applyBorderTheme];
  110. }
  111. - (void)applyBorderTheme {
  112. if (_recordButton) {
  113. [_recordButton.layer setMasksToBounds:YES];
  114. [_recordButton.layer setCornerRadius:4.0f];
  115. [_recordButton.layer setBorderWidth:1.0f];
  116. [_recordButton.layer setBorderColor:TIMCommonDynamicColor(@"separator_color", @"#DBDBDB").CGColor];
  117. }
  118. if (_inputTextView) {
  119. [_inputTextView.layer setMasksToBounds:YES];
  120. // [_inputTextView.layer setCornerRadius:4.0f];
  121. [_inputTextView.layer setCornerRadius:12.0f];
  122. // [_inputTextView.layer setBorderWidth:0.5f];
  123. // [_inputTextView.layer setBorderColor:TIMCommonDynamicColor(@"separator_color", @"#DBDBDB").CGColor];
  124. [_bgView.layer setBorderWidth:0.5f];
  125. [_bgView.layer setBorderColor:TIMCommonDynamicColor(@"separator_color", @"#DBDBDB").CGColor];
  126. }
  127. }
  128. - (void)defaultLayout {
  129. [_lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
  130. make.top.mas_equalTo(0);
  131. make.width.mas_equalTo(self);
  132. make.height.mas_equalTo(TLine_Heigh);
  133. }];
  134. CGSize buttonSize = TTextView_Button_Size;
  135. CGFloat buttonOriginY = (TTextView_Height - buttonSize.height) * 0.5;
  136. [_micButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  137. make.leading.mas_equalTo(self.mas_leading);
  138. make.centerY.mas_equalTo(self);
  139. make.size.mas_equalTo(buttonSize);
  140. }];
  141. [_keyboardButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  142. make.edges.mas_equalTo(_micButton);
  143. }];
  144. [_sendButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  145. make.trailing.mas_equalTo(self.mas_trailing).mas_offset(0);
  146. make.size.mas_equalTo(buttonSize);
  147. make.centerY.mas_equalTo(self);
  148. }];
  149. // [_moreButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  150. // make.trailing.mas_equalTo(self.mas_trailing).mas_offset(0);
  151. // make.size.mas_equalTo(buttonSize);
  152. // make.centerY.mas_equalTo(self);
  153. // }];
  154. // [_faceButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  155. // make.trailing.mas_equalTo(_moreButton.mas_leading).mas_offset(- TTextView_Margin);
  156. // make.size.mas_equalTo(buttonSize);
  157. // make.centerY.mas_equalTo(self);
  158. // }];
  159. [_moreButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  160. make.leading.mas_equalTo(self.mas_leading);
  161. make.centerY.mas_equalTo(self);
  162. make.size.mas_equalTo(buttonSize);
  163. }];
  164. [_faceButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  165. make.trailing.mas_equalTo(_sendButton.mas_leading).mas_offset(- TTextView_Margin * 2.0);
  166. make.size.mas_equalTo(buttonSize);
  167. make.centerY.mas_equalTo(self);
  168. }];
  169. [_recordButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  170. make.leading.mas_equalTo(_micButton.mas_trailing).mas_offset(10);
  171. make.trailing.mas_equalTo(_faceButton.mas_leading).mas_offset(-10);;
  172. make.height.mas_equalTo(TTextView_TextView_Height_Min);
  173. make.centerY.mas_equalTo(self);
  174. }];
  175. [_bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
  176. make.leading.mas_equalTo(_moreButton.mas_trailing).mas_offset(10);
  177. make.trailing.mas_equalTo(_sendButton.mas_leading).mas_offset(-TTextView_Margin);
  178. make.height.mas_equalTo(TTextView_TextView_Height_Min);
  179. make.centerY.mas_equalTo(self);
  180. }];
  181. [_inputTextView mas_remakeConstraints:^(MASConstraintMaker *make) {
  182. if (self.isFromReplyPage) {
  183. make.leading.mas_equalTo(self.mas_leading).mas_offset(10);
  184. }
  185. else {
  186. // make.leading.mas_equalTo(_micButton.mas_trailing).mas_offset(10);
  187. // make.leading.mas_equalTo(self.mas_leading);
  188. make.leading.mas_equalTo(_moreButton.mas_trailing).mas_offset(10);
  189. }
  190. make.trailing.mas_equalTo(_faceButton.mas_leading).mas_offset(-10);
  191. make.height.mas_equalTo(TTextView_TextView_Height_Min);
  192. make.centerY.mas_equalTo(self);
  193. }];
  194. }
  195. - (void)layoutButton:(CGFloat)height {
  196. CGRect frame = self.frame;
  197. CGFloat offset = height - frame.size.height;
  198. frame.size.height = height;
  199. self.frame = frame;
  200. CGSize buttonSize = TTextView_Button_Size;
  201. CGFloat bottomMargin = (TTextView_Height - buttonSize.height) * 0.5;
  202. CGFloat originY = frame.size.height - buttonSize.height - bottomMargin;
  203. CGRect faceFrame = _faceButton.frame;
  204. faceFrame.origin.y = originY;
  205. _faceButton.frame = faceFrame;
  206. CGRect moreFrame = _moreButton.frame;
  207. moreFrame.origin.y = originY;
  208. _moreButton.frame = moreFrame;
  209. CGRect voiceFrame = _micButton.frame;
  210. voiceFrame.origin.y = originY;
  211. _micButton.frame = voiceFrame;
  212. CGRect sendFrame = _sendButton.frame;
  213. sendFrame.origin.y = originY;
  214. _sendButton.frame = sendFrame;
  215. [_keyboardButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  216. make.edges.mas_equalTo(_faceButton);
  217. }];
  218. if (_delegate && [_delegate respondsToSelector:@selector(inputBar:didChangeInputHeight:)]) {
  219. [_delegate inputBar:self didChangeInputHeight:offset];
  220. }
  221. }
  222. #pragma mark - Event response
  223. - (void)onMicButtonClicked:(UIButton *)sender {
  224. _recordButton.hidden = NO;
  225. _inputTextView.hidden = YES;
  226. _micButton.hidden = YES;
  227. _keyboardButton.hidden = NO;
  228. _faceButton.hidden = NO;
  229. [_inputTextView resignFirstResponder];
  230. [self layoutButton:TTextView_Height];
  231. if (_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchMore:)]) {
  232. [_delegate inputBarDidTouchVoice:self];
  233. }
  234. [_keyboardButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  235. make.edges.mas_equalTo(_micButton);
  236. }];
  237. }
  238. - (void)onKeyboardButtonClicked:(UIButton *)sender {
  239. // _micButton.hidden = NO;
  240. _micButton.hidden = YES;
  241. _keyboardButton.hidden = YES;
  242. _recordButton.hidden = YES;
  243. _inputTextView.hidden = NO;
  244. _faceButton.hidden = NO;
  245. [self layoutButton:_inputTextView.frame.size.height + 2 * TTextView_Margin];
  246. if (_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchKeyboard:)]) {
  247. [_delegate inputBarDidTouchKeyboard:self];
  248. }
  249. }
  250. - (void)onFaceEmojiButtonClicked:(UIButton *)sender {
  251. // _micButton.hidden = NO;
  252. _micButton.hidden = YES;
  253. _faceButton.hidden = YES;
  254. _keyboardButton.hidden = NO;
  255. _recordButton.hidden = YES;
  256. _inputTextView.hidden = NO;
  257. if (_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchFace:)]) {
  258. [_delegate inputBarDidTouchFace:self];
  259. }
  260. [_keyboardButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  261. make.edges.mas_equalTo(_faceButton);
  262. }];
  263. }
  264. - (void)onMoreButtonClicked:(UIButton *)sender {
  265. if (_delegate && [_delegate respondsToSelector:@selector(inputBarDidTouchMore:)]) {
  266. [_delegate inputBarDidTouchMore:self];
  267. }
  268. }
  269. - (void)onSendButtonClicked:(UIButton *)sender {
  270. //自定义发送按钮 触发
  271. if (_delegate && [_delegate respondsToSelector:@selector(inputBar:didSendText:)]) {
  272. NSString *sp = [[self.inputTextView.textStorage tui_getPlainString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  273. if (sp.length == 0) {
  274. UIAlertController *ac = [UIAlertController alertControllerWithTitle:TIMCommonLocalizableString(TUIKitInputBlankMessageTitle)
  275. message:nil
  276. preferredStyle:UIAlertControllerStyleAlert];
  277. [ac tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(Confirm) style:UIAlertActionStyleDefault handler:nil]];
  278. [self.mm_viewController presentViewController:ac animated:YES completion:nil];
  279. } else {
  280. [_delegate inputBar:self didSendText:[self.inputTextView.textStorage tui_getPlainString]];
  281. [self clearInput];
  282. }
  283. }
  284. }
  285. - (void)onRecordButtonTouchDown:(UIButton *)sender {
  286. [self.recorder record];
  287. }
  288. - (void)onRecordButtonTouchUpInside:(UIButton *)sender {
  289. self.recordButton.backgroundColor = [UIColor clearColor];
  290. [self.recordButton setTitle:TIMCommonLocalizableString(TUIKitInputHoldToTalk) forState:UIControlStateNormal];
  291. NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:self.recordStartTime];
  292. @weakify(self);
  293. if (interval < 1) {
  294. [self.recordView setStatus:Record_Status_TooShort];
  295. [self.recorder cancel];
  296. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  297. @strongify(self);
  298. [self.recordView removeFromSuperview];
  299. self.recordView = nil;
  300. });
  301. } else if (interval > MIN(59, [TUIChatConfig defaultConfig].maxAudioRecordDuration)) {
  302. [self.recordView setStatus:Record_Status_TooLong];
  303. [self.recorder cancel];
  304. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  305. @strongify(self);
  306. [self.recordView removeFromSuperview];
  307. self.recordView = nil;
  308. });
  309. } else {
  310. /// TUICallKit may need some time to stop all services, so remove UI immediately then stop the recorder.
  311. if (_recordView) {
  312. [self.recordView removeFromSuperview];
  313. self.recordView = nil;
  314. }
  315. dispatch_queue_t main_queue = dispatch_get_main_queue();
  316. dispatch_async(main_queue, ^{
  317. @strongify(self);
  318. dispatch_async(main_queue, ^{
  319. [self.recorder stop];
  320. NSString *path = self.recorder.recordedFilePath;
  321. if (path) {
  322. if (self.delegate && [self.delegate respondsToSelector:@selector(inputBar:didSendVoice:)]) {
  323. [self.delegate inputBar:self didSendVoice:path];
  324. }
  325. }
  326. });
  327. });
  328. }
  329. }
  330. - (void)onRecordButtonTouchCancel:(UIButton *)sender {
  331. [self.recordView removeFromSuperview];
  332. self.recordView = nil;
  333. self.recordButton.backgroundColor = [UIColor clearColor];
  334. [self.recordButton setTitle:TIMCommonLocalizableString(TUIKitInputHoldToTalk) forState:UIControlStateNormal];
  335. [self.recorder cancel];
  336. }
  337. - (void)onRecordButtonTouchDragExit:(UIButton *)sender {
  338. [self.recordView setStatus:Record_Status_Cancel];
  339. [_recordButton setTitle:TIMCommonLocalizableString(TUIKitInputReleaseToCancel) forState:UIControlStateNormal];
  340. }
  341. - (void)onRecordButtonTouchDragEnter:(UIButton *)sender {
  342. [self.recordView setStatus:Record_Status_Recording];
  343. [_recordButton setTitle:TIMCommonLocalizableString(TUIKitInputReleaseToSend) forState:UIControlStateNormal];
  344. }
  345. - (void)showHapticFeedback {
  346. if (@available(iOS 10.0, *)) {
  347. dispatch_async(dispatch_get_main_queue(), ^{
  348. UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];
  349. [generator prepare];
  350. [generator impactOccurred];
  351. });
  352. } else {
  353. // Fallback on earlier versions
  354. }
  355. }
  356. #pragma mark - Text input
  357. #pragma mark-- UITextViewDelegate
  358. - (void)textViewDidBeginEditing:(UITextView *)textView {
  359. self.keyboardButton.hidden = YES;
  360. // self.micButton.hidden = NO;
  361. self.micButton.hidden = YES;
  362. self.faceButton.hidden = NO;
  363. self.isFocusOn = YES;
  364. self.allowSendTypingStatusByChangeWord = YES;
  365. __weak typeof(self) weakSelf = self;
  366. self.sendTypingStatusTimer = [NSTimer tui_scheduledTimerWithTimeInterval:4
  367. repeats:YES
  368. block:^(NSTimer *_Nonnull timer) {
  369. __strong typeof(weakSelf) strongSelf = weakSelf;
  370. strongSelf.allowSendTypingStatusByChangeWord = YES;
  371. }];
  372. if (self.isFocusOn && [textView.textStorage tui_getPlainString].length > 0) {
  373. if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldBeginTyping:)]) {
  374. [_delegate inputTextViewShouldBeginTyping:textView];
  375. }
  376. }
  377. }
  378. - (void)textViewDidEndEditing:(UITextView *)textView {
  379. self.isFocusOn = NO;
  380. if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldEndTyping:)]) {
  381. [_delegate inputTextViewShouldEndTyping:textView];
  382. }
  383. }
  384. - (void)textViewDidChange:(UITextView *)textView {
  385. if (self.allowSendTypingStatusByChangeWord && self.isFocusOn && [textView.textStorage tui_getPlainString].length > 0) {
  386. if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldBeginTyping:)]) {
  387. self.allowSendTypingStatusByChangeWord = NO;
  388. [_delegate inputTextViewShouldBeginTyping:textView];
  389. }
  390. }
  391. if (self.isFocusOn && [textView.textStorage tui_getPlainString].length == 0) {
  392. if (_delegate && [_delegate respondsToSelector:@selector(inputTextViewShouldEndTyping:)]) {
  393. [_delegate inputTextViewShouldEndTyping:textView];
  394. }
  395. }
  396. if (self.inputBarTextChanged) {
  397. self.inputBarTextChanged(_inputTextView);
  398. }
  399. CGSize size = [_inputTextView sizeThatFits:CGSizeMake(_inputTextView.frame.size.width, TTextView_TextView_Height_Max)];
  400. CGFloat oldHeight = _inputTextView.frame.size.height;
  401. CGFloat newHeight = size.height;
  402. if (newHeight > TTextView_TextView_Height_Max) {
  403. newHeight = TTextView_TextView_Height_Max;
  404. }
  405. if (newHeight < TTextView_TextView_Height_Min) {
  406. newHeight = TTextView_TextView_Height_Min;
  407. }
  408. if (oldHeight == newHeight) {
  409. return;
  410. }
  411. __weak typeof(self) ws = self;
  412. [UIView animateWithDuration:0.3
  413. animations:^{
  414. [ws.inputTextView mas_remakeConstraints:^(MASConstraintMaker *make) {
  415. // make.leading.mas_equalTo(ws.micButton.mas_trailing).mas_offset(10);
  416. // make.leading.mas_equalTo(ws.mas_leading);
  417. make.leading.mas_equalTo(ws.moreButton.mas_trailing).mas_offset(10);
  418. make.trailing.mas_equalTo(ws.faceButton.mas_leading).mas_offset(-10);
  419. make.height.mas_equalTo(newHeight);
  420. make.centerY.mas_equalTo(self);
  421. }];
  422. [ws.bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
  423. make.leading.mas_equalTo(ws.moreButton.mas_trailing).mas_offset(10);
  424. make.trailing.mas_equalTo(ws.sendButton.mas_leading).mas_offset(-TTextView_Margin);
  425. make.height.mas_equalTo(newHeight);
  426. make.centerY.mas_equalTo(self);
  427. }];
  428. [ws layoutButton:newHeight + 2 * TTextView_Margin];
  429. }];
  430. }
  431. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  432. if ([text tui_containsString:@"["] && [text tui_containsString:@"]"]) {
  433. NSRange selectedRange = textView.selectedRange;
  434. if (selectedRange.length > 0) {
  435. [textView.textStorage deleteCharactersInRange:selectedRange];
  436. }
  437. NSMutableAttributedString *textChange = [text getAdvancedFormatEmojiStringWithFont:kTUIInputNoramlFont
  438. textColor:kTUIInputNormalTextColor
  439. emojiLocations:nil];
  440. [textView.textStorage insertAttributedString:textChange atIndex:textView.textStorage.length];
  441. dispatch_async(dispatch_get_main_queue(), ^{
  442. self.inputTextView.selectedRange = NSMakeRange(self.inputTextView.textStorage.length + 1, 0);
  443. });
  444. return NO;
  445. }
  446. if ([text isEqualToString:@"\n"]) {
  447. if (_delegate && [_delegate respondsToSelector:@selector(inputBar:didSendText:)]) {
  448. NSString *sp = [[textView.textStorage tui_getPlainString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  449. if (sp.length == 0) {
  450. UIAlertController *ac = [UIAlertController alertControllerWithTitle:TIMCommonLocalizableString(TUIKitInputBlankMessageTitle)
  451. message:nil
  452. preferredStyle:UIAlertControllerStyleAlert];
  453. [ac tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(Confirm) style:UIAlertActionStyleDefault handler:nil]];
  454. [self.mm_viewController presentViewController:ac animated:YES completion:nil];
  455. } else {
  456. [_delegate inputBar:self didSendText:[textView.textStorage tui_getPlainString]];
  457. [self clearInput];
  458. }
  459. }
  460. return NO;
  461. } else if ([text isEqualToString:@""]) {
  462. if (textView.textStorage.length > range.location) {
  463. // Delete the @ message like @xxx at one time
  464. NSAttributedString *lastAttributedStr = [textView.textStorage attributedSubstringFromRange:NSMakeRange(range.location, 1)];
  465. NSString *lastStr = [lastAttributedStr tui_getPlainString];
  466. if (lastStr && lastStr.length > 0 && [lastStr characterAtIndex:0] == ' ') {
  467. NSUInteger location = range.location;
  468. NSUInteger length = range.length;
  469. // corresponds to ascii code
  470. int at = 64;
  471. // (space) ascii
  472. // Space (space) corresponding ascii code
  473. int space = 32;
  474. while (location != 0) {
  475. location--;
  476. length++;
  477. // Convert characters to ascii code, copy to int, avoid out of bounds
  478. int c = (int)[[[textView.textStorage attributedSubstringFromRange:NSMakeRange(location, 1)] tui_getPlainString] characterAtIndex:0];
  479. if (c == at) {
  480. NSString *atText = [[textView.textStorage attributedSubstringFromRange:NSMakeRange(location, length)] tui_getPlainString];
  481. UIFont *textFont = kTUIInputNoramlFont;
  482. NSAttributedString *spaceString = [[NSAttributedString alloc] initWithString:@"" attributes:@{NSFontAttributeName : textFont}];
  483. [textView.textStorage replaceCharactersInRange:NSMakeRange(location, length) withAttributedString:spaceString];
  484. if (self.delegate && [self.delegate respondsToSelector:@selector(inputBar:didDeleteAt:)]) {
  485. [self.delegate inputBar:self didDeleteAt:atText];
  486. }
  487. return NO;
  488. } else if (c == space) {
  489. // Avoid "@nickname Hello, nice to meet you (space) "" Press del after a space to over-delete to @
  490. break;
  491. }
  492. }
  493. }
  494. }
  495. }
  496. // Monitor the input of @ character, including full-width/half-width
  497. else if ([text isEqualToString:@"@"] || [text isEqualToString:@"@"]) {
  498. if (self.delegate && [self.delegate respondsToSelector:@selector(inputBarDidInputAt:)]) {
  499. [self.delegate inputBarDidInputAt:self];
  500. }
  501. return NO;
  502. }
  503. return YES;
  504. }
  505. - (void)onDeleteBackward:(TUIResponderTextView *)textView {
  506. if (self.delegate && [self.delegate respondsToSelector:@selector(inputBarDidDeleteBackward:)]) {
  507. [self.delegate inputBarDidDeleteBackward:self];
  508. }
  509. }
  510. - (void)clearInput {
  511. [_inputTextView.textStorage deleteCharactersInRange:NSMakeRange(0, _inputTextView.textStorage.length)];
  512. [self textViewDidChange:_inputTextView];
  513. }
  514. - (NSString *)getInput {
  515. return [_inputTextView.textStorage tui_getPlainString];
  516. }
  517. - (void)addEmoji:(TUIFaceCellData *)emoji {
  518. // Create emoji attachment
  519. TUIEmojiTextAttachment *emojiTextAttachment = [[TUIEmojiTextAttachment alloc] init];
  520. emojiTextAttachment.faceCellData = emoji;
  521. NSString *localizableFaceName = emoji.name;
  522. // Set tag and image
  523. emojiTextAttachment.emojiTag = localizableFaceName;
  524. emojiTextAttachment.image = [[TUIImageCache sharedInstance] getFaceFromCache:emoji.path];
  525. // Set emoji size
  526. emojiTextAttachment.emojiSize = kTIMDefaultEmojiSize;
  527. NSAttributedString *str = [NSAttributedString attributedStringWithAttachment:emojiTextAttachment];
  528. NSRange selectedRange = _inputTextView.selectedRange;
  529. if (selectedRange.length > 0) {
  530. [_inputTextView.textStorage deleteCharactersInRange:selectedRange];
  531. }
  532. // Insert emoji image
  533. [_inputTextView.textStorage insertAttributedString:str atIndex:_inputTextView.selectedRange.location];
  534. _inputTextView.selectedRange = NSMakeRange(_inputTextView.selectedRange.location + 1, 0);
  535. [self resetTextStyle];
  536. if (_inputTextView.contentSize.height > TTextView_TextView_Height_Max) {
  537. float offset = _inputTextView.contentSize.height - _inputTextView.frame.size.height;
  538. [_inputTextView scrollRectToVisible:CGRectMake(0, offset, _inputTextView.frame.size.width, _inputTextView.frame.size.height) animated:YES];
  539. }
  540. [self textViewDidChange:_inputTextView];
  541. }
  542. - (void)resetTextStyle {
  543. // After changing text selection, should reset style.
  544. NSRange wholeRange = NSMakeRange(0, _inputTextView.textStorage.length);
  545. [_inputTextView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
  546. [_inputTextView.textStorage removeAttribute:NSForegroundColorAttributeName range:wholeRange];
  547. [_inputTextView.textStorage addAttribute:NSForegroundColorAttributeName value:kTUIInputNormalTextColor range:wholeRange];
  548. [_inputTextView.textStorage addAttribute:NSFontAttributeName value:kTUIInputNoramlFont range:wholeRange];
  549. [_inputTextView setFont:kTUIInputNoramlFont];
  550. _inputTextView.textAlignment = isRTL()?NSTextAlignmentRight: NSTextAlignmentLeft;
  551. // In iOS 15.0 and later, you need set styles again as belows
  552. _inputTextView.textColor = kTUIInputNormalTextColor;
  553. _inputTextView.font = kTUIInputNoramlFont;
  554. }
  555. - (void)backDelete {
  556. if (_inputTextView.textStorage.length > 0) {
  557. [_inputTextView.textStorage deleteCharactersInRange:NSMakeRange(_inputTextView.textStorage.length - 1, 1)];
  558. [self textViewDidChange:_inputTextView];
  559. }
  560. }
  561. - (void)updateTextViewFrame {
  562. [self textViewDidChange:[UITextView new]];
  563. }
  564. - (void)changeToKeyboard {
  565. [self onKeyboardButtonClicked:self.keyboardButton];
  566. }
  567. - (void)addDraftToInputBar:(NSAttributedString *)draft {
  568. [self addWordsToInputBar:draft];
  569. }
  570. - (void)addWordsToInputBar:(NSAttributedString *)words {
  571. NSRange selectedRange = self.inputTextView.selectedRange;
  572. if (selectedRange.length > 0) {
  573. [self.inputTextView.textStorage deleteCharactersInRange:selectedRange];
  574. }
  575. // Insert draft
  576. [self.inputTextView.textStorage insertAttributedString:words atIndex:self.inputTextView.selectedRange.location];
  577. self.inputTextView.selectedRange = NSMakeRange(self.inputTextView.textStorage.length + 1, 0);
  578. [self resetTextStyle];
  579. [self updateTextViewFrame];
  580. }
  581. #pragma mark - TUIAudioRecorderDelegate
  582. - (void)audioRecorder:(TUIAudioRecorder *)recorder didCheckPermission:(BOOL)isGranted isFirstTime:(BOOL)isFirstTime {
  583. if (isFirstTime) {
  584. if (!isGranted) {
  585. [self showRequestMicAuthorizationAlert];
  586. }
  587. return;
  588. }
  589. [self updateViewsToRecordingStatus];
  590. }
  591. - (void)showRequestMicAuthorizationAlert {
  592. UIAlertController *ac = [UIAlertController alertControllerWithTitle:TIMCommonLocalizableString(TUIKitInputNoMicTitle)
  593. message:TIMCommonLocalizableString(TUIKitInputNoMicTips)
  594. preferredStyle:UIAlertControllerStyleAlert];
  595. [ac tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(TUIKitInputNoMicOperateLater) style:UIAlertActionStyleCancel handler:nil]];
  596. [ac tuitheme_addAction:[UIAlertAction actionWithTitle:TIMCommonLocalizableString(TUIKitInputNoMicOperateEnable)
  597. style:UIAlertActionStyleDefault
  598. handler:^(UIAlertAction *_Nonnull action) {
  599. UIApplication *app = [UIApplication sharedApplication];
  600. NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  601. if ([app canOpenURL:settingsURL]) {
  602. [app openURL:settingsURL];
  603. }
  604. }]];
  605. dispatch_async(dispatch_get_main_queue(), ^{
  606. [self.mm_viewController presentViewController:ac animated:YES completion:nil];
  607. });
  608. }
  609. - (void)updateViewsToRecordingStatus {
  610. [self.window addSubview:self.recordView];
  611. [self.recordView mas_makeConstraints:^(MASConstraintMaker *make) {
  612. make.center.mas_equalTo(self.window);
  613. make.width.height.mas_equalTo(self.window);
  614. }];
  615. self.recordStartTime = [NSDate date];
  616. [self.recordView setStatus:Record_Status_Recording];
  617. self.recordButton.backgroundColor = [UIColor lightGrayColor];
  618. [self.recordButton setTitle:TIMCommonLocalizableString(TUIKitInputReleaseToSend) forState:UIControlStateNormal];
  619. [self showHapticFeedback];
  620. }
  621. - (void)audioRecorder:(TUIAudioRecorder *)recorder didPowerChanged:(float)power {
  622. if (!self.recordView.hidden) {
  623. [self.recordView setPower:power];
  624. }
  625. }
  626. - (void)audioRecorder:(TUIAudioRecorder *)recorder didRecordTimeChanged:(NSTimeInterval)time {
  627. float uiMaxDuration = MIN(59, [TUIChatConfig defaultConfig].maxAudioRecordDuration);
  628. float realMaxDuration = uiMaxDuration + 0.7;
  629. NSInteger seconds = uiMaxDuration - time;
  630. self.recordView.timeLabel.text = [[NSString alloc] initWithFormat:@"%ld\"", (long)seconds + 1];
  631. if (time >= (uiMaxDuration - 4) && time <= uiMaxDuration) {
  632. NSInteger seconds = uiMaxDuration - time;
  633. /**
  634. * The long type is cast here to eliminate compiler warnings.
  635. * Here +1 is to round up and optimize the time logic.
  636. */
  637. self.recordView.title.text = [NSString stringWithFormat:TIMCommonLocalizableString(TUIKitInputWillFinishRecordInSeconds), (long)seconds + 1];
  638. } else if (time > realMaxDuration) {
  639. [self.recorder stop];
  640. NSString *path = self.recorder.recordedFilePath;
  641. [self.recordView setStatus:Record_Status_TooLong];
  642. @weakify(self);
  643. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  644. @strongify(self);
  645. [self.recordView removeFromSuperview];
  646. self.recordView = nil;
  647. });
  648. if (path) {
  649. if (_delegate && [_delegate respondsToSelector:@selector(inputBar:didSendVoice:)]) {
  650. [_delegate inputBar:self didSendVoice:path];
  651. }
  652. }
  653. }
  654. }
  655. #pragma mark - Getter
  656. - (TUIAudioRecorder *)recorder {
  657. if (!_recorder) {
  658. _recorder = [[TUIAudioRecorder alloc] init];
  659. _recorder.delegate = self;
  660. }
  661. return _recorder;
  662. }
  663. - (TUIRecordView *)recordView {
  664. if (!_recordView) {
  665. _recordView = [[TUIRecordView alloc] init];
  666. _recordView.frame = self.frame;
  667. }
  668. return _recordView;
  669. }
  670. @end