about summary refs log tree commit diff
path: root/src/lib/strings/rich-text-manip.ts
diff options
context:
space:
mode:
authorPaul Frazee <pfrazee@gmail.com>2023-08-16 10:22:50 -0700
committerGitHub <noreply@github.com>2023-08-16 10:22:50 -0700
commit819340dd3c34e89e8cd7126c6f1172aba7a8ebec (patch)
tree91a1a4e3f45d7a0e7c32f530319c6349c778ccfc /src/lib/strings/rich-text-manip.ts
parent5379561934f6249fbbecf33ed0cd10d2d30128f0 (diff)
downloadvoidsky-819340dd3c34e89e8cd7126c6f1172aba7a8ebec.tar.zst
Shorten links in composer to reduce char usage (#1188)
* Modify toShortUrl() to always include the full domain

* Shorten links in the composer to save on characters

* Apply some limits to the link card suggester
Diffstat (limited to 'src/lib/strings/rich-text-manip.ts')
-rw-r--r--src/lib/strings/rich-text-manip.ts34
1 files changed, 34 insertions, 0 deletions
diff --git a/src/lib/strings/rich-text-manip.ts b/src/lib/strings/rich-text-manip.ts
new file mode 100644
index 000000000..d9cd8c071
--- /dev/null
+++ b/src/lib/strings/rich-text-manip.ts
@@ -0,0 +1,34 @@
+import {RichText, UnicodeString} from '@atproto/api'
+import {toShortUrl} from './url-helpers'
+
+export function shortenLinks(rt: RichText): RichText {
+  if (!rt.facets?.length) {
+    return rt
+  }
+  rt = rt.clone()
+  // enumerate the link facets
+  if (rt.facets) {
+    for (const facet of rt.facets) {
+      const isLink = !!facet.features.find(
+        f => f.$type === 'app.bsky.richtext.facet#link',
+      )
+      if (!isLink) {
+        continue
+      }
+
+      // extract and shorten the URL
+      const {byteStart, byteEnd} = facet.index
+      const url = rt.unicodeText.slice(byteStart, byteEnd)
+      const shortened = new UnicodeString(toShortUrl(url))
+
+      // insert the shorten URL
+      rt.insert(byteStart, shortened.utf16)
+      // update the facet to cover the new shortened URL
+      facet.index.byteStart = byteStart
+      facet.index.byteEnd = byteStart + shortened.length
+      // remove the old URL
+      rt.delete(byteStart + shortened.length, byteEnd + shortened.length)
+    }
+  }
+  return rt
+}