@ohkit/text-ellipsis 0.0.1-beta.0 → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.tsx ADDED
@@ -0,0 +1,432 @@
1
+ /**
2
+ * @file 文本截断显示组件
3
+ * @description 基于React封装一个文本截断显示组件,富文本(仅文字样式,图片和表格效果不一定好)同普通文本处理一致
4
+ * @author <wuqiuyang305@126.com>
5
+ */
6
+
7
+ import React, {
8
+ forwardRef,
9
+ useState,
10
+ useMemo,
11
+ useEffect,
12
+ useCallback,
13
+ useRef,
14
+ PropsWithChildren,
15
+ MouseEvent,
16
+ } from "react";
17
+ import "./style.scss";
18
+ import {
19
+ isSafari,
20
+ prefixClassname as p,
21
+ classNames as cx,
22
+ assignRef,
23
+ useRuntime,
24
+ useCompatibleEffect,
25
+ useSyncPropsState,
26
+ } from "@ohkit/utils";
27
+ import { Measure } from "@ohkit/measure";
28
+
29
+ export const c = p("ohkit-text-ellipsis__");
30
+
31
+ interface ITextEllipsis
32
+ extends Pick<
33
+ React.DOMAttributes<HTMLDivElement>,
34
+ | "onMouseEnter"
35
+ | "onMouseLeave"
36
+ | "onPointerEnter"
37
+ | "onPointerLeave"
38
+ | "onFocus"
39
+ | "onClick"
40
+ > {
41
+ /**
42
+ * right | bottom 展开按钮在右下侧还是底部
43
+ * @default right
44
+ */
45
+ uiType?: "right" | "bottom";
46
+ className?: string;
47
+ /**
48
+ * (单位:px)未传入或无效(0也视为无效)则自动取当前文本的行高
49
+ */
50
+ lineHeight?: React.CSSProperties["lineHeight"];
51
+ /**
52
+ * 超过几行折叠(number > 0), 没传或者传入无效值不限制,自动截断到容器的最大高度
53
+ */
54
+ lines?: number;
55
+ /**
56
+ * 展开按钮蒙层背景色(仅支持16进制表示)
57
+ * @default #fff
58
+ */
59
+ maskBgColor?: string;
60
+ /**
61
+ * text|ReactNode 与children任传一个
62
+ */
63
+ content?: React.ReactNode;
64
+ /**
65
+ * 折叠状态
66
+ * @default true
67
+ */
68
+ fold?: boolean;
69
+ /**
70
+ * 显示展开控制按钮
71
+ * @default true
72
+ */
73
+ showFoldControl?: boolean;
74
+ /**
75
+ * 展开按钮位置 uiType='bottom'时有效
76
+ * @default center
77
+ */
78
+ controlPlacement?: 'left' | 'center' | 'right';
79
+ /**
80
+ * 展开按钮文字
81
+ * @default 收起
82
+ */
83
+ foldText?: string;
84
+ /**
85
+ * 展开按钮文字
86
+ * @default 展开
87
+ */
88
+ unfoldText?: string;
89
+ /**
90
+ * 折叠状态下是否显示title属性
91
+ * @default false
92
+ */
93
+ showTitleWhenFold?: boolean;
94
+ /**
95
+ * 折叠状态自定义title属性内容
96
+ */
97
+ titleWhenFold?: string | ((title: string) => string);
98
+ /**
99
+ * 自定义渲染展开按钮
100
+ */
101
+ renderFoldButton?: (fold: boolean) => React.ReactNode;
102
+ /**
103
+ * @param fold 折叠状态,true 折叠,false 展开
104
+ */
105
+ onFoldChange?: (fold: boolean) => void;
106
+ /**
107
+ * @param ellipsis 是否截断,true 截断,false 未截断
108
+ */
109
+ onEllipsisChange?: (ellipsis: boolean) => void;
110
+ /**
111
+ * 关键状态变更触发
112
+ * @param status
113
+ */
114
+ onStatusChange?: (status: {
115
+ fold: boolean;
116
+ ellipsis: boolean;
117
+ title?: string;
118
+ }) => void;
119
+ }
120
+
121
+ export type TextEllipsisProps = PropsWithChildren<ITextEllipsis>;
122
+
123
+ export const TextEllipsis = forwardRef<HTMLDivElement, TextEllipsisProps>((props, ref) => {
124
+ const {
125
+ className,
126
+ lineHeight = "",
127
+ lines,
128
+ maskBgColor = "#fff",
129
+ content,
130
+ children,
131
+ showTitleWhenFold,
132
+ titleWhenFold,
133
+ showFoldControl = true,
134
+ foldText = "收起",
135
+ unfoldText = "展开",
136
+ uiType = "right",
137
+ controlPlacement = 'center',
138
+ renderFoldButton,
139
+ onEllipsisChange,
140
+ onFoldChange,
141
+ onStatusChange,
142
+ onMouseEnter,
143
+ onMouseLeave,
144
+ onPointerEnter,
145
+ onPointerLeave,
146
+ onClick,
147
+ onFocus,
148
+ } = props;
149
+ // 是否截断
150
+ const [ellipsis, setEllipsis] = useState(false);
151
+ const [getLineHeightFail, setGetLineHeightFail] = useState(false);
152
+ // 折叠状态
153
+ const [fold, setFold] = useSyncPropsState(props, 'fold', {defaultValue: true, onChange: onFoldChange});
154
+ const [foldBtnWidth, setFoldBtnWidth] = useState(1);
155
+ const [innerLineHeight, setInnerLineHeight] = useState(
156
+ typeof lineHeight === "string" && lineHeight.endsWith("px")
157
+ ? parseFloat(lineHeight)
158
+ : 0
159
+ );
160
+ const [innerLines = 0, setInnerLines] = useState(lines);
161
+ // children提取的纯文本
162
+ const [textContent, setTextContent] = useState('');
163
+
164
+ const [runtime] = useRuntime({
165
+ contentOffsetHeight: 0,
166
+ ellipsis,
167
+ fold,
168
+ foldBtnWidth,
169
+ textContent,
170
+ onEllipsisChange,
171
+ onFoldChange,
172
+ }, ['onEllipsisChange', 'fold', 'onFoldChange']);
173
+
174
+ const contentRef = useRef<HTMLDivElement>(null);
175
+ const wrapperRef = useRef<HTMLDivElement>(null);
176
+ const containerRef = useRef<HTMLDivElement>(null);
177
+ const btnWrapperRef = useRef<HTMLDivElement>(null);
178
+
179
+ const containerStyle = useMemo(() => {
180
+ return {
181
+ lineHeight: getLineHeightFail // 未传入且获取 lineHeight(px) 失败,则设置 default lineHeight: 1.4(em)
182
+ ? "1.4" // more brower normal default lineHeight
183
+ : lineHeight ? lineHeight : undefined,
184
+ };
185
+ }, [lineHeight, getLineHeightFail]);
186
+
187
+ // 容器样式
188
+ const wrapStyle = useMemo(() => {
189
+ const lines = innerLines;
190
+ if (!ellipsis || !lines || !innerLineHeight) {
191
+ return;
192
+ }
193
+ return {
194
+ // HACK: 兼容safari 15+ 富文本折叠高度丢失问题
195
+ minHeight: fold ? `${(lines - 0.5) * innerLineHeight}px` : undefined,
196
+ WebkitLineClamp: fold ? lines : undefined, // 利用-webkit-line-clamp截断方案
197
+ // Note: safari 对WebkitLineClamp支持太差劲 判断浏览器优雅降级为高度截断方案
198
+ // WebkitLineClamp: isSafari ? undefined : ellipsis && fold && lines, // 利用-webkit-line-clamp截断方案
199
+ // maxHeight: isSafari && ellipsis && fold ? lines * innerLineHeight : undefined,
200
+ paddingBottom:
201
+ uiType === "bottom" || !fold ? `${innerLineHeight}px` : undefined,
202
+ };
203
+ }, [innerLines, innerLineHeight, ellipsis, fold, uiType]);
204
+
205
+ // 展开|收起 按钮样式
206
+ const btnStyle = useMemo(() => {
207
+ if (!fold) {
208
+ return;
209
+ }
210
+ // 按钮padding,取行高
211
+ const padding = innerLineHeight;
212
+ // 蒙层透明度所占比例
213
+ const ratio = uiType === "right" ? Math.min((padding / foldBtnWidth) * 100, 80) : 60;
214
+ // 16进制透明色(考虑简写方式), 不直接使用css的transparent是因为safari的表现是灰色
215
+ const transparent = `${maskBgColor}${
216
+ maskBgColor.length === 4 ? "0" : "00"
217
+ }`;
218
+ return {
219
+ height: `${innerLineHeight}px`,
220
+ lineHeight: `${innerLineHeight}px`,
221
+ paddingTop: uiType === "bottom" ? `${padding}px` : undefined,
222
+ paddingLeft: uiType === "right" ? `${padding}px` : undefined,
223
+ // 渐变蒙层
224
+ background: `linear-gradient(to ${uiType}, ${transparent}, ${maskBgColor} ${ratio}%, ${maskBgColor} 100%)`,
225
+ };
226
+ }, [innerLineHeight, maskBgColor, fold, uiType, foldBtnWidth]);
227
+
228
+ const reorganizeDom = useCallback(() => {
229
+ // safari 中仅改变 WebkitLineClamp 没触发重排,调整微小宽度以触发
230
+ if (contentRef.current) {
231
+ contentRef.current.style.width = "99.999%";
232
+ window.requestAnimationFrame?.(() => {
233
+ if (contentRef.current) {
234
+ contentRef.current.style.width = "100%";
235
+ }
236
+ });
237
+ }
238
+ }, []);
239
+
240
+ const handleFoldChange = useCallback(
241
+ (evt?: MouseEvent<HTMLDivElement>, fold = !runtime.fold) => {
242
+ runtime.fold = fold;
243
+ setFold(fold);
244
+ }, []);
245
+
246
+ const ButtonComp = useMemo(() => {
247
+ return (
248
+ <div
249
+ className={cx(
250
+ "btn-fold-wrapper",
251
+ `btn-fold-wrapper-${uiType}`,
252
+ uiType === "bottom" && `placement-${controlPlacement}`
253
+ )}
254
+ style={btnStyle}
255
+ ref={btnWrapperRef}
256
+ onClick={handleFoldChange}
257
+ >
258
+ {renderFoldButton ? (
259
+ renderFoldButton(fold)
260
+ ) : (
261
+ <div className={"btn-fold"}>{fold ? unfoldText : foldText}</div>
262
+ )}
263
+ </div>
264
+ );
265
+ }, [
266
+ btnStyle,
267
+ fold,
268
+ foldText,
269
+ handleFoldChange,
270
+ renderFoldButton,
271
+ controlPlacement,
272
+ uiType,
273
+ unfoldText,
274
+ ]);
275
+
276
+ // 重置状态
277
+ const resetState = useCallback((newEllipsis = runtime.ellipsis) => {
278
+ const {ellipsis, fold: preFold} = runtime;
279
+ if (newEllipsis !== ellipsis) {
280
+ setEllipsis(newEllipsis);
281
+ runtime.ellipsis = newEllipsis;
282
+ runtime.onEllipsisChange?.(newEllipsis);
283
+ // 从未截断状态切换为截断状态时,自动折叠(即:出现展开按钮)
284
+ if (newEllipsis && !preFold) {
285
+ handleFoldChange(undefined, true);
286
+ }
287
+ }
288
+ }, [handleFoldChange]);
289
+
290
+ const calcEllipsis = useCallback(() => {
291
+ const wrapDom = wrapperRef.current;
292
+ const containerDom = containerRef.current;
293
+ if (!wrapDom || !containerDom) {
294
+ return;
295
+ }
296
+ runtime.contentOffsetHeight = wrapDom.offsetHeight;
297
+ let realLineHeight = 0;
298
+
299
+ // 若外部未传入, 尝试读取当前文本的行高。
300
+ if (!realLineHeight && wrapDom) {
301
+ const realStyle = window.getComputedStyle?.(wrapDom);
302
+ const { lineHeight } = realStyle || {};
303
+ if (lineHeight) {
304
+ // 未设置行高的为 normal
305
+ realLineHeight = parseFloat(lineHeight);
306
+ if (!realLineHeight) {
307
+ setGetLineHeightFail(true);
308
+ }
309
+ }
310
+ }
311
+ // lineHeight同步到innerLineHeight
312
+ if (innerLineHeight !== realLineHeight) {
313
+ setInnerLineHeight(realLineHeight);
314
+ }
315
+ if (!lines) {
316
+ if (runtime.contentOffsetHeight > containerDom?.offsetHeight) {
317
+ const adjustLines = Math.floor(containerDom.offsetHeight / realLineHeight);
318
+ if (innerLines !== adjustLines) {
319
+ setInnerLines(adjustLines);
320
+ }
321
+ resetState(true);
322
+ } else {
323
+ resetState(false);
324
+ }
325
+ } else {
326
+ if (innerLines !== lines) {
327
+ setInnerLines(lines);
328
+ }
329
+ if (runtime.contentOffsetHeight >= (lines + 1) * realLineHeight) {
330
+ resetState(true);
331
+ } else {
332
+ resetState(false);
333
+ }
334
+ }
335
+ }, [lines, innerLineHeight, resetState]);
336
+
337
+ // 监听内容高度,是否需要折叠
338
+ // 用useLayoutEffect方式闪屏显示
339
+ useCompatibleEffect(() => {
340
+ resetState();
341
+ calcEllipsis();
342
+ }, [calcEllipsis, resetState]);
343
+
344
+ // 监听"展开"按钮宽度变化
345
+ useEffect(() => {
346
+ if (ellipsis && btnWrapperRef.current) {
347
+ const {offsetWidth, offsetHeight} = btnWrapperRef.current;
348
+ if (offsetWidth !== runtime.foldBtnWidth) {
349
+ runtime.foldBtnWidth = offsetWidth;
350
+ setFoldBtnWidth(offsetWidth);
351
+ }
352
+ }
353
+ }, [ellipsis, unfoldText, showFoldControl]);
354
+ useEffect(() => {
355
+ if (isSafari) {
356
+ reorganizeDom();
357
+ }
358
+ }, [fold, reorganizeDom]);
359
+ const updateTextContent = useCallback(() => {
360
+ const newTextContent = wrapperRef.current?.textContent || '';
361
+ if (newTextContent !== runtime.textContent) {
362
+ runtime.textContent = newTextContent;
363
+ setTextContent(newTextContent);
364
+ }
365
+ }, []);
366
+ const finalContent = content || children;
367
+ const hoverTitle = useMemo(() => {
368
+ return ellipsis && fold
369
+ ? (typeof titleWhenFold === 'function'
370
+ ? titleWhenFold(textContent)
371
+ : titleWhenFold || textContent)
372
+ : undefined;
373
+ }, [titleWhenFold, ellipsis, fold, textContent]);
374
+ useEffect(() => {
375
+ onStatusChange?.({
376
+ ellipsis,
377
+ fold,
378
+ title: hoverTitle
379
+ });
380
+ }, [onStatusChange, fold, ellipsis, hoverTitle]);
381
+ console.log('[render TextEllipsis]: ellipsis fold: ', ellipsis, fold);
382
+ return (
383
+ <div
384
+ className={cx(c("container"), className)}
385
+ style={containerStyle}
386
+ ref={(r) => {
387
+ assignRef(containerRef, r);
388
+ ref && assignRef(ref, r);
389
+ }}
390
+ onMouseEnter={onMouseEnter}
391
+ onMouseLeave={onMouseLeave}
392
+ onPointerEnter={onPointerEnter}
393
+ onPointerLeave={onPointerLeave}
394
+ onClick={onClick}
395
+ onFocus={onFocus}
396
+ >
397
+ {/* 此dom仅用于计算高度 用.text-ellipsis-inner计算 在不重新初始化情况下切换文本时高度计算有问题 */}
398
+ <Measure offset>
399
+ {({measureRef, contentRect}) => {
400
+ // console.log('contentRect:', contentRect.offset?.height, runtime.contentOffsetHeight);
401
+ const {height} = contentRect.offset || {};
402
+ if (height !== undefined && Math.abs(height - runtime.contentOffsetHeight) > 1) {
403
+ console.log('calcEllipsis');
404
+ calcEllipsis();
405
+ }
406
+ return <div className={"offset-height-computer"} ref={(r) => {
407
+ assignRef(measureRef, r);
408
+ assignRef(wrapperRef, r);
409
+ updateTextContent();
410
+ }}>
411
+ {finalContent}
412
+ </div>
413
+ }}
414
+ </Measure>
415
+ {/* <div className={"offset-height-computer"} ref={wrapperRef}>
416
+ {finalContent}
417
+ </div> */}
418
+ {/* 主文本显示 */}
419
+ <div
420
+ className={"text-ellipsis-inner"}
421
+ title={showTitleWhenFold ? hoverTitle : undefined}
422
+ style={wrapStyle}
423
+ ref={contentRef}
424
+ >
425
+ {/* {finalContent} */}
426
+ {/* firefox >= 133 绝对定位的按钮放文本后面也会被截断隐藏!! , 放文本前面可解决 */}
427
+ {ellipsis && showFoldControl && ButtonComp}
428
+ {finalContent}
429
+ </div>
430
+ </div>
431
+ );
432
+ });
package/src/style.scss ADDED
@@ -0,0 +1,77 @@
1
+ @use '../../style/global.scss' as global;
2
+
3
+ $text-ellipsis-color: #709bff; // #4c84ff;
4
+ $btn-fold-color: #4c84ff; // #727a8b;
5
+ $prefix: global.$comp-prefix;
6
+
7
+ @mixin text-ellipsis-break() {
8
+ overflow-wrap: break-word;
9
+ word-break: break-word;
10
+ }
11
+
12
+ .#{$prefix}-text-ellipsis__ {
13
+ &container {
14
+ display: flex; // INFO: 这里必须非block, safari 13.1.3版本有bug 折叠切换时节点高度未更新
15
+ position: relative;
16
+
17
+ // 保留dom用于计算高度, 不影响视图
18
+ .offset-height-computer {
19
+ visibility: hidden;
20
+ position: absolute;
21
+ pointer-events: none;
22
+ z-index: -1;
23
+ @include text-ellipsis-break();
24
+ }
25
+ .text-ellipsis-inner {
26
+ overflow: hidden;
27
+ position: relative;
28
+ display: -webkit-box;
29
+ text-overflow: ellipsis;
30
+ -webkit-box-orient: vertical;
31
+ @include text-ellipsis-break();
32
+
33
+
34
+ .btn-fold-wrapper {
35
+ position: absolute;
36
+ bottom: 0;
37
+ z-index: 1;
38
+ display: flex;
39
+ align-items: center;
40
+ justify-content: center;
41
+ color: $btn-fold-color;
42
+ user-select: none;
43
+ cursor: pointer;
44
+ &:hover {
45
+ color: $text-ellipsis-color;
46
+ }
47
+ // 展开按钮在右侧
48
+ &-right {
49
+ right: 0;
50
+ padding-left: 24px;
51
+ }
52
+ // 展开按钮在底部(蒙层模式)
53
+ &-bottom {
54
+ width: 100%;
55
+ &.placement-left {
56
+ justify-content: flex-start;
57
+ }
58
+ &.placement-center {
59
+ justify-content: center;
60
+ }
61
+ &.placement-right {
62
+ justify-content: flex-end;
63
+ }
64
+ }
65
+
66
+ .btn-fold {
67
+ display: inline-block;
68
+ // color: inherit;
69
+ // font-size: 12px;
70
+ // border: none;
71
+ // background-color: transparent;
72
+ }
73
+ }
74
+
75
+ }
76
+ }
77
+ }