Skip to content

Commit dc5101f

Browse files
authored
feat: dynamic truncate component (#535)
1 parent c69dda1 commit dc5101f

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
<span
2+
x-data="{
3+
value: '{{ $slot }}',
4+
init() {
5+
new ResizeObserver(() => this.throttledTruncate()).observe(this.$root);
6+
7+
window.addEventListener('resize', () => this.throttledTruncate());
8+
9+
this.truncate();
10+
},
11+
throttleTimeout: null,
12+
throttledTruncate() {
13+
if (this.throttleTimeout !== null) {
14+
clearTimeout(this.throttleTimeout);
15+
}
16+
17+
this.throttleTimeout = setTimeout(() => {
18+
this.truncate();
19+
20+
this.throttleTimeout = null;
21+
}, 50);
22+
},
23+
truncate() {
24+
const el = this.$root;
25+
26+
el.innerHTML = ''
27+
el.appendChild(document.createTextNode(this.value));
28+
29+
if (!this.hasOverflow(el)) {
30+
return;
31+
}
32+
33+
let length = this.value.length;
34+
do {
35+
const a = this.value.substr(0, length);
36+
const b = this.value.substr(-length);
37+
const truncated = a + '...' + b;
38+
39+
el.innerHTML = ''
40+
el.appendChild(document.createTextNode(truncated));
41+
42+
length--;
43+
} while(this.hasOverflow(el) && length >= 0)
44+
},
45+
hasOverflow(el) {
46+
return el.offsetWidth < el.scrollWidth;
47+
},
48+
}"
49+
class="inline-flex overflow-hidden w-full max-w-full whitespace-nowrap"
50+
>{{ $slot }}</span>

src/Providers/UserInterfaceServiceProvider.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,7 @@ private function registerBladeComponents(): void
320320
$blade->component('ark::status-circle', 'ark-status-circle');
321321
$blade->component('ark::svg-lazy', 'ark-svg-lazy');
322322
$blade->component('ark::toast', 'ark-toast');
323+
$blade->component('ark::components.truncate-dynamic', 'ark-truncate-dynamic');
323324
$blade->component('ark::separator', 'ark-separator');
324325
$blade->component('ark::shapes.line', 'ark-placeholder-line');
325326
$blade->component('ark::shapes.square', 'ark-placeholder-square');

0 commit comments

Comments
 (0)