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
This commit is contained in:
Paul Frazee 2023-08-16 10:22:50 -07:00 committed by GitHub
parent 5379561934
commit 819340dd3c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
6 changed files with 123 additions and 26 deletions

View file

@ -14,6 +14,7 @@ import {isNetworkError} from 'lib/strings/errors'
import {LinkMeta} from '../link-meta/link-meta'
import {isWeb} from 'platform/detection'
import {ImageModel} from 'state/models/media/image'
import {shortenLinks} from 'lib/strings/rich-text-manip'
export interface ExternalEmbedDraft {
uri: string
@ -92,7 +93,7 @@ export async function post(store: RootStoreModel, opts: PostOpts) {
| AppBskyEmbedRecordWithMedia.Main
| undefined
let reply
const rt = new RichText(
let rt = new RichText(
{text: opts.rawText.trim()},
{
cleanNewlines: true,
@ -101,6 +102,7 @@ export async function post(store: RootStoreModel, opts: PostOpts) {
opts.onStateChange?.('Processing...')
await rt.detectFacets(store.agent)
rt = shortenLinks(rt)
// filter out any mention facets that didn't map to a user
rt.facets = rt.facets?.filter(facet => {

View file

@ -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
}

View file

@ -42,15 +42,12 @@ export function toShortUrl(url: string): string {
if (urlp.protocol !== 'http:' && urlp.protocol !== 'https:') {
return url
}
const shortened =
urlp.host +
(urlp.pathname === '/' ? '' : urlp.pathname) +
urlp.search +
urlp.hash
if (shortened.length > 30) {
return shortened.slice(0, 27) + '...'
const path =
(urlp.pathname === '/' ? '' : urlp.pathname) + urlp.search + urlp.hash
if (path.length > 15) {
return urlp.host + path.slice(0, 13) + '...'
}
return shortened ? shortened : url
return urlp.host + path
} catch (e) {
return url
}