fix(*): 质量检查与版本发布 - 修复格式门禁和创作灵感兼容导出并发布 v1.6.2

This commit is contained in:
ddcat666 committed 2026-10-08 20:43:15 +08:00
1 parent 04689257d2
commit 9174aae013
86 files changed
+22711 -634

No files matched your search

+6
View File
@@ -1,5 +1,11 @@
# CHANGELOG # CHANGELOG
## v1.6.2
- 优化前后端模块实现,统一图片、视频、流式响应和画布节点处理边界。
- 完善画布节点缩放、素材处理和协议聚合,补充几何、响应流与来源审计合同测试。
- 修复 Quality checks 的后端 Go 格式检查失败,统一提交内容通过 gofmt 校验。
## v1.6.1 ## v1.6.1
- 3D 预演台全面重构:统一工作台布局与深色视觉,新增摆场 / 姿态 / 动画 / 摄影机四种工作模式,时间轴、关键帧与 Auto Key 只在动画模式开放,渲染视图按模式过滤。 - 3D 预演台全面重构:统一工作台布局与深色视觉,新增摆场 / 姿态 / 动画 / 摄影机四种工作模式,时间轴、关键帧与 Auto Key 只在动画模式开放,渲染视图按模式过滤。
+1 -1
View File
@@ -1 +1 @@
v1.6.1 v1.6.2
@@ -2,12 +2,12 @@ package app
import ( import (
"errors" "errors"
"yingce/backend/internal/model"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
"time" "time"
"yingce/backend/internal/model"
) )
func TestCanvasHistoryProtectsMediaAndDeletionWorker(t *testing.T) { func TestCanvasHistoryProtectsMediaAndDeletionWorker(t *testing.T) {
+1 -1
View File
@@ -2,9 +2,9 @@ package app
import ( import (
"errors" "errors"
"net/http"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
"net/http"
) )
type ChannelOrderItem struct { type ChannelOrderItem struct {
+1 -1
View File
@@ -1,8 +1,8 @@
package app package app
import ( import (
"yingce/backend/internal/model"
"testing" "testing"
"yingce/backend/internal/model"
) )
func TestVisualChannelOrderAtomicSnapshotAndPermissions(t *testing.T) { func TestVisualChannelOrderAtomicSnapshotAndPermissions(t *testing.T) {
@@ -1,8 +1,8 @@
package app package app
import ( import (
"yingce/backend/internal/canvas/contract"
"strings" "strings"
"yingce/backend/internal/canvas/contract"
) )
// cloudAgentGenerationSpec 将 Agent 参数和已解析素材转换为画布生成合同。 // cloudAgentGenerationSpec 将 Agent 参数和已解析素材转换为画布生成合同。
+1 -1
View File
@@ -4,10 +4,10 @@ import (
"context" "context"
"crypto/rand" "crypto/rand"
"fmt" "fmt"
"math/big"
"yingce/backend/internal/auth" "yingce/backend/internal/auth"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/sms" "yingce/backend/internal/sms"
"math/big"
) )
type SMSChannelRequest = sms.ChannelRequest type SMSChannelRequest = sms.ChannelRequest
@@ -2,9 +2,9 @@ package app
import ( import (
"context" "context"
"yingce/backend/internal/platform"
"testing" "testing"
"time" "time"
"yingce/backend/internal/platform"
) )
func TestRequestRetryAfterMatchesWindow(t *testing.T) { func TestRequestRetryAfterMatchesWindow(t *testing.T) {
+1 -1
View File
@@ -1,9 +1,9 @@
package app package app
import ( import (
"strings"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/tools" "yingce/backend/internal/tools"
"strings"
) )
type ( type (
+1 -1
View File
@@ -1,9 +1,9 @@
package app package app
import ( import (
"yingce/backend/internal/model"
"strings" "strings"
"testing" "testing"
"yingce/backend/internal/model"
) )
func TestToolPreviewOwnershipAndResourceDeletionGuard(t *testing.T) { func TestToolPreviewOwnershipAndResourceDeletionGuard(t *testing.T) {
+2 -2
View File
@@ -5,13 +5,13 @@ import (
"crypto/sha256" "crypto/sha256"
"encoding/hex" "encoding/hex"
"errors" "errors"
"yingce/backend/internal/kernel"
"yingce/backend/internal/repository"
"log" "log"
"net/mail" "net/mail"
"regexp" "regexp"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/repository"
"yingce/backend/internal/model" "yingce/backend/internal/model"
+1 -1
View File
@@ -9,7 +9,6 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"log" "log"
"math/big" "math/big"
"mime" "mime"
@@ -19,6 +18,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
+1 -1
View File
@@ -4,12 +4,12 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/outbound" "yingce/backend/internal/outbound"
+1 -1
View File
@@ -4,12 +4,12 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"math" "math"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"github.com/google/uuid" "github.com/google/uuid"
) )
+1 -1
View File
@@ -7,13 +7,13 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"regexp" "regexp"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/outbound" "yingce/backend/internal/outbound"
+1 -1
View File
@@ -3,10 +3,10 @@ package auth
import ( import (
"crypto/hmac" "crypto/hmac"
"errors" "errors"
"yingce/backend/internal/kernel"
"log" "log"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
+1 -1
View File
@@ -3,10 +3,10 @@ package auth
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"yingce/backend/internal/kernel"
"strings" "strings"
"testing" "testing"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
+1 -1
View File
@@ -4,12 +4,12 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/outbound" "yingce/backend/internal/outbound"
) )
+1 -1
View File
@@ -4,12 +4,12 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"math" "math"
"net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"github.com/google/uuid" "github.com/google/uuid"
) )
+2 -2
View File
@@ -9,12 +9,12 @@ import (
"errors" "errors"
"fmt" "fmt"
"gorm.io/gorm" "gorm.io/gorm"
"strings"
"time"
"yingce/backend/internal/kernel" "yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
"yingce/backend/internal/sms" "yingce/backend/internal/sms"
"strings"
"time"
) )
type VerificationRequest struct { type VerificationRequest struct {
@@ -2,11 +2,11 @@ package canvas
import ( import (
"encoding/json" "encoding/json"
"yingce/backend/internal/assets"
"yingce/backend/internal/kernel"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"yingce/backend/internal/assets"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
) )
@@ -5,10 +5,10 @@ import (
"errors" "errors"
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
"yingce/backend/internal/repository"
"net/http" "net/http"
"path/filepath" "path/filepath"
"testing" "testing"
"yingce/backend/internal/repository"
"yingce/backend/internal/kernel" "yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
+2 -2
View File
@@ -8,11 +8,11 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/assets"
"yingce/backend/internal/kernel"
"io" "io"
"strings" "strings"
"time" "time"
"yingce/backend/internal/assets"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
+1 -1
View File
@@ -2,9 +2,9 @@ package canvas
import ( import (
"encoding/json" "encoding/json"
"yingce/backend/internal/assets"
"strings" "strings"
"testing" "testing"
"yingce/backend/internal/assets"
"yingce/backend/internal/model" "yingce/backend/internal/model"
) )
@@ -3,9 +3,9 @@ package canvas
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"yingce/backend/internal/kernel"
"math" "math"
"strings" "strings"
"yingce/backend/internal/kernel"
) )
var userAssetKinds = map[string]struct{}{ var userAssetKinds = map[string]struct{}{
+1 -1
View File
@@ -3,11 +3,11 @@ package canvas
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"yingce/backend/internal/kernel"
"net/http" "net/http"
"strings" "strings"
"time" "time"
"unicode/utf8" "unicode/utf8"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
+1 -1
View File
@@ -2,9 +2,9 @@ package canvas
import ( import (
"encoding/json" "encoding/json"
"yingce/backend/internal/kernel"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
) )
func (s *Service) UserAssetsByIDs(userID string, ids []string) ([]json.RawMessage, error) { func (s *Service) UserAssetsByIDs(userID string, ids []string) ([]json.RawMessage, error) {
@@ -3,8 +3,8 @@ package database
import ( import (
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
"yingce/backend/internal/model"
"testing" "testing"
"yingce/backend/internal/model"
) )
func TestCreationMigrationKeepsLegacyTasksNullableAndEnforcesSubmissionUnique(t *testing.T) { func TestCreationMigrationKeepsLegacyTasksNullableAndEnforcesSubmissionUnique(t *testing.T) {
@@ -3,9 +3,9 @@ package database
import ( import (
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
"yingce/backend/internal/model"
"path/filepath" "path/filepath"
"testing" "testing"
"yingce/backend/internal/model"
) )
func TestSkillCurationRootsMigration(t *testing.T) { func TestSkillCurationRootsMigration(t *testing.T) {
@@ -3,9 +3,9 @@ package database
import ( import (
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
"yingce/backend/internal/model"
"path/filepath" "path/filepath"
"testing" "testing"
"yingce/backend/internal/model"
) )
func TestSkillCurationUpgradeAndRollback(t *testing.T) { func TestSkillCurationUpgradeAndRollback(t *testing.T) {
@@ -1,8 +1,8 @@
package database package database
import ( import (
"yingce/backend/internal/model"
"testing" "testing"
"yingce/backend/internal/model"
) )
func TestTaskMediaRecoveryMigrationPreservesHistoricalTasks(t *testing.T) { func TestTaskMediaRecoveryMigrationPreservesHistoricalTasks(t *testing.T) {
+1 -1
View File
@@ -2,8 +2,8 @@ package handler
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"yingce/backend/internal/service"
"net/http" "net/http"
"yingce/backend/internal/service"
) )
func registerChannelOrderRoutes(r *gin.RouterGroup, svc *service.Service) { func registerChannelOrderRoutes(r *gin.RouterGroup, svc *service.Service) {
+1 -1
View File
@@ -2,8 +2,8 @@ package handler
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"yingce/backend/internal/service"
"net/http" "net/http"
"yingce/backend/internal/service"
) )
func RegisterCreationRoutes(r *gin.RouterGroup, svc *service.Service) { func RegisterCreationRoutes(r *gin.RouterGroup, svc *service.Service) {
+2 -2
View File
@@ -2,10 +2,10 @@ package handler
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"yingce/backend/internal/model"
"yingce/backend/internal/service"
"net/http" "net/http"
"time" "time"
"yingce/backend/internal/model"
"yingce/backend/internal/service"
) )
func registerNotificationRoutes(r *gin.RouterGroup, svc *service.Service) { func registerNotificationRoutes(r *gin.RouterGroup, svc *service.Service) {
+1 -1
View File
@@ -3,9 +3,9 @@ package handler
import ( import (
"encoding/json" "encoding/json"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"yingce/backend/internal/service"
"io" "io"
"net/http" "net/http"
"yingce/backend/internal/service"
) )
func registerSkillCurationRoutes(r *gin.RouterGroup, svc *service.Service) { func registerSkillCurationRoutes(r *gin.RouterGroup, svc *service.Service) {
@@ -4,15 +4,15 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"gorm.io/driver/sqlite" "gorm.io/driver/sqlite"
"gorm.io/gorm" "gorm.io/gorm"
"yingce/backend/internal/auth"
"yingce/backend/internal/model"
"yingce/backend/internal/repository"
"yingce/backend/internal/service"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strings" "strings"
"testing" "testing"
"time" "time"
"yingce/backend/internal/auth"
"yingce/backend/internal/model"
"yingce/backend/internal/repository"
"yingce/backend/internal/service"
) )
func TestSkillCurationHTTP(t *testing.T) { func TestSkillCurationHTTP(t *testing.T) {
@@ -2,15 +2,15 @@ package handler
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http"
"net/http/httptest"
"testing"
"time"
"yingce/backend/internal/auth" "yingce/backend/internal/auth"
"yingce/backend/internal/database" "yingce/backend/internal/database"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
"yingce/backend/internal/service" "yingce/backend/internal/service"
"net/http"
"net/http/httptest"
"testing"
"time"
) )
func TestTaskMediaRecoveryHTTPAuthenticationAndOwnership(t *testing.T) { func TestTaskMediaRecoveryHTTPAuthenticationAndOwnership(t *testing.T) {
@@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"io" "io"
"mime" "mime"
"mime/multipart" "mime/multipart"
@@ -12,6 +11,7 @@ import (
"net/url" "net/url"
"strings" "strings"
"unicode/utf8" "unicode/utf8"
"yingce/backend/internal/kernel"
) )
const maxAPICallPayloadBytes = 128 << 10 const maxAPICallPayloadBytes = 128 << 10
+1 -1
View File
@@ -4,7 +4,6 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"log" "log"
"math/rand/v2" "math/rand/v2"
"os" "os"
@@ -12,6 +11,7 @@ import (
"strings" "strings"
"sync" "sync"
"time" "time"
"yingce/backend/internal/kernel"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
) )
@@ -3,9 +3,9 @@ package platform
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"yingce/backend/internal/kernel"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
+1 -1
View File
@@ -5,9 +5,9 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
) )
+1 -1
View File
@@ -5,11 +5,11 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"regexp" "regexp"
"sort" "sort"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
+1 -1
View File
@@ -3,9 +3,9 @@ package prompts
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"yingce/backend/internal/kernel"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
) )
+1 -1
View File
@@ -4,9 +4,9 @@ import (
"errors" "errors"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
"yingce/backend/internal/model"
"slices" "slices"
"time" "time"
"yingce/backend/internal/model"
) )
var ErrChannelOrderChanged = errors.New("列表已发生变化,请重新打开排序后再保存") var ErrChannelOrderChanged = errors.New("列表已发生变化,请重新打开排序后再保存")
+1 -1
View File
@@ -4,8 +4,8 @@ import (
"errors" "errors"
"gorm.io/gorm" "gorm.io/gorm"
"gorm.io/gorm/clause" "gorm.io/gorm/clause"
"yingce/backend/internal/model"
"time" "time"
"yingce/backend/internal/model"
) )
var ErrNotificationLimit = errors.New("通知发送次数已达上限,请稍后再试") var ErrNotificationLimit = errors.New("通知发送次数已达上限,请稍后再试")
+2 -2
View File
@@ -1,11 +1,11 @@
package skills package skills
import ( import (
"strings"
"unicode/utf8"
"yingce/backend/internal/kernel" "yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
"strings"
"unicode/utf8"
) )
type SkillCuration = repository.SkillCuration type SkillCuration = repository.SkillCuration
@@ -1,11 +1,11 @@
package skills package skills
import ( import (
"strings"
"unicode/utf8"
"yingce/backend/internal/kernel" "yingce/backend/internal/kernel"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
"strings"
"unicode/utf8"
) )
func activeCurationRoot(state *SkillCuration, id string) bool { func activeCurationRoot(state *SkillCuration, id string) bool {
@@ -2,10 +2,10 @@ package skills
import ( import (
"encoding/json" "encoding/json"
"yingce/backend/internal/model"
"yingce/backend/internal/repository"
"reflect" "reflect"
"testing" "testing"
"yingce/backend/internal/model"
"yingce/backend/internal/repository"
) )
func TestSkillCurationRootManagementAvailable(t *testing.T) { func TestSkillCurationRootManagementAvailable(t *testing.T) {
@@ -3,9 +3,9 @@ package skills
import ( import (
"encoding/json" "encoding/json"
"gorm.io/gorm" "gorm.io/gorm"
"yingce/backend/internal/model"
"reflect" "reflect"
"testing" "testing"
"yingce/backend/internal/model"
) )
func TestSkillCurationManagementAvailable(t *testing.T) { func TestSkillCurationManagementAvailable(t *testing.T) {
+2 -2
View File
@@ -13,8 +13,6 @@ import (
qiniuAuth "github.com/qiniu/go-sdk/v7/auth" qiniuAuth "github.com/qiniu/go-sdk/v7/auth"
qiniuStorage "github.com/qiniu/go-sdk/v7/storage" qiniuStorage "github.com/qiniu/go-sdk/v7/storage"
cos "github.com/tencentyun/cos-go-sdk-v5" cos "github.com/tencentyun/cos-go-sdk-v5"
"yingce/backend/internal/kernel"
"yingce/backend/internal/outbound"
"io" "io"
"mime" "mime"
"net" "net"
@@ -24,6 +22,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/outbound"
) )
func transferTimeout(setting Settings) time.Duration { func transferTimeout(setting Settings) time.Duration {
+2 -2
View File
@@ -5,13 +5,13 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"yingce/backend/internal/kernel"
"yingce/backend/internal/outbound"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"time" "time"
"yingce/backend/internal/kernel"
"yingce/backend/internal/outbound"
"github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awserr"
@@ -1,13 +1,13 @@
package tools_test package tools_test
import ( import (
"path/filepath"
"strings"
"testing"
"yingce/backend/internal/database" "yingce/backend/internal/database"
"yingce/backend/internal/model" "yingce/backend/internal/model"
"yingce/backend/internal/repository" "yingce/backend/internal/repository"
"yingce/backend/internal/tools" "yingce/backend/internal/tools"
"path/filepath"
"strings"
"testing"
) )
func TestToolsVisibilityTokensSeedAndReferences(t *testing.T) { func TestToolsVisibilityTokensSeedAndReferences(t *testing.T) {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+100 -100
View File
@@ -1,102 +1,102 @@
{ {
"generatedAt": "2026-10-08T05:02:18.039Z", "generatedAt": "2026-10-08T05:02:18.039Z",
"sources": { "sources": {
"seedance": { "seedance": {
"revision": "487c166e2f09487016452b90fec5e19a470af883", "revision": "487c166e2f09487016452b90fec5e19a470af883",
"count": 767, "count": 767,
"categories": { "categories": {
"handheld-ugc-vlog": "手持 UGC Vlog", "handheld-ugc-vlog": "手持 UGC Vlog",
"anime-style-lock": "动漫风格锁定", "anime-style-lock": "动漫风格锁定",
"meme-comedy": "梗图喜剧", "meme-comedy": "梗图喜剧",
"combat-choreography": "打斗编排", "combat-choreography": "打斗编排",
"storyboard-grid-to-video": "分镜表转视频", "storyboard-grid-to-video": "分镜表转视频",
"character-reference-lock": "角色一致性", "character-reference-lock": "角色一致性",
"time-freeze-rewind": "时间冻结与倒放", "time-freeze-rewind": "时间冻结与倒放",
"cinematic-narrative-short": "电影感叙事短片", "cinematic-narrative-short": "电影感叙事短片",
"car-vehicle": "汽车与载具", "car-vehicle": "汽车与载具",
"sports-extreme": "运动极限", "sports-extreme": "运动极限",
"travel-city-walk": "旅行城市漫步", "travel-city-walk": "旅行城市漫步",
"process-transformation-montage": "过程变身蒙太奇", "process-transformation-montage": "过程变身蒙太奇",
"ugc-creator-review": "达人测评", "ugc-creator-review": "达人测评",
"fashion-lookbook": "时尚造型册", "fashion-lookbook": "时尚造型册",
"pet-animal": "宠物与动物", "pet-animal": "宠物与动物",
"3d-cartoon": "3D 卡通", "3d-cartoon": "3D 卡通",
"timeline-shot-script": "时间轴分镜脚本", "timeline-shot-script": "时间轴分镜脚本",
"product-commercial-shotlist": "产品广告分镜", "product-commercial-shotlist": "产品广告分镜",
"stop-motion-cadence": "定格动画节奏", "stop-motion-cadence": "定格动画节奏",
"epic-fantasy-scifi": "史诗奇幻科幻", "epic-fantasy-scifi": "史诗奇幻科幻",
"dialogue-performance-beats": "对白表演节拍", "dialogue-performance-beats": "对白表演节拍",
"music-beat-sync-mv": "音乐卡点 MV", "music-beat-sync-mv": "音乐卡点 MV",
"horror-suspense": "恐怖悬疑", "horror-suspense": "恐怖悬疑",
"pov-continuous-take": "POV 长镜头", "pov-continuous-take": "POV 长镜头",
"game-ui-livestream": "游戏 UI 直播", "game-ui-livestream": "游戏 UI 直播",
"food-asmr": "美食 ASMR", "food-asmr": "美食 ASMR",
"retro-found-footage": "复古伪纪录" "retro-found-footage": "复古伪纪录"
} }
}, },
"haohaoxue": { "haohaoxue": {
"revision": "2026-10-08", "revision": "2026-10-08",
"count": 297, "count": 297,
"categories": { "categories": {
"poster": "海报设计", "poster": "海报设计",
"portrait": "人像摄影", "portrait": "人像摄影",
"illustration": "插画创作", "illustration": "插画创作",
"product": "产品拍摄", "product": "产品拍摄",
"anime": "动漫风格", "anime": "动漫风格",
"3d": "3D 渲染", "3d": "3D 渲染",
"japan": "日式美学", "japan": "日式美学",
"brand": "品牌设计", "brand": "品牌设计",
"fashion": "时尚编辑", "fashion": "时尚编辑",
"social": "社交媒体", "social": "社交媒体",
"other": "其他" "other": "其他"
} }
}, },
"youmind": { "youmind": {
"revision": "nano-banana@99bf4689 + gpt-image-2@3cc3f596", "revision": "nano-banana@99bf4689 + gpt-image-2@3cc3f596",
"count": 255, "count": 255,
"categories": { "categories": {
"profile-avatar": "个人资料 / 头像", "profile-avatar": "个人资料 / 头像",
"social-media-post": "社交媒体帖子", "social-media-post": "社交媒体帖子",
"infographic-edu-visual": "信息图 / 教育视觉图", "infographic-edu-visual": "信息图 / 教育视觉图",
"youtube-thumbnail": "YouTube 缩略图", "youtube-thumbnail": "YouTube 缩略图",
"comic-storyboard": "漫画 / 故事板", "comic-storyboard": "漫画 / 故事板",
"product-marketing": "产品营销", "product-marketing": "产品营销",
"ecommerce-main-image": "电商主图", "ecommerce-main-image": "电商主图",
"game-asset": "游戏素材", "game-asset": "游戏素材",
"poster-flyer": "海报 / 传单", "poster-flyer": "海报 / 传单",
"app-web-design": "App / 网页设计", "app-web-design": "App / 网页设计",
"photography": "摄影", "photography": "摄影",
"cinematic-film-still": "电影 / 电影剧照", "cinematic-film-still": "电影 / 电影剧照",
"anime-manga": "动漫 / 漫画", "anime-manga": "动漫 / 漫画",
"illustration": "插画", "illustration": "插画",
"sketch-line-art": "草图 / 线稿", "sketch-line-art": "草图 / 线稿",
"comic-graphic-novel": "漫画 / 图画小说", "comic-graphic-novel": "漫画 / 图画小说",
"3d-render": "3D 渲染", "3d-render": "3D 渲染",
"chibi-q-style": "Q 版 / Q 萌风", "chibi-q-style": "Q 版 / Q 萌风",
"isometric": "等距", "isometric": "等距",
"pixel-art": "像素艺术", "pixel-art": "像素艺术",
"oil-painting": "油画", "oil-painting": "油画",
"watercolor": "水彩画", "watercolor": "水彩画",
"ink-chinese-style": "水墨 / 中国风", "ink-chinese-style": "水墨 / 中国风",
"retro-vintage": "复古 / 怀旧", "retro-vintage": "复古 / 怀旧",
"cyberpunk-sci-fi": "赛博朋克 / 科幻", "cyberpunk-sci-fi": "赛博朋克 / 科幻",
"minimalism": "极简主义", "minimalism": "极简主义",
"portrait-selfie": "人像 / 自拍", "portrait-selfie": "人像 / 自拍",
"influencer-model": "网红 / 模特", "influencer-model": "网红 / 模特",
"character": "角色", "character": "角色",
"group-couple": "团体 / 情侣", "group-couple": "团体 / 情侣",
"product": "产品", "product": "产品",
"food-drink": "食品 / 饮料", "food-drink": "食品 / 饮料",
"fashion-item": "时尚单品", "fashion-item": "时尚单品",
"animal-creature": "动物 / 生物", "animal-creature": "动物 / 生物",
"vehicle": "车辆", "vehicle": "车辆",
"architecture-interior": "建筑 / 室内设计", "architecture-interior": "建筑 / 室内设计",
"landscape-nature": "风景 / 自然", "landscape-nature": "风景 / 自然",
"cityscape-street": "城市风光 / 街道", "cityscape-street": "城市风光 / 街道",
"diagram-chart": "图表", "diagram-chart": "图表",
"text-typography": "文本 / 排版", "text-typography": "文本 / 排版",
"abstract-background": "摘要 / 背景" "abstract-background": "摘要 / 背景"
} }
}
} }
} }
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+9 -13
View File
@@ -49,9 +49,7 @@ const THUMB_DIR = "inspiration-thumbs";
* 上游封面不可用的条目:封面本身是影片片头白板,画面上只有一个白底和 "MUDA / FILM 01", * 上游封面不可用的条目:封面本身是影片片头白板,画面上只有一个白底和 "MUDA / FILM 01",
* 放在画廊里就是一块空白。清单按 slug 写死,重新同步不会把它带回来。 * 放在画廊里就是一块空白。清单按 slug 写死,重新同步不会把它带回来。
*/ */
const EXCLUDED_SEEDANCE_SLUGS = new Set([ const EXCLUDED_SEEDANCE_SLUGS = new Set(["seedance-make-a-modern-slick-and-punchy-video-for-a-modern-startup-that-works-on-infere-07ba4673539c"]);
"seedance-make-a-modern-slick-and-punchy-video-for-a-modern-startup-that-works-on-infere-07ba4673539c",
]);
/** /**
* 上游模板分类的中文标签。id 来自 awesome-seedance 的 data/case-taxonomy.json, * 上游模板分类的中文标签。id 来自 awesome-seedance 的 data/case-taxonomy.json,
@@ -131,7 +129,9 @@ function clip(value, limit) {
} }
function sanitizeFileName(value) { function sanitizeFileName(value) {
return String(value).replace(/[^a-zA-Z0-9._-]/g, "-").slice(0, 90); return String(value)
.replace(/[^a-zA-Z0-9._-]/g, "-")
.slice(0, 90);
} }
async function fetchText(url, { accept } = {}) { async function fetchText(url, { accept } = {}) {
@@ -373,7 +373,9 @@ function renderSourceRevisions(revisions) {
// 各来源同步时的上游版本号,供灵感页与画廊署名展示。 // 各来源同步时的上游版本号,供灵感页与画廊署名展示。
export const HIGHLIGHT_REVISIONS = { export const HIGHLIGHT_REVISIONS = {
${Object.entries(revisions).map(([name, value]) => ` ${name}: ${JSON.stringify(value)},`).join("\n")} ${Object.entries(revisions)
.map(([name, value]) => ` ${name}: ${JSON.stringify(value)},`)
.join("\n")}
}; };
`; `;
} }
@@ -533,11 +535,7 @@ async function main() {
pruned += pruneOrphanThumbs(pipeline.name, thumbNames); pruned += pruneOrphanThumbs(pipeline.name, thumbNames);
highlights[pipeline.name] = thumbed; highlights[pipeline.name] = thumbed;
writeFileSync( writeFileSync(join(PUBLIC_DIR, pipeline.file), JSON.stringify({ source: pipeline.name, revision: loaded.revision, count: entries.length, categories: loaded.categories ?? {}, entries: entries.map(toCatalogEntry) }), "utf8");
join(PUBLIC_DIR, pipeline.file),
JSON.stringify({ source: pipeline.name, revision: loaded.revision, count: entries.length, categories: loaded.categories ?? {}, entries: entries.map(toCatalogEntry) }),
"utf8",
);
console.log(`${pipeline.name.padEnd(12)}: ${loaded.note} → 入库 ${entries.length} 条,本地缩略图 ${thumbed.length} 张`); console.log(`${pipeline.name.padEnd(12)}: ${loaded.note} → 入库 ${entries.length} 条,本地缩略图 ${thumbed.length} 张`);
} }
@@ -547,9 +545,7 @@ async function main() {
const manifest = { const manifest = {
generatedAt: new Date().toISOString(), generatedAt: new Date().toISOString(),
sources: Object.fromEntries( sources: Object.fromEntries(Object.entries(revisions).map(([name, revision]) => [name, { revision, count: counts[name], categories: categoriesBySource[name] ?? {} }])),
Object.entries(revisions).map(([name, revision]) => [name, { revision, count: counts[name], categories: categoriesBySource[name] ?? {} }]),
),
}; };
writeFileSync(join(PUBLIC_DIR, "manifest.json"), JSON.stringify(manifest, null, 2), "utf8"); writeFileSync(join(PUBLIC_DIR, "manifest.json"), JSON.stringify(manifest, null, 2), "utf8");
+61 -28
View File
@@ -19,32 +19,65 @@ export function AudioSettingsPanel({ config, onConfigChange, theme, showTitle =
const format = normalizeAudioFormatForConfig(config, config.audioFormat); const format = normalizeAudioFormatForConfig(config, config.audioFormat);
const speed = normalizeAudioSpeedValue(config.audioSpeed); const speed = normalizeAudioSpeedValue(config.audioSpeed);
const selectVoice = (value: string) => onConfigChange("audioVoice", value); const selectVoice = (value: string) => onConfigChange("audioVoice", value);
return <ImageSettingsTheme theme={theme}> return (
<section className={className} style={{ color: theme.node.text }} onPointerDown={(event) => event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()} aria-label="音频生成参数"> <ImageSettingsTheme theme={theme}>
{showTitle ? <h3 className="text-base font-semibold">音频设置</h3> : null} <section className={className} style={{ color: theme.node.text }} onPointerDown={(event) => event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()} aria-label="音频生成参数">
<fieldset className="space-y-2"> {showTitle ? <h3 className="text-base font-semibold">音频设置</h3> : null}
<legend className="mb-2 text-xs" style={{ color: theme.node.muted }}>音色</legend> <fieldset className="space-y-2">
{streaming ? <> <legend className="mb-2 text-xs" style={{ color: theme.node.muted }}>
<p className="text-xs leading-5" style={{ color: theme.node.muted }}>无参考素材时按提示词生成;可连接最多 3 段音频或 1 张图片,图片与音频不能混用。</p> 音色
<Select className="w-full" ariaLabel="音色" value={voice} onChange={selectVoice} options={[{ value: "", label: "不指定音色" }, ...(voice ? [{ value: voice, label: `当前音色 · ${voice}` }] : [])]} /> </legend>
</> : <> {streaming ? (
<Input aria-label="渠道音色 ID" value={config.audioVoice || ""} list={listId} placeholder="输入渠道音色 ID" onChange={(event) => selectVoice(event.target.value)} /> <>
<datalist id={listId}>{currentVoice.map((item) => <option value={item.value} key={item.value}>{item.label}</option>)}</datalist> <p className="text-xs leading-5" style={{ color: theme.node.muted }}>
<Radio.Group aria-label="常用音色" value={voice} onChange={(event) => selectVoice(event.target.value)} options={currentVoice} className="flex flex-wrap gap-2" /> 无参考素材时按提示词生成;可连接最多 3 段音频或 1 张图片,图片与音频不能混用。
</>} </p>
</fieldset> <Select className="w-full" ariaLabel="音色" value={voice} onChange={selectVoice} options={[{ value: "", label: "不指定音色" }, ...(voice ? [{ value: voice, label: `当前音色 · ${voice}` }] : [])]} />
<fieldset> </>
<legend className="mb-2 text-xs" style={{ color: theme.node.muted }}>音频格式</legend> ) : (
<Radio.Group aria-label="音频格式" value={format} options={formats} onChange={(event) => onConfigChange("audioFormat", event.target.value)} className="flex flex-wrap gap-2" /> <>
</fieldset> <Input aria-label="渠道音色 ID" value={config.audioVoice || ""} list={listId} placeholder="输入渠道音色 ID" onChange={(event) => selectVoice(event.target.value)} />
<fieldset className="space-y-2"> <datalist id={listId}>
<legend className="mb-2 text-xs" style={{ color: theme.node.muted }}>语速</legend> {currentVoice.map((item) => (
<Radio.Group aria-label="常用语速" value={speed} options={["0.75", "1", "1.25", "1.5"].map((value) => ({ value, label: audioSpeedLabel(value) }))} onChange={(event) => onConfigChange("audioSpeed", event.target.value)} /> <option value={item.value} key={item.value}>
<InputNumber aria-label="自定义语速" min={0.25} max={4} step={0.05} value={Number(speed)} className="w-full" onChange={(value) => { if (value !== null) onConfigChange("audioSpeed", normalizeAudioSpeedValue(String(value))); }} /> {item.label}
</fieldset> </option>
{!streaming ? <label className="flex flex-col gap-2 text-xs" style={{ color: theme.node.muted }}>声音指令 ))}
<Input.TextArea aria-label="声音指令" rows={3} value={config.audioInstructions || ""} placeholder="例如:自然、温暖的旁白" onChange={(event) => onConfigChange("audioInstructions", event.target.value)} /> </datalist>
</label> : null} <Radio.Group aria-label="常用音色" value={voice} onChange={(event) => selectVoice(event.target.value)} options={currentVoice} className="flex flex-wrap gap-2" />
</section> </>
</ImageSettingsTheme>; )}
</fieldset>
<fieldset>
<legend className="mb-2 text-xs" style={{ color: theme.node.muted }}>
音频格式
</legend>
<Radio.Group aria-label="音频格式" value={format} options={formats} onChange={(event) => onConfigChange("audioFormat", event.target.value)} className="flex flex-wrap gap-2" />
</fieldset>
<fieldset className="space-y-2">
<legend className="mb-2 text-xs" style={{ color: theme.node.muted }}>
语速
</legend>
<Radio.Group aria-label="常用语速" value={speed} options={["0.75", "1", "1.25", "1.5"].map((value) => ({ value, label: audioSpeedLabel(value) }))} onChange={(event) => onConfigChange("audioSpeed", event.target.value)} />
<InputNumber
aria-label="自定义语速"
min={0.25}
max={4}
step={0.05}
value={Number(speed)}
className="w-full"
onChange={(value) => {
if (value !== null) onConfigChange("audioSpeed", normalizeAudioSpeedValue(String(value)));
}}
/>
</fieldset>
{!streaming ? (
<label className="flex flex-col gap-2 text-xs" style={{ color: theme.node.muted }}>
声音指令
<Input.TextArea aria-label="声音指令" rows={3} value={config.audioInstructions || ""} placeholder="例如:自然、温暖的旁白" onChange={(event) => onConfigChange("audioInstructions", event.target.value)} />
</label>
) : null}
</section>
</ImageSettingsTheme>
);
} }
@@ -5,8 +5,14 @@ export function composerReferences(inputs: NodeGenerationInput[], skills: Canvas
const media = inputs.map((input): CanvasResourceReference => { const media = inputs.map((input): CanvasResourceReference => {
const label = generationInputMentionLabel(input, inputs); const label = generationInputMentionLabel(input, inputs);
return { return {
id: `composer:${input.nodeId}`, nodeId: input.nodeId, kind: input.type, label, id: `composer:${input.nodeId}`,
mentionToken: `@${label}`, title: input.title, active: true, text: input.text, nodeId: input.nodeId,
kind: input.type,
label,
mentionToken: `@${label}`,
title: input.title,
active: true,
text: input.text,
previewUrl: input.sourceKind === "drawing" ? undefined : input.image?.dataUrl || input.previewUrl, previewUrl: input.sourceKind === "drawing" ? undefined : input.image?.dataUrl || input.previewUrl,
}; };
}); });
@@ -9,9 +9,14 @@ export type CanvasImageCropRect = ImageCropRect;
type CropProps = { dataUrl: string; open: boolean; onClose: () => void; onConfirm: (crop: CanvasImageCropRect) => void }; type CropProps = { dataUrl: string; open: boolean; onClose: () => void; onConfirm: (crop: CanvasImageCropRect) => void };
const initialSelection: ImageCropRect = { x: 0.1, y: 0.1, width: 0.8, height: 0.8 }; const initialSelection: ImageCropRect = { x: 0.1, y: 0.1, width: 0.8, height: 0.8 };
const grips: { name: string; vector: CropGrip }[] = [ const grips: { name: string; vector: CropGrip }[] = [
{ name: "nw", vector: [-1, -1] }, { name: "n", vector: [0, -1] }, { name: "ne", vector: [1, -1] }, { name: "nw", vector: [-1, -1] },
{ name: "w", vector: [-1, 0] }, { name: "e", vector: [1, 0] }, { name: "n", vector: [0, -1] },
{ name: "sw", vector: [-1, 1] }, { name: "s", vector: [0, 1] }, { name: "se", vector: [1, 1] }, { name: "ne", vector: [1, -1] },
{ name: "w", vector: [-1, 0] },
{ name: "e", vector: [1, 0] },
{ name: "sw", vector: [-1, 1] },
{ name: "s", vector: [0, 1] },
{ name: "se", vector: [1, 1] },
]; ];
type Gesture = { pointer: number; origin: [number, number]; display: [number, number]; selection: ImageCropRect; grip: CropGrip | null }; type Gesture = { pointer: number; origin: [number, number]; display: [number, number]; selection: ImageCropRect; grip: CropGrip | null };
@@ -31,7 +36,8 @@ function CropEditor({ dataUrl, onClose, onConfirm }: CropProps) {
if (event.button !== 0 || gesture.current || !stage.current || !size) return; if (event.button !== 0 || gesture.current || !stage.current || !size) return;
const bounds = stage.current.getBoundingClientRect(); const bounds = stage.current.getBoundingClientRect();
if (!bounds.width || !bounds.height) return; if (!bounds.width || !bounds.height) return;
event.preventDefault(); event.stopPropagation(); event.preventDefault();
event.stopPropagation();
event.currentTarget.setPointerCapture(event.pointerId); event.currentTarget.setPointerCapture(event.pointerId);
gesture.current = { pointer: event.pointerId, origin: [event.clientX, event.clientY], display: [bounds.width, bounds.height], selection, grip }; gesture.current = { pointer: event.pointerId, origin: [event.clientX, event.clientY], display: [bounds.width, bounds.height], selection, grip };
}; };
@@ -42,61 +48,116 @@ function CropEditor({ dataUrl, onClose, onConfirm }: CropProps) {
}; };
const choose = (value: string) => { const choose = (value: string) => {
if (!size) return; if (!size) return;
const ratio = value === "原图" ? 1 : (() => { const [w, h] = value.split(":").map(Number); return (w * size.height) / (h * size.width); })(); const ratio =
setSelection((box) => selectAspect(box, ratio)); setPreset(value); setLocked(true); value === "原图"
? 1
: (() => {
const [w, h] = value.split(":").map(Number);
return (w * size.height) / (h * size.width);
})();
setSelection((box) => selectAspect(box, ratio));
setPreset(value);
setLocked(true);
}; };
return ( return (
<AppModal open centered width={780} title="裁剪图片" onCancel={onClose} onOk={() => size && onConfirm(selection)} okText="确认裁剪" okButtonProps={{ disabled: !size }}> <AppModal open centered width={780} title="裁剪图片" onCancel={onClose} onOk={() => size && onConfirm(selection)} okText="确认裁剪" okButtonProps={{ disabled: !size }}>
<div className="space-y-4"> <div className="space-y-4">
<div className="flex justify-center"> <div className="flex justify-center">
<div ref={stage} className="relative inline-block max-w-full touch-none select-none overflow-hidden rounded-lg" <div
ref={stage}
className="relative inline-block max-w-full touch-none select-none overflow-hidden rounded-lg"
onPointerMove={(event) => { onPointerMove={(event) => {
const drag = gesture.current; const drag = gesture.current;
if (!drag || drag.pointer !== event.pointerId) return; if (!drag || drag.pointer !== event.pointerId) return;
const dx = (event.clientX - drag.origin[0]) / drag.display[0]; const dx = (event.clientX - drag.origin[0]) / drag.display[0];
const dy = (event.clientY - drag.origin[1]) / drag.display[1]; const dy = (event.clientY - drag.origin[1]) / drag.display[1];
setSelection(drag.grip ? resizeSelection(drag.selection, drag.grip, dx, dy, locked) : translateSelection(drag.selection, dx, dy)); setSelection(drag.grip ? resizeSelection(drag.selection, drag.grip, dx, dy, locked) : translateSelection(drag.selection, dx, dy));
}} onPointerUp={finish} onPointerCancel={finish} onLostPointerCapture={finish}> }}
onPointerUp={finish}
onPointerCancel={finish}
onLostPointerCapture={finish}
>
<img src={dataUrl} alt="待裁剪图片" draggable={false} className="block max-h-[60vh] max-w-full" /> <img src={dataUrl} alt="待裁剪图片" draggable={false} className="block max-h-[60vh] max-w-full" />
{size ? <div role="group" aria-label="裁剪区域" tabIndex={0} className="absolute cursor-move border border-white outline-none focus-visible:ring-2 focus-visible:ring-primary" {size ? (
style={{ left: `${selection.x * 100}%`, top: `${selection.y * 100}%`, width: `${selection.width * 100}%`, height: `${selection.height * 100}%`, boxShadow: "0 0 0 100vmax rgb(0 0 0 / 55%)" }} <div
onPointerDown={(event) => begin(event, null)} role="group"
onKeyDown={(event) => { aria-label="裁剪区域"
const vectors: Record<string, readonly [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] }; tabIndex={0}
const direction = vectors[event.key]; className="absolute cursor-move border border-white outline-none focus-visible:ring-2 focus-visible:ring-primary"
if (!direction) return; style={{ left: `${selection.x * 100}%`, top: `${selection.y * 100}%`, width: `${selection.width * 100}%`, height: `${selection.height * 100}%`, boxShadow: "0 0 0 100vmax rgb(0 0 0 / 55%)" }}
event.preventDefault(); event.stopPropagation(); onPointerDown={(event) => begin(event, null)}
const step = event.shiftKey ? 10 : 1;
setSelection((box) => translateSelection(box, (direction[0] * step) / size.width, (direction[1] * step) / size.height));
}}>
<svg viewBox="0 0 3 3" preserveAspectRatio="none" className="pointer-events-none absolute inset-0 h-full w-full" aria-hidden="true">
<path d="M1 0V3M2 0V3M0 1H3M0 2H3" stroke="white" strokeOpacity={0.5} strokeWidth={1} vectorEffect="non-scaling-stroke" />
</svg>
{grips.map(({ name, vector }) => <button type="button" key={name} aria-label={`调整裁剪框 ${name}`} className="absolute size-3 rounded-full border border-black bg-white"
style={{ left: `${(vector[0] + 1) * 50}%`, top: `${(vector[1] + 1) * 50}%`, transform: "translate(-50%, -50%)", cursor: `${name}-resize` }}
onPointerDown={(event) => begin(event, vector)}
onKeyDown={(event) => { onKeyDown={(event) => {
if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return; const vectors: Record<string, readonly [number, number]> = { ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1] };
event.preventDefault(); event.stopPropagation(); const direction = vectors[event.key];
if (!direction) return;
event.preventDefault();
event.stopPropagation();
const step = event.shiftKey ? 10 : 1; const step = event.shiftKey ? 10 : 1;
const dx = (event.key === "ArrowLeft" ? -step : event.key === "ArrowRight" ? step : 0) / size.width; setSelection((box) => translateSelection(box, (direction[0] * step) / size.width, (direction[1] * step) / size.height));
const dy = (event.key === "ArrowUp" ? -step : event.key === "ArrowDown" ? step : 0) / size.height; }}
setSelection((box) => resizeSelection(box, vector, dx, dy, locked)); >
}} />)} <svg viewBox="0 0 3 3" preserveAspectRatio="none" className="pointer-events-none absolute inset-0 h-full w-full" aria-hidden="true">
</div> : null} <path d="M1 0V3M2 0V3M0 1H3M0 2H3" stroke="white" strokeOpacity={0.5} strokeWidth={1} vectorEffect="non-scaling-stroke" />
</svg>
{grips.map(({ name, vector }) => (
<button
type="button"
key={name}
aria-label={`调整裁剪框 ${name}`}
className="absolute size-3 rounded-full border border-black bg-white"
style={{ left: `${(vector[0] + 1) * 50}%`, top: `${(vector[1] + 1) * 50}%`, transform: "translate(-50%, -50%)", cursor: `${name}-resize` }}
onPointerDown={(event) => begin(event, vector)}
onKeyDown={(event) => {
if (!["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
event.preventDefault();
event.stopPropagation();
const step = event.shiftKey ? 10 : 1;
const dx = (event.key === "ArrowLeft" ? -step : event.key === "ArrowRight" ? step : 0) / size.width;
const dy = (event.key === "ArrowUp" ? -step : event.key === "ArrowDown" ? step : 0) / size.height;
setSelection((box) => resizeSelection(box, vector, dx, dy, locked));
}}
/>
))}
</div>
) : null}
</div> </div>
</div> </div>
<div className="flex flex-wrap gap-2" role="group" aria-label="常用裁剪比例"> <div className="flex flex-wrap gap-2" role="group" aria-label="常用裁剪比例">
{["原图", "1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16"].map((value) => <Button key={value} size="small" disabled={!size} aria-pressed={preset === value} onClick={() => choose(value)}>{value}</Button>)} {["原图", "1:1", "3:2", "2:3", "4:3", "3:4", "16:9", "9:16"].map((value) => (
<Button key={value} size="small" disabled={!size} aria-pressed={preset === value} onClick={() => choose(value)}>
{value}
</Button>
))}
</div> </div>
<div className="flex flex-wrap items-center justify-between gap-3 text-sm"> <div className="flex flex-wrap items-center justify-between gap-3 text-sm">
<output>{output ? `输出 ${output.width} × ${output.height} px` : error || "正在读取图片…"}</output> <output>{output ? `输出 ${output.width} × ${output.height} px` : error || "正在读取图片…"}</output>
<div className="flex gap-2"> <div className="flex gap-2">
<Button disabled={!size} aria-pressed={locked} onClick={() => { setLocked(!locked); setPreset(""); }}>{locked ? "解除比例锁定" : "锁定当前比例"}</Button> <Button
<Button onClick={() => { setSelection(initialSelection); setLocked(false); setPreset(""); }}>重置</Button> disabled={!size}
aria-pressed={locked}
onClick={() => {
setLocked(!locked);
setPreset("");
}}
>
{locked ? "解除比例锁定" : "锁定当前比例"}
</Button>
<Button
onClick={() => {
setSelection(initialSelection);
setLocked(false);
setPreset("");
}}
>
重置
</Button>
</div> </div>
</div> </div>
{error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null} {error ? (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
) : null}
</div> </div>
</AppModal> </AppModal>
); );
@@ -29,8 +29,12 @@ function SplitEditor({ dataUrl, onClose, onConfirm }: SplitDialogProps) {
<div className="relative max-w-full overflow-hidden"> <div className="relative max-w-full overflow-hidden">
<img alt="待切分图片" src={dataUrl} draggable={false} className="block max-h-[340px] max-w-full object-contain" /> <img alt="待切分图片" src={dataUrl} draggable={false} className="block max-h-[340px] max-w-full object-contain" />
<svg className="pointer-events-none absolute inset-0 h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true"> <svg className="pointer-events-none absolute inset-0 h-full w-full" viewBox="0 0 100 100" preserveAspectRatio="none" aria-hidden="true">
{Array.from({ length: grid.columns - 1 }, (_, i) => <line key={`v${i}`} x1={(100 * (i + 1)) / grid.columns} x2={(100 * (i + 1)) / grid.columns} y1={0} y2={100} stroke="white" strokeWidth={1} vectorEffect="non-scaling-stroke" />)} {Array.from({ length: grid.columns - 1 }, (_, i) => (
{Array.from({ length: grid.rows - 1 }, (_, i) => <line key={`h${i}`} y1={(100 * (i + 1)) / grid.rows} y2={(100 * (i + 1)) / grid.rows} x1={0} x2={100} stroke="white" strokeWidth={1} vectorEffect="non-scaling-stroke" />)} <line key={`v${i}`} x1={(100 * (i + 1)) / grid.columns} x2={(100 * (i + 1)) / grid.columns} y1={0} y2={100} stroke="white" strokeWidth={1} vectorEffect="non-scaling-stroke" />
))}
{Array.from({ length: grid.rows - 1 }, (_, i) => (
<line key={`h${i}`} y1={(100 * (i + 1)) / grid.rows} y2={(100 * (i + 1)) / grid.rows} x1={0} x2={100} stroke="white" strokeWidth={1} vectorEffect="non-scaling-stroke" />
))}
</svg> </svg>
</div> </div>
<figcaption className="text-sm text-muted-foreground">{size ? `${size.width} × ${size.height} px` : error || "正在读取图片…"}</figcaption> <figcaption className="text-sm text-muted-foreground">{size ? `${size.width} × ${size.height} px` : error || "正在读取图片…"}</figcaption>
@@ -43,7 +47,11 @@ function SplitEditor({ dataUrl, onClose, onConfirm }: SplitDialogProps) {
</label> </label>
))} ))}
<output className="text-sm text-muted-foreground">{previewSize ? `每块约 ${previewSize.width} × ${previewSize.height} px;边缘像素会完整保留。` : "等待有效图片尺寸"}</output> <output className="text-sm text-muted-foreground">{previewSize ? `每块约 ${previewSize.width} × ${previewSize.height} px;边缘像素会完整保留。` : "等待有效图片尺寸"}</output>
{error || (size && !valid) ? <p role="alert" className="text-sm text-destructive">{error || "行列数超过图片像素尺寸,请减少切分数量"}</p> : null} {error || (size && !valid) ? (
<p role="alert" className="text-sm text-destructive">
{error || "行列数超过图片像素尺寸,请减少切分数量"}
</p>
) : null}
</div> </div>
</div> </div>
</AppModal> </AppModal>
@@ -29,7 +29,8 @@ function ResizeEditor({ dataUrl, onClose, onConfirm }: UpscaleDialogProps) {
<figcaption className="text-sm text-muted-foreground">{size ? `原图 ${size.width} × ${size.height} px` : error || "正在读取图片…"}</figcaption> <figcaption className="text-sm text-muted-foreground">{size ? `原图 ${size.width} × ${size.height} px` : error || "正在读取图片…"}</figcaption>
</figure> </figure>
<div className="flex flex-col gap-5"> <div className="flex flex-col gap-5">
<label className="flex flex-col gap-2 text-sm">目标长边 <label className="flex flex-col gap-2 text-sm">
目标长边
<Select aria-label="目标长边" value={target} onChange={setChosen} options={pixelTargets.map((pixels) => ({ value: pixels, label: `${pixels} px`, disabled: pixels <= edge }))} /> <Select aria-label="目标长边" value={target} onChange={setChosen} options={pixelTargets.map((pixels) => ({ value: pixels, label: `${pixels} px`, disabled: pixels <= edge }))} />
</label> </label>
<fieldset className="space-y-2"> <fieldset className="space-y-2">
@@ -41,7 +42,11 @@ function ResizeEditor({ dataUrl, onClose, onConfirm }: UpscaleDialogProps) {
</Radio.Group> </Radio.Group>
</fieldset> </fieldset>
<output className="text-sm">{output ? `输出 ${output.width} × ${output.height} px` : "等待读取尺寸"}</output> <output className="text-sm">{output ? `输出 ${output.width} × ${output.height} px` : "等待读取尺寸"}</output>
{error || (size && !ready) ? <p role="alert" className="text-sm text-destructive">{error || (edge >= MAX_UPSCALE_LONG_EDGE ? "图片已达到 4K,无需放大" : "请选择大于原图的目标尺寸")}</p> : null} {error || (size && !ready) ? (
<p role="alert" className="text-sm text-destructive">
{error || (edge >= MAX_UPSCALE_LONG_EDGE ? "图片已达到 4K,无需放大" : "请选择大于原图的目标尺寸")}
</p>
) : null}
</div> </div>
</div> </div>
</AppModal> </AppModal>
@@ -21,16 +21,52 @@ export function CanvasSettingsPopover({ label, summary, children, placement = "t
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const id = useId(); const id = useId();
const theme = canvasThemes[useActiveTheme()]; const theme = canvasThemes[useActiveTheme()];
const change = (next: boolean) => { setOpen(next); onOpenChange?.(next); }; const change = (next: boolean) => {
setOpen(next);
onOpenChange?.(next);
};
return ( return (
<Popover open={open} onOpenChange={change} trigger="click" placement={placement} getPopupContainer={getPopupContainer} autoAdjustOverflow={autoAdjustOverflow} <Popover
arrow={false} destroyOnHidden styles={{ root: { zIndex: "var(--z-dialog-popover)" }, container: { background: theme.canvas.background, color: theme.node.text, padding: 12 } }} open={open}
content={<section id={id} aria-label={label} data-canvas-no-zoom data-canvas-wheel-scroll className="canvas-image-settings-popover overflow-y-auto overscroll-contain" style={{ width: `min(${width}px, calc(100vw - 48px))`, maxHeight: "min(560px, calc(100dvh - 100px))" }} onOpenChange={change}
onPointerDown={(event) => event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()} onClick={(event) => event.stopPropagation()} trigger="click"
onKeyDown={(event) => { event.stopPropagation(); if (event.key === "Escape") change(false); }}>{children}</section>}> placement={placement}
<Button type="text" size="small" aria-expanded={open} aria-controls={open ? id : undefined} aria-label={`${label}:${summary}`} title={`${label} · ${summary}`} getPopupContainer={getPopupContainer}
autoAdjustOverflow={autoAdjustOverflow}
arrow={false}
destroyOnHidden
styles={{ root: { zIndex: "var(--z-dialog-popover)" }, container: { background: theme.canvas.background, color: theme.node.text, padding: 12 } }}
content={
<section
id={id}
aria-label={label}
data-canvas-no-zoom
data-canvas-wheel-scroll
className="canvas-image-settings-popover overflow-y-auto overscroll-contain"
style={{ width: `min(${width}px, calc(100vw - 48px))`, maxHeight: "min(560px, calc(100dvh - 100px))" }}
onPointerDown={(event) => event.stopPropagation()}
onMouseDown={(event) => event.stopPropagation()}
onClick={(event) => event.stopPropagation()}
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === "Escape") change(false);
}}
>
{children}
</section>
}
>
<Button
type="text"
size="small"
aria-expanded={open}
aria-controls={open ? id : undefined}
aria-label={`${label}:${summary}`}
title={`${label} · ${summary}`}
className={`canvas-generation-settings-trigger ${buttonClassName || "!h-8 !max-w-[180px] !justify-start !rounded-full !px-2.5"}`} className={`canvas-generation-settings-trigger ${buttonClassName || "!h-8 !max-w-[180px] !justify-start !rounded-full !px-2.5"}`}
style={{ background: theme.node.fill, color: theme.node.text }} icon={<Settings2 className="size-3.5" />}> style={{ background: theme.node.fill, color: theme.node.text }}
icon={<Settings2 className="size-3.5" />}
>
<span className="truncate">{summary}</span> <span className="truncate">{summary}</span>
</Button> </Button>
</Popover> </Popover>
@@ -18,16 +18,44 @@ export function CanvasSizePicker({ value, className, onChange }: CanvasSizePicke
}; };
return ( return (
<div className={className} data-canvas-no-zoom onPointerDown={(event) => event.stopPropagation()}> <div className={className} data-canvas-no-zoom onPointerDown={(event) => event.stopPropagation()}>
<Select ariaLabel="生成比例" className="canvas-compact-control canvas-control-select h-full w-full" placeholder="比例" showSearch <Select
value={value || undefined} options={options} searchValue={query} open={expanded} popupMatchSelectWidth={false} ariaLabel="生成比例"
onSearch={(text) => { draft.current = text; setQuery(text); }} onOpenChange={setExpanded} className="canvas-compact-control canvas-control-select h-full w-full"
onChange={commit} onBlur={() => { if (draft.current.trim()) commit(draft.current); else setExpanded(false); }} placeholder="比例"
showSearch
value={value || undefined}
options={options}
searchValue={query}
open={expanded}
popupMatchSelectWidth={false}
onSearch={(text) => {
draft.current = text;
setQuery(text);
}}
onOpenChange={setExpanded}
onChange={commit}
onBlur={() => {
if (draft.current.trim()) commit(draft.current);
else setExpanded(false);
}}
onInputKeyDown={(event) => { onInputKeyDown={(event) => {
if (event.nativeEvent.isComposing) return; if (event.nativeEvent.isComposing) return;
if (event.key === "Enter" && draft.current.trim()) { event.preventDefault(); commit(draft.current); } if (event.key === "Enter" && draft.current.trim()) {
if (event.key === "Escape") { draft.current = ""; setQuery(""); setExpanded(false); } event.preventDefault();
commit(draft.current);
}
if (event.key === "Escape") {
draft.current = "";
setQuery("");
setExpanded(false);
}
}} }}
popupRender={(menu) => <div onPointerDown={(event) => event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()}>{menu}</div>} /> popupRender={(menu) => (
<div onPointerDown={(event) => event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()}>
{menu}
</div>
)}
/>
</div> </div>
); );
} }
+61 -35
View File
@@ -45,7 +45,26 @@ type PinchState = {
initialScale: number; initialScale: number;
}; };
export function CanvasViewport({ interactive = true, containerRef, viewport, appearance, backgroundMode = "lines", onViewportChange, onViewportPreviewChange, onCanvasMouseDown, boxSelectEnabled = false, onCanvasDoubleClick, onCanvasDeselect, onContextMenu, onDrop, onFileDragEnter, onFileDragLeave, onFileDragOver, graphicsLayer, children }: CanvasViewportProps) { export function CanvasViewport({
interactive = true,
containerRef,
viewport,
appearance,
backgroundMode = "lines",
onViewportChange,
onViewportPreviewChange,
onCanvasMouseDown,
boxSelectEnabled = false,
onCanvasDoubleClick,
onCanvasDeselect,
onContextMenu,
onDrop,
onFileDragEnter,
onFileDragLeave,
onFileDragOver,
graphicsLayer,
children,
}: CanvasViewportProps) {
const colorTheme = useActiveTheme(); const colorTheme = useActiveTheme();
const resolvedAppearance = resolveCanvasAppearance(appearance, colorTheme); const resolvedAppearance = resolveCanvasAppearance(appearance, colorTheme);
const panState = useRef({ const panState = useRef({
@@ -118,7 +137,9 @@ export function CanvasViewport({ interactive = true, containerRef, viewport, app
[containerRef], [containerRef],
); );
const syncViewport = useCallback(() => { if (interactive) onViewportChange(viewportRef.current); }, [interactive, onViewportChange]); const syncViewport = useCallback(() => {
if (interactive) onViewportChange(viewportRef.current);
}, [interactive, onViewportChange]);
const scheduleViewportChange = useCallback( const scheduleViewportChange = useCallback(
(next: ViewportTransform, commitAfterIdle = false) => { (next: ViewportTransform, commitAfterIdle = false) => {
@@ -128,14 +149,15 @@ export function CanvasViewport({ interactive = true, containerRef, viewport, app
const container = containerRef.current; const container = containerRef.current;
if (container) container.dataset.canvasViewportInteracting = "true"; if (container) container.dataset.canvasViewportInteracting = "true";
nextViewportRef.current = next; nextViewportRef.current = next;
if (!frameRef.current) frameRef.current = requestAnimationFrame((now) => { if (!frameRef.current)
frameRef.current = null; frameRef.current = requestAnimationFrame((now) => {
const pending = nextViewportRef.current; frameRef.current = null;
if (!pending) return; const pending = nextViewportRef.current;
const notify = now - lastPreviewNotifyRef.current >= 32; if (!pending) return;
applyCanvasLiveViewport(containerRef.current, pending, notify); const notify = now - lastPreviewNotifyRef.current >= 32;
if (notify) lastPreviewNotifyRef.current = now; applyCanvasLiveViewport(containerRef.current, pending, notify);
}); if (notify) lastPreviewNotifyRef.current = now;
});
if (!commitAfterIdle) return; if (!commitAfterIdle) return;
if (syncTimerRef.current) clearTimeout(syncTimerRef.current); if (syncTimerRef.current) clearTimeout(syncTimerRef.current);
syncTimerRef.current = setTimeout(() => { syncTimerRef.current = setTimeout(() => {
@@ -203,11 +225,14 @@ export function CanvasViewport({ interactive = true, containerRef, viewport, app
if (looksLikeTrackpadPan) { if (looksLikeTrackpadPan) {
const panX = event.shiftKey && absX < 1 ? deltaY : deltaX; const panX = event.shiftKey && absX < 1 ? deltaY : deltaX;
scheduleViewportChange({ scheduleViewportChange(
x: current.x - panX, {
y: current.y - (event.shiftKey && absX < 1 ? 0 : deltaY), x: current.x - panX,
k: current.k, y: current.y - (event.shiftKey && absX < 1 ? 0 : deltaY),
}, true); k: current.k,
},
true,
);
return; return;
} }
@@ -221,11 +246,14 @@ export function CanvasViewport({ interactive = true, containerRef, viewport, app
const worldX = (mouseX - current.x) / current.k; const worldX = (mouseX - current.x) / current.k;
const worldY = (mouseY - current.y) / current.k; const worldY = (mouseY - current.y) / current.k;
scheduleViewportChange({ scheduleViewportChange(
x: mouseX - worldX * newScale, {
y: mouseY - worldY * newScale, x: mouseX - worldX * newScale,
k: newScale, y: mouseY - worldY * newScale,
}, true); k: newScale,
},
true,
);
}, },
[containerRef, scheduleViewportChange], [containerRef, scheduleViewportChange],
); );
@@ -317,7 +345,6 @@ export function CanvasViewport({ interactive = true, containerRef, viewport, app
setIsPanning(true); setIsPanning(true);
document.body.style.cursor = "grabbing"; document.body.style.cursor = "grabbing";
} }
}; };
useEffect(() => { useEffect(() => {
@@ -425,16 +452,18 @@ export function CanvasViewport({ interactive = true, containerRef, viewport, app
data-canvas-viewport data-canvas-viewport
data-canvas-pan-state={isPanning ? "grabbing" : isSpacePressed || !boxSelectEnabled ? "grab" : undefined} data-canvas-pan-state={isPanning ? "grabbing" : isSpacePressed || !boxSelectEnabled ? "grab" : undefined}
className={`relative h-full w-full select-none overflow-hidden touch-none ${isPanning ? "cursor-grabbing" : isSpacePressed || !boxSelectEnabled ? "cursor-grab" : "canvas-cursor-select"}`} className={`relative h-full w-full select-none overflow-hidden touch-none ${isPanning ? "cursor-grabbing" : isSpacePressed || !boxSelectEnabled ? "cursor-grab" : "canvas-cursor-select"}`}
style={{ style={
background: resolvedAppearance.background, {
overscrollBehavior: "none", background: resolvedAppearance.background,
"--canvas-live-x": `${viewport.x}px`, overscrollBehavior: "none",
"--canvas-live-y": `${viewport.y}px`, "--canvas-live-x": `${viewport.x}px`,
"--canvas-live-scale": viewport.k, "--canvas-live-y": `${viewport.y}px`,
"--canvas-live-inverse-scale": 1 / Math.max(viewport.k, 0.05), "--canvas-live-scale": viewport.k,
"--canvas-committed-scale": viewport.k, "--canvas-live-inverse-scale": 1 / Math.max(viewport.k, 0.05),
"--canvas-live-scale-ratio": 1, "--canvas-committed-scale": viewport.k,
} as React.CSSProperties} "--canvas-live-scale-ratio": 1,
} as React.CSSProperties
}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onDoubleClick={(event) => { onDoubleClick={(event) => {
const target = event.target instanceof Element ? event.target : null; const target = event.target instanceof Element ? event.target : null;
@@ -476,10 +505,7 @@ export function CanvasViewport({ interactive = true, containerRef, viewport, app
> >
<CanvasGrid appearance={appearance} mode={backgroundMode} /> <CanvasGrid appearance={appearance} mode={backgroundMode} />
{graphicsLayer} {graphicsLayer}
<div <div data-canvas-world-layer className="canvas-world-layer absolute origin-top-left">
data-canvas-world-layer
className="canvas-world-layer absolute origin-top-left"
>
<div data-canvas-world-raster-layer className="canvas-world-raster-layer absolute origin-top-left"> <div data-canvas-world-raster-layer className="canvas-world-raster-layer absolute origin-top-left">
{children} {children}
</div> </div>
@@ -25,8 +25,12 @@ export function useCanvasNodeResize(node: CanvasNodeData, scale: number, minimum
let previous = origin; let previous = origin;
const minimum = getNodeMinSize(node.type); const minimum = getNodeMinSize(node.type);
const snapshot = { const snapshot = {
position: { ...node.position }, width: node.width, height: node.height, corner, position: { ...node.position },
minimumWidth: minimum.width, minimumHeight: minimumHeight ?? minimum.height, width: node.width,
height: node.height,
corner,
minimumWidth: minimum.width,
minimumHeight: minimumHeight ?? minimum.height,
ratio: shouldKeepAspectRatio(node) ? (node.metadata?.naturalWidth || node.width) / (node.metadata?.naturalHeight || node.height || 1) : undefined, ratio: shouldKeepAspectRatio(node) ? (node.metadata?.naturalWidth || node.width) / (node.metadata?.naturalHeight || node.height || 1) : undefined,
}; };
const listeners = new AbortController(); const listeners = new AbortController();
@@ -43,12 +47,32 @@ export function useCanvasNodeResize(node: CanvasNodeData, scale: number, minimum
}; };
target.setPointerCapture(pointer); target.setPointerCapture(pointer);
target.addEventListener("pointermove", move, { signal: listeners.signal }); target.addEventListener("pointermove", move, { signal: listeners.signal });
target.addEventListener("pointerup", (next) => { target.addEventListener(
if (next.pointerId !== pointer) return; "pointerup",
try { move(next); } finally { stop(); } (next) => {
}, { signal: listeners.signal }); if (next.pointerId !== pointer) return;
target.addEventListener("pointercancel", (next) => { if (next.pointerId === pointer) stop(); }, { signal: listeners.signal }); try {
target.addEventListener("lostpointercapture", (next) => { if (next.pointerId === pointer) stop(); }, { signal: listeners.signal }); move(next);
} finally {
stop();
}
},
{ signal: listeners.signal },
);
target.addEventListener(
"pointercancel",
(next) => {
if (next.pointerId === pointer) stop();
},
{ signal: listeners.signal },
);
target.addEventListener(
"lostpointercapture",
(next) => {
if (next.pointerId === pointer) stop();
},
{ signal: listeners.signal },
);
window.addEventListener("blur", stop, { signal: listeners.signal }); window.addEventListener("blur", stop, { signal: listeners.signal });
dispose.current = stop; dispose.current = stop;
}; };
@@ -11,15 +11,24 @@ export function ImageGenerationPending({ className, label = "正在生成图片"
useEffect(() => { useEffect(() => {
const update = () => setElapsed(Math.max(0, Date.now() - startedAt)); const update = () => setElapsed(Math.max(0, Date.now() - startedAt));
const clock = window.setInterval(update, 1000); const clock = window.setInterval(update, 1000);
const onVisible = () => { if (!document.hidden) update(); }; const onVisible = () => {
if (!document.hidden) update();
};
document.addEventListener("visibilitychange", onVisible); document.addEventListener("visibilitychange", onVisible);
return () => { window.clearInterval(clock); document.removeEventListener("visibilitychange", onVisible); }; return () => {
window.clearInterval(clock);
document.removeEventListener("visibilitychange", onVisible);
};
}, [startedAt]); }, [startedAt]);
return ( return (
<div aria-busy="true" className={cn("flex flex-col items-center justify-center gap-3 rounded-lg bg-surface-active p-4 text-muted-foreground", compact ? "min-h-24" : "aspect-[4/3]", className)}> <div aria-busy="true" className={cn("flex flex-col items-center justify-center gap-3 rounded-lg bg-surface-active p-4 text-muted-foreground", compact ? "min-h-24" : "aspect-[4/3]", className)}>
<LoaderCircle aria-hidden="true" className="size-5 animate-spin motion-reduce:animate-none" /> <LoaderCircle aria-hidden="true" className="size-5 animate-spin motion-reduce:animate-none" />
<span role="status" className="text-sm font-medium">{label}</span> <span role="status" className="text-sm font-medium">
<time className="text-xs tabular-nums" dateTime={`PT${Math.floor(elapsed / 1000)}S`}>已等待 {formatDuration(elapsed)}</time> {label}
</span>
<time className="text-xs tabular-nums" dateTime={`PT${Math.floor(elapsed / 1000)}S`}>
已等待 {formatDuration(elapsed)}
</time>
</div> </div>
); );
} }
+1 -3
View File
@@ -36,9 +36,7 @@ export function resolveUpscaleSize(width: number, height: number, requested: num
assertPixelSize({ width, height }); assertPixelSize({ width, height });
if (!Number.isFinite(requested) || requested <= 0) throw new RangeError("目标尺寸无效"); if (!Number.isFinite(requested) || requested <= 0) throw new RangeError("目标尺寸无效");
const edge = Math.max(1, Math.min(MAX_UPSCALE_LONG_EDGE, Math.round(requested))); const edge = Math.max(1, Math.min(MAX_UPSCALE_LONG_EDGE, Math.round(requested)));
return width >= height return width >= height ? { width: edge, height: Math.max(1, Math.round((height / width) * edge)) } : { width: Math.max(1, Math.round((width / height) * edge)), height: edge };
? { width: edge, height: Math.max(1, Math.round((height / width) * edge)) }
: { width: Math.max(1, Math.round((width / height) * edge)), height: edge };
} }
export function resolveCropPixels(size: PixelSize, selection?: ImageCropRect): ImageCropRect { export function resolveCropPixels(size: PixelSize, selection?: ImageCropRect): ImageCropRect {
+9 -3
View File
@@ -28,10 +28,14 @@ function decodeDataUrl(url: string): { bytes: Uint8Array<ArrayBuffer>; mimeType:
const encoded = new TextEncoder().encode(payload); const encoded = new TextEncoder().encode(payload);
const output: number[] = []; const output: number[] = [];
for (let cursor = 0; cursor < encoded.length; cursor++) { for (let cursor = 0; cursor < encoded.length; cursor++) {
if (encoded[cursor] !== 37) { output.push(encoded[cursor]); continue; } if (encoded[cursor] !== 37) {
output.push(encoded[cursor]);
continue;
}
const hex = String.fromCharCode(...encoded.slice(cursor + 1, cursor + 3)); const hex = String.fromCharCode(...encoded.slice(cursor + 1, cursor + 3));
if (!/^[0-9a-f]{2}$/i.test(hex)) throw new Error("图片数据包含无效的转义字符"); if (!/^[0-9a-f]{2}$/i.test(hex)) throw new Error("图片数据包含无效的转义字符");
output.push(parseInt(hex, 16)); cursor += 2; output.push(parseInt(hex, 16));
cursor += 2;
} }
bytes = Uint8Array.from(output); bytes = Uint8Array.from(output);
} }
@@ -47,7 +51,9 @@ export function getDataUrlByteSize(url: string): number {
return Math.floor(payload.replace(/=+$/, "").length * 0.75); return Math.floor(payload.replace(/=+$/, "").length * 0.75);
} }
return decodeDataUrl(url).bytes.byteLength; return decodeDataUrl(url).bytes.byteLength;
} catch { return 0; } } catch {
return 0;
}
} }
export async function readFileAsDataUrl(file: Blob): Promise<string> { export async function readFileAsDataUrl(file: Blob): Promise<string> {
+135 -17
View File
@@ -127,23 +127,141 @@ const curatedWorks: CreationInspiration[] = [
mode: "text", mode: "text",
prompt: "请帮我写一场发生在暖色灯光客厅里的母女对话戏:女儿准备离开家乡,母亲表面平静但一直在整理旧物,用动作和潜台词推进情绪。", prompt: "请帮我写一场发生在暖色灯光客厅里的母女对话戏:女儿准备离开家乡,母亲表面平静但一直在整理旧物,用动作和潜台词推进情绪。",
}, },
{ title: "森林里的最后一封信", description: "童话叙事 · 从角色愿望建立冲突", image: "/short-drama-styles/storybook-fantasy.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Storyteller", prompt: "作为故事讲述者,为亲子观众写一个关于坚持的森林童话。主角是一只替动物送信的小狐狸,它必须在第一场雪之前送出一封没有地址的信。先给出角色的愿望与阻碍,再设计三个递进的事件,最后用一个可见的行动完成情绪转折。避免说教。" }, {
{ title: "末班车上的陌生人", description: "短剧编剧 · 让对白藏住真正目的", image: "/short-drama-styles/urban-live-action.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Screenwriter", prompt: "作为编剧,设计一段发生在末班公交车上的三分钟短剧。两位陌生人都声称自己丢失了一本笔记,但只有一人说真话。先定义人物动机、场景限制和各自隐瞒的信息,再写动作、对白与反转结尾。全剧限制两个角色、一个场景,适合低成本实拍。" }, title: "森林里的最后一封信",
{ title: "未来城市的记忆修补师", description: "科幻大纲 · 世界规则与人物代价", image: "/short-drama-styles/future-tech.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Novelist", prompt: "作为小说家,构思一部关于记忆修补师的未来都市短篇。城市居民能删除痛苦记忆,但主角发现每次删除都会遗失一种颜色。建立三条世界规则、主人公的核心缺陷、五个转折和付出代价的结局。先交付故事大纲,不直接铺写长篇。" }, description: "童话叙事 · 从角色愿望建立冲突",
{ title: "把告别写成一场雨", description: "诗性旁白 · 少解释,多感官细节", image: "/short-drama-styles/nature-healing.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Poet", prompt: "作为诗人,为一段雨中离乡的影像写四组中文旁白,每组不超过四十字。分别使用气味、触感、声音与光线表达告别,不直接使用悲伤、不舍或想念等情绪词。用朴素、可朗读的语言,给每组留一个停顿。" }, image: "/short-drama-styles/storybook-fantasy.jpg",
{ title: "一瓶饮料的夏日故事", description: "广告策划 · 人群、主张与三个镜头", image: "/short-drama-styles/real-life.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Advertiser", prompt: "作为广告策划,为面向年轻通勤者的无糖气泡饮料设计十五秒广告。定义目标人群、核心场景和一句传播主张,再给出三个镜头的画面、时长、音效与字幕。不要虚构营养或功效数据,用下班后一口清爽的体验讲故事。" }, mode: "text",
{ title: "独立咖啡店的视觉语言", description: "品牌创意 · 让配色和语气讲同一件事", image: "/short-drama-styles/retro-hong-kong.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Creative Branding Strategist", prompt: "作为品牌策略师,为社区里一家安静的独立咖啡店提出三种视觉方向。品牌重视慢节奏、邻里关系和手作。每种方向包含色彩、摄影氛围、文字语气、三条社交内容主题和差异化理由。不要模仿已有连锁品牌的标识。" }, sourceId: "chatgpt-prompts",
{ title: "给剧本做一次镜头诊断", description: "创作复盘 · 从叙事到声音提出修改", image: "/short-drama-styles/black-white-noir.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Film Critic", prompt: "请以电影评论者的视角审阅我接下来提供的剧本或分镜,从叙事、人物、构图、运镜和声音五个维度提出反馈。每条意见都引用我提供的片段,并给出一个能实际拍摄的修改方案。还没有收到材料时,先向我索取,不要假装看过影片。" }, credit: "Storyteller",
{ title: "旧城街景的时代考据", description: "历史场景 · 区分史实、推测和虚构", image: "/short-drama-styles/period-live-action.jpg", mode: "text", sourceId: "chatgpt-prompts", credit: "Historian", prompt: "作为历史研究者,协助我设计民国早期城市街景的影视场景。先问清具体年份、地点和人物阶层,再列出服饰、交通、招牌、建筑和日常用语的考据清单。明确区分有来源的史实、合理推测与戏剧性虚构,不编造文献。" }, prompt: "作为故事讲述者,为亲子观众写一个关于坚持的森林童话。主角是一只替动物送信的小狐狸,它必须在第一场雪之前送出一封没有地址的信。先给出角色的愿望与阻碍,再设计三个递进的事件,最后用一个可见的行动完成情绪转折。避免说教。",
{ title: "月面独行", description: "远景到特写 · 太空探索的孤独感", image: "/short-drama-styles/space-opera.jpg", mode: "video", prompt: "月球背面的荒原,宇航员独自走向一座废弃天线。镜头从极远景缓慢推进,低角度阳光在月尘上拉出长影,步伐沉重,头盔反射星光,克制冷色,宽银幕电影构图,无字幕。" }, },
{ title: "手作星球早餐", description: "定格动画 · 柔软材质与小动作", image: "/short-drama-styles/clay-stop-motion.jpg", mode: "video", prompt: "黏土定格动画风格,一位小小宇航员在圆形厨房煎一颗星星形状的鸡蛋,鸡蛋轻轻跳起。手作指纹质感、暖奶油色、柔和侧光,固定中景,动作简短连续,可爱但不夸张。" }, {
{ title: "山水之间的一叶舟", description: "水墨留白 · 横向移镜与轻雾", image: "/short-drama-styles/ink-narrative.jpg", mode: "video", prompt: "中国水墨动画,一叶小舟缓缓穿过层叠远山,薄雾留白,舟上人抬手触碰落下的花瓣。镜头平稳横移,墨色有自然晕染,少量朱红点缀,画面安静,动作节奏舒缓。" }, title: "末班车上的陌生人",
{ title: "雨后的玻璃花房", description: "治愈场景 · 前景水滴与逆光", image: "/short-drama-styles/nature-healing.jpg", mode: "video", prompt: "清晨雨后的玻璃花房,镜头透过挂着水滴的叶片缓缓推向盛开的白花,阳光从侧后方进入,浅景深,真实植物纹理,空气中薄薄水汽,宁静自然,无人物和文字。" }, description: "短剧编剧 · 让对白藏住真正目的",
{ title: "都市少女角色转面", description: "角色概念 · 统一服装与形体比例", image: "/short-drama-styles/chinese-2d.jpg", mode: "image", prompt: "原创二维动画都市少女角色设定,短发、宽松工装夹克和帆布包,正面、侧面与背面三视图,服装细节和身高比例一致,干净线稿配平涂阴影,暖灰背景,不添加文字,不模仿已有动漫角色。" }, image: "/short-drama-styles/urban-live-action.jpg",
{ title: "梦境里的倒置房间", description: "超现实概念 · 重力反转与柔光", image: "/short-drama-styles/surreal-dream.jpg", mode: "image", prompt: "超现实电影场景概念图,一间漂浮在云海中的倒置卧室,床和书桌悬在天花板上,一扇门通向浅粉色天空。低饱和奶油与雾蓝色,柔和漫反射,精确透视,细腻材质,无人物,无文字。" }, mode: "text",
{ title: "海边旅店的黄昏", description: "实拍场景 · 用道具留下人物痕迹", image: "/short-drama-styles/urban-live-action.jpg", mode: "image", prompt: "沿海小城旧旅店房间的电影置景概念图,窗外是黄昏海面,风吹动米白窗帘,桌上有两杯没有喝完的茶和一本翻开的书。暖橙与浅蓝对比,自然胶片颗粒,眼平中广角,没有人物和可读文字。" }, sourceId: "chatgpt-prompts",
{ title: "鲜亮漫画封面", description: "平面构成 · 大色块与戏剧性透视", image: "/short-drama-styles/comic-pop.jpg", mode: "image", prompt: "原创漫画封面插画,一位骑单车的城市信使跃过雨后积水,戏剧性低角度透视,青蓝、珊瑚红与暖黄色大色块,半调网点,清晰黑色轮廓,背景简洁,为顶部标题留白但不生成文字。" }, credit: "Screenwriter",
{ title: "烘焙店的秘密帮手", description: "三维角色 · 柔和材质与亲切表情", image: "/short-drama-styles/three-d-cartoon.jpg", mode: "image", prompt: "原创三维动画角色概念图,一只穿着面粉围裙的小浣熊站在烘焙台前,鼻尖沾着面粉,手里举着刚烤好的面包。柔软毛发、温暖侧光、自然可爱的比例,橘棕色和奶油白配色,背景轻微虚化。" }, prompt: "作为编剧,设计一段发生在末班公交车上的三分钟短剧。两位陌生人都声称自己丢失了一本笔记,但只有一人说真话。先定义人物动机、场景限制和各自隐瞒的信息,再写动作、对白与反转结尾。全剧限制两个角色、一个场景,适合低成本实拍。",
},
{
title: "未来城市的记忆修补师",
description: "科幻大纲 · 世界规则与人物代价",
image: "/short-drama-styles/future-tech.jpg",
mode: "text",
sourceId: "chatgpt-prompts",
credit: "Novelist",
prompt: "作为小说家,构思一部关于记忆修补师的未来都市短篇。城市居民能删除痛苦记忆,但主角发现每次删除都会遗失一种颜色。建立三条世界规则、主人公的核心缺陷、五个转折和付出代价的结局。先交付故事大纲,不直接铺写长篇。",
},
{
title: "把告别写成一场雨",
description: "诗性旁白 · 少解释,多感官细节",
image: "/short-drama-styles/nature-healing.jpg",
mode: "text",
sourceId: "chatgpt-prompts",
credit: "Poet",
prompt: "作为诗人,为一段雨中离乡的影像写四组中文旁白,每组不超过四十字。分别使用气味、触感、声音与光线表达告别,不直接使用悲伤、不舍或想念等情绪词。用朴素、可朗读的语言,给每组留一个停顿。",
},
{
title: "一瓶饮料的夏日故事",
description: "广告策划 · 人群、主张与三个镜头",
image: "/short-drama-styles/real-life.jpg",
mode: "text",
sourceId: "chatgpt-prompts",
credit: "Advertiser",
prompt: "作为广告策划,为面向年轻通勤者的无糖气泡饮料设计十五秒广告。定义目标人群、核心场景和一句传播主张,再给出三个镜头的画面、时长、音效与字幕。不要虚构营养或功效数据,用下班后一口清爽的体验讲故事。",
},
{
title: "独立咖啡店的视觉语言",
description: "品牌创意 · 让配色和语气讲同一件事",
image: "/short-drama-styles/retro-hong-kong.jpg",
mode: "text",
sourceId: "chatgpt-prompts",
credit: "Creative Branding Strategist",
prompt: "作为品牌策略师,为社区里一家安静的独立咖啡店提出三种视觉方向。品牌重视慢节奏、邻里关系和手作。每种方向包含色彩、摄影氛围、文字语气、三条社交内容主题和差异化理由。不要模仿已有连锁品牌的标识。",
},
{
title: "给剧本做一次镜头诊断",
description: "创作复盘 · 从叙事到声音提出修改",
image: "/short-drama-styles/black-white-noir.jpg",
mode: "text",
sourceId: "chatgpt-prompts",
credit: "Film Critic",
prompt: "请以电影评论者的视角审阅我接下来提供的剧本或分镜,从叙事、人物、构图、运镜和声音五个维度提出反馈。每条意见都引用我提供的片段,并给出一个能实际拍摄的修改方案。还没有收到材料时,先向我索取,不要假装看过影片。",
},
{
title: "旧城街景的时代考据",
description: "历史场景 · 区分史实、推测和虚构",
image: "/short-drama-styles/period-live-action.jpg",
mode: "text",
sourceId: "chatgpt-prompts",
credit: "Historian",
prompt: "作为历史研究者,协助我设计民国早期城市街景的影视场景。先问清具体年份、地点和人物阶层,再列出服饰、交通、招牌、建筑和日常用语的考据清单。明确区分有来源的史实、合理推测与戏剧性虚构,不编造文献。",
},
{
title: "月面独行",
description: "远景到特写 · 太空探索的孤独感",
image: "/short-drama-styles/space-opera.jpg",
mode: "video",
prompt: "月球背面的荒原,宇航员独自走向一座废弃天线。镜头从极远景缓慢推进,低角度阳光在月尘上拉出长影,步伐沉重,头盔反射星光,克制冷色,宽银幕电影构图,无字幕。",
},
{
title: "手作星球早餐",
description: "定格动画 · 柔软材质与小动作",
image: "/short-drama-styles/clay-stop-motion.jpg",
mode: "video",
prompt: "黏土定格动画风格,一位小小宇航员在圆形厨房煎一颗星星形状的鸡蛋,鸡蛋轻轻跳起。手作指纹质感、暖奶油色、柔和侧光,固定中景,动作简短连续,可爱但不夸张。",
},
{
title: "山水之间的一叶舟",
description: "水墨留白 · 横向移镜与轻雾",
image: "/short-drama-styles/ink-narrative.jpg",
mode: "video",
prompt: "中国水墨动画,一叶小舟缓缓穿过层叠远山,薄雾留白,舟上人抬手触碰落下的花瓣。镜头平稳横移,墨色有自然晕染,少量朱红点缀,画面安静,动作节奏舒缓。",
},
{
title: "雨后的玻璃花房",
description: "治愈场景 · 前景水滴与逆光",
image: "/short-drama-styles/nature-healing.jpg",
mode: "video",
prompt: "清晨雨后的玻璃花房,镜头透过挂着水滴的叶片缓缓推向盛开的白花,阳光从侧后方进入,浅景深,真实植物纹理,空气中薄薄水汽,宁静自然,无人物和文字。",
},
{
title: "都市少女角色转面",
description: "角色概念 · 统一服装与形体比例",
image: "/short-drama-styles/chinese-2d.jpg",
mode: "image",
prompt: "原创二维动画都市少女角色设定,短发、宽松工装夹克和帆布包,正面、侧面与背面三视图,服装细节和身高比例一致,干净线稿配平涂阴影,暖灰背景,不添加文字,不模仿已有动漫角色。",
},
{
title: "梦境里的倒置房间",
description: "超现实概念 · 重力反转与柔光",
image: "/short-drama-styles/surreal-dream.jpg",
mode: "image",
prompt: "超现实电影场景概念图,一间漂浮在云海中的倒置卧室,床和书桌悬在天花板上,一扇门通向浅粉色天空。低饱和奶油与雾蓝色,柔和漫反射,精确透视,细腻材质,无人物,无文字。",
},
{
title: "海边旅店的黄昏",
description: "实拍场景 · 用道具留下人物痕迹",
image: "/short-drama-styles/urban-live-action.jpg",
mode: "image",
prompt: "沿海小城旧旅店房间的电影置景概念图,窗外是黄昏海面,风吹动米白窗帘,桌上有两杯没有喝完的茶和一本翻开的书。暖橙与浅蓝对比,自然胶片颗粒,眼平中广角,没有人物和可读文字。",
},
{
title: "鲜亮漫画封面",
description: "平面构成 · 大色块与戏剧性透视",
image: "/short-drama-styles/comic-pop.jpg",
mode: "image",
prompt: "原创漫画封面插画,一位骑单车的城市信使跃过雨后积水,戏剧性低角度透视,青蓝、珊瑚红与暖黄色大色块,半调网点,清晰黑色轮廓,背景简洁,为顶部标题留白但不生成文字。",
},
{
title: "烘焙店的秘密帮手",
description: "三维角色 · 柔和材质与亲切表情",
image: "/short-drama-styles/three-d-cartoon.jpg",
mode: "image",
prompt: "原创三维动画角色概念图,一只穿着面粉围裙的小浣熊站在烘焙台前,鼻尖沾着面粉,手里举着刚烤好的面包。柔软毛发、温暖侧光、自然可爱的比例,橘棕色和奶油白配色,背景轻微虚化。",
},
]; ];
/** 本项目编写的条目,灵感页把它单独作为「原创」分类。 */ /** 本项目编写的条目,灵感页把它单独作为「原创」分类。 */
+45 -15
View File
@@ -5,23 +5,44 @@ import type { ReferenceAudio, ReferenceVideo } from "@/types/media";
// Existing channel contract values; these are not a claim about every provider's current limits. // Existing channel contract values; these are not a claim about every provider's current limits.
export const SEEDANCE_REFERENCE_LIMITS = { images: 9, videos: 3, audios: 3, imageMaxBytes: 30 * 1048576, videoMaxBytes: 50 * 1048576, audioMaxBytes: 15 * 1048576 }; export const SEEDANCE_REFERENCE_LIMITS = { images: 9, videos: 3, audios: 3, imageMaxBytes: 30 * 1048576, videoMaxBytes: 50 * 1048576, audioMaxBytes: 15 * 1048576 };
export const seedanceResolutionOptions = [{ label: "480P", value: "480p" }, { label: "720P", value: "720p" }, { label: "1080P", value: "1080p" }] as const; export const seedanceResolutionOptions = [
{ label: "480P", value: "480p" },
{ label: "720P", value: "720p" },
{ label: "1080P", value: "1080p" },
] as const;
export const seedanceRatioOptions = [ export const seedanceRatioOptions = [
{ label: "横屏", value: "16:9" }, { label: "竖屏", value: "9:16" }, { label: "方形", value: "1:1" }, { label: "横屏", value: "16:9" },
{ label: "标准横屏", value: "4:3" }, { label: "标准竖屏", value: "3:4" }, { label: "宽银幕", value: "21:9" }, { label: "自适应", value: "adaptive" }, { label: "竖屏", value: "9:16" },
{ label: "方形", value: "1:1" },
{ label: "标准横屏", value: "4:3" },
{ label: "标准竖屏", value: "3:4" },
{ label: "宽银幕", value: "21:9" },
{ label: "自适应", value: "adaptive" },
] as const; ] as const;
export const seedanceDurationOptions = VIDEO_DURATION_OPTIONS; export const seedanceDurationOptions = VIDEO_DURATION_OPTIONS;
const rasterRows: Record<string, readonly string[]> = { const rasterRows: Record<string, readonly string[]> = {
"16:9": ["864x496", "1280x720", "1920x1080"], "4:3": ["752x560", "1112x834", "1664x1248"], "16:9": ["864x496", "1280x720", "1920x1080"],
"1:1": ["640x640", "960x960", "1440x1440"], "3:4": ["560x752", "834x1112", "1248x1664"], "4:3": ["752x560", "1112x834", "1664x1248"],
"9:16": ["496x864", "720x1280", "1080x1920"], "21:9": ["992x432", "1470x630", "2206x946"], "1:1": ["640x640", "960x960", "1440x1440"],
"3:4": ["560x752", "834x1112", "1248x1664"],
"9:16": ["496x864", "720x1280", "1080x1920"],
"21:9": ["992x432", "1470x630", "2206x946"],
}; };
const ratios = Object.keys(rasterRows).map((label) => { const [w, h] = label.split(":").map(Number); return { label, ratio: w / h }; }); const ratios = Object.keys(rasterRows).map((label) => {
const [w, h] = label.split(":").map(Number);
return { label, ratio: w / h };
});
export function isSeedanceVideoModel(model: string): boolean { return /seedance/i.test(model); } export function isSeedanceVideoModel(model: string): boolean {
export function isSeedanceFastModel(model: string): boolean { return isSeedanceVideoModel(model) && /fast/i.test(model); } return /seedance/i.test(model);
export function isArkPlanBaseUrl(baseUrl: string): boolean { return /\/api\/plan\/v3/i.test(baseUrl); } }
export function isSeedanceFastModel(model: string): boolean {
return isSeedanceVideoModel(model) && /fast/i.test(model);
}
export function isArkPlanBaseUrl(baseUrl: string): boolean {
return /\/api\/plan\/v3/i.test(baseUrl);
}
export function isSeedanceVideoConfig(config: AiConfig | Pick<AiConfig, "model" | "videoModel" | "baseUrl">): boolean { export function isSeedanceVideoConfig(config: AiConfig | Pick<AiConfig, "model" | "videoModel" | "baseUrl">): boolean {
const request = "channels" in config ? resolveModelRequestConfig(config, config.model || config.videoModel) : config; const request = "channels" in config ? resolveModelRequestConfig(config, config.model || config.videoModel) : config;
@@ -39,7 +60,9 @@ export function normalizeSeedanceResolution(value: string, model = ""): string {
const supported = isSeedanceFastModel(model) ? ["480p", "720p"] : ["480p", "720p", "1080p", "2160p"]; const supported = isSeedanceFastModel(model) ? ["480p", "720p"] : ["480p", "720p", "1080p", "2160p"];
return supported.includes(requested) ? requested : "720p"; return supported.includes(requested) ? requested : "720p";
} }
export function normalizeSeedanceDuration(value: string): number { return +normalizeVideoDuration(value); } export function normalizeSeedanceDuration(value: string): number {
return +normalizeVideoDuration(value);
}
export function normalizeSeedanceRatio(value: string): string { export function normalizeSeedanceRatio(value: string): string {
if (Object.hasOwn(rasterRows, value)) return value; if (Object.hasOwn(rasterRows, value)) return value;
@@ -50,7 +73,10 @@ export function normalizeSeedanceRatio(value: string): string {
let distance = Infinity; let distance = Infinity;
for (const entry of ratios) { for (const entry of ratios) {
const next = Math.abs(entry.ratio - requested); const next = Math.abs(entry.ratio - requested);
if (next < distance) { distance = next; nearest = entry; } if (next < distance) {
distance = next;
nearest = entry;
}
} }
return nearest.label; return nearest.label;
} }
@@ -61,11 +87,15 @@ export function seedancePixelLabel(resolution: string, ratio: string): string {
const column = ["480p", "720p", "1080p"].indexOf(normalizeSeedanceResolution(resolution)); const column = ["480p", "720p", "1080p"].indexOf(normalizeSeedanceResolution(resolution));
return column < 0 ? "" : rasterRows[aspect]?.[column] || ""; return column < 0 ? "" : rasterRows[aspect]?.[column] || "";
} }
export function boolConfig(value: string | undefined, fallback: boolean): boolean { return value === "true" || (value !== "false" && fallback); } export function boolConfig(value: string | undefined, fallback: boolean): boolean {
return value === "true" || (value !== "false" && fallback);
}
export function seedanceReferenceLabel(kind: "image" | "video" | "audio", index: number): string { export function seedanceReferenceLabel(kind: "image" | "video" | "audio", index: number): string {
return `${({ image: "图片", video: "视频", audio: "音频" })[kind]}${index + 1}`; return `${{ image: "图片", video: "视频", audio: "音频" }[kind]}${index + 1}`;
}
export function buildSeedancePromptText(prompt: string, _images: ReferenceImage[], _videos: ReferenceVideo[], _audios: ReferenceAudio[]): string {
return prompt.trim();
} }
export function buildSeedancePromptText(prompt: string, _images: ReferenceImage[], _videos: ReferenceVideo[], _audios: ReferenceAudio[]): string { return prompt.trim(); }
type VideoRule = { valid: (video: ReferenceVideo) => boolean; message: string }; type VideoRule = { valid: (video: ReferenceVideo) => boolean; message: string };
const videoRules: VideoRule[] = [ const videoRules: VideoRule[] = [
+25 -2
View File
@@ -27,7 +27,19 @@ export async function readAssetPackage(file: File): Promise<Asset[]> {
const manifestBlob = archive.get("assets.json"); const manifestBlob = archive.get("assets.json");
if (!manifestBlob) throw new Error("素材包缺少 assets.json"); if (!manifestBlob) throw new Error("素材包缺少 assets.json");
const manifest: unknown = JSON.parse(await manifestBlob.text()); const manifest: unknown = JSON.parse(await manifestBlob.text());
if (!manifest || typeof manifest !== "object" || !("app" in manifest) || manifest.app !== "yingce" || !("version" in manifest) || manifest.version !== 1 || !("assets" in manifest) || !Array.isArray(manifest.assets) || !("files" in manifest) || !Array.isArray(manifest.files)) throw new Error("素材包格式或版本不受支持"); if (
!manifest ||
typeof manifest !== "object" ||
!("app" in manifest) ||
manifest.app !== "yingce" ||
!("version" in manifest) ||
manifest.version !== 1 ||
!("assets" in manifest) ||
!Array.isArray(manifest.assets) ||
!("files" in manifest) ||
!Array.isArray(manifest.files)
)
throw new Error("素材包格式或版本不受支持");
const images = new Set<string>(); const images = new Set<string>();
for (const asset of manifest.assets) { for (const asset of manifest.assets) {
if (!asset || typeof asset !== "object" || typeof asset.id !== "string" || !asset.data || typeof asset.data !== "object" || typeof asset.kind !== "string") throw new Error("素材包包含无效素材"); if (!asset || typeof asset !== "object" || typeof asset.id !== "string" || !asset.data || typeof asset.data !== "object" || typeof asset.kind !== "string") throw new Error("素材包包含无效素材");
@@ -35,7 +47,18 @@ export async function readAssetPackage(file: File): Promise<Asset[]> {
} }
// Validate the whole manifest before making the first persistent write. // Validate the whole manifest before making the first persistent write.
const writes = manifest.files.map((entry: unknown) => { const writes = manifest.files.map((entry: unknown) => {
if (!entry || typeof entry !== "object" || !("storageKey" in entry) || typeof entry.storageKey !== "string" || !entry.storageKey || !("path" in entry) || typeof entry.path !== "string" || !("mimeType" in entry) || typeof entry.mimeType !== "string") throw new Error("素材包文件索引无效"); if (
!entry ||
typeof entry !== "object" ||
!("storageKey" in entry) ||
typeof entry.storageKey !== "string" ||
!entry.storageKey ||
!("path" in entry) ||
typeof entry.path !== "string" ||
!("mimeType" in entry) ||
typeof entry.mimeType !== "string"
)
throw new Error("素材包文件索引无效");
const blob = archive.get(entry.path); const blob = archive.get(entry.path);
if (!blob) throw new Error(`素材包缺少文件:${entry.path}`); if (!blob) throw new Error(`素材包缺少文件:${entry.path}`);
if ("bytes" in entry && entry.bytes !== blob.size) throw new Error(`素材包文件大小不匹配:${entry.path}`); if ("bytes" in entry && entry.bytes !== blob.size) throw new Error(`素材包文件大小不匹配:${entry.path}`);
@@ -107,13 +107,13 @@
/* 玻璃质感边框:亮描边勾出面板边缘,内侧一圈高光给厚度, /* 玻璃质感边框:亮描边勾出面板边缘,内侧一圈高光给厚度,
外圈大而软的投影把面板从背景里"抬"起来,避免看成扁平纸片。 外圈大而软的投影把面板从背景里"抬"起来,避免看成扁平纸片。
阴影只留三层——11 张卡片都在动,每多一层就是每帧多一次大范围重绘。 */ 阴影只留三层——11 张卡片都在动,每多一层就是每帧多一次大范围重绘。 */
border: 1px solid rgba(255, 255, 255, .5); border: 1px solid rgba(255, 255, 255, 0.5);
border-radius: var(--r-2xl, 16px); border-radius: var(--r-2xl, 16px);
background: var(--creation-surface-raised, #f0f1ee); background: var(--creation-surface-raised, #f0f1ee);
box-shadow: box-shadow:
inset 0 1px 0 rgba(255, 255, 255, .55), inset 0 1px 0 rgba(255, 255, 255, 0.55),
0 0 0 1px rgba(0, 0, 0, .07), 0 0 0 1px rgba(0, 0, 0, 0.07),
0 28px 54px -26px rgba(0, 0, 0, .52); 0 28px 54px -26px rgba(0, 0, 0, 0.52);
cursor: pointer; cursor: pointer;
/* 只有最前面那张能点,后面的点击会穿到页面上,不去抢焦点。 */ /* 只有最前面那张能点,后面的点击会穿到页面上,不去抢焦点。 */
pointer-events: none; pointer-events: none;
@@ -124,15 +124,12 @@
/* 先把卡片按自身尺寸对中,再叠加纵深位移与缩放——位移不会被 scale 影响。 /* 先把卡片按自身尺寸对中,再叠加纵深位移与缩放——位移不会被 scale 影响。
--card-enter-y / --card-enter-scale 是入场位移,封面就绪后归零, --card-enter-y / --card-enter-scale 是入场位移,封面就绪后归零,
所以卡片是"从略下方、略小的位置浮上来",而不是硬闪出来。 */ 所以卡片是"从略下方、略小的位置浮上来",而不是硬闪出来。 */
transform: transform: translate(-50%, -50%) translate(var(--card-x, 0px), var(--card-enter-y, 44px)) scale(calc(var(--card-scale, 1) * var(--card-enter-scale, 0.95)));
translate(-50%, -50%)
translate(var(--card-x, 0px), var(--card-enter-y, 44px))
scale(calc(var(--card-scale, 1) * var(--card-enter-scale, .95)));
/* 只动 transform 和 opacity,两者都能交给合成层,不触发重排重绘。 /* 只动 transform 和 opacity,两者都能交给合成层,不触发重排重绘。
缓动先缓后快再长尾软着陆,观感是镜头平稳推拉而不是"弹"过去。 */ 缓动先缓后快再长尾软着陆,观感是镜头平稳推拉而不是"弹"过去。 */
transition: transition:
transform 660ms cubic-bezier(.32, .72, 0, 1), transform 660ms cubic-bezier(0.32, 0.72, 0, 1),
opacity 520ms cubic-bezier(.4, 0, .2, 1); opacity 520ms cubic-bezier(0.4, 0, 0.2, 1);
} }
/* 封面已就绪:放行这张卡。 */ /* 封面已就绪:放行这张卡。 */
@@ -151,13 +148,10 @@
独立属性会插在 transform 之前合成,卡片会被缩放带得偏离原位。 独立属性会插在 transform 之前合成,卡片会被缩放带得偏离原位。
抬起用更短的时长——切换是运镜,悬停是手感,两者不该共用一个节奏。 */ 抬起用更短的时长——切换是运镜,悬停是手感,两者不该共用一个节奏。 */
.creation-tunnel-card.is-active:hover { .creation-tunnel-card.is-active:hover {
transform: transform: translate(-50%, -50%) translate(var(--card-x, 0px), calc(var(--card-enter-y, 0px) - 14px)) scale(calc(var(--card-scale, 1) * var(--card-enter-scale, 1) * 1.04));
translate(-50%, -50%)
translate(var(--card-x, 0px), calc(var(--card-enter-y, 0px) - 14px))
scale(calc(var(--card-scale, 1) * var(--card-enter-scale, 1) * 1.04));
transition: transition:
transform 240ms cubic-bezier(.2, .8, .3, 1), transform 240ms cubic-bezier(0.2, 0.8, 0.3, 1),
opacity 520ms cubic-bezier(.4, 0, .2, 1); opacity 520ms cubic-bezier(0.4, 0, 0.2, 1);
} }
/* 玻璃罩:斜向高光 + 底部压暗,让面板读起来是一块有厚度的玻璃,不是一张图。 */ /* 玻璃罩:斜向高光 + 底部压暗,让面板读起来是一块有厚度的玻璃,不是一张图。 */
@@ -165,9 +159,7 @@
content: ""; content: "";
position: absolute; position: absolute;
inset: 0; inset: 0;
background: background: linear-gradient(158deg, rgba(255, 255, 255, 0.3), rgba(255, 255, 255, 0) 40%), linear-gradient(0deg, rgba(0, 0, 0, 0.18), rgba(0, 0, 0, 0) 44%);
linear-gradient(158deg, rgba(255, 255, 255, .3), rgba(255, 255, 255, 0) 40%),
linear-gradient(0deg, rgba(0, 0, 0, .18), rgba(0, 0, 0, 0) 44%);
pointer-events: none; pointer-events: none;
} }
@@ -186,13 +178,13 @@
flex-direction: column; flex-direction: column;
gap: var(--space-1, 4px); gap: var(--space-1, 4px);
padding: 44px var(--space-4, 16px) var(--space-3, 12px); padding: 44px var(--space-4, 16px) var(--space-3, 12px);
background: linear-gradient(transparent, rgba(0, 0, 0, .52) 40%, rgba(0, 0, 0, .84)); background: linear-gradient(transparent, rgba(0, 0, 0, 0.52) 40%, rgba(0, 0, 0, 0.84));
color: #fff; color: #fff;
text-align: left; text-align: left;
text-shadow: 0 1px 8px rgba(0, 0, 0, .55); text-shadow: 0 1px 8px rgba(0, 0, 0, 0.55);
opacity: 0; opacity: 0;
/* 比位移稍慢一点收尾,避免文字跟着画面一起"闪"进闪出。 */ /* 比位移稍慢一点收尾,避免文字跟着画面一起"闪"进闪出。 */
transition: opacity 380ms cubic-bezier(.4, 0, .2, 1); transition: opacity 380ms cubic-bezier(0.4, 0, 0.2, 1);
} }
.creation-tunnel-card.is-active .creation-tunnel-card-info { .creation-tunnel-card.is-active .creation-tunnel-card-info {
@@ -205,7 +197,7 @@
gap: var(--space-1, 4px); gap: var(--space-1, 4px);
font-size: var(--fs-label, 11px); font-size: var(--fs-label, 11px);
line-height: 1.2; line-height: 1.2;
opacity: .84; opacity: 0.84;
} }
.creation-tunnel-card-cta svg { .creation-tunnel-card-cta svg {
@@ -224,7 +216,7 @@
overflow: hidden; overflow: hidden;
font-size: var(--fs-caption, 12px); font-size: var(--fs-caption, 12px);
line-height: 1.45; line-height: 1.45;
opacity: .84; opacity: 0.84;
-webkit-box-orient: vertical; -webkit-box-orient: vertical;
-webkit-line-clamp: 2; -webkit-line-clamp: 2;
} }
@@ -243,7 +235,7 @@
background: color-mix(in srgb, var(--user-surface) 62%, transparent); background: color-mix(in srgb, var(--user-surface) 62%, transparent);
border: 1px solid color-mix(in srgb, var(--user-ink) 14%, transparent); border: 1px solid color-mix(in srgb, var(--user-ink) 14%, transparent);
border-radius: var(--r-full, 999px); border-radius: var(--r-full, 999px);
box-shadow: 0 14px 30px -14px rgba(0, 0, 0, .55); box-shadow: 0 14px 30px -14px rgba(0, 0, 0, 0.55);
-webkit-backdrop-filter: blur(18px) saturate(1.3); -webkit-backdrop-filter: blur(18px) saturate(1.3);
backdrop-filter: blur(18px) saturate(1.3); backdrop-filter: blur(18px) saturate(1.3);
cursor: pointer; cursor: pointer;
@@ -311,7 +303,7 @@
.creation-inspiration-credit summary { .creation-inspiration-credit summary {
cursor: pointer; cursor: pointer;
list-style: none; list-style: none;
opacity: .72; opacity: 0.72;
transition: opacity var(--user-motion, 180ms) ease; transition: opacity var(--user-motion, 180ms) ease;
} }
@@ -341,10 +333,7 @@
} }
.creation-tunnel-card.is-active:hover { .creation-tunnel-card.is-active:hover {
transform: transform: translate(-50%, -50%) translate(var(--card-x, 0px), 0) scale(var(--card-scale, 1));
translate(-50%, -50%)
translate(var(--card-x, 0px), 0)
scale(var(--card-scale, 1));
} }
.creation-gallery-arrow { .creation-gallery-arrow {
@@ -385,4 +374,4 @@
.creation-tunnel-card-desc { .creation-tunnel-card-desc {
-webkit-line-clamp: 1; -webkit-line-clamp: 1;
} }
} }
@@ -205,13 +205,7 @@ export function CreationInspirationTunnel({ mode, onStartPrompt }: { mode: Creat
if (!shots.length) return null; if (!shots.length) return null;
return ( return (
<div <div className="creation-inspiration-tunnel" onPointerEnter={() => setPaused(true)} onPointerLeave={() => setPaused(false)} onFocusCapture={() => setPaused(true)} onBlurCapture={() => setPaused(false)}>
className="creation-inspiration-tunnel"
onPointerEnter={() => setPaused(true)}
onPointerLeave={() => setPaused(false)}
onFocusCapture={() => setPaused(true)}
onBlurCapture={() => setPaused(false)}
>
<div ref={stageRef} className="creation-gallery-stage" aria-hidden="true"> <div ref={stageRef} className="creation-gallery-stage" aria-hidden="true">
{shots.map((inspiration, index) => { {shots.map((inspiration, index) => {
const id = catalogIdOf(inspiration); const id = catalogIdOf(inspiration);
@@ -269,10 +263,14 @@ export function CreationInspirationTunnel({ mode, onStartPrompt }: { mode: Creat
用 !important 改写 color / background 并把 transform 顶成 translateY(-1px), 用 !important 改写 color / background 并把 transform 顶成 translateY(-1px),
按钮会当场掉半个身位。带 span 的按钮不在那条规则的射程内。 */} 按钮会当场掉半个身位。带 span 的按钮不在那条规则的射程内。 */}
<button type="button" className="creation-gallery-arrow is-prev" aria-label="上一张灵感" onClick={() => step(-1)}> <button type="button" className="creation-gallery-arrow is-prev" aria-label="上一张灵感" onClick={() => step(-1)}>
<span className="creation-gallery-arrow-icon"><ChevronLeft aria-hidden="true" /></span> <span className="creation-gallery-arrow-icon">
<ChevronLeft aria-hidden="true" />
</span>
</button> </button>
<button type="button" className="creation-gallery-arrow is-next" aria-label="下一张灵感" onClick={() => step(1)}> <button type="button" className="creation-gallery-arrow is-next" aria-label="下一张灵感" onClick={() => step(1)}>
<span className="creation-gallery-arrow-icon"><ChevronRight aria-hidden="true" /></span> <span className="creation-gallery-arrow-icon">
<ChevronRight aria-hidden="true" />
</span>
</button> </button>
{/* 卡片本身对辅助技术隐藏,切换结果靠这条播报传达。 */} {/* 卡片本身对辅助技术隐藏,切换结果靠这条播报传达。 */}
@@ -281,4 +279,4 @@ export function CreationInspirationTunnel({ mode, onStartPrompt }: { mode: Creat
</p> </p>
</div> </div>
); );
} }
@@ -0,0 +1,9 @@
import { curatedInspirations, inspirationSources } from "@/lib/inspirations/catalog";
/** Compatibility exports for the original creation page inspiration contract. */
export const creationFeaturedWorks = curatedInspirations.map(({ sourceId, credit, ...item }) => ({
...item,
...(sourceId === "chatgpt-prompts" && credit ? { source: credit } : {}),
}));
export const inspirationSource = inspirationSources["chatgpt-prompts"];
+142 -91
View File
@@ -90,13 +90,21 @@ export default function InspirationsPage() {
let cancelled = false; let cancelled = false;
setLoadError(""); setLoadError("");
loadInspirationCatalog() loadInspirationCatalog()
.then((loaded) => { if (!cancelled) setCatalog(loaded); }) .then((loaded) => {
.catch((error) => { if (!cancelled) setLoadError(error instanceof Error ? error.message : "灵感目录加载失败"); }); if (!cancelled) setCatalog(loaded);
return () => { cancelled = true; }; })
.catch((error) => {
if (!cancelled) setLoadError(error instanceof Error ? error.message : "灵感目录加载失败");
});
return () => {
cancelled = true;
};
}, [reloadKey]); }, [reloadKey]);
// 筛选条件一变就回第一页,否则会停在一个已经不存在的位置上。 // 筛选条件一变就回第一页,否则会停在一个已经不存在的位置上。
useEffect(() => { setPage(1); }, [source, modeFilter, category, view, sort, debouncedSearch, pageSize]); useEffect(() => {
setPage(1);
}, [source, modeFilter, category, view, sort, debouncedSearch, pageSize]);
const overlay = useMemo(() => ({ custom, overrides, hidden }), [custom, hidden, overrides]); const overlay = useMemo(() => ({ custom, overrides, hidden }), [custom, hidden, overrides]);
const resolved = useMemo(() => (catalog ? resolveInspirations(catalog.entries, overlay) : []), [catalog, overlay]); const resolved = useMemo(() => (catalog ? resolveInspirations(catalog.entries, overlay) : []), [catalog, overlay]);
@@ -136,9 +144,7 @@ export default function InspirationsPage() {
merged.set(option.id, { label: option.label, count: (current?.count ?? 0) + option.count }); merged.set(option.id, { label: option.label, count: (current?.count ?? 0) + option.count });
} }
} }
return [...merged.entries()] return [...merged.entries()].sort((left, right) => right[1].count - left[1].count || left[1].label.localeCompare(right[1].label, "zh-Hans-CN")).map(([value, { label, count }]) => ({ value, label, count }));
.sort((left, right) => right[1].count - left[1].count || left[1].label.localeCompare(right[1].label, "zh-Hans-CN"))
.map(([value, { label, count }]) => ({ value, label, count }));
}, [catalog, source]); }, [catalog, source]);
const sourceCounts = useMemo(() => { const sourceCounts = useMemo(() => {
@@ -194,75 +200,101 @@ export default function InspirationsPage() {
const paged = useMemo(() => visible.slice((page - 1) * pageSize, page * pageSize), [visible, page, pageSize]); const paged = useMemo(() => visible.slice((page - 1) * pageSize, page * pageSize), [visible, page, pageSize]);
const handleUse = useCallback((item: CreationInspiration) => { const handleUse = useCallback(
navigate("/create", { state: { inspirationPrompt: fillablePrompt(item), inspirationMode: item.mode } }); (item: CreationInspiration) => {
}, [navigate]); navigate("/create", { state: { inspirationPrompt: fillablePrompt(item), inspirationMode: item.mode } });
},
[navigate],
);
const handleCopy = useCallback((text: string, label: string) => { const handleCopy = useCallback(
void navigator.clipboard.writeText(text).then( (text: string, label: string) => {
() => message.success(`${label}已复制`), void navigator.clipboard.writeText(text).then(
() => message.error("复制失败,请手动选中文本"), () => message.success(`${label}已复制`),
); () => message.error("复制失败,请手动选中文本"),
}, [message]); );
},
[message],
);
const handleDelete = useCallback((item: CreationInspiration) => { const handleDelete = useCallback(
const id = catalogIdOf(item); (item: CreationInspiration) => {
const isCustom = isCustomInspiration(id); const id = catalogIdOf(item);
modal.confirm({ const isCustom = isCustomInspiration(id);
className: "workspace-modal workspace-modal-compact", modal.confirm({
title: isCustom ? "删除这条灵感?" : "从库中隐藏这条灵感?", className: "workspace-modal workspace-modal-compact",
content: isCustom title: isCustom ? "删除这条灵感?" : "从库中隐藏这条灵感?",
? `「${item.title}」会从本地灵感库移除,此操作不可撤销。` content: isCustom ? `「${item.title}」会从本地灵感库移除,此操作不可撤销。` : `「${item.title}」来自外部目录,不能真正删除;隐藏后可用「已隐藏」视图恢复,重新导入外部目录也不会让它复现。`,
: `「${item.title}」来自外部目录,不能真正删除;隐藏后可用「已隐藏」视图恢复,重新导入外部目录也不会让它复现。`, okText: isCustom ? "删除" : "隐藏",
okText: isCustom ? "删除" : "隐藏", okButtonProps: { danger: true },
okButtonProps: { danger: true }, cancelText: "保留",
cancelText: "保留", onOk: () => {
onOk: () => { removeEntry(id);
removeEntry(id); if (detail && catalogIdOf(detail) === id) setDetail(null);
if (detail && catalogIdOf(detail) === id) setDetail(null); message.success(isCustom ? "已删除" : "已隐藏");
message.success(isCustom ? "已删除" : "已隐藏"); },
}, });
}); },
}, [detail, message, modal, removeEntry]); [detail, message, modal, removeEntry],
);
const handleSubmit = useCallback((draft: Parameters<typeof createEntry>[0]) => { const handleSubmit = useCallback(
if (editing) { (draft: Parameters<typeof createEntry>[0]) => {
updateEntry(catalogIdOf(editing), draft); if (editing) {
message.success("已保存修改"); updateEntry(catalogIdOf(editing), draft);
setDetail((current) => (current && catalogIdOf(current) === catalogIdOf(editing) ? { ...current, ...draft } : current)); message.success("已保存修改");
setEditing(null); setDetail((current) => (current && catalogIdOf(current) === catalogIdOf(editing) ? { ...current, ...draft } : current));
return; setEditing(null);
} return;
createEntry(draft); }
// 新建后把筛选整体清掉:自建条目的来源固定是「原创」、分类也常和当前筛选不符, createEntry(draft);
// 不清的话用户刚点完"创建"却看不到自己建的东西。 // 新建后把筛选整体清掉:自建条目的来源固定是「原创」、分类也常和当前筛选不符,
setSource("all"); // 不清的话用户刚点完"创建"却看不到自己建的东西。
setModeFilter("all"); setSource("all");
setCategory("all"); setModeFilter("all");
setView("all"); setCategory("all");
setSearch(""); setView("all");
message.success("灵感已创建"); setSearch("");
}, [createEntry, editing, message, updateEntry]); message.success("灵感已创建");
},
[createEntry, editing, message, updateEntry],
);
const handleExport = useCallback(() => { const handleExport = useCallback(() => {
downloadText(exportPayload(), exportFileName()); downloadText(exportPayload(), exportFileName());
message.success("已导出本地改动(自建条目 / 改写 / 隐藏 / 收藏)"); message.success("已导出本地改动(自建条目 / 改写 / 隐藏 / 收藏)");
}, [exportPayload, message]); }, [exportPayload, message]);
const handleImportFile = useCallback(async (file: File) => { const handleImportFile = useCallback(
try { async (file: File) => {
const result = importPayload(await file.text()); try {
message.success(`导入完成:新增 ${result.created},覆盖 ${result.updated}${result.skipped ? `,跳过 ${result.skipped} 条无效数据` : ""}`); const result = importPayload(await file.text());
} catch (error) { message.success(`导入完成:新增 ${result.created},覆盖 ${result.updated}${result.skipped ? `,跳过 ${result.skipped} 条无效数据` : ""}`);
message.error(error instanceof Error ? error.message : "导入失败"); } catch (error) {
} message.error(error instanceof Error ? error.message : "导入失败");
}, [importPayload, message]); }
},
[importPayload, message],
);
const headerActions = ( const headerActions = (
<> <>
<Button icon={<Import className="size-4" />} onClick={() => importRef.current?.click()}>导入</Button> <Button icon={<Import className="size-4" />} onClick={() => importRef.current?.click()}>
<Button icon={<Download className="size-4" />} onClick={handleExport}>导出</Button> 导入
<Button type="primary" icon={<Plus className="size-4" />} onClick={() => { setEditing(null); setEditorOpen(true); }}>新建灵感</Button> </Button>
<Button icon={<Download className="size-4" />} onClick={handleExport}>
导出
</Button>
<Button
type="primary"
icon={<Plus className="size-4" />}
onClick={() => {
setEditing(null);
setEditorOpen(true);
}}
>
新建灵感
</Button>
<input <input
ref={importRef} ref={importRef}
type="file" type="file"
@@ -282,11 +314,7 @@ export default function InspirationsPage() {
return ( return (
<WorkspacePage> <WorkspacePage>
<PageHeader <PageHeader title="灵感库" description={`${total} 条提示词,按来源、分类和创作类型挑,点开可以一键带去创作页`} actions={headerActions} />
title="灵感库"
description={`${total} 条提示词,按来源、分类和创作类型挑,点开可以一键带去创作页`}
actions={headerActions}
/>
{loadError ? ( {loadError ? (
<WorkspaceErrorState title="灵感目录加载失败" description={loadError} onRetry={() => setReloadKey((key) => key + 1)} /> <WorkspaceErrorState title="灵感目录加载失败" description={loadError} onRetry={() => setReloadKey((key) => key + 1)} />
@@ -307,13 +335,7 @@ export default function InspirationsPage() {
<span className="inspiration-chip-count">{source === "all" ? resolved.length : (sourceCounts.get(source) ?? 0)}</span> <span className="inspiration-chip-count">{source === "all" ? resolved.length : (sourceCounts.get(source) ?? 0)}</span>
</button> </button>
{categoryChoices.slice(0, 16).map((choice) => ( {categoryChoices.slice(0, 16).map((choice) => (
<button <button key={choice.value} type="button" className="inspiration-chip" aria-pressed={category === choice.value} onClick={() => setCategory(category === choice.value ? "all" : choice.value)}>
key={choice.value}
type="button"
className="inspiration-chip"
aria-pressed={category === choice.value}
onClick={() => setCategory(category === choice.value ? "all" : choice.value)}
>
{choice.label} {choice.label}
<span className="inspiration-chip-count">{choice.count}</span> <span className="inspiration-chip-count">{choice.count}</span>
</button> </button>
@@ -321,14 +343,7 @@ export default function InspirationsPage() {
</div> </div>
<div className="flex flex-wrap items-center gap-2"> <div className="flex flex-wrap items-center gap-2">
<Input <Input allowClear prefix={<Search className="size-4 text-foreground/40" />} placeholder="搜标题、描述或标签" value={search} onChange={(event) => setSearch(event.target.value)} className="max-w-xs" />
allowClear
prefix={<Search className="size-4 text-foreground/40" />}
placeholder="搜标题、描述或标签"
value={search}
onChange={(event) => setSearch(event.target.value)}
className="max-w-xs"
/>
<SegmentedControl options={VIEW_OPTIONS} value={view} onChange={(value) => setView(value as ViewFilter)} /> <SegmentedControl options={VIEW_OPTIONS} value={view} onChange={(value) => setView(value as ViewFilter)} />
<Select <Select
options={[ options={[
@@ -339,7 +354,10 @@ export default function InspirationsPage() {
})), })),
]} ]}
value={source} value={source}
onChange={(value) => { setSource(value as SourceFilter); setCategory("all"); }} onChange={(value) => {
setSource(value as SourceFilter);
setCategory("all");
}}
className="w-52" className="w-52"
/> />
<Select options={SORT_OPTIONS} value={sort} onChange={(value) => setSort(value as SortKey)} className="w-32" /> <Select options={SORT_OPTIONS} value={sort} onChange={(value) => setSort(value as SortKey)} className="w-32" />
@@ -370,13 +388,28 @@ export default function InspirationsPage() {
<span className="inspiration-card-source">{inspirationSourceOf(item).label}</span> <span className="inspiration-card-source">{inspirationSourceOf(item).label}</span>
<div className="inspiration-card-actions"> <div className="inspiration-card-actions">
<Tooltip title={favorite ? "取消收藏" : "收藏"}> <Tooltip title={favorite ? "取消收藏" : "收藏"}>
<button type="button" className="inspiration-card-action" aria-pressed={favorite} onClick={(event) => { event.stopPropagation(); toggleFavorite(id); }}> <button
type="button"
className="inspiration-card-action"
aria-pressed={favorite}
onClick={(event) => {
event.stopPropagation();
toggleFavorite(id);
}}
>
<Heart className="size-3.5" fill={favorite ? "currentColor" : "none"} /> <Heart className="size-3.5" fill={favorite ? "currentColor" : "none"} />
</button> </button>
</Tooltip> </Tooltip>
{view === "hidden" ? ( {view === "hidden" ? (
<Tooltip title="恢复显示"> <Tooltip title="恢复显示">
<button type="button" className="inspiration-card-action" onClick={(event) => { event.stopPropagation(); restoreEntry(id); }}> <button
type="button"
className="inspiration-card-action"
onClick={(event) => {
event.stopPropagation();
restoreEntry(id);
}}
>
<RotateCcw className="size-3.5" /> <RotateCcw className="size-3.5" />
</button> </button>
</Tooltip> </Tooltip>
@@ -390,7 +423,10 @@ export default function InspirationsPage() {
], ],
onClick: ({ key, domEvent }) => { onClick: ({ key, domEvent }) => {
domEvent.stopPropagation(); domEvent.stopPropagation();
if (key === "edit") { setEditing(item); setEditorOpen(true); } if (key === "edit") {
setEditing(item);
setEditorOpen(true);
}
if (key === "delete") handleDelete(item); if (key === "delete") handleDelete(item);
}, },
}} }}
@@ -423,7 +459,15 @@ export default function InspirationsPage() {
/> />
)} )}
<PaginationBar current={page} pageSize={pageSize} total={visible.length} onChange={(next, size) => { setPage(next); setPageSize(size); }} /> <PaginationBar
current={page}
pageSize={pageSize}
total={visible.length}
onChange={(next, size) => {
setPage(next);
setPageSize(size);
}}
/>
</div> </div>
)} )}
@@ -435,7 +479,11 @@ export default function InspirationsPage() {
onUse={handleUse} onUse={handleUse}
onCopy={handleCopy} onCopy={handleCopy}
onToggleFavorite={(item) => toggleFavorite(catalogIdOf(item))} onToggleFavorite={(item) => toggleFavorite(catalogIdOf(item))}
onEdit={(item) => { setDetail(null); setEditing(item); setEditorOpen(true); }} onEdit={(item) => {
setDetail(null);
setEditing(item);
setEditorOpen(true);
}}
onDelete={handleDelete} onDelete={handleDelete}
/> />
@@ -443,7 +491,10 @@ export default function InspirationsPage() {
open={editorOpen} open={editorOpen}
item={editing} item={editing}
categoryOptions={categoryChoices} categoryOptions={categoryChoices}
onClose={() => { setEditorOpen(false); setEditing(null); }} onClose={() => {
setEditorOpen(false);
setEditing(null);
}}
onSubmit={handleSubmit} onSubmit={handleSubmit}
/> />
</WorkspacePage> </WorkspacePage>
@@ -41,14 +41,7 @@ export function InspirationDetailModal({
const custom = item ? isCustomInspiration(catalogIdOf(item)) : false; const custom = item ? isCustomInspiration(catalogIdOf(item)) : false;
return ( return (
<AppModal <AppModal open={Boolean(item)} onCancel={onClose} width={880} title={null} footer={null}>
open={Boolean(item)}
onCancel={onClose}
width={880}
title={null}
footer={null}
styles={{ body: { padding: 0 } }}
>
{item ? ( {item ? (
<div className="flex max-h-[76vh] flex-col"> <div className="flex max-h-[76vh] flex-col">
<div className="relative shrink-0 overflow-hidden" style={{ borderRadius: "var(--r-xl, 14px)" }}> <div className="relative shrink-0 overflow-hidden" style={{ borderRadius: "var(--r-xl, 14px)" }}>
@@ -68,22 +61,36 @@ export function InspirationDetailModal({
</button> </button>
</Tooltip> </Tooltip>
<Tooltip title="编辑"> <Tooltip title="编辑">
<button type="button" className="inspiration-icon-button" onClick={() => onEdit(item)}><Pencil className="size-4" /></button> <button type="button" className="inspiration-icon-button" onClick={() => onEdit(item)}>
<Pencil className="size-4" />
</button>
</Tooltip> </Tooltip>
<Tooltip title={custom ? "删除" : "从库中隐藏"}> <Tooltip title={custom ? "删除" : "从库中隐藏"}>
<button type="button" className="inspiration-icon-button" onClick={() => onDelete(item)}><Trash2 className="size-4" /></button> <button type="button" className="inspiration-icon-button" onClick={() => onDelete(item)}>
<Trash2 className="size-4" />
</button>
</Tooltip> </Tooltip>
</div> </div>
</div> </div>
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<MetaRow label="来源">{source?.name ?? "原创"}{item.credit ? ` · ${item.credit}` : ""}</MetaRow> <MetaRow label="来源">
{source?.name ?? "原创"}
{item.credit ? ` · ${item.credit}` : ""}
</MetaRow>
<MetaRow label="分类">{categoryLabel(item)}</MetaRow> <MetaRow label="分类">{categoryLabel(item)}</MetaRow>
<MetaRow label="类型">{modeLabels[item.mode]}{item.ratio ? ` · ${item.ratio}` : ""}</MetaRow> <MetaRow label="类型">
{modeLabels[item.mode]}
{item.ratio ? ` · ${item.ratio}` : ""}
</MetaRow>
{item.tags?.length ? ( {item.tags?.length ? (
<MetaRow label="标签"> <MetaRow label="标签">
<span className="flex flex-wrap gap-1.5"> <span className="flex flex-wrap gap-1.5">
{item.tags.map((tag) => <span key={tag} className="inspiration-chip">{tag}</span>)} {item.tags.map((tag) => (
<span key={tag} className="inspiration-chip">
{tag}
</span>
))}
</span> </span>
</MetaRow> </MetaRow>
) : null} ) : null}
@@ -102,7 +109,9 @@ export function InspirationDetailModal({
<div className="flex shrink-0 items-center justify-end gap-2 border-t border-foreground/8 px-5 py-3"> <div className="flex shrink-0 items-center justify-end gap-2 border-t border-foreground/8 px-5 py-3">
<Button onClick={onClose}>关闭</Button> <Button onClick={onClose}>关闭</Button>
<Button type="primary" icon={<Wand2 className="size-4" />} onClick={() => onUse(item)}>用这个创意创作</Button> <Button type="primary" icon={<Wand2 className="size-4" />} onClick={() => onUse(item)}>
用这个创意创作
</Button>
</div> </div>
</div> </div>
) : null} ) : null}
@@ -115,7 +124,9 @@ function PromptSection({ label, text, onCopy }: { label: string; text: string; o
<section className="flex flex-col gap-2"> <section className="flex flex-col gap-2">
<div className="flex items-center justify-between gap-2"> <div className="flex items-center justify-between gap-2">
<h3 className="text-xs font-medium text-foreground/58">{label}</h3> <h3 className="text-xs font-medium text-foreground/58">{label}</h3>
<Button size="small" icon={<Copy className="size-3.5" />} onClick={() => onCopy(text, label)}>复制</Button> <Button size="small" icon={<Copy className="size-3.5" />} onClick={() => onCopy(text, label)}>
复制
</Button>
</div> </div>
<div className="inspiration-prompt-block">{text}</div> <div className="inspiration-prompt-block">{text}</div>
</section> </section>
@@ -77,12 +77,26 @@ export function InspirationEditorModal({
open={open} open={open}
title={item ? "编辑灵感" : "新建灵感"} title={item ? "编辑灵感" : "新建灵感"}
width={720} width={720}
onCancel={() => { form.resetFields(); onClose(); }} onCancel={() => {
afterOpenChange={(visible) => { if (visible) form.setFieldsValue(toFormValues(item)); }} form.resetFields();
onClose();
}}
afterOpenChange={(visible) => {
if (visible) form.setFieldsValue(toFormValues(item));
}}
footer={ footer={
<div className="flex justify-end gap-2"> <div className="flex justify-end gap-2">
<Button onClick={() => { form.resetFields(); onClose(); }}>取消</Button> <Button
<Button type="primary" onClick={() => void handleOk()}>{item ? "保存" : "创建"}</Button> onClick={() => {
form.resetFields();
onClose();
}}
>
取消
</Button>
<Button type="primary" onClick={() => void handleOk()}>
{item ? "保存" : "创建"}
</Button>
</div> </div>
} }
> >
+8 -8
View File
@@ -20,7 +20,7 @@
text-align: left; text-align: left;
cursor: pointer; cursor: pointer;
transition: transition:
transform var(--user-motion, 180ms) cubic-bezier(.2, .8, .3, 1), transform var(--user-motion, 180ms) cubic-bezier(0.2, 0.8, 0.3, 1),
box-shadow var(--user-motion, 180ms) ease, box-shadow var(--user-motion, 180ms) ease,
border-color var(--user-motion, 180ms) ease; border-color var(--user-motion, 180ms) ease;
} }
@@ -49,7 +49,7 @@
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: cover; object-fit: cover;
transition: transform 420ms cubic-bezier(.2, .8, .3, 1); transition: transform 420ms cubic-bezier(0.2, 0.8, 0.3, 1);
} }
.inspiration-card:hover .inspiration-card-cover img { .inspiration-card:hover .inspiration-card-cover img {
@@ -62,7 +62,7 @@
position: absolute; position: absolute;
inset: auto 0 0; inset: auto 0 0;
height: 46%; height: 46%;
background: linear-gradient(transparent, rgba(0, 0, 0, .58)); background: linear-gradient(transparent, rgba(0, 0, 0, 0.58));
pointer-events: none; pointer-events: none;
} }
@@ -73,7 +73,7 @@
z-index: 1; z-index: 1;
padding: 3px var(--space-2, 8px); padding: 3px var(--space-2, 8px);
border-radius: var(--r-full, 999px); border-radius: var(--r-full, 999px);
background: rgba(20, 22, 26, .48); background: rgba(20, 22, 26, 0.48);
color: #fff; color: #fff;
font-size: var(--fs-tiny, 10px); font-size: var(--fs-tiny, 10px);
line-height: 1.6; line-height: 1.6;
@@ -104,8 +104,8 @@
width: 28px; width: 28px;
height: 28px; height: 28px;
color: #fff; color: #fff;
background: rgba(20, 22, 26, .5); background: rgba(20, 22, 26, 0.5);
border: 1px solid rgba(255, 255, 255, .18); border: 1px solid rgba(255, 255, 255, 0.18);
border-radius: var(--r-full, 999px); border-radius: var(--r-full, 999px);
cursor: pointer; cursor: pointer;
-webkit-backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
@@ -114,7 +114,7 @@
} }
.inspiration-card-action:hover { .inspiration-card-action:hover {
background: rgba(20, 22, 26, .72); background: rgba(20, 22, 26, 0.72);
} }
.inspiration-card-action.is-on { .inspiration-card-action.is-on {
@@ -197,7 +197,7 @@
/* 标签里的计数:比正文弱一档,但仍要在两种底色上都读得出来。 */ /* 标签里的计数:比正文弱一档,但仍要在两种底色上都读得出来。 */
.inspiration-chip-count { .inspiration-chip-count {
font-variant-numeric: tabular-nums; font-variant-numeric: tabular-nums;
opacity: .58; opacity: 0.58;
} }
/* 卡片上的分类/署名标签是纯展示,不参与点击,去掉指针与悬停反馈。 */ /* 卡片上的分类/署名标签是纯展示,不参与点击,去掉指针与悬停反馈。 */
+70 -54
View File
@@ -1,16 +1,13 @@
import axios from "axios"; import axios from "axios";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { consumeJsonEvents } from "@/lib/json-event-stream"; import { consumeJsonEvents } from "@/lib/json-event-stream";
import type { import type { ChatCompletionPayload, ChatCompletionStreamState, GeminiPart, GeminiPayload, GeminiStreamState, ImageApiResponse, ResponseApiPayload, ResponseStreamState, ResponseToolCall, ToolResponseResult } from "@/services/api/image-contracts";
ChatCompletionPayload, ChatCompletionStreamState, GeminiPart, GeminiPayload, GeminiStreamState,
ImageApiResponse, ResponseApiPayload, ResponseStreamState, ResponseToolCall, ToolResponseResult,
} from "@/services/api/image-contracts";
type TextSink = (text: string) => void; type TextSink = (text: string) => void;
type TextState = { text: string; reasoning: string }; type TextState = { text: string; reasoning: string };
function record(value: unknown): Record<string, unknown> { function record(value: unknown): Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}; return value !== null && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
} }
function text(value: unknown): string { function text(value: unknown): string {
@@ -137,16 +134,20 @@ export async function readFetchError(response: Response, fallback: string) {
const status = readStatusError(response.status, fallback); const status = readStatusError(response.status, fallback);
if (!body) return status; if (!body) return status;
let payload: unknown; let payload: unknown;
try { payload = JSON.parse(body); } catch { return body.slice(0, 300) || status; } try {
payload = JSON.parse(body);
} catch {
return body.slice(0, 300) || status;
}
return responseErrorMessage(payload) || status; return responseErrorMessage(payload) || status;
} }
export async function readJsonPayload<T>(response: Response, fallback: string): Promise<T> { export async function readJsonPayload<T>(response: Response, fallback: string): Promise<T> {
const body = await response.text(); const body = await response.text();
try { return JSON.parse(body) as T; } catch { try {
const detail = /^\s*(?:<!doctype|<html)/i.test(body) return JSON.parse(body) as T;
? "后端代理返回了前端网页,请检查 VITE_CANVAS_BACKEND_URL 和反向代理配置" } catch {
: `${fallback}:接口没有返回有效 JSON`; const detail = /^\s*(?:<!doctype|<html)/i.test(body) ? "后端代理返回了前端网页,请检查 VITE_CANVAS_BACKEND_URL 和反向代理配置" : `${fallback}:接口没有返回有效 JSON`;
throw new Error(detail); throw new Error(detail);
} }
} }
@@ -165,54 +166,69 @@ const responseChannels: Record<string, keyof TextState> = {
}; };
export function consumeResponseStreamText(state: ResponseStreamState, chunk: string, onDelta?: TextSink, onReasoning?: TextSink, flush = false) { export function consumeResponseStreamText(state: ResponseStreamState, chunk: string, onDelta?: TextSink, onReasoning?: TextSink, flush = false) {
consumeJsonEvents(state, chunk, (payload) => { consumeJsonEvents(
const event = record(payload); state,
const failure = responseErrorMessage(event); chunk,
if (failure) state.error = failure; (payload) => {
const type = text(event.type); const event = record(payload);
const separator = type.lastIndexOf("."); const failure = responseErrorMessage(event);
const field = Object.hasOwn(responseChannels, type.slice(0, separator)) ? responseChannels[type.slice(0, separator)] : undefined; if (failure) state.error = failure;
const action = type.slice(separator + 1); const type = text(event.type);
if (field && (action === "delta" || action === "done")) { const separator = type.lastIndexOf(".");
updateText(state, field, action === "done" ? event.text : event.delta, field === "text" ? onDelta : onReasoning, action === "done"); const field = Object.hasOwn(responseChannels, type.slice(0, separator)) ? responseChannels[type.slice(0, separator)] : undefined;
} const action = type.slice(separator + 1);
if (type === "response.completed" && event.response !== null && typeof event.response === "object" && !Array.isArray(event.response)) { if (field && (action === "delta" || action === "done")) {
state.payload = event.response as ResponseApiPayload; updateText(state, field, action === "done" ? event.text : event.delta, field === "text" ? onDelta : onReasoning, action === "done");
} else if (Array.isArray(event.output)) state.payload = event as ResponseApiPayload; }
}, flush); if (type === "response.completed" && event.response !== null && typeof event.response === "object" && !Array.isArray(event.response)) {
state.payload = event.response as ResponseApiPayload;
} else if (Array.isArray(event.output)) state.payload = event as ResponseApiPayload;
},
flush,
);
} }
export function consumeChatCompletionStreamText(state: ChatCompletionStreamState, chunk: string, onDelta?: TextSink, onReasoning?: TextSink, flush = false) { export function consumeChatCompletionStreamText(state: ChatCompletionStreamState, chunk: string, onDelta?: TextSink, onReasoning?: TextSink, flush = false) {
consumeJsonEvents(state, chunk, (payload) => { consumeJsonEvents(
const event = record(payload); state,
const failure = responseErrorMessage(event); chunk,
if (failure) state.error = failure; (payload) => {
const first = Array.isArray(event.choices) ? record(event.choices[0]) : {}; const event = record(payload);
const delta = record(first.delta); const failure = responseErrorMessage(event);
updateText(state, "text", delta.content, onDelta); if (failure) state.error = failure;
const reasoning = text(delta.reasoning_content) || text(delta.reasoning) || text(delta.reasoning_text); const first = Array.isArray(event.choices) ? record(event.choices[0]) : {};
if (reasoning) updateText(state, "reasoning", reasoning, onReasoning); const delta = record(first.delta);
if (!Array.isArray(delta.tool_calls)) return; updateText(state, "text", delta.content, onDelta);
for (const [fallback, raw] of delta.tool_calls.entries()) { const reasoning = text(delta.reasoning_content) || text(delta.reasoning) || text(delta.reasoning_text);
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) continue; if (reasoning) updateText(state, "reasoning", reasoning, onReasoning);
const call = record(raw); if (!Array.isArray(delta.tool_calls)) return;
const index = typeof call.index === "number" ? call.index : fallback; for (const [fallback, raw] of delta.tool_calls.entries()) {
const previous = state.toolCalls.get(index); if (raw === null || typeof raw !== "object" || Array.isArray(raw)) continue;
const fn = record(call.function); const call = record(raw);
state.toolCalls.set(index, { const index = typeof call.index === "number" ? call.index : fallback;
id: text(call.id) || previous?.id || "", const previous = state.toolCalls.get(index);
name: text(fn.name) || previous?.name || "", const fn = record(call.function);
arguments: (previous?.arguments || "") + text(fn.arguments), state.toolCalls.set(index, {
}); id: text(call.id) || previous?.id || "",
} name: text(fn.name) || previous?.name || "",
}, flush); arguments: (previous?.arguments || "") + text(fn.arguments),
});
}
},
flush,
);
} }
export function consumeGeminiStreamText(state: GeminiStreamState, chunk: string, onDelta?: TextSink, onReasoning?: TextSink, flush = false) { export function consumeGeminiStreamText(state: GeminiStreamState, chunk: string, onDelta?: TextSink, onReasoning?: TextSink, flush = false) {
consumeJsonEvents(state, chunk, (payload) => { consumeJsonEvents(
const result = parseGeminiToolResponse(payload as GeminiPayload); state,
if (result.reasoning) updateText(state, "reasoning", result.reasoning, onReasoning); chunk,
if (result.content) updateText(state, "text", result.content, onDelta); (payload) => {
state.toolCalls.push(...result.toolCalls); const result = parseGeminiToolResponse(payload as GeminiPayload);
}, flush); if (result.reasoning) updateText(state, "reasoning", result.reasoning, onReasoning);
if (result.content) updateText(state, "text", result.content, onDelta);
state.toolCalls.push(...result.toolCalls);
},
flush,
);
} }
+9 -3
View File
@@ -63,15 +63,21 @@ export function delay(ms: number, signal?: AbortSignal) {
else resolve(); else resolve();
}; };
const cancel = () => finish(true); const cancel = () => finish(true);
if (signal?.aborted) { cancel(); return; } if (signal?.aborted) {
cancel();
return;
}
signal?.addEventListener("abort", cancel, { once: true }); signal?.addEventListener("abort", cancel, { once: true });
timer = setTimeout(() => finish(false), ms); timer = setTimeout(() => finish(false), ms);
}); });
} }
export async function blobToDataUrl(blob: Blob) { export async function blobToDataUrl(blob: Blob) {
try { return await readFileAsDataUrl(blob); } try {
catch { throw new Error("读取本地素材失败"); } return await readFileAsDataUrl(blob);
} catch {
throw new Error("读取本地素材失败");
}
} }
export async function videoResultFromUrl(url: string, options?: RequestOptions): Promise<VideoGenerationResult> { export async function videoResultFromUrl(url: string, options?: RequestOptions): Promise<VideoGenerationResult> {
+1 -3
View File
@@ -69,9 +69,7 @@ async function buildCatalog(): Promise<InspirationCatalog> {
const category = entry.category?.trim(); const category = entry.category?.trim();
if (category) counts.set(category, (counts.get(category) ?? 0) + 1); if (category) counts.set(category, (counts.get(category) ?? 0) + 1);
} }
categoriesBySource[sourceId] = [...counts.entries()] categoriesBySource[sourceId] = [...counts.entries()].map(([id, count]) => ({ id, label: labels[id] ?? id, count })).sort((left, right) => right.count - left.count || left.label.localeCompare(right.label, "zh-Hans-CN"));
.map(([id, count]) => ({ id, label: labels[id] ?? id, count }))
.sort((left, right) => right.count - left.count || left.label.localeCompare(right.label, "zh-Hans-CN"));
} }
return { return {
+12 -10
View File
@@ -34,17 +34,19 @@ describe("图片工具像素合同", () => {
}); });
test("锁定比例时八个手柄在各种拖动下都保持比例与图内边界", () => { test("锁定比例时八个手柄在各种拖动下都保持比例与图内边界", () => {
const box = { x: 0.1, y: 0.2, width: 0.6, height: 0.4 }; const box = { x: 0.1, y: 0.2, width: 0.6, height: 0.4 };
for (const x of [-1, 0, 1] as const) for (const y of [-1, 0, 1] as const) { for (const x of [-1, 0, 1] as const)
if (!x && !y) continue; for (const y of [-1, 0, 1] as const) {
for (const dx of [-3, -0.1, 0, 0.1, 3]) for (const dy of [-3, -0.1, 0, 0.1, 3]) { if (!x && !y) continue;
const next = resizeSelection(box, [x, y] as CropGrip, dx, dy, true); for (const dx of [-3, -0.1, 0, 0.1, 3])
expect(next.width / next.height).toBeCloseTo(1.5, 8); for (const dy of [-3, -0.1, 0, 0.1, 3]) {
expect(next.x).toBeGreaterThanOrEqual(-1e-12); const next = resizeSelection(box, [x, y] as CropGrip, dx, dy, true);
expect(next.y).toBeGreaterThanOrEqual(-1e-12); expect(next.width / next.height).toBeCloseTo(1.5, 8);
expect(next.x + next.width).toBeLessThanOrEqual(1 + 1e-12); expect(next.x).toBeGreaterThanOrEqual(-1e-12);
expect(next.y + next.height).toBeLessThanOrEqual(1 + 1e-12); expect(next.y).toBeGreaterThanOrEqual(-1e-12);
expect(next.x + next.width).toBeLessThanOrEqual(1 + 1e-12);
expect(next.y + next.height).toBeLessThanOrEqual(1 + 1e-12);
}
} }
}
}); });
test("极窄比例切换后仍可自由拖动手柄", () => { test("极窄比例切换后仍可自由拖动手柄", () => {
const box = selectAspect({ x: 0.1, y: 0.1, width: 0.8, height: 0.8 }, 0.02); const box = selectAspect({ x: 0.1, y: 0.1, width: 0.8, height: 0.8 }, 0.02);
+36 -20
View File
@@ -2,8 +2,12 @@ import { describe, expect, test } from "bun:test";
import { solveNodeResize, type NodeResizeCorner, type NodeResizeSnapshot } from "../src/lib/canvas/node-resize-geometry"; import { solveNodeResize, type NodeResizeCorner, type NodeResizeSnapshot } from "../src/lib/canvas/node-resize-geometry";
const initial: NodeResizeSnapshot = { const initial: NodeResizeSnapshot = {
position: { x: -30, y: 70 }, width: 400, height: 200, position: { x: -30, y: 70 },
minimumWidth: 100, minimumHeight: 80, corner: "bottom-right", width: 400,
height: 200,
minimumWidth: 100,
minimumHeight: 80,
corner: "bottom-right",
}; };
const corners: NodeResizeCorner[] = ["top-left", "top-right", "bottom-left", "bottom-right"]; const corners: NodeResizeCorner[] = ["top-left", "top-right", "bottom-left", "bottom-right"];
@@ -16,34 +20,46 @@ function opposite(box: { position: { x: number; y: number }; width: number; heig
describe("node resize geometry", () => { describe("node resize geometry", () => {
test("all corners retain the opposite anchor at minimum sizes and across the anchor", () => { test("all corners retain the opposite anchor at minimum sizes and across the anchor", () => {
for (const corner of corners) for (const x of [-2000, -50, 0, 75, 2000]) for (const y of [-2000, -50, 0, 75, 2000]) { for (const corner of corners)
const start = { ...initial, corner }; for (const x of [-2000, -50, 0, 75, 2000])
const next = solveNodeResize(start, { x, y }); for (const y of [-2000, -50, 0, 75, 2000]) {
expect(opposite(next, corner)).toEqual(opposite(start, corner)); const start = { ...initial, corner };
expect(next.width).toBeGreaterThanOrEqual(100); const next = solveNodeResize(start, { x, y });
expect(next.height).toBeGreaterThanOrEqual(80); expect(opposite(next, corner)).toEqual(opposite(start, corner));
} expect(next.width).toBeGreaterThanOrEqual(100);
expect(next.height).toBeGreaterThanOrEqual(80);
}
}); });
test("free resize grows the dragged corner in world coordinates", () => { test("free resize grows the dragged corner in world coordinates", () => {
expect(solveNodeResize({ ...initial, corner: "top-left" }, { x: -60, y: -30 })).toEqual({ expect(solveNodeResize({ ...initial, corner: "top-left" }, { x: -60, y: -30 })).toEqual({
position: { x: -90, y: 40 }, width: 460, height: 230, position: { x: -90, y: 40 },
width: 460,
height: 230,
}); });
expect(solveNodeResize(initial, { x: 60, y: 30 })).toEqual({ expect(solveNodeResize(initial, { x: 60, y: 30 })).toEqual({
position: initial.position, width: 460, height: 230, position: initial.position,
width: 460,
height: 230,
}); });
}); });
test("media preserves ratio, both minimums and the fixed anchor", () => { test("media preserves ratio, both minimums and the fixed anchor", () => {
for (const ratio of [0.1, 0.5, 1, 2, 10]) for (const corner of corners) for (const delta of [{ x: -5000, y: 3000 }, { x: 50, y: -60 }, { x: 3000, y: -5000 }]) { for (const ratio of [0.1, 0.5, 1, 2, 10])
const start = { ...initial, corner, ratio }; for (const corner of corners)
const next = solveNodeResize(start, delta); for (const delta of [
expect(next.width / next.height).toBeCloseTo(ratio, 10); { x: -5000, y: 3000 },
expect(next.width).toBeGreaterThanOrEqual(100); { x: 50, y: -60 },
expect(next.height).toBeGreaterThanOrEqual(80); { x: 3000, y: -5000 },
expect(opposite(next, corner).x).toBeCloseTo(opposite(start, corner).x, 8); ]) {
expect(opposite(next, corner).y).toBeCloseTo(opposite(start, corner).y, 8); const start = { ...initial, corner, ratio };
} const next = solveNodeResize(start, delta);
expect(next.width / next.height).toBeCloseTo(ratio, 10);
expect(next.width).toBeGreaterThanOrEqual(100);
expect(next.height).toBeGreaterThanOrEqual(80);
expect(opposite(next, corner).x).toBeCloseTo(opposite(start, corner).x, 8);
expect(opposite(next, corner).y).toBeCloseTo(opposite(start, corner).y, 8);
}
}); });
test("dominant pointer axis and horizontal ties preserve the existing gesture", () => { test("dominant pointer axis and horizontal ties preserve the existing gesture", () => {
+96 -26
View File
@@ -1,6 +1,16 @@
import { describe, expect, spyOn, test } from "bun:test"; import { describe, expect, spyOn, test } from "bun:test";
import { consumeJsonEvents } from "../src/lib/json-event-stream"; import { consumeJsonEvents } from "../src/lib/json-event-stream";
import { consumeChatCompletionStreamText, consumeGeminiStreamText, consumeResponseStreamText, parseGeminiImagePayload, parseGeminiToolResponse, parseToolResponse, readFetchError, readJsonPayload, responseErrorMessage } from "../src/services/api/image-response"; import {
consumeChatCompletionStreamText,
consumeGeminiStreamText,
consumeResponseStreamText,
parseGeminiImagePayload,
parseGeminiToolResponse,
parseToolResponse,
readFetchError,
readJsonPayload,
responseErrorMessage,
} from "../src/services/api/image-response";
import { blobToDataUrl, delay } from "../src/services/api/video-response"; import { blobToDataUrl, delay } from "../src/services/api/video-response";
import type { ChatCompletionStreamState, GeminiStreamState, ResponseStreamState } from "../src/services/api/image-contracts"; import type { ChatCompletionStreamState, GeminiStreamState, ResponseStreamState } from "../src/services/api/image-contracts";
@@ -38,12 +48,26 @@ describe("provider response replacement contracts", () => {
{ type: "response.reasoning_summary_text.done", text: "why" }, { type: "response.reasoning_summary_text.done", text: "why" },
{ type: "constructor.delta", delta: "ignore" }, { type: "constructor.delta", delta: "ignore" },
{ type: "response.completed", response: payload }, { type: "response.completed", response: payload },
].map(frame).join(""); ]
.map(frame)
.join("");
for (let split = 0; split <= stream.length; split++) { for (let split = 0; split <= stream.length; split++) {
const state: ResponseStreamState = { buffer: "", text: "", reasoning: "" }; const state: ResponseStreamState = { buffer: "", text: "", reasoning: "" };
const visible: string[] = [], reasoning: string[] = []; const visible: string[] = [],
consumeResponseStreamText(state, stream.slice(0, split), (value) => visible.push(value), (value) => reasoning.push(value)); reasoning: string[] = [];
consumeResponseStreamText(state, stream.slice(split), (value) => visible.push(value), (value) => reasoning.push(value), true); consumeResponseStreamText(
state,
stream.slice(0, split),
(value) => visible.push(value),
(value) => reasoning.push(value),
);
consumeResponseStreamText(
state,
stream.slice(split),
(value) => visible.push(value),
(value) => reasoning.push(value),
true,
);
expect(visible).toEqual(["A", "AB"]); expect(visible).toEqual(["A", "AB"]);
expect(reasoning).toEqual(["why"]); expect(reasoning).toEqual(["why"]);
expect(state.payload).toEqual(payload); expect(state.payload).toEqual(payload);
@@ -58,9 +82,36 @@ describe("provider response replacement contracts", () => {
test("Chat Completions interleaves indexed tool fragments and reasoning aliases", () => { test("Chat Completions interleaves indexed tool fragments and reasoning aliases", () => {
const stream = [ const stream = [
{ choices: [{ delta: { content: "OK", reasoning: "r", tool_calls: [{ index: 3, id: "three", function: { name: "search", arguments: '{"q":' } }, { index: 1, id: "one", function: { name: "read", arguments: '{"id":' } }] } }] }, {
{ choices: [{ delta: { reasoning_text: "s", tool_calls: [{ index: 1, function: { arguments: '1}' } }, { index: 3, function: { arguments: '"画布"}' } }] } }] }, choices: [
].map(frame).join(""); {
delta: {
content: "OK",
reasoning: "r",
tool_calls: [
{ index: 3, id: "three", function: { name: "search", arguments: '{"q":' } },
{ index: 1, id: "one", function: { name: "read", arguments: '{"id":' } },
],
},
},
],
},
{
choices: [
{
delta: {
reasoning_text: "s",
tool_calls: [
{ index: 1, function: { arguments: "1}" } },
{ index: 3, function: { arguments: '"画布"}' } },
],
},
},
],
},
]
.map(frame)
.join("");
for (let split = 0; split <= stream.length; split++) { for (let split = 0; split <= stream.length; split++) {
const state: ChatCompletionStreamState = { buffer: "", text: "", reasoning: "", toolCalls: new Map() }; const state: ChatCompletionStreamState = { buffer: "", text: "", reasoning: "", toolCalls: new Map() };
consumeChatCompletionStreamText(state, stream.slice(0, split)); consumeChatCompletionStreamText(state, stream.slice(0, split));
@@ -73,12 +124,21 @@ describe("provider response replacement contracts", () => {
}); });
test("Gemini preserves thought signatures and tool order without mixing thought text", () => { test("Gemini preserves thought signatures and tool order without mixing thought text", () => {
const payload = { candidates: [{ content: { parts: [{ thought: true, text: "plan" }, { text: "answer" }, { functionCall: { id: "a", name: "read", args: { id: 1 } }, thought_signature: "sig-a" }] } }, { content: { parts: [{ functionCall: { id: "b", name: "search" }, thoughtSignature: "sig-b" }] } }] }; const payload = {
candidates: [
{ content: { parts: [{ thought: true, text: "plan" }, { text: "answer" }, { functionCall: { id: "a", name: "read", args: { id: 1 } }, thought_signature: "sig-a" }] } },
{ content: { parts: [{ functionCall: { id: "b", name: "search" }, thoughtSignature: "sig-b" }] } },
],
};
const result = parseGeminiToolResponse(payload); const result = parseGeminiToolResponse(payload);
expect(result).toEqual({ content: "answer", reasoning: "plan", toolCalls: [ expect(result).toEqual({
{ id: "a", type: "function", function: { name: "read", arguments: '{"id":1}' }, thoughtSignature: "sig-a" }, content: "answer",
{ id: "b", type: "function", function: { name: "search", arguments: '{}' }, thoughtSignature: "sig-b" }, reasoning: "plan",
] }); toolCalls: [
{ id: "a", type: "function", function: { name: "read", arguments: '{"id":1}' }, thoughtSignature: "sig-a" },
{ id: "b", type: "function", function: { name: "search", arguments: "{}" }, thoughtSignature: "sig-b" },
],
});
const stream = frame(payload); const stream = frame(payload);
const state: GeminiStreamState = { buffer: "", text: "", reasoning: "", toolCalls: [] }; const state: GeminiStreamState = { buffer: "", text: "", reasoning: "", toolCalls: [] };
for (const character of stream) consumeGeminiStreamText(state, character); for (const character of stream) consumeGeminiStreamText(state, character);
@@ -87,25 +147,33 @@ describe("provider response replacement contracts", () => {
}); });
test("image sources preserve MIME and source order; Responses chooses explicit output text", () => { test("image sources preserve MIME and source order; Responses chooses explicit output text", () => {
expect(parseGeminiImagePayload({ candidates: [{ content: { parts: [ expect(
{ inlineData: { mimeType: "image/jpeg", data: "AAA=" } }, parseGeminiImagePayload({
{ inline_data: { mime_type: "image/webp", data: "BBB=" } }, candidates: [{ content: { parts: [{ inlineData: { mimeType: "image/jpeg", data: "AAA=" } }, { inline_data: { mime_type: "image/webp", data: "BBB=" } }, { fileData: { fileUri: "https://example.test/image" } }, { text: "ignored" }] } }],
{ fileData: { fileUri: "https://example.test/image" } }, }).map((image) => image.dataUrl),
{ text: "ignored" }, ).toEqual(["data:image/jpeg;base64,AAA=", "data:image/webp;base64,BBB=", "https://example.test/image"]);
] } }] }).map((image) => image.dataUrl)).toEqual(["data:image/jpeg;base64,AAA=", "data:image/webp;base64,BBB=", "https://example.test/image"]);
expect(() => parseGeminiImagePayload({ candidates: [] })).toThrow("Gemini 接口没有返回图片"); expect(() => parseGeminiImagePayload({ candidates: [] })).toThrow("Gemini 接口没有返回图片");
expect(parseToolResponse({ output_text: "explicit", output: [{ type: "message", content: [{ text: "fallback" }] }, { type: "function_call", id: "item", call_id: "call", name: "read" }] })).toEqual({ expect(
content: "explicit", toolCalls: [{ id: "call", type: "function", function: { name: "read", arguments: "{}" } }], parseToolResponse({
output_text: "explicit",
output: [
{ type: "message", content: [{ text: "fallback" }] },
{ type: "function_call", id: "item", call_id: "call", name: "read" },
],
}),
).toEqual({
content: "explicit",
toolCalls: [{ id: "call", type: "function", function: { name: "read", arguments: "{}" } }],
}); });
}); });
test("HTTP and JSON errors retain precedence and distinguish proxy HTML", async () => { test("HTTP and JSON errors retain precedence and distinguish proxy HTML", async () => {
expect(responseErrorMessage({ msg: "first", error: { message: "second" }, response: { error: { message: "third" } } })).toBe("first"); expect(responseErrorMessage({ msg: "first", error: { message: "second" }, response: { error: { message: "third" } } })).toBe("first");
expect(await readFetchError(new Response('{"error":{"message":"denied"}}', { status: 403 }), "失败")).toBe("denied"); expect(await readFetchError(new Response('{"error":{"message":"denied"}}', { status: 403 }), "失败")).toBe("denied");
expect(await readFetchError(new Response('{}', { status: 429 }), "失败")).toBe("请求被限流或额度不足,请稍后重试"); expect(await readFetchError(new Response("{}", { status: 429 }), "失败")).toBe("请求被限流或额度不足,请稍后重试");
expect(await readFetchError(new Response('x'.repeat(400), { status: 500 }), "失败")).toHaveLength(300); expect(await readFetchError(new Response("x".repeat(400), { status: 500 }), "失败")).toHaveLength(300);
await expect(readJsonPayload(new Response('<!doctype html><html>'), "失败")).rejects.toThrow("后端代理返回了前端网页"); await expect(readJsonPayload(new Response("<!doctype html><html>"), "失败")).rejects.toThrow("后端代理返回了前端网页");
await expect(readJsonPayload(new Response('not-json'), "失败")).rejects.toThrow("接口没有返回有效 JSON"); await expect(readJsonPayload(new Response("not-json"), "失败")).rejects.toThrow("接口没有返回有效 JSON");
}); });
test("video polling removes abort listeners on completion and cancellation", async () => { test("video polling removes abort listeners on completion and cancellation", async () => {
@@ -119,7 +187,9 @@ describe("provider response replacement contracts", () => {
await expect(pending).rejects.toMatchObject({ name: "AbortError" }); await expect(pending).rejects.toMatchObject({ name: "AbortError" });
expect(remove).toHaveBeenCalledTimes(2); expect(remove).toHaveBeenCalledTimes(2);
await expect(delay(0, controller.signal)).rejects.toMatchObject({ name: "AbortError" }); await expect(delay(0, controller.signal)).rejects.toMatchObject({ name: "AbortError" });
} finally { remove.mockRestore(); } } finally {
remove.mockRestore();
}
}); });
test("video data URLs preserve raw bytes and MIME without FileReader", async () => { test("video data URLs preserve raw bytes and MIME without FileReader", async () => {