feat: inline review-comment composer + WebView code editor
- diff lines are tappable; PullDiff opens a composer that posts a positioned inline review comment (path + new_position) - CodeEditor: self-contained WebView editor with line numbers, tab handling and lightweight syntax highlighting (no remote code / bundled editor assets); used by Quick Edit - i18n (en/nl) for inline comments
This commit is contained in:
1 parent
587bf732b5
commit
eed9c91274
6 files changed
+291
-16
No files matched your search
@@ -0,0 +1,171 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { StyleSheet } from 'react-native';
|
||||
import { WebView } from 'react-native-webview';
|
||||
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
|
||||
/** Minimal keyword sets for the languages we highlight in the WebView editor. */
|
||||
const KEYWORDS: Record<string, string[]> = {
|
||||
javascript: ['const', 'let', 'var', 'function', 'return', 'if', 'else', 'for', 'while', 'import', 'from', 'export', 'class', 'new', 'await', 'async', 'try', 'catch', 'throw', 'typeof', 'interface', 'type', 'extends', 'implements', 'public', 'private', 'void', 'null', 'true', 'false'],
|
||||
python: ['def', 'return', 'if', 'elif', 'else', 'for', 'while', 'import', 'from', 'class', 'try', 'except', 'raise', 'with', 'as', 'lambda', 'None', 'True', 'False', 'and', 'or', 'not', 'in', 'is', 'async', 'await'],
|
||||
go: ['package', 'import', 'func', 'return', 'if', 'else', 'for', 'range', 'var', 'const', 'type', 'struct', 'interface', 'map', 'chan', 'go', 'defer', 'nil', 'true', 'false', 'switch', 'case'],
|
||||
ruby: ['def', 'end', 'if', 'else', 'elsif', 'unless', 'while', 'do', 'class', 'module', 'require', 'return', 'nil', 'true', 'false', 'yield', 'begin', 'rescue'],
|
||||
rust: ['fn', 'let', 'mut', 'pub', 'use', 'struct', 'enum', 'impl', 'trait', 'return', 'if', 'else', 'for', 'while', 'match', 'self', 'true', 'false', 'async', 'await'],
|
||||
java: ['class', 'public', 'private', 'protected', 'static', 'void', 'return', 'if', 'else', 'for', 'while', 'new', 'import', 'package', 'interface', 'extends', 'implements', 'try', 'catch', 'throw', 'null', 'true', 'false'],
|
||||
};
|
||||
|
||||
const EXT_LANGUAGE: Record<string, string> = {
|
||||
js: 'javascript',
|
||||
jsx: 'javascript',
|
||||
ts: 'javascript',
|
||||
tsx: 'javascript',
|
||||
mjs: 'javascript',
|
||||
cjs: 'javascript',
|
||||
py: 'python',
|
||||
go: 'go',
|
||||
rb: 'ruby',
|
||||
rs: 'rust',
|
||||
java: 'java',
|
||||
kt: 'java',
|
||||
swift: 'java',
|
||||
c: 'java',
|
||||
h: 'java',
|
||||
cpp: 'java',
|
||||
hpp: 'java',
|
||||
cs: 'java',
|
||||
php: 'java',
|
||||
json: 'javascript',
|
||||
yml: 'python',
|
||||
yaml: 'python',
|
||||
toml: 'python',
|
||||
sh: 'python',
|
||||
bash: 'python',
|
||||
};
|
||||
|
||||
export function languageForPath(path: string): string {
|
||||
const ext = path.split('.').pop()?.toLowerCase() ?? '';
|
||||
return EXT_LANGUAGE[ext] ?? 'plain';
|
||||
}
|
||||
|
||||
export interface CodeEditorProps {
|
||||
/** Initial content — the WebView owns the text while editing. */
|
||||
value: string;
|
||||
onChangeText: (value: string) => void;
|
||||
language?: string;
|
||||
editable?: boolean;
|
||||
}
|
||||
|
||||
function escapeHtml(value: string): string {
|
||||
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
}
|
||||
|
||||
function buildHtml(value: string, language: string, editable: boolean, c: {
|
||||
bg: string;
|
||||
fg: string;
|
||||
gutter: string;
|
||||
keyword: string;
|
||||
string: string;
|
||||
comment: string;
|
||||
number: string;
|
||||
caret: string;
|
||||
}): string {
|
||||
const keywords = KEYWORDS[language] ?? [];
|
||||
return `<!DOCTYPE html><html><head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||
<style>
|
||||
html,body{margin:0;padding:0;height:100%;background:${c.bg};}
|
||||
#wrap{display:flex;height:100%;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:13px;line-height:18px;}
|
||||
#gutter{padding:8px 8px 8px 10px;color:${c.gutter};text-align:right;user-select:none;white-space:pre;overflow:hidden;background:${c.bg};}
|
||||
#editor{position:relative;flex:1;overflow:auto;}
|
||||
#hl,#ta{margin:0;padding:8px 12px;font:inherit;line-height:18px;white-space:pre;tab-size:2;word-wrap:normal;}
|
||||
#hl{position:absolute;top:0;left:0;pointer-events:none;}
|
||||
#ta{position:relative;width:100%;height:100%;min-height:300px;border:0;outline:0;resize:none;background:transparent;color:${c.fg};caret-color:${c.caret};}
|
||||
.kw{color:${c.keyword}} .str{color:${c.string}} .com{color:${c.comment}} .num{color:${c.number}}
|
||||
</style></head><body>
|
||||
<div id="wrap">
|
||||
<div id="gutter"></div>
|
||||
<div id="editor">
|
||||
<pre id="hl"></pre>
|
||||
<textarea id="ta" spellcheck="false" autocapitalize="off" autocomplete="off" autocorrect="off"${editable ? '' : ' readonly'}>${escapeHtml(value)}</textarea>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
var ta=document.getElementById('ta'), hl=document.getElementById('hl'), gutter=document.getElementById('gutter');
|
||||
var KEYWORDS=new Set(${JSON.stringify(keywords)});
|
||||
function esc(s){return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');}
|
||||
function highlight(line){
|
||||
var out=esc(line);
|
||||
out=out.replace(/(\\/\\/[^\\n]*|#[^\\n]*)/g,'<span class="com">$1</span>');
|
||||
out=out.replace(/('([^'\\\\]|\\\\.)*'|"([^"\\\\]|\\\\.)*")/g,'<span class="str">$1</span>');
|
||||
out=out.replace(/\\b(\\d+)\\b/g,'<span class="num">$1</span>');
|
||||
out=out.replace(/\\b([A-Za-z_]\\w*)\\b/g,function(m,k){return KEYWORDS.has(k)?'<span class="kw">'+k+'</span>':m;});
|
||||
return out;
|
||||
}
|
||||
function render(){
|
||||
var lines=ta.value.split('\\n');
|
||||
hl.innerHTML=lines.map(highlight).join('\\n');
|
||||
gutter.textContent=lines.map(function(_,i){return i+1;}).join('\\n');
|
||||
}
|
||||
function emit(){ window.ReactNativeWebView.postMessage(JSON.stringify({type:'change',value:ta.value})); }
|
||||
ta.addEventListener('input',function(){render();emit();});
|
||||
ta.addEventListener('scroll',function(){gutter.scrollTop=ta.scrollTop;hl.scrollTop=ta.scrollTop;hl.scrollLeft=ta.scrollLeft;});
|
||||
ta.addEventListener('keydown',function(e){
|
||||
if(e.key==='Tab'){e.preventDefault();var s=ta.selectionStart,en=ta.selectionEnd;
|
||||
ta.value=ta.value.slice(0,s)+' '+ta.value.slice(en);ta.selectionStart=ta.selectionEnd=s+2;render();emit();}
|
||||
});
|
||||
render();
|
||||
</script></body></html>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* A self-contained WebView code editor with line numbers and lightweight syntax
|
||||
* highlighting. It runs entirely from an inline HTML document (no remote code
|
||||
* and no bundled editor assets), keeping the security surface minimal.
|
||||
*/
|
||||
export function CodeEditor({ value, onChangeText, language = 'plain', editable = true }: CodeEditorProps) {
|
||||
const { colors } = useTheme();
|
||||
// The WebView owns the text while editing, so the HTML is built from the
|
||||
// initial value only; callers remount the component (via `key`) to load a
|
||||
// different file.
|
||||
const [initialValue] = useState(value);
|
||||
const html = useMemo(
|
||||
() =>
|
||||
buildHtml(initialValue, language, editable, {
|
||||
bg: colors.codeBackground,
|
||||
fg: colors.text,
|
||||
gutter: colors.textTertiary,
|
||||
keyword: colors.primary,
|
||||
string: colors.success,
|
||||
comment: colors.textTertiary,
|
||||
number: colors.info,
|
||||
caret: colors.primary,
|
||||
}),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[language, editable, colors.codeBackground, colors.text],
|
||||
);
|
||||
|
||||
return (
|
||||
<WebView
|
||||
style={styles.webview}
|
||||
originWhitelist={['*']}
|
||||
source={{ html }}
|
||||
onMessage={(event) => {
|
||||
try {
|
||||
const payload = JSON.parse(event.nativeEvent.data) as { type: string; value?: string };
|
||||
if (payload.type === 'change' && typeof payload.value === 'string') {
|
||||
onChangeText(payload.value);
|
||||
}
|
||||
} catch {
|
||||
// Ignore malformed messages from the WebView.
|
||||
}
|
||||
}}
|
||||
keyboardDisplayRequiresUserAction={false}
|
||||
hideKeyboardAccessoryView
|
||||
setSupportMultipleWindows={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
webview: { flex: 1, backgroundColor: 'transparent' },
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
* with the theme's diff colors. `parseDiff` is pure and unit-tested.
|
||||
*/
|
||||
|
||||
import { ScrollView, StyleSheet, Text, View } from 'react-native';
|
||||
import { Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { useTheme } from '@/theme/theme-provider';
|
||||
@@ -106,7 +106,7 @@ export function parseDiff(raw: string): DiffFile[] {
|
||||
return files;
|
||||
}
|
||||
|
||||
function DiffLineRow({ line }: { line: DiffLine }) {
|
||||
function DiffLineRow({ line, onPress }: { line: DiffLine; onPress?: () => void }) {
|
||||
const { colors } = useTheme();
|
||||
const style = {
|
||||
add: { backgroundColor: colors.diffAdd, color: colors.diffAddText, sign: '+' },
|
||||
@@ -116,7 +116,7 @@ function DiffLineRow({ line }: { line: DiffLine }) {
|
||||
meta: { backgroundColor: 'transparent', color: colors.textTertiary, sign: '' },
|
||||
}[line.type];
|
||||
|
||||
return (
|
||||
const row = (
|
||||
<View style={[styles.line, { backgroundColor: style.backgroundColor }]}>
|
||||
<Text style={[styles.sign, { color: style.color }]}>{style.sign}</Text>
|
||||
<Text style={[styles.code, { color: style.color }]} selectable>
|
||||
@@ -124,6 +124,13 @@ function DiffLineRow({ line }: { line: DiffLine }) {
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
if (!onPress) return row;
|
||||
return (
|
||||
<Pressable onPress={onPress} accessibilityRole="button">
|
||||
{row}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
export interface DiffViewProps {
|
||||
@@ -131,10 +138,15 @@ export interface DiffViewProps {
|
||||
/** When set, only the matching file's hunks are rendered. */
|
||||
pathFilter?: string;
|
||||
emptyLabel: string;
|
||||
/**
|
||||
* Called with the 1-based position of a tapped line within its file's diff
|
||||
* (Gitea's `new_position`) — used to attach an inline review comment.
|
||||
*/
|
||||
onLinePress?: (filePath: string, position: number) => void;
|
||||
}
|
||||
|
||||
/** Horizontally scrollable, color-coded unified diff. Place inside a non-scroll Screen. */
|
||||
export function DiffView({ raw, pathFilter, emptyLabel }: DiffViewProps) {
|
||||
export function DiffView({ raw, pathFilter, emptyLabel, onLinePress }: DiffViewProps) {
|
||||
const files = parseDiff(raw).filter((file) => !pathFilter || file.path === pathFilter);
|
||||
|
||||
if (files.length === 0) {
|
||||
@@ -161,7 +173,13 @@ export function DiffView({ raw, pathFilter, emptyLabel }: DiffViewProps) {
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator>
|
||||
<View>
|
||||
{file.lines.map((line, index) => (
|
||||
<DiffLineRow key={index} line={line} />
|
||||
<DiffLineRow
|
||||
key={index}
|
||||
line={line}
|
||||
onPress={
|
||||
onLinePress ? () => onLinePress(file.path, index + 1) : undefined
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</ScrollView>
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Alert, StyleSheet, Switch, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { CodeEditor, languageForPath } from '@/components/git/code-editor';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
@@ -170,15 +171,13 @@ function FileEditForm({ owner, name, path, initialRef, entry, repo, branches, on
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<TextArea
|
||||
<View style={styles.editorWrap}>
|
||||
<CodeEditor
|
||||
value={draft}
|
||||
onChangeText={setDraft}
|
||||
minHeight={360}
|
||||
mono
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
testID="file-editor"
|
||||
language={languageForPath(path)}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{branchProtected ? (
|
||||
<AppText variant="caption" tone="warning">
|
||||
@@ -285,6 +284,7 @@ function FileEditForm({ owner, name, path, initialRef, entry, repo, branches, on
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
toolbar: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
|
||||
editorWrap: { height: 380, borderRadius: 10, overflow: 'hidden' },
|
||||
pathLabel: { flex: 1 },
|
||||
sectionLabel: { marginBottom: spacing.sm },
|
||||
switchRow: {
|
||||
|
||||
@@ -1,20 +1,33 @@
|
||||
import { useState } from 'react';
|
||||
import { Alert, StyleSheet, View } from 'react-native';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { DiffView } from '@/components/git/diff';
|
||||
import { Screen } from '@/components/layout/screen';
|
||||
import { AppText } from '@/components/ui/app-text';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card } from '@/components/ui/card';
|
||||
import { TextArea } from '@/components/ui/text-area';
|
||||
import { ErrorState, LoadingView } from '@/components/ui/state-views';
|
||||
import { apiErrorMessage } from '@/core/api/error-text';
|
||||
import { usePullDiff } from '@/features/issues/queries';
|
||||
import { useCreatePullReview, usePull, usePullDiff } from '@/features/issues/queries';
|
||||
import { spacing } from '@/theme/tokens';
|
||||
import type { RepositoryStackParamList } from '@/navigation/types';
|
||||
import type { ScreenProps } from '@/navigation/typing';
|
||||
|
||||
type Props = ScreenProps<RepositoryStackParamList, 'PullDiff'>;
|
||||
|
||||
/** Native unified diff for a pull request (all files, or a single `path`). */
|
||||
/** Native unified diff for a pull request (all files, or a single `path`).
|
||||
* Tapping a line opens an inline review-comment composer. */
|
||||
export function PullDiffScreen({ route }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const { owner, name, index, path } = route.params;
|
||||
const query = usePullDiff(owner, name, index);
|
||||
const pull = usePull(owner, name, index);
|
||||
const createReview = useCreatePullReview(owner, name, index);
|
||||
|
||||
const [target, setTarget] = useState<{ path: string; position: number } | null>(null);
|
||||
const [body, setBody] = useState('');
|
||||
|
||||
if (query.isPending) return <LoadingView label={t('pulls.loadingDiff')} />;
|
||||
if (query.isError) {
|
||||
@@ -28,9 +41,74 @@ export function PullDiffScreen({ route }: Props) {
|
||||
);
|
||||
}
|
||||
|
||||
const submit = () => {
|
||||
if (!target || body.trim().length === 0) return;
|
||||
createReview.mutate(
|
||||
{
|
||||
event: 'COMMENT',
|
||||
commitId: pull.data?.head?.sha,
|
||||
comments: [{ path: target.path, new_position: target.position, body: body.trim() }],
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
setTarget(null);
|
||||
setBody('');
|
||||
Alert.alert(t('pulls.inlineCommentAddedTitle'), t('pulls.inlineCommentAddedBody'));
|
||||
},
|
||||
onError: (error) => Alert.alert(t('errors.title'), apiErrorMessage(error, t)),
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen padded={false} scroll={false}>
|
||||
<DiffView raw={query.data ?? ''} pathFilter={path} emptyLabel={t('pulls.noChanges')} />
|
||||
<DiffView
|
||||
raw={query.data ?? ''}
|
||||
pathFilter={path}
|
||||
emptyLabel={t('pulls.noChanges')}
|
||||
onLinePress={(filePath, position) => {
|
||||
setTarget({ path: filePath, position });
|
||||
setBody('');
|
||||
}}
|
||||
/>
|
||||
|
||||
{target ? (
|
||||
<Card style={styles.composer}>
|
||||
<AppText variant="caption" tone="tertiary" numberOfLines={1}>
|
||||
<AppText variant="monoSmall" tone="tertiary">
|
||||
{target.path}
|
||||
</AppText>
|
||||
{` : ${target.position}`}
|
||||
</AppText>
|
||||
<TextArea
|
||||
value={body}
|
||||
onChangeText={setBody}
|
||||
placeholder={t('pulls.inlineCommentPlaceholder')}
|
||||
minHeight={72}
|
||||
autoFocus
|
||||
/>
|
||||
<View style={styles.composerActions}>
|
||||
<Button
|
||||
label={t('common.cancel')}
|
||||
variant="ghost"
|
||||
size="md"
|
||||
onPress={() => setTarget(null)}
|
||||
/>
|
||||
<Button
|
||||
label={t('pulls.inlineCommentSubmit')}
|
||||
size="md"
|
||||
loading={createReview.isPending}
|
||||
disabled={body.trim().length === 0}
|
||||
onPress={submit}
|
||||
/>
|
||||
</View>
|
||||
</Card>
|
||||
) : null}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
composer: { gap: spacing.sm, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: 'rgba(128,128,128,0.3)' },
|
||||
composerActions: { flexDirection: 'row', justifyContent: 'flex-end', gap: spacing.sm },
|
||||
});
|
||||
@@ -315,7 +315,11 @@
|
||||
"body": "Review comment",
|
||||
"placeholder": "Write your review…",
|
||||
"submit": "Submit review"
|
||||
}
|
||||
},
|
||||
"inlineCommentPlaceholder": "Comment on this line…",
|
||||
"inlineCommentSubmit": "Comment",
|
||||
"inlineCommentAddedTitle": "Comment added",
|
||||
"inlineCommentAddedBody": "Your inline review comment was posted."
|
||||
},
|
||||
"comments": {
|
||||
"title": "Comments",
|
||||
|
||||
@@ -315,7 +315,11 @@
|
||||
"body": "Review-opmerking",
|
||||
"placeholder": "Schrijf je review…",
|
||||
"submit": "Review versturen"
|
||||
}
|
||||
},
|
||||
"inlineCommentPlaceholder": "Reageer op deze regel…",
|
||||
"inlineCommentSubmit": "Reageren",
|
||||
"inlineCommentAddedTitle": "Reactie toegevoegd",
|
||||
"inlineCommentAddedBody": "Je inline review-reactie is geplaatst."
|
||||
},
|
||||
"comments": {
|
||||
"title": "Reacties",
|
||||
|
||||
Reference in new issue
Block a user