feat: add EditorGridSizePicker and EditorSelectionFrame components; implement FreeCreateView for article management; introduce ArticleSelectionOptimizeService for optimizing article selections

This commit is contained in:
2026-04-06 22:18:55 +08:00
parent 08ace0a9e0
commit 1e844704e4
20 changed files with 3033 additions and 740 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,299 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, type Component, type CSSProperties } from "vue";
type EditorActionMenuItem = {
key: string;
label: string;
icon?: Component;
danger?: boolean;
disabled?: boolean;
active?: boolean;
};
type EditorActionMenuGroup = {
key: string;
columns?: number;
items: EditorActionMenuItem[];
};
const props = defineProps<{
x: number;
y: number;
groups: EditorActionMenuGroup[];
variant?: "tile" | "inline";
minWidth?: string;
maxWidth?: string;
}>();
const emit = defineEmits<{
select: [key: string];
}>();
const menuRef = ref<HTMLElement | null>(null);
const frame = ref({
x: props.x,
y: props.y,
});
const resolvedVariant = computed(() => props.variant ?? "inline");
const menuStyle = computed<CSSProperties>(() => {
const style: CSSProperties = {
left: `${frame.value.x}px`,
top: `${frame.value.y}px`,
};
if (props.minWidth) {
style.minWidth = props.minWidth;
}
if (props.maxWidth) {
style.maxWidth = props.maxWidth;
}
return style;
});
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
function syncMenuFrame(): void {
void nextTick(() => {
const menu = menuRef.value;
if (!menu) {
return;
}
const offset = 16;
frame.value = {
x: clamp(props.x, offset, Math.max(offset, window.innerWidth - menu.offsetWidth - offset)),
y: clamp(props.y, offset, Math.max(offset, window.innerHeight - menu.offsetHeight - offset)),
};
});
}
function handleWindowResize(): void {
syncMenuFrame();
}
function handleSelect(item: EditorActionMenuItem): void {
if (item.disabled) {
return;
}
emit("select", item.key);
}
function resolveGroupStyle(group: EditorActionMenuGroup): CSSProperties {
return {
gridTemplateColumns: `repeat(${Math.max(group.columns ?? group.items.length, 1)}, minmax(0, 1fr))`,
};
}
watch(
() => ({
x: props.x,
y: props.y,
groups: props.groups,
minWidth: props.minWidth,
maxWidth: props.maxWidth,
variant: resolvedVariant.value,
}),
() => {
syncMenuFrame();
},
{
immediate: true,
deep: true,
flush: "post",
},
);
onMounted(() => {
window.addEventListener("resize", handleWindowResize);
syncMenuFrame();
});
onBeforeUnmount(() => {
window.removeEventListener("resize", handleWindowResize);
});
</script>
<template>
<Teleport to="body">
<div
ref="menuRef"
class="editor-action-menu"
:class="`editor-action-menu--${resolvedVariant}`"
:style="menuStyle"
@pointerdown.stop
@contextmenu.prevent
>
<template v-for="(group, groupIndex) in groups" :key="group.key">
<div class="editor-action-menu__group" :style="resolveGroupStyle(group)">
<button
v-for="item in group.items"
:key="item.key"
type="button"
class="editor-action-menu__action"
:class="{
'editor-action-menu__action--active': item.active,
'editor-action-menu__action--danger': item.danger,
}"
:disabled="item.disabled"
@click="handleSelect(item)"
>
<component :is="item.icon" v-if="item.icon" />
<span>{{ item.label }}</span>
</button>
</div>
<div v-if="groupIndex < groups.length - 1" class="editor-action-menu__divider"></div>
</template>
</div>
</Teleport>
</template>
<style scoped>
.editor-action-menu {
position: fixed;
z-index: 1200;
display: flex;
flex-direction: column;
}
.editor-action-menu--tile {
gap: 16px;
padding: 16px;
border: 1px solid #edf2fa;
border-radius: 16px;
background: #ffffff;
box-shadow:
0 20px 48px rgba(15, 23, 42, 0.08),
0 6px 16px rgba(15, 23, 42, 0.04);
}
.editor-action-menu--inline {
gap: 10px;
padding: 12px;
border: 1px solid #e8eef8;
border-radius: 16px;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.98) 0%, rgba(248, 251, 255, 0.98) 100%);
box-shadow:
0 20px 48px rgba(15, 23, 42, 0.1),
0 6px 18px rgba(15, 23, 42, 0.06);
backdrop-filter: blur(14px);
}
.editor-action-menu__group {
display: grid;
gap: 12px;
}
.editor-action-menu--inline .editor-action-menu__group {
gap: 10px;
}
.editor-action-menu__divider {
height: 1px;
background: #f0f3f8;
}
.editor-action-menu__action {
border: 1px solid transparent;
cursor: pointer;
transition: all 0.2s ease;
}
.editor-action-menu__action span {
line-height: 1.4;
}
.editor-action-menu__action :deep(svg) {
transition: color 0.2s ease;
}
.editor-action-menu--tile .editor-action-menu__action {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 10px;
min-height: 86px;
padding: 12px 10px;
border-radius: 12px;
background: #f7f9fa;
color: #3f4a5c;
}
.editor-action-menu--tile .editor-action-menu__action span {
font-size: 13px;
font-weight: 600;
text-align: center;
}
.editor-action-menu--tile .editor-action-menu__action :deep(svg) {
font-size: 22px;
color: #5c6b81;
}
.editor-action-menu--tile .editor-action-menu__action:hover:not(:disabled) {
background: #eff4ff;
border-color: #c2d6ff;
color: #245bdb;
}
.editor-action-menu--tile .editor-action-menu__action:hover:not(:disabled) :deep(svg) {
color: #245bdb;
}
.editor-action-menu--inline .editor-action-menu__action {
display: flex;
align-items: center;
gap: 10px;
min-height: 46px;
padding: 0 14px;
border-radius: 12px;
background: #f7f9fc;
color: #344054;
font-size: 13px;
font-weight: 600;
}
.editor-action-menu--inline .editor-action-menu__action :deep(svg) {
font-size: 18px;
color: #52607a;
}
.editor-action-menu--inline .editor-action-menu__action:hover:not(:disabled),
.editor-action-menu--inline .editor-action-menu__action--active {
border-color: #c8d8ff;
background: #edf4ff;
color: #245bdb;
transform: translateY(-1px);
}
.editor-action-menu--inline .editor-action-menu__action:hover:not(:disabled) :deep(svg),
.editor-action-menu--inline .editor-action-menu__action--active :deep(svg) {
color: #245bdb;
}
.editor-action-menu__action--danger:hover:not(:disabled) {
border-color: #ffd2cf;
background: #fff1f0;
color: #cf1322;
}
.editor-action-menu__action--danger:hover:not(:disabled) :deep(svg) {
color: #cf1322;
}
.editor-action-menu--tile .editor-action-menu__action:disabled {
opacity: 0.46;
}
.editor-action-menu__action:disabled {
cursor: not-allowed;
}
</style>
@@ -0,0 +1,586 @@
<script setup lang="ts">
import { CheckOutlined, CloseOutlined, DeleteOutlined, LoadingOutlined, RedoOutlined } from "@ant-design/icons-vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, type CSSProperties } from "vue";
type EditorAiAssistStatus = "idle" | "generating" | "completed" | "error";
const props = defineProps<{
x: number;
y: number;
width: number;
prompt: string;
status: EditorAiAssistStatus;
streaming: boolean;
hasPreview: boolean;
error: string;
title: string;
promptPlaceholder: string;
continuePlaceholder?: string;
loadingLabel: string;
errorLabel: string;
disclaimer: string;
historyLabel?: string;
regenerateLabel: string;
discardLabel: string;
applyLabel: string;
}>();
const emit = defineEmits<{
"update:prompt": [value: string];
submit: [];
close: [];
reset: [];
apply: [];
}>();
const IDLE_MAX_WIDTH = 760;
const panelRef = ref<HTMLElement | null>(null);
const promptInputRef = ref<HTMLInputElement | null>(null);
const frame = ref({
x: props.x,
y: props.y,
width: props.width,
});
const promptValue = computed({
get: () => props.prompt,
set: (value: string) => {
emit("update:prompt", value);
},
});
const resolvedContinuePlaceholder = computed(
() => props.continuePlaceholder?.trim() || props.promptPlaceholder,
);
const panelStyle = computed<CSSProperties>(() => ({
left: `${frame.value.x}px`,
top: `${frame.value.y}px`,
width: `${frame.value.width}px`,
}));
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
function syncPanelFrame(): void {
void nextTick(() => {
const panel = panelRef.value;
if (!panel) {
return;
}
const offset = 16;
const maxWidth = Math.max(240, window.innerWidth - offset * 2);
const width =
props.status === "idle"
? Math.min(props.width, maxWidth, IDLE_MAX_WIDTH)
: Math.min(props.width, maxWidth);
frame.value = {
x: clamp(props.x - width / 2, offset, Math.max(offset, window.innerWidth - width - offset)),
y: clamp(props.y, offset, Math.max(offset, window.innerHeight - panel.offsetHeight - offset)),
width,
};
});
}
function focusPromptInput(): void {
if (props.status !== "idle") {
return;
}
void nextTick(() => {
promptInputRef.value?.focus();
promptInputRef.value?.setSelectionRange(props.prompt.length, props.prompt.length);
});
}
function handleWindowResize(): void {
syncPanelFrame();
}
watch(
() => ({
x: props.x,
y: props.y,
width: props.width,
status: props.status,
hasPreview: props.hasPreview,
error: props.error,
}),
() => {
syncPanelFrame();
focusPromptInput();
},
{
immediate: true,
flush: "post",
},
);
onMounted(() => {
window.addEventListener("resize", handleWindowResize);
syncPanelFrame();
focusPromptInput();
});
onBeforeUnmount(() => {
window.removeEventListener("resize", handleWindowResize);
});
</script>
<template>
<Teleport to="body">
<div
ref="panelRef"
class="editor-ai-assist"
:style="panelStyle"
@pointerdown.stop
@contextmenu.prevent
>
<div class="editor-ai-assist__shell">
<div v-if="status === 'idle'" class="editor-ai-assist__bar">
<div class="editor-ai-assist__bar-icon">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none">
<path d="M6.75 15.25L8.78 9.78L14.25 7.75L12.22 13.22L6.75 15.25Z" stroke="url(#editor-ai-assist-gradient)" stroke-width="2" stroke-linejoin="round" />
<path d="M14.5 4.5L15.07 6.43L17 7L15.07 7.57L14.5 9.5L13.93 7.57L12 7L13.93 6.43L14.5 4.5Z" fill="url(#editor-ai-assist-gradient)" />
<path d="M18 13L18.58 14.92L20.5 15.5L18.58 16.08L18 18L17.42 16.08L15.5 15.5L17.42 14.92L18 13Z" fill="url(#editor-ai-assist-gradient)" />
<defs>
<linearGradient id="editor-ai-assist-gradient" x1="4.5" y1="4.5" x2="20.5" y2="18.5" gradientUnits="userSpaceOnUse">
<stop stop-color="#245bdb" />
<stop offset="1" stop-color="#ef5da8" />
</linearGradient>
</defs>
</svg>
</div>
<span class="editor-ai-assist__bar-label">{{ title }}</span>
<input
ref="promptInputRef"
v-model="promptValue"
type="text"
class="editor-ai-assist__bar-input"
:placeholder="promptPlaceholder"
@keydown.enter.prevent="emit('submit')"
/>
<div class="editor-ai-assist__bar-actions">
<button type="button" class="editor-ai-assist__icon-button" @click="emit('close')">
<CloseOutlined />
</button>
<span class="editor-ai-assist__divider"></span>
<button type="button" class="editor-ai-assist__send-button" @click="emit('submit')">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="22" y1="2" x2="11" y2="13"></line>
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
</svg>
</button>
</div>
</div>
<div v-else class="editor-ai-assist__result">
<div class="editor-ai-assist__result-box">
<div class="editor-ai-assist__result-content">
<slot v-if="hasPreview" name="preview"></slot>
<div v-else-if="streaming" class="editor-ai-assist__placeholder">
<LoadingOutlined />
<span>{{ loadingLabel }}</span>
</div>
<div v-else class="editor-ai-assist__placeholder editor-ai-assist__placeholder--error">
{{ error || errorLabel }}
</div>
</div>
<div class="editor-ai-assist__result-footer">
<span>{{ disclaimer }}</span>
<span class="editor-ai-assist__result-badges">
<CheckOutlined />
<span class="editor-ai-assist__thumb">👍</span>
<span class="editor-ai-assist__thumb editor-ai-assist__thumb--down">👍</span>
</span>
</div>
</div>
<div class="editor-ai-assist__toolbar">
<div class="editor-ai-assist__toolbar-head">
<button type="button" class="editor-ai-assist__back-button" @click="emit('reset')">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="19" y1="12" x2="5" y2="12"></line>
<polyline points="12 19 5 12 12 5"></polyline>
</svg>
<span>{{ title }}</span>
</button>
<div class="editor-ai-assist__history">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<polyline points="12 6 12 12 16 14"></polyline>
</svg>
<span>{{ historyLabel || "1/1" }}</span>
<button
type="button"
class="editor-ai-assist__icon-button editor-ai-assist__icon-button--close"
@click="emit('close')"
>
<CloseOutlined />
</button>
</div>
</div>
<div class="editor-ai-assist__toolbar-body">
<div class="editor-ai-assist__continue">
<input
v-model="promptValue"
type="text"
:placeholder="resolvedContinuePlaceholder"
@keydown.enter.prevent="emit('submit')"
/>
<button type="button" class="editor-ai-assist__continue-send" @click="emit('submit')">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="22" y1="2" x2="11" y2="13"></line>
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
</svg>
</button>
</div>
<div class="editor-ai-assist__toolbar-actions">
<button type="button" class="editor-ai-assist__toolbar-button" @click="emit('submit')">
<RedoOutlined />
<span>{{ regenerateLabel }}</span>
</button>
<button type="button" class="editor-ai-assist__toolbar-button" @click="emit('close')">
<DeleteOutlined />
<span>{{ discardLabel }}</span>
</button>
<button
type="button"
class="editor-ai-assist__toolbar-button editor-ai-assist__toolbar-button--primary"
@click="emit('apply')"
>
<span>{{ applyLabel }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</Teleport>
</template>
<style scoped>
.editor-ai-assist {
position: fixed;
z-index: 1300;
max-width: min(1120px, calc(100vw - 32px));
}
.editor-ai-assist__shell {
display: flex;
flex-direction: column;
}
.editor-ai-assist__bar {
display: flex;
align-items: center;
gap: 12px;
padding: 10px 16px;
border-radius: 999px;
background: #ffffff;
box-shadow:
0 4px 20px rgba(15, 23, 42, 0.08),
0 0 0 1px rgba(15, 23, 42, 0.04);
}
.editor-ai-assist__bar-icon {
display: flex;
align-items: center;
justify-content: center;
margin-right: -4px;
}
.editor-ai-assist__bar-label {
color: #101828;
font-size: 15px;
font-weight: 700;
white-space: nowrap;
}
.editor-ai-assist__bar-input {
flex: 1;
min-width: 280px;
border: none;
outline: none;
background: transparent;
color: #344054;
font-size: 14px;
}
.editor-ai-assist__bar-input::placeholder {
color: #98a2b3;
}
.editor-ai-assist__bar-actions {
display: flex;
align-items: center;
gap: 8px;
}
.editor-ai-assist__divider {
width: 1px;
height: 16px;
margin: 0 4px;
background: #eaecf0;
}
.editor-ai-assist__icon-button {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: 999px;
background: transparent;
color: #667085;
cursor: pointer;
transition: all 0.2s ease;
}
.editor-ai-assist__icon-button:hover {
background: #f2f4f7;
color: #344054;
}
.editor-ai-assist__send-button {
display: flex;
align-items: center;
justify-content: center;
width: 32px;
height: 32px;
border: none;
border-radius: 999px;
background: #245bdb;
color: #ffffff;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 2px 8px rgba(36, 91, 219, 0.28);
}
.editor-ai-assist__send-button:hover {
background: #1d4fc4;
}
.editor-ai-assist__result {
width: 100%;
overflow: hidden;
border-radius: 16px;
background: #ffffff;
box-shadow:
0 8px 32px rgba(15, 23, 42, 0.1),
0 0 0 1px rgba(15, 23, 42, 0.05);
}
.editor-ai-assist__result-box {
margin: 12px;
overflow: hidden;
border: 1px solid #eef2f6;
border-radius: 12px;
background: #f8fafc;
}
.editor-ai-assist__result-content {
min-height: 80px;
max-height: 300px;
padding: 16px;
overflow-y: auto;
color: #101828;
font-size: 15px;
line-height: 1.6;
}
.editor-ai-assist__placeholder {
display: flex;
align-items: center;
gap: 8px;
color: #667085;
}
.editor-ai-assist__placeholder--error {
color: #ef4444;
}
.editor-ai-assist__result-footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 16px;
border-top: 1px solid rgba(226, 232, 240, 0.6);
background: rgba(255, 255, 255, 0.5);
color: #94a3b8;
font-size: 12px;
}
.editor-ai-assist__result-badges {
display: inline-flex;
align-items: center;
gap: 8px;
}
.editor-ai-assist__result-badges :deep(svg) {
color: #52c41a;
}
.editor-ai-assist__thumb {
font-size: 14px;
}
.editor-ai-assist__thumb--down {
display: inline-block;
transform: scaleY(-1);
}
.editor-ai-assist__toolbar {
display: flex;
flex-direction: column;
padding: 0 16px 16px;
}
.editor-ai-assist__toolbar-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
color: #64748b;
font-size: 13px;
}
.editor-ai-assist__back-button {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 0;
border: none;
background: transparent;
color: inherit;
cursor: pointer;
font-weight: 500;
}
.editor-ai-assist__back-button:hover {
color: #334155;
}
.editor-ai-assist__history {
display: inline-flex;
align-items: center;
gap: 8px;
}
.editor-ai-assist__icon-button--close {
margin-left: 8px;
}
.editor-ai-assist__toolbar-body {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
}
.editor-ai-assist__continue {
display: flex;
flex: 1;
align-items: center;
padding: 4px 4px 4px 16px;
border: 1px solid #e2e8f0;
border-radius: 20px;
background: #f8fafc;
}
.editor-ai-assist__continue input {
flex: 1;
border: none;
outline: none;
background: transparent;
color: #334155;
font-size: 13px;
}
.editor-ai-assist__continue-send {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: 999px;
background: #e8efff;
color: #245bdb;
cursor: pointer;
}
.editor-ai-assist__toolbar-actions {
display: flex;
align-items: center;
gap: 8px;
}
.editor-ai-assist__toolbar-button {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border: none;
border-radius: 8px;
background: transparent;
color: #475569;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
}
.editor-ai-assist__toolbar-button:hover {
background: #f1f5f9;
}
.editor-ai-assist__toolbar-button--primary {
background: #245bdb;
color: #ffffff;
}
.editor-ai-assist__toolbar-button--primary:hover {
background: #1d4fc4;
}
@media (max-width: 768px) {
.editor-ai-assist {
max-width: calc(100vw - 24px);
}
.editor-ai-assist__bar {
flex-wrap: wrap;
border-radius: 24px;
}
.editor-ai-assist__bar-input {
min-width: 100%;
}
.editor-ai-assist__toolbar-body {
flex-direction: column;
align-items: stretch;
}
.editor-ai-assist__toolbar-actions {
justify-content: stretch;
flex-wrap: wrap;
}
.editor-ai-assist__toolbar-button {
justify-content: center;
flex: 1 1 calc(50% - 8px);
}
.editor-ai-assist__toolbar-button--primary {
flex-basis: 100%;
}
}
</style>
@@ -0,0 +1,245 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
const props = withDefaults(
defineProps<{
emptyLabel: string;
hint: string;
initialRows?: number;
initialCols?: number;
maxRows?: number;
maxCols?: number;
expandStep?: number;
cellSize?: number;
gap?: number;
}>(),
{
initialRows: 4,
initialCols: 10,
maxRows: 15,
maxCols: 15,
expandStep: 2,
cellSize: 22,
gap: 6,
},
);
const emit = defineEmits<{
select: [row: number, col: number];
}>();
const gridRef = ref<HTMLElement | null>(null);
const rows = ref(props.initialRows);
const cols = ref(props.initialCols);
const previewRow = ref(0);
const previewCol = ref(0);
const pointerActive = ref(false);
const gridStyle = computed(() => ({
gridTemplateColumns: `repeat(${cols.value}, ${props.cellSize}px)`,
gap: `${props.gap}px`,
}));
const cellStyle = computed(() => ({
width: `${props.cellSize}px`,
height: `${props.cellSize}px`,
}));
const cells = computed(() => {
const entries: Array<{ key: string; row: number; col: number }> = [];
for (let row = 1; row <= rows.value; row += 1) {
for (let col = 1; col <= cols.value; col += 1) {
entries.push({ key: `${row}-${col}`, row, col });
}
}
return entries;
});
const selectionLabel = computed(() => {
if (!previewRow.value || !previewCol.value) {
return props.emptyLabel;
}
return `${previewRow.value} × ${previewCol.value}`;
});
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
function ensureCapacity(row: number, col: number): void {
while (row > rows.value && rows.value < props.maxRows) {
rows.value = Math.min(props.maxRows, rows.value + props.expandStep);
}
while (col > cols.value && cols.value < props.maxCols) {
cols.value = Math.min(props.maxCols, cols.value + props.expandStep);
}
if (row === rows.value && rows.value < props.maxRows) {
rows.value = Math.min(props.maxRows, rows.value + props.expandStep);
}
if (col === cols.value && cols.value < props.maxCols) {
cols.value = Math.min(props.maxCols, cols.value + props.expandStep);
}
}
function updatePreview(row: number, col: number): void {
const nextRow = clamp(row, 1, props.maxRows);
const nextCol = clamp(col, 1, props.maxCols);
ensureCapacity(nextRow, nextCol);
previewRow.value = nextRow;
previewCol.value = nextCol;
}
function resolveSizeFromPointer(clientX: number, clientY: number): { row: number; col: number } | null {
const grid = gridRef.value;
if (!grid) {
return null;
}
const rect = grid.getBoundingClientRect();
const stepX = props.cellSize + props.gap;
const stepY = props.cellSize + props.gap;
const relativeX = clientX - rect.left;
const relativeY = clientY - rect.top;
return {
row: clamp(Math.ceil((relativeY + props.gap) / stepY), 1, props.maxRows),
col: clamp(Math.ceil((relativeX + props.gap) / stepX), 1, props.maxCols),
};
}
function beginSelection(row: number, col: number): void {
pointerActive.value = true;
updatePreview(row, col);
}
function handleWindowPointerMove(event: PointerEvent): void {
if (!pointerActive.value) {
return;
}
const nextSize = resolveSizeFromPointer(event.clientX, event.clientY);
if (!nextSize) {
return;
}
updatePreview(nextSize.row, nextSize.col);
}
function handleWindowPointerUp(): void {
if (!pointerActive.value) {
return;
}
pointerActive.value = false;
if (!previewRow.value || !previewCol.value) {
return;
}
emit("select", previewRow.value, previewCol.value);
}
onMounted(() => {
window.addEventListener("pointermove", handleWindowPointerMove);
window.addEventListener("pointerup", handleWindowPointerUp);
});
onBeforeUnmount(() => {
window.removeEventListener("pointermove", handleWindowPointerMove);
window.removeEventListener("pointerup", handleWindowPointerUp);
});
</script>
<template>
<div class="editor-grid-size-picker" @pointerdown.stop>
<div class="editor-grid-size-picker__status">{{ selectionLabel }}</div>
<div ref="gridRef" class="editor-grid-size-picker__grid" :style="gridStyle">
<button
v-for="cell in cells"
:key="cell.key"
type="button"
class="editor-grid-size-picker__cell"
:style="cellStyle"
:class="{
'editor-grid-size-picker__cell--active': cell.row <= previewRow && cell.col <= previewCol,
}"
@mouseenter="updatePreview(cell.row, cell.col)"
@focus="updatePreview(cell.row, cell.col)"
@pointerdown.prevent.stop="beginSelection(cell.row, cell.col)"
@keydown.enter.prevent="emit('select', cell.row, cell.col)"
@keydown.space.prevent="emit('select', cell.row, cell.col)"
></button>
</div>
<div class="editor-grid-size-picker__hint">{{ hint }}</div>
</div>
</template>
<style scoped>
.editor-grid-size-picker {
position: absolute;
top: calc(100% + 12px);
left: -18px;
z-index: 24;
width: max-content;
max-width: min(calc(100vw - 48px), 520px);
padding: 18px;
border: 1px solid #e3e9f4;
border-radius: 20px;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.98) 0%, rgba(248, 250, 255, 0.98) 100%);
box-shadow:
0 18px 40px rgba(15, 23, 42, 0.14),
0 2px 8px rgba(15, 23, 42, 0.06);
backdrop-filter: blur(16px);
}
.editor-grid-size-picker__status {
margin-bottom: 14px;
color: #101828;
font-size: 14px;
font-weight: 700;
text-align: center;
}
.editor-grid-size-picker__grid {
display: grid;
justify-content: start;
}
.editor-grid-size-picker__cell {
padding: 0;
border: 1px solid #d5dbe7;
border-radius: 4px;
background: #ffffff;
cursor: crosshair;
transition:
border-color 0.14s ease,
background-color 0.14s ease,
transform 0.14s ease,
box-shadow 0.14s ease;
}
.editor-grid-size-picker__cell:hover,
.editor-grid-size-picker__cell--active {
border-color: #2f6bff;
background: rgba(47, 107, 255, 0.14);
box-shadow: inset 0 0 0 1px rgba(47, 107, 255, 0.08);
}
.editor-grid-size-picker__cell:focus-visible {
outline: 2px solid rgba(47, 107, 255, 0.36);
outline-offset: 2px;
}
.editor-grid-size-picker__hint {
margin-top: 12px;
color: #667085;
font-size: 12px;
line-height: 1.4;
}
</style>
@@ -0,0 +1,105 @@
<script setup lang="ts">
import { computed } from "vue";
type SelectionHandle = "nw" | "ne" | "sw" | "se";
const props = defineProps<{
x: number;
y: number;
width: number;
height: number;
}>();
const emit = defineEmits<{
"resize-start": [event: PointerEvent, handle: SelectionHandle];
}>();
const frameStyle = computed(() => ({
left: `${props.x}px`,
top: `${props.y}px`,
width: `${props.width}px`,
height: `${props.height}px`,
}));
function handleResizeStart(event: PointerEvent, handle: SelectionHandle): void {
emit("resize-start", event, handle);
}
</script>
<template>
<div class="editor-selection-frame" :style="frameStyle">
<button
type="button"
class="editor-selection-frame__handle editor-selection-frame__handle--nw"
@pointerdown="handleResizeStart($event, 'nw')"
></button>
<button
type="button"
class="editor-selection-frame__handle editor-selection-frame__handle--ne"
@pointerdown="handleResizeStart($event, 'ne')"
></button>
<button
type="button"
class="editor-selection-frame__handle editor-selection-frame__handle--sw"
@pointerdown="handleResizeStart($event, 'sw')"
></button>
<button
type="button"
class="editor-selection-frame__handle editor-selection-frame__handle--se"
@pointerdown="handleResizeStart($event, 'se')"
></button>
</div>
</template>
<style scoped>
.editor-selection-frame {
position: absolute;
z-index: 1;
box-sizing: border-box;
border: 2px solid #2f6bff;
border-radius: 18px;
box-shadow:
0 0 0 1px rgba(255, 255, 255, 0.9),
0 14px 28px rgba(47, 107, 255, 0.12);
pointer-events: none;
}
.editor-selection-frame__handle {
position: absolute;
width: 14px;
height: 14px;
border: 2px solid #ffffff;
border-radius: 999px;
background: #2f6bff;
box-shadow: 0 4px 10px rgba(47, 107, 255, 0.28);
pointer-events: auto;
}
.editor-selection-frame__handle--nw {
top: 0;
left: 0;
cursor: nwse-resize;
transform: translate(-50%, -50%);
}
.editor-selection-frame__handle--ne {
top: 0;
right: 0;
cursor: nesw-resize;
transform: translate(50%, -50%);
}
.editor-selection-frame__handle--sw {
bottom: 0;
left: 0;
cursor: nesw-resize;
transform: translate(-50%, 50%);
}
.editor-selection-frame__handle--se {
right: 0;
bottom: 0;
cursor: nwse-resize;
transform: translate(50%, 50%);
}
</style>
+52 -4
View File
@@ -53,7 +53,7 @@ const enUS = {
articleCreation: "Article Creation", articleCreation: "Article Creation",
templates: "Templates", templates: "Templates",
custom: "Custom Generation", custom: "Custom Generation",
optimize: "Optimization", freeCreate: "Free Create",
media: "Media", media: "Media",
brandManagement: "Brand Management", brandManagement: "Brand Management",
brands: "Brand Library", brands: "Brand Library",
@@ -106,9 +106,9 @@ const enUS = {
title: "Custom Generation", title: "Custom Generation",
description: "Generate articles with custom prompt rules, instant or scheduled.", description: "Generate articles with custom prompt rules, instant or scheduled.",
}, },
optimize: { freeCreate: {
title: "Article Optimization", title: "Free Create",
description: "No matching backend APIs exist in this repository yet.", description: "Create and edit articles freely, no templates or AI generation required.",
}, },
media: { media: {
title: "Media Management", title: "Media Management",
@@ -209,8 +209,32 @@ const enUS = {
custom_generation: "Custom generation", custom_generation: "Custom generation",
instant_task: "Instant task", instant_task: "Instant task",
schedule_task: "Scheduled task", schedule_task: "Scheduled task",
free_create: "Free create",
}, },
}, },
freeCreate: {
actions: {
create: "New Article",
},
filters: {
publishStatus: "Publish Status",
keyword: "Search",
createdTime: "Created Time",
createdTimeStart: "Start",
createdTimeEnd: "End",
keywordPlaceholder: "Search by title",
},
list: {
eyebrow: "Free Create",
count: "{count} articles",
empty: "No articles yet. Click \"New Article\" to start creating.",
edit: "Edit article",
deleteConfirm: "Are you sure you want to delete this article?",
deleteSuccess: "Article deleted",
deleteError: "Failed to delete article",
},
createError: "Failed to create article",
},
templates: { templates: {
eyebrow: "Article Creation", eyebrow: "Article Creation",
actions: { actions: {
@@ -431,6 +455,30 @@ const enUS = {
resetSize: "Reset size", resetSize: "Reset size",
delete: "Delete image", delete: "Delete image",
}, },
aiOptimize: {
title: "AI Optimize",
subtitle: "Supports contiguous multi-block selections and generates a rewrite from your instruction",
originalLabel: "Selected text",
previewLabel: "Preview",
previewPlaceholder: "After you enter an instruction, the AI rewrite will stream here.",
generating: "Generating...",
streamingHint: "Building a stronger version of the selected text in real time...",
disclaimer: "AI output is for reference only. Review it before replacing the original text.",
promptLabel: "Instruction",
promptPlaceholder: "For example: make it more natural, classroom-friendly, and persuasive while keeping the facts unchanged.",
generate: "Generate",
regenerate: "Regenerate",
stop: "Stop",
replace: "Replace selection",
close: "Keep original",
messages: {
selectionRequired: "Select one block or multiple contiguous blocks of article text first.",
promptRequired: "Enter an instruction first.",
selectionChanged: "The original selection changed. Please select it again before replacing.",
empty: "There is no AI content ready to replace yet.",
failed: "AI optimization failed. Please try again later.",
},
},
messages: { messages: {
saved: "Article saved.", saved: "Article saved.",
generating: "This article is still generating. Try editing it later.", generating: "This article is still generating. Try editing it later.",
+52 -4
View File
@@ -53,7 +53,7 @@ const zhCN = {
articleCreation: "文章创作", articleCreation: "文章创作",
templates: "模版创作", templates: "模版创作",
custom: "自定义生成", custom: "自定义生成",
optimize: "文章优化", freeCreate: "自由创作",
media: "媒体管理", media: "媒体管理",
brandManagement: "品牌管理", brandManagement: "品牌管理",
brands: "品牌词库", brands: "品牌词库",
@@ -106,9 +106,9 @@ const zhCN = {
title: "自定义生成", title: "自定义生成",
description: "基于自定义 Prompt 规则灵活生成文章,支持即时与定时任务。", description: "基于自定义 Prompt 规则灵活生成文章,支持即时与定时任务。",
}, },
optimize: { freeCreate: {
title: "文章优化", title: "自由创作",
description: "当前仓库还没有匹配的后端接口,页面暂保持为设计占位。", description: "自由创建并编辑文章,无需模版或AI生成。",
}, },
media: { media: {
title: "媒体管理", title: "媒体管理",
@@ -209,8 +209,32 @@ const zhCN = {
custom_generation: "自定义生成", custom_generation: "自定义生成",
instant_task: "即时任务", instant_task: "即时任务",
schedule_task: "定时任务", schedule_task: "定时任务",
free_create: "自由创作",
}, },
}, },
freeCreate: {
actions: {
create: "新建文章",
},
filters: {
publishStatus: "发布状态",
keyword: "搜索文章",
createdTime: "创建时间",
createdTimeStart: "开始时间",
createdTimeEnd: "结束时间",
keywordPlaceholder: "请输入标题内容搜索",
},
list: {
eyebrow: "自由创作",
count: "共 {count} 篇文章",
empty: "还未创建文章,点击「新建文章」开始创作~",
edit: "编辑文章",
deleteConfirm: "确认删除这篇文章吗?",
deleteSuccess: "文章已删除",
deleteError: "删除文章失败",
},
createError: "创建文章失败",
},
templates: { templates: {
eyebrow: "Article Creation", eyebrow: "Article Creation",
actions: { actions: {
@@ -438,6 +462,30 @@ const zhCN = {
resetSize: "重置大小", resetSize: "重置大小",
delete: "删除图片", delete: "删除图片",
}, },
aiOptimize: {
title: "AI 优化",
subtitle: "支持连续多段选中,基于你的优化要求生成候选改写",
originalLabel: "当前选中文字",
previewLabel: "优化预览",
previewPlaceholder: "输入你的优化要求后,AI 会在这里实时生成候选内容。",
generating: "正在生成中...",
streamingHint: "正在根据你的要求逐步生成更合适的表达...",
disclaimer: "AI 生成内容仅供参考,请确认后再替换原文。",
promptLabel: "优化要求",
promptPlaceholder: "例如:更自然一点,适合课堂导入,保留原有信息但更有感染力。",
generate: "开始生成",
regenerate: "重新生成",
stop: "停止",
replace: "替换原文",
close: "先不替换",
messages: {
selectionRequired: "请先选中一段或连续多段需要优化的正文内容。",
promptRequired: "请先输入你的优化要求。",
selectionChanged: "原选区已变化,请重新选中后再替换。",
empty: "当前还没有可替换的 AI 内容。",
failed: "AI 优化失败,请稍后重试。",
},
},
messages: { messages: {
saved: "文章已保存", saved: "文章已保存",
generating: "文章还在生成中,请稍后再编辑。", generating: "文章还在生成中,请稍后再编辑。",
+1 -1
View File
@@ -72,7 +72,7 @@ const navSections = computed(() => [
items: [ items: [
{ key: "/articles/templates", label: t("nav.templates") }, { key: "/articles/templates", label: t("nav.templates") },
{ key: "/articles/custom", label: t("nav.custom") }, { key: "/articles/custom", label: t("nav.custom") },
{ key: "/articles/optimize", label: t("nav.optimize") }, { key: "/articles/free-create", label: t("nav.freeCreate") },
{ key: "/media", label: t("nav.media"), icon: GlobalOutlined }, { key: "/media", label: t("nav.media"), icon: GlobalOutlined },
], ],
}, },
+87 -14
View File
@@ -5,6 +5,7 @@ import type {
ArticleImageUploadResponse, ArticleImageUploadResponse,
ArticleListParams, ArticleListParams,
ArticleListResponse, ArticleListResponse,
CreateArticleRequest,
ArticleVersion, ArticleVersion,
AuthTokens, AuthTokens,
Brand, Brand,
@@ -210,6 +211,9 @@ export const articlesApi = {
list(params: ArticleListParams) { list(params: ArticleListParams) {
return apiClient.get<ArticleListResponse>("/api/tenant/articles", { params }); return apiClient.get<ArticleListResponse>("/api/tenant/articles", { params });
}, },
create(payload: CreateArticleRequest = {}) {
return apiClient.post<ArticleDetail, CreateArticleRequest>("/api/tenant/articles", payload);
},
detail(id: number) { detail(id: number) {
return apiClient.get<ArticleDetail>(`/api/tenant/articles/${id}`); return apiClient.get<ArticleDetail>(`/api/tenant/articles/${id}`);
}, },
@@ -305,6 +309,24 @@ export interface ArticleGenerationStreamEvent {
updated_at?: string; updated_at?: string;
} }
export interface ArticleSelectionOptimizeRequest {
title: string;
markdown_content: string;
selected_text: string;
instruction: string;
}
export interface ArticleSelectionOptimizeStreamEvent {
type: string;
article_id: number;
status?: string;
delta?: string;
content?: string;
error?: string;
model?: string;
done?: boolean;
}
export function isGenerationStreamEnabled(): boolean { export function isGenerationStreamEnabled(): boolean {
return generationStreamEnabled; return generationStreamEnabled;
} }
@@ -316,18 +338,65 @@ export async function subscribeArticleGeneration(
onClose?: () => void; onClose?: () => void;
}, },
signal: AbortSignal, signal: AbortSignal,
): Promise<void> {
return subscribeSSE<ArticleGenerationStreamEvent>(
`/api/tenant/articles/${articleId}/stream`,
{
method: "GET",
},
handlers,
signal,
);
}
export async function streamArticleSelectionOptimize(
articleId: number,
payload: ArticleSelectionOptimizeRequest,
handlers: {
onEvent: (event: ArticleSelectionOptimizeStreamEvent) => void;
onClose?: () => void;
},
signal: AbortSignal,
): Promise<void> {
return subscribeSSE<ArticleSelectionOptimizeStreamEvent>(
`/api/tenant/articles/${articleId}/selection-optimize/stream`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
},
handlers,
signal,
);
}
type SSEEventShape = {
type: string;
};
async function subscribeSSE<TEvent extends SSEEventShape>(
path: string,
init: RequestInit,
handlers: {
onEvent: (event: TEvent) => void;
onClose?: () => void;
},
signal: AbortSignal,
): Promise<void> { ): Promise<void> {
const accessToken = getStoredAccessToken(); const accessToken = getStoredAccessToken();
if (!accessToken) { if (!accessToken) {
throw new Error("missing access token"); throw new Error("missing access token");
} }
const response = await fetch(`${baseURL}/api/tenant/articles/${articleId}/stream`, { const requestHeaders = new Headers(init.headers);
method: "GET", requestHeaders.set("Accept", "text/event-stream");
headers: { requestHeaders.set("Authorization", `Bearer ${accessToken}`);
Accept: "text/event-stream",
Authorization: `Bearer ${accessToken}`, const response = await fetch(`${baseURL}${path}`, {
}, ...init,
headers: requestHeaders,
signal, signal,
}); });
@@ -350,11 +419,11 @@ export async function subscribeArticleGeneration(
} }
buffer += decoder.decode(value, { stream: true }); buffer += decoder.decode(value, { stream: true });
buffer = consumeSSEBuffer(buffer, handlers.onEvent); buffer = consumeSSEBuffer<TEvent>(buffer, handlers.onEvent);
} }
buffer += decoder.decode(); buffer += decoder.decode();
consumeSSEBuffer(buffer, handlers.onEvent); consumeSSEBuffer<TEvent>(buffer, handlers.onEvent);
} finally { } finally {
reader.releaseLock(); reader.releaseLock();
handlers.onClose?.(); handlers.onClose?.();
@@ -543,9 +612,9 @@ export function normalizeInputParams(
}; };
} }
function consumeSSEBuffer( function consumeSSEBuffer<TEvent extends SSEEventShape>(
buffer: string, buffer: string,
onEvent: (event: ArticleGenerationStreamEvent) => void, onEvent: (event: TEvent) => void,
): string { ): string {
let next = buffer; let next = buffer;
@@ -558,7 +627,7 @@ function consumeSSEBuffer(
const rawEvent = next.slice(0, delimiterIndex); const rawEvent = next.slice(0, delimiterIndex);
next = next.slice(delimiterIndex + 2); next = next.slice(delimiterIndex + 2);
const parsed = parseSSEEvent(rawEvent); const parsed = parseSSEEvent<TEvent>(rawEvent);
if (parsed) { if (parsed) {
onEvent(parsed); onEvent(parsed);
} }
@@ -567,7 +636,7 @@ function consumeSSEBuffer(
return next; return next;
} }
function parseSSEEvent(raw: string): ArticleGenerationStreamEvent | null { function parseSSEEvent<TEvent extends SSEEventShape>(raw: string): TEvent | null {
const lines = raw.split(/\r?\n/); const lines = raw.split(/\r?\n/);
let event = "message"; let event = "message";
const dataLines: string[] = []; const dataLines: string[] = [];
@@ -586,9 +655,13 @@ function parseSSEEvent(raw: string): ArticleGenerationStreamEvent | null {
return null; return null;
} }
const data = JSON.parse(dataLines.join("\n")) as unknown as ArticleGenerationStreamEvent; const data = JSON.parse(dataLines.join("\n")) as Record<string, unknown> | null;
if (!data || Array.isArray(data)) {
return null;
}
return { return {
...data, ...data,
type: event, type: event,
}; } as TEvent;
} }
+3
View File
@@ -54,6 +54,9 @@ export function getSourceTypeLabel(sourceType?: string | null, generationMode?:
if (sourceType === "template") { if (sourceType === "template") {
return i18n.global.t("status.sourceType.template"); return i18n.global.t("status.sourceType.template");
} }
if (sourceType === "free_create") {
return i18n.global.t("status.sourceType.free_create");
}
if (sourceType === "custom_generation") { if (sourceType === "custom_generation") {
if (generationMode === "schedule") { if (generationMode === "schedule") {
return i18n.global.t("status.sourceType.schedule_task"); return i18n.global.t("status.sourceType.schedule_task");
+1 -1
View File
@@ -69,7 +69,7 @@ const app = createApp(App);
const IconFont = createFromIconfontCN({ const IconFont = createFromIconfontCN({
// 需要替换为你自己真实项目的 js 地址,才能显示出你的 '#icon-line-global_undo'。 // 需要替换为你自己真实项目的 js 地址,才能显示出你的 '#icon-line-global_undo'。
scriptUrl: "//at.alicdn.com/t/c/font_5154382_bf9lssq7ar.js", scriptUrl: "//at.alicdn.com/t/c/font_5154382_922oh81rh1.js",
}); });
app.component("IconFont", IconFont); app.component("IconFont", IconFont);
+6 -6
View File
@@ -77,13 +77,13 @@ const router = createRouter({
}, },
}, },
{ {
path: "articles/optimize", path: "articles/free-create",
name: "articles-optimize", name: "articles-free-create",
component: () => import("@/views/FeatureStubView.vue"), component: () => import("@/views/FreeCreateView.vue"),
meta: { meta: {
titleKey: "route.optimize.title", titleKey: "route.freeCreate.title",
descriptionKey: "route.optimize.description", descriptionKey: "route.freeCreate.description",
navKey: "/articles/optimize", navKey: "/articles/free-create",
}, },
}, },
{ {
@@ -171,11 +171,30 @@ async function handlePublished(): Promise<void> {
]); ]);
} }
const isFreeCreateEmpty = computed(
() =>
detail.value?.source_type === "free_create" &&
title.value.trim() === "" &&
markdown.value.trim() === "",
);
const isFreeCreateInitiallyEmpty = computed(
() =>
detail.value?.source_type === "free_create" &&
initialTitle.value.trim() === "" &&
initialMarkdown.value.trim() === "",
);
function handleBack(): void { function handleBack(): void {
if (saveMutation.isPending.value) { if (saveMutation.isPending.value) {
return; return;
} }
if (isFreeCreateEmpty.value) {
void cleanupEmptyFreeCreate();
return;
}
if (hasChanges.value) { if (hasChanges.value) {
leaveModalOpen.value = true; leaveModalOpen.value = true;
return; return;
@@ -184,6 +203,19 @@ function handleBack(): void {
navigateBack(); navigateBack();
} }
async function cleanupEmptyFreeCreate(): Promise<void> {
try {
await articlesApi.remove(articleId.value);
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["articles"] }),
queryClient.invalidateQueries({ queryKey: ["workspace"] }),
]);
} catch {
// ignore cleanup errors
}
navigateBack();
}
function navigateBack(): void { function navigateBack(): void {
if (window.history.length > 1) { if (window.history.length > 1) {
void router.back(); void router.back();
@@ -199,6 +231,10 @@ function handleStay(): void {
function handleDiscardLeave(): void { function handleDiscardLeave(): void {
leaveModalOpen.value = false; leaveModalOpen.value = false;
if (isFreeCreateInitiallyEmpty.value) {
void cleanupEmptyFreeCreate();
return;
}
navigateBack(); navigateBack();
} }
@@ -293,6 +329,7 @@ function serializePlatformSelection(platformIds: string[]): string {
<MilkdownProvider> <MilkdownProvider>
<ArticleEditorCanvas <ArticleEditorCanvas
:key="String(articleId)" :key="String(articleId)"
:article-id="articleId"
v-model:title="title" v-model:title="title"
v-model="markdown" v-model="markdown"
:disabled="editorLocked" :disabled="editorLocked"
+477
View File
@@ -0,0 +1,477 @@
<script setup lang="ts">
import {
DeleteOutlined,
EditOutlined,
SendOutlined,
PlusOutlined,
LoadingOutlined,
} from "@ant-design/icons-vue";
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
import { message } from "ant-design-vue";
import type { ArticleListItem, ArticleListParams } from "@geo/shared-types";
import type { TableColumnsType } from "ant-design-vue";
import type { Dayjs } from "dayjs";
import { computed, onBeforeUnmount, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import PublishArticleModal from "@/components/PublishArticleModal.vue";
import { articlesApi } from "@/lib/api";
import { formatError } from "@/lib/errors";
import {
formatDateTime,
getGenerateStatusMeta,
getPublishStatusMeta,
getSourceTypeLabel,
} from "@/lib/display";
const queryClient = useQueryClient();
const router = useRouter();
const { t } = useI18n();
const publishModalOpen = ref(false);
const selectedPublishArticleId = ref<number | null>(null);
const page = ref(1);
const pageSize = ref(10);
const createdRange = ref<[Dayjs, Dayjs] | null>(null);
const draftFilters = reactive<{
publish_status?: string;
keyword?: string;
created_from?: string;
created_to?: string;
}>({
keyword: "",
});
const appliedFilters = reactive<{
publish_status?: string;
keyword?: string;
created_from?: string;
created_to?: string;
}>({
keyword: "",
});
const articleParams = computed<ArticleListParams>(() => {
const params: ArticleListParams = {
page: page.value,
page_size: pageSize.value,
source_type: "free_create",
};
if (appliedFilters.publish_status) {
params.publish_status = appliedFilters.publish_status;
}
if (appliedFilters.keyword?.trim()) {
params.keyword = appliedFilters.keyword.trim();
}
if (appliedFilters.created_from) {
params.created_from = appliedFilters.created_from;
}
if (appliedFilters.created_to) {
params.created_to = appliedFilters.created_to;
}
return params;
});
const articleListQuery = useQuery({
queryKey: computed(() => ["articles", "list", articleParams.value]),
queryFn: () => articlesApi.list(articleParams.value),
});
const deleteMutation = useMutation({
mutationFn: (articleId: number) => articlesApi.remove(articleId),
onSuccess: async () => {
message.success(t("freeCreate.list.deleteSuccess"));
await Promise.all([
queryClient.invalidateQueries({ queryKey: ["articles"] }),
queryClient.invalidateQueries({ queryKey: ["workspace"] }),
]);
},
onError: (error) => {
message.error(formatError(error) || t("freeCreate.list.deleteError"));
},
});
const createMutation = useMutation({
mutationFn: () => articlesApi.create({}),
onSuccess: (data) => {
void router.push({ name: "article-editor", params: { id: String(data.id) } });
},
onError: (error) => {
message.error(formatError(error) || t("freeCreate.createError"));
},
});
const publishStatusOptions = computed(() => [
{ label: getPublishStatusMeta("unpublished").label, value: "unpublished" },
{ label: getPublishStatusMeta("publishing").label, value: "publishing" },
{ label: getPublishStatusMeta("success").label, value: "success" },
{ label: getPublishStatusMeta("partial_success").label, value: "partial_success" },
{ label: getPublishStatusMeta("failed").label, value: "failed" },
{ label: getPublishStatusMeta("pending_review").label, value: "pending_review" },
]);
const articleColumns = computed<TableColumnsType<ArticleListItem>>(() => [
{
title: t("common.title"),
dataIndex: "title",
key: "title",
},
{
title: t("common.publishStatus"),
dataIndex: "publish_status",
key: "publish_status",
width: 128,
},
{
title: t("common.wordCount"),
dataIndex: "word_count",
key: "word_count",
width: 100,
},
{
title: t("common.actions"),
key: "actions",
width: 156,
align: "right",
},
]);
function applyFilters(): void {
page.value = 1;
appliedFilters.publish_status = draftFilters.publish_status;
appliedFilters.keyword = draftFilters.keyword?.trim() || "";
appliedFilters.created_from = createdRange.value?.[0]?.toISOString();
appliedFilters.created_to = createdRange.value?.[1]?.toISOString();
}
function resetFilters(): void {
draftFilters.publish_status = undefined;
draftFilters.keyword = "";
createdRange.value = null;
applyFilters();
}
function openEditor(article: ArticleListItem): void {
void router.push({ name: "article-editor", params: { id: String(article.id) } });
}
function openPublish(article: ArticleListItem): void {
selectedPublishArticleId.value = article.id;
publishModalOpen.value = true;
}
function canPublishArticle(status: string): boolean {
return status === "completed";
}
function handleTableChange(nextPage: number, nextPageSize: number): void {
page.value = nextPage;
pageSize.value = nextPageSize;
}
async function handleDelete(articleId: number): Promise<void> {
await deleteMutation.mutateAsync(articleId);
}
function handleCreate(): void {
createMutation.mutate();
}
</script>
<template>
<div class="free-create-view">
<section class="free-create-view__top-card">
<div class="free-create-view__header">
<div class="free-create-view__header-title">
<h2>{{ t('route.freeCreate.title') }}</h2>
<p>{{ t('route.freeCreate.description') }}</p>
</div>
<div class="free-create-view__header-actions">
<a-button type="primary" :loading="createMutation.isPending.value" @click="handleCreate">
<template #icon><PlusOutlined /></template>
{{ t("freeCreate.actions.create") }}
</a-button>
</div>
</div>
<a-divider style="margin: 0; border-color: #f0f0f0;" />
<div class="free-create-view__filters">
<div class="free-create-view__filters-inline">
<div class="free-create-view__filter-item">
<label>{{ t("freeCreate.filters.publishStatus") }}:</label>
<a-select
v-model:value="draftFilters.publish_status"
allow-clear
:options="publishStatusOptions"
:placeholder="t('common.selectPlease')"
@change="applyFilters"
/>
</div>
<div class="free-create-view__filter-item">
<label>{{ t("freeCreate.filters.createdTime") }}:</label>
<a-range-picker
v-model:value="createdRange"
allow-clear
show-time
format="YYYY-MM-DD HH:mm"
:placeholder="[
t('freeCreate.filters.createdTimeStart'),
t('freeCreate.filters.createdTimeEnd'),
]"
@change="applyFilters"
/>
</div>
<div class="free-create-view__filter-item">
<label>{{ t("freeCreate.filters.keyword") }}:</label>
<a-input-search
v-model:value="draftFilters.keyword"
:placeholder="t('freeCreate.filters.keywordPlaceholder')"
@search="applyFilters"
@pressEnter="applyFilters"
/>
</div>
<a-button @click="resetFilters" class="free-create-view__reset-btn">{{ t("common.reset") }}</a-button>
</div>
</div>
</section>
<section class="free-create-view__table-card">
<div class="free-create-view__table-head">
<div>
<p class="eyebrow">{{ t("freeCreate.list.eyebrow") }}</p>
<h3>{{ t("freeCreate.list.count", { count: articleListQuery.data.value?.total ?? 0 }) }}</h3>
</div>
<a-button type="link" @click="articleListQuery.refetch()">
{{ t("common.refresh") }}
</a-button>
</div>
<a-table
:columns="articleColumns"
:data-source="articleListQuery.data.value?.items || []"
:loading="articleListQuery.isPending.value"
row-key="id"
:pagination="{
current: page,
pageSize,
total: articleListQuery.data.value?.total || 0,
showSizeChanger: true,
onChange: handleTableChange,
onShowSizeChange: handleTableChange,
}"
>
<template #emptyText>{{ t("freeCreate.list.empty") }}</template>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'title'">
<div class="free-create-view__title-cell">
<strong>{{ record.title || t("article.untitled") }}</strong>
<span>
{{ getSourceTypeLabel(record.source_type) }} · {{ formatDateTime(record.created_at) }}
</span>
</div>
</template>
<template v-else-if="column.key === 'publish_status'">
<a-tag :color="getPublishStatusMeta(record.publish_status).color">
{{ getPublishStatusMeta(record.publish_status).label }}
</a-tag>
</template>
<template v-else-if="column.key === 'word_count'">
{{ record.word_count || "--" }}
</template>
<template v-else-if="column.key === 'actions'">
<div class="table-actions-row">
<a-tooltip
:title="canPublishArticle(record.generate_status) ? t('media.publish.title') : t('templates.list.publishDisabled')"
>
<span>
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-publish"
:disabled="!canPublishArticle(record.generate_status)"
@click="openPublish(record)"
>
<SendOutlined />
</a-button>
</span>
</a-tooltip>
<a-tooltip :title="t('freeCreate.list.edit')">
<span>
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-edit"
@click="openEditor(record)"
>
<EditOutlined />
</a-button>
</span>
</a-tooltip>
<a-popconfirm
:title="t('freeCreate.list.deleteConfirm')"
@confirm="handleDelete(record.id)"
>
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-delete"
:loading="deleteMutation.isPending.value"
:title="t('common.delete')"
>
<DeleteOutlined />
</a-button>
</a-popconfirm>
</div>
</template>
</template>
</a-table>
</section>
<PublishArticleModal
v-model:open="publishModalOpen"
:article-id="selectedPublishArticleId"
/>
</div>
</template>
<style scoped>
.free-create-view {
display: flex;
flex-direction: column;
gap: 22px;
}
.free-create-view__top-card {
background: #fff;
border: 1px solid #e6edf5;
border-radius: 12px;
overflow: hidden;
}
.free-create-view__header {
display: flex;
justify-content: space-between;
align-items: flex-start;
padding: 24px;
}
.free-create-view__header-title h2 {
margin: 0;
font-size: 20px;
font-weight: 600;
color: #1a1a1a;
line-height: 1.4;
}
.free-create-view__header-title p {
margin: 6px 0 0 0;
font-size: 13px;
color: #8c8c8c;
}
.free-create-view__header-actions {
display: flex;
gap: 12px;
}
.free-create-view__filters {
padding: 20px 24px;
}
.free-create-view__table-card {
padding: 24px;
background: #fff;
border: 1px solid #e6edf5;
border-radius: 12px;
}
.free-create-view__filters-inline {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 16px 24px;
}
.free-create-view__reset-btn {
flex-shrink: 0;
margin-left: auto;
}
.free-create-view__filter-item {
display: flex;
align-items: center;
gap: 8px;
}
.free-create-view__filter-item label {
color: #101828;
font-size: 14px;
font-weight: 500;
white-space: nowrap;
}
.free-create-view__filter-item :deep(.ant-select) {
min-width: 140px;
}
.free-create-view__filter-item :deep(.ant-picker) {
width: 320px;
}
.free-create-view__filter-item :deep(.ant-input-affix-wrapper),
.free-create-view__filter-item :deep(.ant-input-search) {
width: 240px;
}
.free-create-view__table-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
}
.free-create-view__table-head h3 {
margin: 6px 0 0;
font-size: 24px;
}
.free-create-view__title-cell {
display: flex;
flex-direction: column;
gap: 4px;
}
.free-create-view__title-cell span {
color: var(--muted);
font-size: 12px;
}
@media (max-width: 1200px) {
.free-create-view__filter-item :deep(.ant-picker) {
width: 280px;
}
}
@media (max-width: 720px) {
.free-create-view__table-head {
flex-direction: column;
align-items: stretch;
}
}
</style>
+4
View File
@@ -267,6 +267,10 @@ export interface ArticleDetail {
created_at: string; created_at: string;
} }
export interface CreateArticleRequest {
title?: string;
}
export interface UpdateArticleRequest { export interface UpdateArticleRequest {
title: string; title: string;
markdown_content: string; markdown_content: string;
+1 -1
View File
@@ -48,7 +48,7 @@ llm:
provider: ark provider: ark
base_url: https://ark.cn-beijing.volces.com/api/v3 base_url: https://ark.cn-beijing.volces.com/api/v3
api_key: "7fb6c66b-129c-4935-9617-709236c4205a" api_key: "7fb6c66b-129c-4935-9617-709236c4205a"
model: doubao-seed-2-0-lite-260215 model: doubao-seed-2-0-mini-260215 #doubao-seed-2-0-lite-260215
knowledge_url_model: doubao-seed-2-0-mini-260215 knowledge_url_model: doubao-seed-2-0-mini-260215
timeout: 2m timeout: 2m
max_output_tokens: 16000 max_output_tokens: 16000
@@ -0,0 +1,228 @@
package app
import (
"context"
"fmt"
"strings"
"time"
"unicode/utf8"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/geo-platform/tenant-api/internal/shared/auth"
"github.com/geo-platform/tenant-api/internal/shared/llm"
"github.com/geo-platform/tenant-api/internal/shared/response"
)
const (
maxOptimizeInstructionChars = 800
maxOptimizeMarkdownContextLen = 6000
minOptimizeSelectedTextRunes = 2
optimizeSelectionTimeout = 90 * time.Second
)
type ArticleSelectionOptimizeRequest struct {
Title string `json:"title"`
MarkdownContent string `json:"markdown_content"`
SelectedText string `json:"selected_text"`
Instruction string `json:"instruction"`
}
type ArticleSelectionOptimizeResult struct {
Content string `json:"content"`
Model string `json:"model"`
}
type ArticleSelectionOptimizeService struct {
pool *pgxpool.Pool
llm llm.Client
defaultMaxOutTokens int64
}
func NewArticleSelectionOptimizeService(
pool *pgxpool.Pool,
llmClient llm.Client,
defaultMaxOutTokens int64,
) *ArticleSelectionOptimizeService {
return &ArticleSelectionOptimizeService{
pool: pool,
llm: llmClient,
defaultMaxOutTokens: defaultMaxOutTokens,
}
}
func (s *ArticleSelectionOptimizeService) ValidateRequest(
ctx context.Context,
articleID int64,
req ArticleSelectionOptimizeRequest,
) error {
if err := s.validateLLM(); err != nil {
return err
}
if err := validateOptimizeSelectionPayload(req); err != nil {
return err
}
actor := auth.MustActor(ctx)
return s.ensureArticleEditable(ctx, articleID, actor.TenantID)
}
func (s *ArticleSelectionOptimizeService) OptimizeSelection(
ctx context.Context,
req ArticleSelectionOptimizeRequest,
onDelta func(string),
) (*ArticleSelectionOptimizeResult, error) {
result, err := s.llm.Generate(
ctx,
llm.GenerateRequest{
Prompt: buildOptimizeSelectionPrompt(req),
Timeout: optimizeSelectionTimeout,
MaxOutputTokens: s.resolveMaxOutputTokens(req.SelectedText),
},
onDelta,
)
if err != nil {
return nil, response.ErrInternal(50019, "article_selection_optimize_failed", err.Error())
}
content := strings.TrimSpace(result.Content)
if content == "" {
return nil, response.ErrInternal(50019, "article_selection_optimize_failed", "optimized content is empty")
}
return &ArticleSelectionOptimizeResult{
Content: content,
Model: result.Model,
}, nil
}
func (s *ArticleSelectionOptimizeService) validateLLM() error {
if err := s.llm.Validate(); err != nil {
return response.ErrServiceUnavailable(50304, "llm_unavailable", "llm provider is not configured")
}
return nil
}
func (s *ArticleSelectionOptimizeService) ensureArticleEditable(
ctx context.Context,
articleID int64,
tenantID int64,
) error {
var generateStatus string
err := s.pool.QueryRow(
ctx,
`SELECT generate_status
FROM articles
WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL`,
articleID,
tenantID,
).Scan(&generateStatus)
if err != nil {
if err == pgx.ErrNoRows {
return response.ErrNotFound(40411, "article_not_found", "article not found")
}
return response.ErrInternal(50020, "article_lookup_failed", "failed to query article state")
}
if generateStatus != "completed" {
return response.ErrConflict(40913, "article_not_optimizable", "only completed articles can be optimized")
}
return nil
}
func (s *ArticleSelectionOptimizeService) resolveMaxOutputTokens(selectedText string) int64 {
limit := s.defaultMaxOutTokens
if limit <= 0 {
limit = 1200
}
estimated := int64(utf8.RuneCountInString(strings.TrimSpace(selectedText))*4 + 240)
if estimated < 256 {
estimated = 256
}
if estimated > limit {
return limit
}
return estimated
}
func validateOptimizeSelectionPayload(req ArticleSelectionOptimizeRequest) error {
selectedText := strings.TrimSpace(req.SelectedText)
if utf8.RuneCountInString(selectedText) < minOptimizeSelectedTextRunes {
return response.ErrBadRequest(40019, "selected_text_required", "selected_text is required")
}
instruction := strings.TrimSpace(req.Instruction)
if instruction == "" {
return response.ErrBadRequest(40020, "optimize_instruction_required", "instruction is required")
}
if len([]rune(instruction)) > maxOptimizeInstructionChars {
return response.ErrBadRequest(
40021,
"optimize_instruction_too_long",
fmt.Sprintf("instruction cannot exceed %d characters", maxOptimizeInstructionChars),
)
}
return nil
}
func buildOptimizeSelectionPrompt(req ArticleSelectionOptimizeRequest) string {
title := sanitizeOptimizePromptSection(req.Title, 300)
markdownContent := sanitizeOptimizePromptSection(req.MarkdownContent, maxOptimizeMarkdownContextLen)
selectedText := sanitizeOptimizePromptSection(req.SelectedText, 2000)
instruction := sanitizeOptimizePromptSection(req.Instruction, maxOptimizeInstructionChars)
var builder strings.Builder
builder.WriteString("你是一名资深中文内容编辑。请根据用户要求,优化一段文章选中文本。\n")
builder.WriteString("请严格遵守以下规则:\n")
builder.WriteString("1. 只输出优化后的正文内容,不要输出解释、标题、引号、前后缀说明或 Markdown 代码块。\n")
builder.WriteString("2. 保持原文事实、结论、人物、时间、数字和专有名词准确,不得编造信息。\n")
builder.WriteString("3. 优先遵循用户给出的优化要求,同时让表达与整篇文章风格保持自然一致。\n")
builder.WriteString("4. 如果原文是一段话,默认输出一段话;除非用户明确要求改成其他结构。\n")
builder.WriteString("5. 不要复述“以下是优化结果”等说明性文字。\n")
if title != "" {
builder.WriteString("\n文章标题:\n")
builder.WriteString(title)
builder.WriteString("\n")
}
if markdownContent != "" {
builder.WriteString("\n文章草稿(用于参考语气和上下文,可能不是最终定稿):\n")
builder.WriteString(markdownContent)
builder.WriteString("\n")
}
builder.WriteString("\n待优化原文:\n")
builder.WriteString(selectedText)
builder.WriteString("\n")
builder.WriteString("\n用户的优化要求:\n")
builder.WriteString(instruction)
builder.WriteString("\n")
builder.WriteString("\n现在请直接输出优化后的文本。")
return builder.String()
}
func sanitizeOptimizePromptSection(value string, maxRunes int) string {
normalized := strings.TrimSpace(value)
if normalized == "" {
return ""
}
normalized = strings.ReplaceAll(normalized, "\u0000", "")
normalized = strings.ReplaceAll(normalized, "\r\n", "\n")
normalized = strings.ReplaceAll(normalized, "\r", "\n")
runes := []rune(normalized)
if maxRunes > 0 && len(runes) > maxRunes {
return strings.TrimSpace(string(runes[:maxRunes])) + "\n...[内容已截断]"
}
return normalized
}
@@ -314,6 +314,54 @@ func (s *ArticleService) Detail(ctx context.Context, id int64) (*ArticleDetailRe
return &d, nil return &d, nil
} }
type CreateArticleRequest struct {
Title string `json:"title"`
}
func (s *ArticleService) Create(ctx context.Context, req CreateArticleRequest) (*ArticleDetailResponse, error) {
actor := auth.MustActor(ctx)
title := strings.TrimSpace(req.Title)
tx, err := s.pool.Begin(ctx)
if err != nil {
return nil, response.ErrInternal(50014, "create_failed", "failed to begin article creation transaction")
}
defer tx.Rollback(ctx)
var articleID int64
if err := tx.QueryRow(ctx, `
INSERT INTO articles (tenant_id, source_type, template_id, generate_status, publish_status)
VALUES ($1, 'free_create', NULL, 'completed', 'unpublished')
RETURNING id
`, actor.TenantID).Scan(&articleID); err != nil {
return nil, response.ErrInternal(50014, "create_failed", "failed to create article")
}
sourceLabel := "自由创作"
var versionID int64
if err := tx.QueryRow(ctx, `
INSERT INTO article_versions (article_id, version_no, title, html_content, markdown_content, word_count, source_label)
VALUES ($1, 1, $2, NULL, '', 0, $3)
RETURNING id
`, articleID, title, sourceLabel).Scan(&versionID); err != nil {
return nil, response.ErrInternal(50014, "create_failed", "failed to create article version")
}
if _, err := tx.Exec(ctx, `
UPDATE articles SET current_version_id = $1, updated_at = NOW()
WHERE id = $2 AND tenant_id = $3
`, versionID, articleID, actor.TenantID); err != nil {
return nil, response.ErrInternal(50014, "create_failed", "failed to link article version")
}
if err := tx.Commit(ctx); err != nil {
return nil, response.ErrInternal(50014, "create_failed", "failed to commit article creation")
}
return s.Detail(ctx, articleID)
}
type UpdateArticleRequest struct { type UpdateArticleRequest struct {
Title string `json:"title"` Title string `json:"title"`
MarkdownContent string `json:"markdown_content"` MarkdownContent string `json:"markdown_content"`
@@ -1,10 +1,13 @@
package transport package transport
import ( import (
"context"
"encoding/json" "encoding/json"
"errors"
"io" "io"
"net/http" "net/http"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -17,6 +20,7 @@ import (
type ArticleHandler struct { type ArticleHandler struct {
svc *app.ArticleService svc *app.ArticleService
selectionOptimize *app.ArticleSelectionOptimizeService
promptGenerateSvc *app.PromptRuleGenerationService promptGenerateSvc *app.PromptRuleGenerationService
streams *stream.GenerationHub streams *stream.GenerationHub
streamEnabled bool streamEnabled bool
@@ -39,6 +43,11 @@ func NewArticleHandler(a *bootstrap.App) *ArticleHandler {
return &ArticleHandler{ return &ArticleHandler{
svc: app.NewArticleService(a.DB, a.AuditLogs, a.ObjectStorage), svc: app.NewArticleService(a.DB, a.AuditLogs, a.ObjectStorage),
selectionOptimize: app.NewArticleSelectionOptimizeService(
a.DB,
a.LLM,
a.Config.LLM.MaxOutputTokens,
),
promptGenerateSvc: app.NewPromptRuleGenerationService( promptGenerateSvc: app.NewPromptRuleGenerationService(
a.DB, a.DB,
a.LLM, a.LLM,
@@ -124,6 +133,22 @@ func (h *ArticleHandler) GenerateFromRule(c *gin.Context) {
response.SuccessWithStatus(c, http.StatusCreated, data) response.SuccessWithStatus(c, http.StatusCreated, data)
} }
func (h *ArticleHandler) Create(c *gin.Context) {
var req app.CreateArticleRequest
if err := c.ShouldBindJSON(&req); err != nil {
// Allow empty body
req = app.CreateArticleRequest{}
}
data, err := h.svc.Create(c.Request.Context(), req)
if err != nil {
response.Error(c, err)
return
}
response.SuccessWithStatus(c, http.StatusCreated, data)
}
func (h *ArticleHandler) Detail(c *gin.Context) { func (h *ArticleHandler) Detail(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64) id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil { if err != nil {
@@ -210,6 +235,111 @@ func (h *ArticleHandler) UploadImage(c *gin.Context) {
response.SuccessWithStatus(c, http.StatusCreated, data) response.SuccessWithStatus(c, http.StatusCreated, data)
} }
type articleSelectionOptimizeStreamEvent struct {
ArticleID int64 `json:"article_id"`
Status string `json:"status,omitempty"`
Delta string `json:"delta,omitempty"`
Content string `json:"content,omitempty"`
Error string `json:"error,omitempty"`
Model string `json:"model,omitempty"`
Done bool `json:"done"`
}
func (h *ArticleHandler) OptimizeSelectionStream(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
response.Error(c, response.ErrBadRequest(40001, "invalid_id", "article id must be a number"))
return
}
var req app.ArticleSelectionOptimizeRequest
if err := c.ShouldBindJSON(&req); err != nil {
response.Error(c, response.ErrBadRequest(40013, "invalid_payload", err.Error()))
return
}
if err := h.selectionOptimize.ValidateRequest(c.Request.Context(), id, req); err != nil {
response.Error(c, err)
return
}
c.Header("Content-Type", "text/event-stream")
c.Header("Cache-Control", "no-cache")
c.Header("Connection", "keep-alive")
c.Header("X-Accel-Buffering", "no")
flusher, ok := c.Writer.(http.Flusher)
if !ok {
response.Error(c, response.ErrInternal(50011, "stream_unsupported", "response writer does not support streaming"))
return
}
if err := writeSSE(c, "start", articleSelectionOptimizeStreamEvent{
ArticleID: id,
Status: "generating",
Done: false,
}); err != nil {
return
}
flusher.Flush()
streamCtx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
var streamed strings.Builder
var streamWriteErr error
result, err := h.selectionOptimize.OptimizeSelection(streamCtx, req, func(delta string) {
if delta == "" || streamWriteErr != nil {
return
}
streamed.WriteString(delta)
if writeErr := writeSSE(c, "delta", articleSelectionOptimizeStreamEvent{
ArticleID: id,
Status: "generating",
Delta: delta,
Content: streamed.String(),
Done: false,
}); writeErr != nil {
streamWriteErr = writeErr
cancel()
return
}
flusher.Flush()
})
if streamWriteErr != nil {
return
}
if err != nil {
if errors.Is(streamCtx.Err(), context.Canceled) {
return
}
appErr := response.Normalize(err)
_ = writeSSE(c, "error", articleSelectionOptimizeStreamEvent{
ArticleID: id,
Status: "failed",
Content: strings.TrimSpace(streamed.String()),
Error: resolveOptimizeStreamErrorMessage(appErr),
Done: true,
})
flusher.Flush()
return
}
if err := writeSSE(c, "completed", articleSelectionOptimizeStreamEvent{
ArticleID: id,
Status: "completed",
Content: result.Content,
Model: result.Model,
Done: true,
}); err != nil {
return
}
flusher.Flush()
}
func (h *ArticleHandler) Stream(c *gin.Context) { func (h *ArticleHandler) Stream(c *gin.Context) {
if !h.streamEnabled { if !h.streamEnabled {
response.Error(c, response.ErrNotFound(40412, "generation_stream_disabled", "generation stream is disabled")) response.Error(c, response.ErrNotFound(40412, "generation_stream_disabled", "generation stream is disabled"))
@@ -324,3 +454,16 @@ func writeSSE(c *gin.Context, event string, payload interface{}) error {
} }
return nil return nil
} }
func resolveOptimizeStreamErrorMessage(appErr *response.AppError) string {
if appErr == nil {
return "optimize selection failed"
}
if detail := strings.TrimSpace(appErr.Detail); detail != "" {
return detail
}
if message := strings.TrimSpace(appErr.Message); message != "" {
return message
}
return "optimize selection failed"
}
@@ -50,8 +50,10 @@ func RegisterRoutes(app *bootstrap.App) {
articles := protected.Group("/tenant/articles") articles := protected.Group("/tenant/articles")
artHandler := NewArticleHandler(app) artHandler := NewArticleHandler(app)
articles.GET("", artHandler.List) articles.GET("", artHandler.List)
articles.POST("", artHandler.Create)
articles.POST("/generate-from-rule", artHandler.GenerateFromRule) articles.POST("/generate-from-rule", artHandler.GenerateFromRule)
articles.POST("/:id/images", artHandler.UploadImage) articles.POST("/:id/images", artHandler.UploadImage)
articles.POST("/:id/selection-optimize/stream", artHandler.OptimizeSelectionStream)
articles.GET("/:id", artHandler.Detail) articles.GET("/:id", artHandler.Detail)
articles.PUT("/:id", artHandler.Update) articles.PUT("/:id", artHandler.Update)
articles.GET("/:id/stream", artHandler.Stream) articles.GET("/:id/stream", artHandler.Stream)