Skip to content

Commit 9ee7fc7

Browse files
simonhampclaude
andauthored
Link URLs in commits and replies, as the web does (#28)
A URL or bare domain in a commit or reply is now a link in Commit Blue, found with the web's rules from linkified-text.tsx and the server's Urls.php. It shows shortened the way the web shows it. A dev/null commit shows as its author and short hash and opens in the app. A GitHub repository, issue or pull request shows as GitHub writes it. Everything else opens in the in-app browser. The web puts a dev/null or GitHub icon before those named links. Text runs can't hold an icon, so the app leaves it out. URLs are split out before mentions and the wordmark, as on the web, so a /dev/null inside a URL now stays part of the link. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6c17929 commit 9ee7fc7

9 files changed

Lines changed: 429 additions & 17 deletions

File tree

‎app/Devnull/Data/BodyLink.php‎

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
<?php
2+
3+
namespace App\Devnull\Data;
4+
5+
/**
6+
* A URL in a commit's prose, shown as the web's LinkifiedText shows it: a commit
7+
* on dev/null as its author and short hash, a GitHub repository, issue or pull
8+
* request as GitHub writes it, and anything else shortened the way X does.
9+
*
10+
* The rules are the web's, from linkified-text.tsx and app/Services/Urls.php.
11+
* A commit opens in the app, and everything else in the browser.
12+
*/
13+
final readonly class BodyLink
14+
{
15+
/**
16+
* Top-level domains a bare domain like "nativephp.com" may end with. It's
17+
* an allowlist because most file extensions are real TLDs too, so the ones
18+
* that read like code or files (sh, py, rs, md, ...) are left out.
19+
*/
20+
private const array TopLevelDomains = [
21+
'com', 'org', 'net', 'edu', 'gov', 'mil', 'info', 'biz', 'io', 'dev', 'app', 'co', 'ai', 'me', 'xyz', 'tech',
22+
'gg', 'tv', 'fm', 'ly', 'to', 'is', 'blog', 'cloud', 'site', 'online', 'design', 'studio', 'tools', 'software',
23+
'codes', 'wiki', 'news', 'website', 'club', 'ninja', 'rocks', 'academy', 'guide', 'social', 'digital', 'agency',
24+
'fyi', 'lol', 'live',
25+
'uk', 'de', 'fr', 'nl', 'es', 'it', 'pt', 'br', 'ca', 'au', 'jp', 'ch', 'se', 'no', 'dk', 'fi', 'be', 'at', 'ie',
26+
'nz', 'us', 'eu', 'cz', 'sk', 'hu', 'ro', 'bg', 'gr', 'hr', 'si', 'ee', 'lv', 'lt', 'ru', 'ua', 'tr', 'il', 'za',
27+
'mx', 'ar', 'kr', 'cn', 'tw', 'hk', 'sg', 'vn', 'th',
28+
];
29+
30+
/**
31+
* First path segments that are GitHub's own pages rather than an owner.
32+
*/
33+
private const array GitHubPages = [
34+
'about', 'apps', 'codespaces', 'collections', 'customer-stories', 'enterprise', 'events', 'explore', 'features',
35+
'issues', 'login', 'marketplace', 'new', 'notifications', 'orgs', 'organizations', 'pricing', 'pulls', 'search',
36+
'security', 'settings', 'site', 'sponsors', 'topics', 'trending', 'users',
37+
];
38+
39+
/**
40+
* A commit on dev/null with nothing after its id.
41+
*/
42+
private const string CommitLink = '/^https?:\/\/(?:www\.)?dev-null\.sh\/@([A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38})\/commits\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i';
43+
44+
/**
45+
* A GitHub repository, issue or pull request with nothing after its name or number.
46+
*/
47+
private const string GitHubLink = '/^https?:\/\/(?:www\.)?github\.com\/([A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38})\/([A-Za-z0-9._-]{1,100})(?:\/(issues|pull)\/([1-9][0-9]{0,9}))?$/i';
48+
49+
private const int MaxLength = 2048;
50+
51+
private const int MaxShortenedPathLength = 20;
52+
53+
/**
54+
* @param string $href Where it goes: the URL, with https:// before a bare domain.
55+
* @param string $shown What it shows.
56+
* @param string $prefix What it shows muted before that: a commit's author or a repository's owner, and "/".
57+
* @param string|null $commit The id of the dev/null commit it opens in the app.
58+
*/
59+
private function __construct(public string $href, public string $shown, public string $prefix = '', public ?string $commit = null) {}
60+
61+
/**
62+
* Every link in some prose, in order, with where it starts and how long it
63+
* is as written, in code points. Punctuation that ends the sentence rather
64+
* than the URL stays prose.
65+
*
66+
* @return list<array{0: int, 1: int, 2: self}>
67+
*/
68+
public static function in(string $prose): array
69+
{
70+
preg_match_all(self::pattern(), $prose, $matches, PREG_OFFSET_CAPTURE);
71+
72+
$links = [];
73+
74+
foreach ($matches[0] as [$candidate, $byte]) {
75+
$written = self::withoutTrailingPunctuation($candidate);
76+
$href = preg_match('/^(https?)(:\/\/.*)$/is', $written, $scheme) === 1 ? strtolower($scheme[1]).$scheme[2] : 'https://'.$written;
77+
78+
if (str_ends_with($href, '://') || mb_strlen($href) > self::MaxLength) {
79+
continue;
80+
}
81+
82+
$links[] = [mb_strlen(substr($prose, 0, $byte)), mb_strlen($written), self::to($written, $href)];
83+
}
84+
85+
return $links;
86+
}
87+
88+
/**
89+
* Whether it shows as a name and a short hash or number rather than as a URL.
90+
*/
91+
public function isNamed(): bool
92+
{
93+
return $this->prefix !== '';
94+
}
95+
96+
private static function to(string $written, string $href): self
97+
{
98+
if (preg_match(self::CommitLink, $written, $commit) === 1) {
99+
$id = strtolower($commit[2]);
100+
101+
return new self($href, substr(str_replace('-', '', $id), -7), $commit[1].'/', $id);
102+
}
103+
104+
if (preg_match(self::GitHubLink, $href, $gitHub) === 1 && ! in_array(strtolower($gitHub[1]), self::GitHubPages, true)) {
105+
return new self($href, $gitHub[2].(isset($gitHub[4]) ? '#'.$gitHub[4] : ''), $gitHub[1].'/');
106+
}
107+
108+
return new self($href, self::shorten($written));
109+
}
110+
111+
/**
112+
* Like X: without its scheme or "www.", with the whole host, and at most 20
113+
* characters after it, the last an ellipsis when it's cut. A cut never splits
114+
* a percent-encoded character.
115+
*/
116+
private static function shorten(string $url): string
117+
{
118+
$url = (string) preg_replace('/^(?:https?:\/\/)?(?:www\.(?=[^\/?#]*\.))?/i', '', $url);
119+
$host = (string) preg_replace('/[\/?#].*$/su', '', $url);
120+
$path = mb_substr($url, mb_strlen($host));
121+
122+
if (mb_strlen($path) <= self::MaxShortenedPathLength) {
123+
return $url;
124+
}
125+
126+
$kept = (string) preg_replace('/%[0-9A-Fa-f]?$/', '', mb_substr($path, 0, self::MaxShortenedPathLength - 1));
127+
128+
return $host.$kept.'…';
129+
}
130+
131+
/**
132+
* A URL with a scheme, or a bare domain: ASCII labels ending in an allowed
133+
* TLD, then maybe a path, query or fragment. A bare domain can't follow a
134+
* letter, digit, "_", ".", "/", "@" or "-", its TLD is all lowercase or all
135+
* uppercase, and it ends the word without a "(" or another label after it.
136+
*/
137+
private static function pattern(): string
138+
{
139+
$topLevelDomains = implode('|', [...self::TopLevelDomains, ...array_map(strtoupper(...), self::TopLevelDomains)]);
140+
141+
return '/\b[Hh][Tt][Tt][Pp][Ss]?:\/\/[^\s<>]+'
142+
.'|(?<![\p{L}\p{N}_.\/@-])(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+(?:'.$topLevelDomains.')'
143+
.'(?![\p{L}\p{N}_(-]|\.[A-Za-z0-9])(?:[\/?#][^\s<>]*)?/u';
144+
}
145+
146+
/**
147+
* Strips punctuation that ends a sentence rather than the URL, keeping
148+
* closing brackets that pair with one inside it.
149+
*/
150+
private static function withoutTrailingPunctuation(string $url): string
151+
{
152+
do {
153+
$previous = $url;
154+
$url = mb_rtrim($url, '.,;:!?\'"');
155+
156+
foreach (['(' => ')', '[' => ']'] as $open => $close) {
157+
if (str_ends_with($url, $close) && mb_substr_count($url, $open) < mb_substr_count($url, $close)) {
158+
$url = mb_substr($url, 0, -1);
159+
}
160+
}
161+
} while ($url !== $previous);
162+
163+
return $url;
164+
}
165+
}

‎app/Devnull/Data/BodyRun.php‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
namespace App\Devnull\Data;
44

55
/**
6-
* A run of a paragraph: plain prose, a mention, inline code, or a standalone
7-
* `/dev/null`, which draws as the wordmark.
6+
* A run of a paragraph: plain prose, a mention, inline code, a link, or a
7+
* standalone `/dev/null`, which draws as the wordmark. A link's text is the
8+
* URL as written.
89
*/
910
final readonly class BodyRun
1011
{
11-
public function __construct(public string $text, public ?string $username = null, public bool $isCode = false, public bool $isWordmark = false) {}
12+
public function __construct(public string $text, public ?string $username = null, public bool $isCode = false, public bool $isWordmark = false, public ?BodyLink $link = null) {}
1213

1314
public function isMention(): bool
1415
{

‎app/Devnull/Data/Commit.php‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,27 @@ public function plainText(): string
227227
));
228228
}
229229

230+
/**
231+
* The links in the body, in the order it draws them. A long commit's
232+
* preview is cut at a space, so its links are the first of these.
233+
*
234+
* @return list<BodyLink>
235+
*/
236+
public function links(): array
237+
{
238+
$links = [];
239+
240+
foreach ($this->content as $block) {
241+
foreach ($block->runs as $run) {
242+
if ($run->link !== null) {
243+
$links[] = $run->link;
244+
}
245+
}
246+
}
247+
248+
return $links;
249+
}
250+
230251
public function isDeleted(): bool
231252
{
232253
return $this->deletedAt !== null;

‎app/Devnull/Data/CommitBody.php‎

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
/**
66
* Turns a commit's `body_segments` into blocks to draw, the way the web's
7-
* CommitBody does: prose (with mentions linked, and `/dev/null` as the
8-
* wordmark) and inline code flow together in paragraphs, and fenced code
7+
* CommitBody does: prose (with URLs and mentions linked, and `/dev/null` as
8+
* the wordmark) and inline code flow together in paragraphs, and fenced code
99
* blocks stand on their own.
1010
*
1111
* Mention offsets count code points into the whole body, but segments aren't
@@ -60,12 +60,12 @@ public static function blocks(string $body, ?array $segments, array $mentions =
6060
$start = $text === '' ? false : mb_strpos($body, $text, $cursor);
6161

6262
if ($start === false) {
63-
array_push($runs, ...self::withWordmarks($text.($cut ? self::Ellipsis : '')));
63+
array_push($runs, ...self::withLinks($text.($cut ? self::Ellipsis : ''), null, []));
6464

6565
break;
6666
}
6767

68-
array_push($runs, ...self::withMentions($text, $start, $mentions));
68+
array_push($runs, ...self::withLinks($text, $start, $mentions));
6969
$cursor = $start + mb_strlen($text);
7070

7171
if ($cut) {
@@ -106,6 +106,38 @@ public static function blocks(string $body, ?array $segments, array $mentions =
106106
return $blocks;
107107
}
108108

109+
/**
110+
* Splits prose that starts at $start in the body around the links inside
111+
* it, then the prose between them around its mentions, as the web does.
112+
* Prose that wasn't found in the body has no start, so no mentions.
113+
*
114+
* @param list<Mention> $mentions
115+
* @return list<BodyRun>
116+
*/
117+
private static function withLinks(string $text, ?int $start, array $mentions): array
118+
{
119+
$runs = [];
120+
$position = 0;
121+
$prose = fn (string $part, int $at): array => $start === null
122+
? self::withWordmarks($part)
123+
: self::withMentions($part, $start + $at, $mentions);
124+
125+
foreach (BodyLink::in($text) as [$offset, $length, $link]) {
126+
if ($offset > $position) {
127+
array_push($runs, ...$prose(mb_substr($text, $position, $offset - $position), $position));
128+
}
129+
130+
$runs[] = new BodyRun(mb_substr($text, $offset, $length), link: $link);
131+
$position = $offset + $length;
132+
}
133+
134+
if ($position < mb_strlen($text)) {
135+
array_push($runs, ...$prose(mb_substr($text, $position), $position));
136+
}
137+
138+
return $runs;
139+
}
140+
109141
/**
110142
* Splits prose that starts at $start in the body around the mentions inside it.
111143
*

‎app/NativeComponents/Concerns/ShowsCommits.php‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,23 @@ public function openImage(string $id, int $index = 0): void
182182
$this->openInBrowser(($this->shownCommit($id)?->images[$index] ?? null)?->url);
183183
}
184184

185+
/**
186+
* Opens a link in a commit's body, by its place among the body's links: a
187+
* commit on dev/null here in the app, anything else in the browser.
188+
*/
189+
public function openLink(string $id, int $index): void
190+
{
191+
$link = $this->shownCommit($id)?->links()[$index] ?? null;
192+
193+
if ($link?->commit !== null) {
194+
$this->openCommit($link->commit);
195+
196+
return;
197+
}
198+
199+
$this->openInBrowser($link?->href);
200+
}
201+
185202
/**
186203
* Share link: the web's copy-link button. The share sheet has Copy, and AirDrop and Messages besides.
187204
*/

‎resources/views/native/partials/commit-body.blade.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,13 +11,19 @@
1111
slash, even after a space, so a zero-width space (U+200B) after a space lets the line break there as a browser
1212
would; without it, a few wordmarks in a row can't wrap at all. VoiceOver skips both and still reads "/dev/null".
1313
14+
A link is Commit Blue and opens on a tap, numbered by its place among the body's links. Like the web, a URL shows
15+
shortened, and a dev/null commit or a GitHub repository, issue or pull request shows as a mono name with the owner
16+
muted, held on one line by a word joiner after its slash. The web's dev/null and GitHub marks before those are icons,
17+
which text runs can't hold, so they're left out.
18+
1419
A body too long to show whole in a list shows its start, as devnull cut it, and "Show more" in Commit Blue, which
1520
opens the rest where it is. The commit a page is about ($focused) is always whole. $muted sets it in muted ink, for
1621
the commits around the one a page is about.
1722
--}}
1823
@php($size ??= 'text-[15px]')
1924
@php($ink = ($muted ?? false) ? 'text-theme-ink-muted' : 'text-theme-ink')
2025
@php($folded = ! ($focused ?? false) && $commit->isFolded() && ! in_array($commit->id, $unfolded ?? [], true))
26+
@php($linkIndex = 0)
2127
@foreach ($folded ? $commit->previewContent : $commit->content as $block)
2228
@if ($block->isCode())
2329
<native:column class="w-full mt-1 mb-1 rounded-md border border-theme-hairline bg-theme-wash">
@@ -32,6 +38,10 @@
3238
<native:text :text="$run->text" font="semibold" class="font-semibold text-theme-primary" @press="openProfile('{{ $run->username }}')" />
3339
@elseif ($run->isCode)
3440
<native:text :text="$run->text" font="mono" class="text-[13px] bg-theme-wash" />
41+
@elseif ($run->link?->isNamed())
42+
<native:text font="mono" class="text-[13px] text-theme-primary" @press="openLink('{{ $commit->id }}', {{ $linkIndex++ }})"><native:text :text="$run->link->prefix" class="text-theme-ink-muted" />&#x2060;<native:text :text="$run->link->shown" /></native:text>
43+
@elseif ($run->link)
44+
<native:text :text="$run->link->shown" class="text-theme-primary" @press="openLink('{{ $commit->id }}', {{ $linkIndex++ }})" />
3545
@elseif ($run->isWordmark)
3646
@php($afterSpace = $loop->index > 0 && ctype_space(substr($block->runs[$loop->index - 1]->text, -1)))
3747
<native:text font="semibold" class="font-semibold tracking-tight">@if ($afterSpace)&#x200B;@endif/&#x2060;dev<native:text text="/" font="default" class="font-normal text-theme-lane-0" />&#x2060;null</native:text>

‎tests/Feature/Screens/LogTest.php‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,39 @@
223223
->and(strtolower($slash['dark_color']))->toBe(strtolower(config('native-ui.theme.dark.lane-0')));
224224
});
225225

226+
it('links URLs in Commit Blue, opening a dev/null commit here and anything else in the browser', function () {
227+
Http::fake(['devnull.test/*' => Http::response(pageJson([commitJson([
228+
'id' => 'c1',
229+
'body' => 'Read https://www.example.com/a-long-path-to-the-release-notes, then https://dev-null.sh/@Hacksore/commits/01a14a9d-7971-73ea-8f35-135fe5149ca8 and github.com/laravel/framework/pull/42',
230+
])]))]);
231+
232+
$screen = Native::visit('/log');
233+
$primary = strtolower(config('native-ui.theme.light.primary'));
234+
$link = findNode($screen->tree(), fn (array $node): bool => ($node['props']['text'] ?? null) === 'example.com/a-long-path-to-the…');
235+
$repository = findNode($screen->tree(), fn (array $node): bool => ($node['children'][0]['props']['text'] ?? null) === 'laravel/');
236+
237+
expect(paragraphRuns($screen, 'Read'))->toBe([
238+
['Read '],
239+
['example.com/a-long-path-to-the…', 'link'],
240+
[', then '],
241+
['Hacksore/5149ca8', 'link'],
242+
[' and '],
243+
['laravel/framework#42', 'link'],
244+
])
245+
->and(strtolower($link['props']['color']))->toBe($primary)
246+
->and($repository['props']['font_name'])->toBe('mono')
247+
->and(strtolower($repository['props']['color']))->toBe($primary)
248+
->and(strtolower($repository['children'][0]['props']['color']))->toBe(strtolower(config('native-ui.theme.light.ink-muted')));
249+
250+
$screen->press("openLink('c1', 0)")
251+
->assertNativeCalled('Browser.OpenInApp', fn (array $params): bool => $params['url'] === 'https://www.example.com/a-long-path-to-the-release-notes')
252+
->press("openLink('c1', 2)")
253+
->assertNativeCalled('Browser.OpenInApp', fn (array $params): bool => $params['url'] === 'https://github.com/laravel/framework/pull/42')
254+
->assertNoNavigation()
255+
->press("openLink('c1', 1)")
256+
->assertNavigatedTo('/log/commits/01a14a9d-7971-73ea-8f35-135fe5149ca8');
257+
});
258+
226259
it('shows a link preview as a compact row and opens it in the browser', function () {
227260
Http::fake(['devnull.test/*' => Http::response(pageJson([commitJson([
228261
'id' => 'c1',

0 commit comments

Comments
 (0)