From 718a853de573f0cec73774f303c594730592c6f7 Mon Sep 17 00:00:00 2001 From: ychao_1983 Date: Tue, 21 Jun 2022 11:25:14 +0800 Subject: [PATCH 01/35] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/attachment.go | 29 +++++++++++ models/dataset.go | 109 +++++++++++++++++++++++++++++++++++---- models/dataset_star.go | 7 +++ routers/admin/dataset.go | 7 +-- routers/home.go | 23 +++++---- routers/repo/dataset.go | 84 ++++++++++++++++++++++++++++++ routers/routes/routes.go | 5 ++ routers/user/profile.go | 1 + 8 files changed, 243 insertions(+), 22 deletions(-) diff --git a/models/attachment.go b/models/attachment.go index 6fb98a07d0..31aefb3d10 100755 --- a/models/attachment.go +++ b/models/attachment.go @@ -560,6 +560,35 @@ func GetAttachmentSizeByDatasetID(datasetID int64) (int64, error) { return total, nil } +func AttachmentsByDatasetOption(datasets []int64, opts *SearchDatasetOptions) ([]*Attachment, error) { + sess := x.NewSession() + defer sess.Close() + var cond = builder.NewCond() + cond = cond.And(builder.In("attachment.dataset_id", datasets)) + if opts.JustNeedZipFile { + cond = cond.And(builder.Gt{"attachment.decompress_state": 0}) + } + if opts.PublicOnly { + cond = cond.And(builder.Gt{"attachment.decompress_state": 0}) + } + if opts.CloudBrainType >= 0 { + cond = cond.And(builder.Eq{"attachment.type": opts.CloudBrainType}) + } + if opts.UploadAttachmentByMe { + cond = cond.And( + builder.Eq{"attachment.uploader_id": opts.OwnerID}, + ) + } + + attachments := make([]*Attachment, 0) + if err := sess.Table(&Attachment{}).Where(cond). + Find(&attachments); err != nil { + return nil, fmt.Errorf("Find: %v", err) + } + return attachments, nil + +} + func GetAllAttachmentSize() (int64, error) { return x.SumInt(&Attachment{}, "size") } diff --git a/models/dataset.go b/models/dataset.go index b7186ac0b5..4122b63b2c 100755 --- a/models/dataset.go +++ b/models/dataset.go @@ -81,12 +81,14 @@ func (datasets DatasetList) loadAttributes(e Engine) error { if err := e. Where("id > 0"). In("id", keysInt64(userIdSet)). + Cols("id", "lower_name", "name", "full_name", "email"). Find(&users); err != nil { return fmt.Errorf("find users: %v", err) } if err := e. Where("id > 0"). In("id", keysInt64(set)). + Cols("id", "owner_id", "owner_name", "lower_name", "name", "description", "alias", "lower_alias"). Find(&repos); err != nil { return fmt.Errorf("find repos: %v", err) } @@ -98,19 +100,77 @@ func (datasets DatasetList) loadAttributes(e Engine) error { return nil } +func (datasets DatasetList) loadAttachmentAttributes(opts *SearchDatasetOptions) error { + if len(datasets) == 0 { + return nil + } + datasetIDs := make([]int64, len(datasets)) + for i := range datasets { + datasetIDs[i] = datasets[i].ID + } + attachments, err := AttachmentsByDatasetOption(datasetIDs, opts) + if err != nil { + return fmt.Errorf("GetAttachmentsByDatasetIds failed error: %v", err) + } + + permissionMap := make(map[int64]*Permission, len(datasets)) + + for _, attachment := range attachments { + + for i := range datasets { + if attachment.DatasetID == datasets[i].ID { + if opts.StarByMe { + var permission *Permission + if permission = permissionMap[datasets[i].ID]; permission == nil { + permissionInstance, err := GetUserRepoPermission(datasets[i].Repo, opts.User) + if err != nil { + return fmt.Errorf("GetPermission failed error: %v", err) + } + permission = &permissionInstance + } + + if permission.HasAccess() { + datasets[i].Attachments = append(datasets[i].Attachments, attachment) + } else if !attachment.IsPrivate { + datasets[i].Attachments = append(datasets[i].Attachments, attachment) + } + } else { + datasets[i].Attachments = append(datasets[i].Attachments, attachment) + } + + } + + } + + } + + for i := range datasets { + datasets[i].Repo.Owner = nil + } + return nil + +} + type SearchDatasetOptions struct { Keyword string OwnerID int64 + User *User RepoID int64 IncludePublic bool RecommendOnly bool Category string Task string License string - DatasetIDs []int64 + DatasetIDs []int64 // 目前只在StarByMe为true时起作用 ListOptions SearchOrderBy - IsOwner bool + IsOwner bool + StarByMe bool + CloudBrainType int //0 cloudbrain 1 modelarts -1 all + PublicOnly bool + JustNeedZipFile bool + NeedAttachment bool + UploadAttachmentByMe bool } func CreateDataset(dataset *Dataset) (err error) { @@ -159,29 +219,36 @@ func SearchDatasetCondition(opts *SearchDatasetOptions) builder.Cond { if opts.RepoID > 0 { cond = cond.And(builder.Eq{"dataset.repo_id": opts.RepoID}) } - if opts.IncludePublic { + + if opts.PublicOnly { + cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic}) + cond = cond.And(builder.Eq{"attachment.is_private": false}) + } else if opts.IncludePublic { cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic}) cond = cond.And(builder.Eq{"attachment.is_private": false}) if opts.OwnerID > 0 { - subCon := builder.NewCond() subCon = subCon.And(builder.Eq{"repository.owner_id": opts.OwnerID}) subCon = generateFilterCond(opts, subCon) cond = cond.Or(subCon) } - } else if opts.OwnerID > 0 { + } else if opts.OwnerID > 0 && !opts.StarByMe && !opts.UploadAttachmentByMe { cond = cond.And(builder.Eq{"repository.owner_id": opts.OwnerID}) if !opts.IsOwner { cond = cond.And(builder.Eq{"dataset.status": DatasetStatusPublic}) cond = cond.And(builder.Eq{"attachment.is_private": false}) } } - if len(opts.DatasetIDs) > 0 { - subCon := builder.NewCond() - subCon = subCon.And(builder.In("dataset.id", opts.DatasetIDs)) - cond = cond.Or(subCon) + + if opts.StarByMe { + cond = cond.And(builder.In("dataset.id", opts.DatasetIDs)) + } else { + subCon := builder.NewCond() + subCon = subCon.And(builder.In("dataset.id", opts.DatasetIDs)) + cond = cond.Or(subCon) + } } return cond @@ -207,6 +274,17 @@ func generateFilterCond(opts *SearchDatasetOptions, cond builder.Cond) builder.C cond = cond.And(builder.Eq{"dataset.recommend": opts.RecommendOnly}) } + if opts.JustNeedZipFile { + cond = cond.And(builder.Gt{"attachment.decompress_state": 0}) + } + + if opts.CloudBrainType >= 0 { + cond = cond.And(builder.Eq{"attachment.type": opts.CloudBrainType}) + } + if opts.UploadAttachmentByMe { + cond = cond.And(builder.Eq{"attachment.uploader_id": opts.OwnerID}) + } + return cond } @@ -245,6 +323,12 @@ func SearchDatasetByCondition(opts *SearchDatasetOptions, cond builder.Cond) (Da return nil, 0, fmt.Errorf("LoadAttributes: %v", err) } + if opts.NeedAttachment { + if err = datasets.loadAttachmentAttributes(opts); err != nil { + return nil, 0, fmt.Errorf("LoadAttributes: %v", err) + } + } + return datasets, count, nil } @@ -460,5 +544,12 @@ func GetCollaboratorDatasetIdsByUserID(userID int64) []int64 { _ = x.Table("dataset").Join("INNER", "collaboration", "dataset.repo_id = collaboration.repo_id and collaboration.mode>0 and collaboration.user_id=?", userID). Cols("dataset.id").Find(&datasets) return datasets +} +func GetTeamDatasetIdsByUserID(userID int64) []int64 { + var datasets []int64 + _ = x.Table("dataset").Join("INNER", "team_repo", "dataset.repo_id = team_repo.repo_id"). + Join("INNER", "team_user", "team_repo.team_id=team_user.team_id and team_user.uid=?", userID). + Cols("dataset.id").Find(&datasets) + return datasets } diff --git a/models/dataset_star.go b/models/dataset_star.go index 4b22c28555..2cbd9dc8d8 100644 --- a/models/dataset_star.go +++ b/models/dataset_star.go @@ -68,3 +68,10 @@ func isDatasetStaring(e Engine, userID, datasetID int64) bool { has, _ := e.Get(&DatasetStar{0, userID, datasetID, 0}) return has } + +func GetDatasetIdsStarByUser(userID int64) []int64 { + var datasets []int64 + _ = x.Table("dataset_star").Where("uid=?", userID). + Cols("dataset_star.dataset_id").Find(&datasets) + return datasets +} diff --git a/routers/admin/dataset.go b/routers/admin/dataset.go index d1a8f27803..9651233b31 100644 --- a/routers/admin/dataset.go +++ b/routers/admin/dataset.go @@ -77,9 +77,10 @@ func Datasets(ctx *context.Context) { Page: page, PageSize: setting.UI.ExplorePagingNum, }, - Keyword: keyword, - RecommendOnly: ctx.QueryBool("recommend"), - SearchOrderBy: orderBy, + Keyword: keyword, + RecommendOnly: ctx.QueryBool("recommend"), + CloudBrainType: -1, + SearchOrderBy: orderBy, }) if err != nil { ctx.ServerError("SearchDataset", err) diff --git a/routers/home.go b/routers/home.go index ae184a72aa..dcd30a1394 100755 --- a/routers/home.go +++ b/routers/home.go @@ -346,19 +346,22 @@ func ExploreDatasets(ctx *context.Context) { var datasetsIds []int64 if ownerID > 0 { - datasetsIds = models.GetCollaboratorDatasetIdsByUserID(ownerID) + collaboratorDatasetsIds := models.GetCollaboratorDatasetIdsByUserID(ownerID) + teamDatasetsIds := models.GetTeamDatasetIdsByUserID(ownerID) + datasetsIds = append(collaboratorDatasetsIds, teamDatasetsIds...) } opts := &models.SearchDatasetOptions{ - Keyword: keyword, - IncludePublic: true, - SearchOrderBy: orderBy, - Category: category, - Task: task, - License: license, - OwnerID: ownerID, - DatasetIDs: datasetsIds, - RecommendOnly: ctx.QueryBool("recommend"), + Keyword: keyword, + IncludePublic: true, + SearchOrderBy: orderBy, + Category: category, + Task: task, + License: license, + OwnerID: ownerID, + DatasetIDs: datasetsIds, + RecommendOnly: ctx.QueryBool("recommend"), + CloudBrainType: -1, ListOptions: models.ListOptions{ Page: page, PageSize: 30, diff --git a/routers/repo/dataset.go b/routers/repo/dataset.go index 133262bf35..08db5a6135 100755 --- a/routers/repo/dataset.go +++ b/routers/repo/dataset.go @@ -410,6 +410,90 @@ func MyDatasets(ctx *context.Context) { }) } +func datasetMultiple(ctx *context.Context, opts *models.SearchDatasetOptions) { + page := ctx.QueryInt("page") + cloudbrainType := ctx.QueryInt("type") + keyword := strings.Trim(ctx.Query("q"), " ") + orderBy := models.SearchOrderByRecentUpdated + var ownerID int64 + if ctx.User != nil { + ownerID = ctx.User.ID + } + + opts.Keyword = keyword + opts.SearchOrderBy = orderBy + opts.OwnerID = ownerID + opts.RecommendOnly = ctx.QueryBool("recommend") + opts.CloudBrainType = cloudbrainType + opts.ListOptions = models.ListOptions{ + Page: page, + PageSize: setting.UI.DatasetPagingNum, + } + opts.NeedAttachment = true + opts.JustNeedZipFile = true + opts.User = ctx.User + + datasets, count, err := models.SearchDataset(opts) + + if err != nil { + ctx.ServerError("datasets", err) + return + } + + data, err := json.Marshal(datasets) + if err != nil { + log.Error("json.Marshal failed:", err.Error()) + ctx.JSON(200, map[string]string{ + "result_code": "-1", + "error_msg": err.Error(), + "data": "", + }) + return + } + ctx.JSON(200, map[string]string{ + "result_code": "0", + "data": string(data), + "count": strconv.FormatInt(count, 10), + }) + +} + +func CurrentRepoDatasetMultiple(ctx *context.Context) { + + opts := &models.SearchDatasetOptions{ + RepoID: ctx.Repo.Repository.ID, + } + datasetMultiple(ctx, opts) + +} + +func MyDatasetsMultiple(ctx *context.Context) { + + opts := &models.SearchDatasetOptions{ + UploadAttachmentByMe: true, + } + datasetMultiple(ctx, opts) + +} + +func PublicDatasetMultiple(ctx *context.Context) { + + opts := &models.SearchDatasetOptions{ + PublicOnly: true, + } + datasetMultiple(ctx, opts) + +} + +func MyFavoriteDatasetMultiple(ctx *context.Context) { + + opts := &models.SearchDatasetOptions{ + StarByMe: true, + DatasetIDs: models.GetDatasetIdsStarByUser(ctx.User.ID), + } + datasetMultiple(ctx, opts) +} + func PublicDataset(ctx *context.Context) { page := ctx.QueryInt("page") cloudbrainType := ctx.QueryInt("type") diff --git a/routers/routes/routes.go b/routers/routes/routes.go index 7732ff2176..d65f4a88e8 100755 --- a/routers/routes/routes.go +++ b/routers/routes/routes.go @@ -1026,6 +1026,11 @@ func RegisterRoutes(m *macaron.Macaron) { m.Get("/public_datasets", repo.PublicDataset) m.Get("/my_favorite", repo.MyFavoriteDataset) + m.Get("/current_repo_m", repo.CurrentRepoDatasetMultiple) + m.Get("/my_datasets_m", repo.MyDatasetsMultiple) + m.Get("/public_datasets_m", repo.PublicDatasetMultiple) + m.Get("/my_favorite_m", repo.MyFavoriteDatasetMultiple) + m.Group("/status", func() { m.Get("/:uuid", repo.GetDatasetStatus) }) diff --git a/routers/user/profile.go b/routers/user/profile.go index f82c03a755..30808f2353 100755 --- a/routers/user/profile.go +++ b/routers/user/profile.go @@ -263,6 +263,7 @@ func Profile(ctx *context.Context) { Page: page, PageSize: setting.UI.ExplorePagingNum, }, + CloudBrainType: -1, } if len(datasetSearchOptions.SearchOrderBy) == 0 { -- 2.34.1 From 91455626a1a0ce18c5bd7823b6a9ecb3a7bf4455 Mon Sep 17 00:00:00 2001 From: liuzx Date: Tue, 21 Jun 2022 17:57:10 +0800 Subject: [PATCH 02/35] test --- routers/repo/modelarts.go | 1 + 1 file changed, 1 insertion(+) diff --git a/routers/repo/modelarts.go b/routers/repo/modelarts.go index 12a5a06230..f2fa4e3707 100755 --- a/routers/repo/modelarts.go +++ b/routers/repo/modelarts.go @@ -985,6 +985,7 @@ func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) FlavorName := form.FlavorName VersionCount := modelarts.VersionCount EngineName := form.EngineName + dataPath = "/test-opendata/attachment/1/2/12974bf4-3865-4995-a14f-e9e2af343f2f12974bf4-3865-4995-a14f-e9e2af343f2f/;s3://test-opendata/attachment/1/2/12974bf4-3865-4995-a14f-e9e2af343f2f12974bf4-3865-4995-a14f-e9e2af343f2f/" count, err := models.GetCloudbrainTrainJobCountByUserID(ctx.User.ID) if err != nil { -- 2.34.1 From b017248de66ebd45e62155a672272b87c40896de Mon Sep 17 00:00:00 2001 From: liuzx Date: Wed, 22 Jun 2022 17:03:22 +0800 Subject: [PATCH 03/35] =?UTF-8?q?=E4=BA=91=E8=84=91=E4=BA=8C=E5=A4=9A?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E9=80=89=E6=8B=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routers/repo/modelarts.go | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/routers/repo/modelarts.go b/routers/repo/modelarts.go index f2fa4e3707..269c7425e2 100755 --- a/routers/repo/modelarts.go +++ b/routers/repo/modelarts.go @@ -979,14 +979,19 @@ func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/" logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/" - dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" + // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" branch_name := form.BranchName isLatestVersion := modelarts.IsLatestVersion FlavorName := form.FlavorName VersionCount := modelarts.VersionCount EngineName := form.EngineName - dataPath = "/test-opendata/attachment/1/2/12974bf4-3865-4995-a14f-e9e2af343f2f12974bf4-3865-4995-a14f-e9e2af343f2f/;s3://test-opendata/attachment/1/2/12974bf4-3865-4995-a14f-e9e2af343f2f12974bf4-3865-4995-a14f-e9e2af343f2f/" - + dataPath, err := GetObsDataPath(uuid) + if err != nil { + log.Error("GetObsDataPath failed:%v", err, ctx.Data["MsgID"]) + trainJobErrorNewDataPrepare(ctx, form) + ctx.RenderWithErr("GetObsDataPath error", tplModelArtsTrainJobNew, &form) + return + } count, err := models.GetCloudbrainTrainJobCountByUserID(ctx.User.ID) if err != nil { log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"]) @@ -2421,3 +2426,24 @@ func TrainJobDownloadLogFile(ctx *context.Context) { ctx.Resp.Header().Set("Cache-Control", "max-age=0") http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently) } +func GetObsDataPath(uuid string) (string, error) { + var obsDataPath string + list := strings.Split(uuid, ";") + for k, uuidStr := range list { + _, err := models.GetAttachmentByUUID(uuidStr) + if err != nil { + log.Error("GetAttachmentByUUID failed:%v", err) + return "", err + } else { + if k <= 0 { + obsDataPath = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" + } + if k > 0 { + obsDataPathNext := ";" + "s3://" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" + obsDataPath = obsDataPath + obsDataPathNext + } + + } + } + return obsDataPath, nil +} -- 2.34.1 From 674de083a12a5573ffca9a8c852b6e83139e9f9e Mon Sep 17 00:00:00 2001 From: liuzx Date: Wed, 22 Jun 2022 18:05:01 +0800 Subject: [PATCH 04/35] =?UTF-8?q?=E4=BA=91=E8=84=91=E4=BA=8C=E5=A4=9A?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E9=9B=86=E9=80=89=E6=8B=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- modules/modelarts/modelarts.go | 19 +++------ modules/setting/setting.go | 2 + routers/repo/modelarts.go | 70 +++++++++++++++++++++++++--------- 3 files changed, 59 insertions(+), 32 deletions(-) diff --git a/modules/modelarts/modelarts.go b/modules/modelarts/modelarts.go index 78b40fd563..5988e62bbd 100755 --- a/modules/modelarts/modelarts.go +++ b/modules/modelarts/modelarts.go @@ -1,13 +1,14 @@ package modelarts import ( - "code.gitea.io/gitea/modules/timeutil" "encoding/json" "errors" "fmt" "path" "strconv" + "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" @@ -96,6 +97,7 @@ type GenerateTrainJobReq struct { VersionCount int EngineName string TotalVersionCount int + DatasetName string } type GenerateInferenceJobReq struct { @@ -335,11 +337,6 @@ func GenerateTrainJob(ctx *context.Context, req *GenerateTrainJobReq) (err error return err } - attach, err := models.GetAttachmentByUUID(req.Uuid) - if err != nil { - log.Error("GetAttachmentByUUID(%s) failed:%v", strconv.FormatInt(jobResult.JobID, 10), err.Error()) - return err - } jobId := strconv.FormatInt(jobResult.JobID, 10) err = models.CreateCloudbrain(&models.Cloudbrain{ Status: TransTrainJobStatus(jobResult.Status), @@ -353,7 +350,7 @@ func GenerateTrainJob(ctx *context.Context, req *GenerateTrainJobReq) (err error VersionID: jobResult.VersionID, VersionName: jobResult.VersionName, Uuid: req.Uuid, - DatasetName: attach.Name, + DatasetName: req.DatasetName, CommitID: req.CommitID, IsLatestVersion: req.IsLatestVersion, ComputeResource: models.NPUResource, @@ -408,12 +405,6 @@ func GenerateTrainJobVersion(ctx *context.Context, req *GenerateTrainJobReq, job return err } - attach, err := models.GetAttachmentByUUID(req.Uuid) - if err != nil { - log.Error("GetAttachmentByUUID(%s) failed:%v", strconv.FormatInt(jobResult.JobID, 10), err.Error()) - return err - } - var jobTypes []string jobTypes = append(jobTypes, string(models.JobTypeTrain)) repo := ctx.Repo.Repository @@ -441,7 +432,7 @@ func GenerateTrainJobVersion(ctx *context.Context, req *GenerateTrainJobReq, job VersionID: jobResult.VersionID, VersionName: jobResult.VersionName, Uuid: req.Uuid, - DatasetName: attach.Name, + DatasetName: req.DatasetName, CommitID: req.CommitID, IsLatestVersion: req.IsLatestVersion, PreVersionName: req.PreVersionName, diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 5c87b68c5a..8c26c7b9ec 100755 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -465,6 +465,7 @@ var ( MaxDuration int64 TrainGpuTypes string TrainResourceSpecs string + MaxDatasetNum int //benchmark config IsBenchmarkEnabled bool @@ -1294,6 +1295,7 @@ func NewContext() { MaxDuration = sec.Key("MAX_DURATION").MustInt64(14400) TrainGpuTypes = sec.Key("TRAIN_GPU_TYPES").MustString("") TrainResourceSpecs = sec.Key("TRAIN_RESOURCE_SPECS").MustString("") + MaxDatasetNum = sec.Key("MAX_DATASET_NUM").MustInt(5) sec = Cfg.Section("benchmark") IsBenchmarkEnabled = sec.Key("ENABLED").MustBool(false) diff --git a/routers/repo/modelarts.go b/routers/repo/modelarts.go index 269c7425e2..b1864136af 100755 --- a/routers/repo/modelarts.go +++ b/routers/repo/modelarts.go @@ -985,13 +985,21 @@ func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) FlavorName := form.FlavorName VersionCount := modelarts.VersionCount EngineName := form.EngineName - dataPath, err := GetObsDataPath(uuid) + if IsDatasetUseCountExceed(uuid) { + log.Error("DatasetUseCount is Exceed:%v") + trainJobErrorNewDataPrepare(ctx, form) + ctx.RenderWithErr("DatasetUseCount is Exceed", tplModelArtsTrainJobNew, &form) + return + } + datasetName, err := GetDatasetNameByUUID(uuid) if err != nil { - log.Error("GetObsDataPath failed:%v", err, ctx.Data["MsgID"]) + log.Error("GetDatasetNameByUUID failed:%v", err, ctx.Data["MsgID"]) trainJobErrorNewDataPrepare(ctx, form) - ctx.RenderWithErr("GetObsDataPath error", tplModelArtsTrainJobNew, &form) + ctx.RenderWithErr("GetDatasetNameByUUID error", tplModelArtsTrainJobNew, &form) return } + dataPath := GetObsDataPathByUUID(uuid) + count, err := models.GetCloudbrainTrainJobCountByUserID(ctx.User.ID) if err != nil { log.Error("GetCloudbrainTrainJobCountByUserID failed:%v", err, ctx.Data["MsgID"]) @@ -1167,6 +1175,7 @@ func TrainJobCreate(ctx *context.Context, form auth.CreateModelArtsTrainJobForm) EngineName: EngineName, VersionCount: VersionCount, TotalVersionCount: modelarts.TotalVersionCount, + DatasetName: datasetName, } //将params转换Parameters.Parameter,出错时返回给前端 @@ -1228,13 +1237,22 @@ func TrainJobCreateVersion(ctx *context.Context, form auth.CreateModelArtsTrainJ codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath + VersionOutputPath + "/" outputObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.OutputPath + VersionOutputPath + "/" logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/" - dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" + // dataPath := "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" branch_name := form.BranchName PreVersionName := form.VersionName FlavorName := form.FlavorName EngineName := form.EngineName isLatestVersion := modelarts.IsLatestVersion + datasetName, err := GetDatasetNameByUUID(uuid) + if err != nil { + log.Error("GetDatasetNameByUUID failed:%v", err, ctx.Data["MsgID"]) + trainJobErrorNewDataPrepare(ctx, form) + ctx.RenderWithErr("GetDatasetNameByUUID error", tplModelArtsTrainJobNew, &form) + return + } + dataPath := GetObsDataPathByUUID(uuid) + canNewJob, _ := canUserCreateTrainJobVersion(ctx, latestTask.UserID) if !canNewJob { ctx.RenderWithErr("user cann't new trainjob", tplModelArtsTrainJobVersionNew, &form) @@ -1392,6 +1410,7 @@ func TrainJobCreateVersion(ctx *context.Context, form auth.CreateModelArtsTrainJ EngineName: EngineName, PreVersionName: PreVersionName, TotalVersionCount: latestTask.TotalVersionCount + 1, + DatasetName: datasetName, } err = modelarts.GenerateTrainJobVersion(ctx, req, jobID) @@ -2426,24 +2445,39 @@ func TrainJobDownloadLogFile(ctx *context.Context) { ctx.Resp.Header().Set("Cache-Control", "max-age=0") http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently) } -func GetObsDataPath(uuid string) (string, error) { +func GetObsDataPathByUUID(uuid string) string { var obsDataPath string - list := strings.Split(uuid, ";") - for k, uuidStr := range list { - _, err := models.GetAttachmentByUUID(uuidStr) + uuidList := strings.Split(uuid, ";") + for k, _ := range uuidList { + if k <= 0 { + obsDataPath = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" + } + if k > 0 { + obsDataPathNext := ";" + "s3://" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" + obsDataPath = obsDataPath + obsDataPathNext + } + + } + return obsDataPath +} +func GetDatasetNameByUUID(uuid string) (string, error) { + uuidList := strings.Split(uuid, ";") + var datasetName string + for _, uuidStr := range uuidList { + attach, err := models.GetAttachmentByUUID(uuidStr) if err != nil { log.Error("GetAttachmentByUUID failed:%v", err) return "", err - } else { - if k <= 0 { - obsDataPath = "/" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" - } - if k > 0 { - obsDataPathNext := ";" + "s3://" + setting.Bucket + "/" + setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + uuid + "/" - obsDataPath = obsDataPath + obsDataPathNext - } - } + datasetName = datasetName + attach.Name + ";" + } + return datasetName, nil +} +func IsDatasetUseCountExceed(uuid string) bool { + uuidList := strings.Split(uuid, ";") + if len(uuidList) > setting.MaxDatasetNum { + return true + } else { + return false } - return obsDataPath, nil } -- 2.34.1 From e9ec5e63880fbac0e9d4e4e57ea9059c1c0927c5 Mon Sep 17 00:00:00 2001 From: liuzx Date: Wed, 22 Jun 2022 18:08:23 +0800 Subject: [PATCH 05/35] fix-bug --- routers/repo/modelarts.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/routers/repo/modelarts.go b/routers/repo/modelarts.go index b1864136af..0a4a9bbc10 100755 --- a/routers/repo/modelarts.go +++ b/routers/repo/modelarts.go @@ -1244,11 +1244,17 @@ func TrainJobCreateVersion(ctx *context.Context, form auth.CreateModelArtsTrainJ EngineName := form.EngineName isLatestVersion := modelarts.IsLatestVersion + if IsDatasetUseCountExceed(uuid) { + log.Error("DatasetUseCount is Exceed:%v") + versionErrorDataPrepare(ctx, form) + ctx.RenderWithErr("DatasetUseCount is Exceed", tplModelArtsTrainJobVersionNew, &form) + return + } datasetName, err := GetDatasetNameByUUID(uuid) if err != nil { log.Error("GetDatasetNameByUUID failed:%v", err, ctx.Data["MsgID"]) - trainJobErrorNewDataPrepare(ctx, form) - ctx.RenderWithErr("GetDatasetNameByUUID error", tplModelArtsTrainJobNew, &form) + versionErrorDataPrepare(ctx, form) + ctx.RenderWithErr("GetDatasetNameByUUID error", tplModelArtsTrainJobVersionNew, &form) return } dataPath := GetObsDataPathByUUID(uuid) -- 2.34.1 From 123d9399b3c4ca5253bb771e29333e2e02738ea5 Mon Sep 17 00:00:00 2001 From: ychao_1983 Date: Thu, 23 Jun 2022 14:30:30 +0800 Subject: [PATCH 06/35] =?UTF-8?q?=E5=BC=95=E7=94=A8=E6=AC=A1=E6=95=B0?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=A4=9A=E6=95=B0=E6=8D=AE=E9=9B=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/attachment.go | 4 +++- models/dataset.go | 18 +++++++++++++++--- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/models/attachment.go b/models/attachment.go index 31aefb3d10..e1af2e0794 100755 --- a/models/attachment.go +++ b/models/attachment.go @@ -110,8 +110,10 @@ func (a *Attachment) IncreaseDownloadCount() error { } func IncreaseAttachmentUseNumber(uuid string) error { + + uuidInCondition := "(" + strings.ReplaceAll(uuid, ";", ",") + ")" // Update use number. - if _, err := x.Exec("UPDATE `attachment` SET use_number=use_number+1 WHERE uuid=?", uuid); err != nil { + if _, err := x.Exec("UPDATE `attachment` SET use_number=use_number+1 WHERE uuid in", uuidInCondition); err != nil { return fmt.Errorf("increase attachment use count: %v", err) } diff --git a/models/dataset.go b/models/dataset.go index 4122b63b2c..2194aa42b3 100755 --- a/models/dataset.go +++ b/models/dataset.go @@ -445,10 +445,22 @@ func UpdateDataset(ctx DBContext, rel *Dataset) error { func IncreaseDatasetUseCount(uuid string) { IncreaseAttachmentUseNumber(uuid) + attachments, _ := GetAttachmentsByUUIDs(strings.Split(uuid, ";")) - attachment, _ := GetAttachmentByUUID(uuid) - if attachment != nil { - x.Exec("UPDATE `dataset` SET use_count=use_count+1 WHERE id=?", attachment.DatasetID) + countMap := make(map[int64]int) + + for _, attachment := range attachments { + value, ok := countMap[attachment.DatasetID] + if ok { + countMap[attachment.DatasetID] = value + 1 + } else { + countMap[attachment.DatasetID] = 1 + } + + } + + for key, value := range countMap { + x.Exec("UPDATE `dataset` SET use_count=use_count+? WHERE id=?", value, key) } } -- 2.34.1 From b9cb90d85e00f9c365619859a43bc35dd20f6eed Mon Sep 17 00:00:00 2001 From: ychao_1983 Date: Thu, 23 Jun 2022 15:46:37 +0800 Subject: [PATCH 07/35] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- models/attachment.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/models/attachment.go b/models/attachment.go index e1af2e0794..9b0083aaa9 100755 --- a/models/attachment.go +++ b/models/attachment.go @@ -111,9 +111,14 @@ func (a *Attachment) IncreaseDownloadCount() error { func IncreaseAttachmentUseNumber(uuid string) error { - uuidInCondition := "(" + strings.ReplaceAll(uuid, ";", ",") + ")" + uuidArray := strings.Split(uuid, ";") + for i := range uuidArray { + uuidArray[i] = "'" + uuidArray[i] + "'" + } + + uuidInCondition := "(" + strings.Join(uuidArray, ",") + ")" // Update use number. - if _, err := x.Exec("UPDATE `attachment` SET use_number=use_number+1 WHERE uuid in", uuidInCondition); err != nil { + if _, err := x.Exec("UPDATE `attachment` SET use_number=use_number+1 WHERE uuid in " + uuidInCondition); err != nil { return fmt.Errorf("increase attachment use count: %v", err) } -- 2.34.1 From 3a2c7a315e2d873208acb628f31c3fd07b47f83a Mon Sep 17 00:00:00 2001 From: zhoupzh Date: Fri, 24 Jun 2022 18:16:04 +0800 Subject: [PATCH 08/35] fix issue --- templates/repo/cloudbrain/new.tmpl | 10 +- templates/repo/cloudbrain/trainjob/new.tmpl | 5 +- templates/repo/modelarts/notebook/new.tmpl | 5 +- .../js/components/dataset/selectDataset.vue | 1028 ++++ web_src/js/index.js | 4356 ++++++++--------- 5 files changed, 3207 insertions(+), 2197 deletions(-) create mode 100644 web_src/js/components/dataset/selectDataset.vue diff --git a/templates/repo/cloudbrain/new.tmpl b/templates/repo/cloudbrain/new.tmpl index 107415e04e..1586956b83 100755 --- a/templates/repo/cloudbrain/new.tmpl +++ b/templates/repo/cloudbrain/new.tmpl @@ -104,6 +104,7 @@ top: 14px; z-index: 2; */ } +
@@ -119,8 +120,8 @@
{{template "repo/header" .}}
-
+ {{template "base/alert" .}}

@@ -218,8 +219,10 @@
+
- {{template "custom/select_dataset" .}} +
+
- {{template "custom/select_dataset" .}} +
+ +
+ + + + + + +
+ {{ data.desc }} +
+ {{ node.label }} + +
+ {{ node.label }} + + chen/datset +
+ {{ node.label }} +
+
+
+
+
+ + +
+
+ + + + + + + +
+ {{ data.desc }} +
+ {{ node.label }} + +
+ {{ node.label }} + + chen/datset +
+ {{ node.label }} +
+
+
+
+
+ + +
+
+ + + + + + + +
+ {{ data.desc }} +
+ {{ node.label }} + +
+ {{ node.label }} + + chen/datset +
+ {{ node.label }} +
+
+
+
+
+ + +
+
+ + + + + + + +
+ {{ data.desc }} +
+ {{ node.label }} + +
+ {{ node.label }} + + chen/datset +
+ {{ node.label }} +
+
+
+
+
+ + +
+
+ + + +
+ 已选择数据集 +
+
+ + + +
+
+ aaaa +
+
+ + +
+ + + + + diff --git a/web_src/js/index.js b/web_src/js/index.js index ef12b4158b..8ada2242ae 100755 --- a/web_src/js/index.js +++ b/web_src/js/index.js @@ -2,65 +2,66 @@ /* exported timeAddManual, toggleStopwatch, cancelStopwatch */ /* exported toggleDeadlineForm, setDeadline, updateDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */ -import './publicpath.js'; -import './polyfills.js'; -import './features/letteravatar.js' -import Vue from 'vue'; -import ElementUI from 'element-ui'; -import 'element-ui/lib/theme-chalk/index.css'; -import axios from 'axios'; -import qs from 'qs'; -import Cookies from 'js-cookie' -import 'jquery.are-you-sure'; -import './vendor/semanticdropdown.js'; -import { svg } from './utils.js'; -import echarts from 'echarts' -import initContextPopups from './features/contextpopup.js'; -import initGitGraph from './features/gitgraph.js'; -import initClipboard from './features/clipboard.js'; -import initUserHeatmap from './features/userheatmap.js'; -import initDateTimePicker from './features/datetimepicker.js'; -import initContextMenu from './features/contexmenu.js'; +import "./publicpath.js"; +import "./polyfills.js"; +import "./features/letteravatar.js"; +import Vue from "vue"; +import ElementUI from "element-ui"; +import "element-ui/lib/theme-chalk/index.css"; +import axios from "axios"; +import qs from "qs"; +import Cookies from "js-cookie"; +import "jquery.are-you-sure"; +import "./vendor/semanticdropdown.js"; +import { svg } from "./utils.js"; +import echarts from "echarts"; +import initContextPopups from "./features/contextpopup.js"; +import initGitGraph from "./features/gitgraph.js"; +import initClipboard from "./features/clipboard.js"; +import initUserHeatmap from "./features/userheatmap.js"; +import initDateTimePicker from "./features/datetimepicker.js"; +import initContextMenu from "./features/contexmenu.js"; import { initTribute, issuesTribute, - emojiTribute -} from './features/tribute.js'; -import createDropzone from './features/dropzone.js'; -import highlight from './features/highlight.js'; -import ActivityTopAuthors from './components/ActivityTopAuthors.vue'; + emojiTribute, +} from "./features/tribute.js"; +import createDropzone from "./features/dropzone.js"; +import highlight from "./features/highlight.js"; +import ActivityTopAuthors from "./components/ActivityTopAuthors.vue"; import { initNotificationsTable, - initNotificationCount -} from './features/notification.js'; -import { createCodeEditor } from './features/codeeditor.js'; -import MinioUploader from './components/MinioUploader.vue'; -import EditAboutInfo from './components/EditAboutInfo.vue'; + initNotificationCount, +} from "./features/notification.js"; +import { createCodeEditor } from "./features/codeeditor.js"; +import MinioUploader from "./components/MinioUploader.vue"; +import EditAboutInfo from "./components/EditAboutInfo.vue"; // import Images from './components/Images.vue'; -import EditTopics from './components/EditTopics.vue'; -import DataAnalysis from './components/DataAnalysis.vue' -import Contributors from './components/Contributors.vue' -import Model from './components/Model.vue'; -import WxAutorize from './components/WxAutorize.vue' -import initCloudrain from './features/cloudrbanin.js' -import initImage from './features/images.js' +import EditTopics from "./components/EditTopics.vue"; +import DataAnalysis from "./components/DataAnalysis.vue"; +import Contributors from "./components/Contributors.vue"; +import Model from "./components/Model.vue"; +import WxAutorize from "./components/WxAutorize.vue"; +import initCloudrain from "./features/cloudrbanin.js"; +import initImage from "./features/images.js"; +import selectDataset from "./components/dataset/selectDataset.vue"; // import $ from 'jquery.js' -import router from './router/index.js' +import router from "./router/index.js"; +import { Message } from "element-ui"; Vue.use(ElementUI); Vue.prototype.$axios = axios; Vue.prototype.$Cookies = Cookies; Vue.prototype.qs = qs; +Vue.prototype.$message = Message; const { AppSubUrl, StaticUrlPrefix, csrf } = window.config; -Object.defineProperty(Vue.prototype, '$echarts', { - value: echarts -}) +Object.defineProperty(Vue.prototype, "$echarts", { + value: echarts, +}); function htmlEncode(text) { - return jQuery('
') - .text(text) - .html(); + return jQuery("
").text(text).html(); } let previewFileModes; @@ -70,28 +71,28 @@ const commentMDEditors = {}; $.fn.tab.settings.silent = true; function initCommentPreviewTab($form) { - const $tabMenu = $form.find('.tabular.menu'); - $tabMenu.find('.item').tab(); + const $tabMenu = $form.find(".tabular.menu"); + $tabMenu.find(".item").tab(); $tabMenu - .find(`.item[data-tab="${$tabMenu.data('preview')}"]`) - .on('click', function () { + .find(`.item[data-tab="${$tabMenu.data("preview")}"]`) + .on("click", function () { const $this = $(this); $.post( - $this.data('url'), + $this.data("url"), { _csrf: csrf, - mode: 'gfm', - context: $this.data('context'), + mode: "gfm", + context: $this.data("context"), text: $form - .find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`) - .val() + .find(`.tab[data-tab="${$tabMenu.data("write")}"] textarea`) + .val(), }, (data) => { const $previewPanel = $form.find( - `.tab[data-tab="${$tabMenu.data('preview')}"]` + `.tab[data-tab="${$tabMenu.data("preview")}"]` ); $previewPanel.html(data); - $('pre code', $previewPanel[0]).each(function () { + $("pre code", $previewPanel[0]).each(function () { highlight(this); }); } @@ -102,37 +103,37 @@ function initCommentPreviewTab($form) { } function initEditPreviewTab($form) { - const $tabMenu = $form.find('.tabular.menu'); - $tabMenu.find('.item').tab(); + const $tabMenu = $form.find(".tabular.menu"); + $tabMenu.find(".item").tab(); const $previewTab = $tabMenu.find( - `.item[data-tab="${$tabMenu.data('preview')}"]` + `.item[data-tab="${$tabMenu.data("preview")}"]` ); if ($previewTab.length) { - previewFileModes = $previewTab.data('preview-file-modes').split(','); - $previewTab.on('click', function () { + previewFileModes = $previewTab.data("preview-file-modes").split(","); + $previewTab.on("click", function () { const $this = $(this); - let context = `${$this.data('context')}/`; - const treePathEl = $form.find('input#tree_path'); + let context = `${$this.data("context")}/`; + const treePathEl = $form.find("input#tree_path"); if (treePathEl.length > 0) { context += treePathEl.val(); } - context = context.substring(0, context.lastIndexOf('/')); + context = context.substring(0, context.lastIndexOf("/")); $.post( - $this.data('url'), + $this.data("url"), { _csrf: csrf, - mode: 'gfm', + mode: "gfm", context, text: $form - .find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`) - .val() + .find(`.tab[data-tab="${$tabMenu.data("write")}"] textarea`) + .val(), }, (data) => { const $previewPanel = $form.find( - `.tab[data-tab="${$tabMenu.data('preview')}"]` + `.tab[data-tab="${$tabMenu.data("preview")}"]` ); $previewPanel.html(data); - $('pre code', $previewPanel[0]).each(function () { + $("pre code", $previewPanel[0]).each(function () { highlight(this); }); } @@ -142,24 +143,24 @@ function initEditPreviewTab($form) { } function initEditDiffTab($form) { - const $tabMenu = $form.find('.tabular.menu'); - $tabMenu.find('.item').tab(); + const $tabMenu = $form.find(".tabular.menu"); + $tabMenu.find(".item").tab(); $tabMenu - .find(`.item[data-tab="${$tabMenu.data('diff')}"]`) - .on('click', function () { + .find(`.item[data-tab="${$tabMenu.data("diff")}"]`) + .on("click", function () { const $this = $(this); $.post( - $this.data('url'), + $this.data("url"), { _csrf: csrf, - context: $this.data('context'), + context: $this.data("context"), content: $form - .find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`) - .val() + .find(`.tab[data-tab="${$tabMenu.data("write")}"] textarea`) + .val(), }, (data) => { const $diffPreviewPanel = $form.find( - `.tab[data-tab="${$tabMenu.data('diff')}"]` + `.tab[data-tab="${$tabMenu.data("diff")}"]` ); $diffPreviewPanel.html(data); } @@ -168,66 +169,64 @@ function initEditDiffTab($form) { } function initEditForm() { - if ($('.edit.form').length === 0) { + if ($(".edit.form").length === 0) { return; } - initEditPreviewTab($('.edit.form')); - initEditDiffTab($('.edit.form')); + initEditPreviewTab($(".edit.form")); + initEditDiffTab($(".edit.form")); } function initBranchSelector() { - const $selectBranch = $('.ui.select-branch'); - const $branchMenu = $selectBranch.find('.reference-list-menu'); - $branchMenu.find('.item:not(.no-select)').click(function () { - $($(this).data('id-selector')).val($(this).data('id')); - $selectBranch.find('.ui .branch-name').text($(this).data('name')); + const $selectBranch = $(".ui.select-branch"); + const $branchMenu = $selectBranch.find(".reference-list-menu"); + $branchMenu.find(".item:not(.no-select)").click(function () { + $($(this).data("id-selector")).val($(this).data("id")); + $selectBranch.find(".ui .branch-name").text($(this).data("name")); }); - $selectBranch.find('.reference.column').on('click', function () { - $selectBranch.find('.scrolling.reference-list-menu').css('display', 'none'); - $selectBranch.find('.reference .text').addClass('black'); - $($(this).data('target')).css('display', 'block'); - $(this) - .find('.text.black') - .removeClass('black'); + $selectBranch.find(".reference.column").on("click", function () { + $selectBranch.find(".scrolling.reference-list-menu").css("display", "none"); + $selectBranch.find(".reference .text").addClass("black"); + $($(this).data("target")).css("display", "block"); + $(this).find(".text.black").removeClass("black"); return false; }); } function initLabelEdit() { // Create label - const $newLabelPanel = $('.new-label.segment'); - $('.new-label.button').on('click', () => { + const $newLabelPanel = $(".new-label.segment"); + $(".new-label.button").on("click", () => { $newLabelPanel.show(); }); - $('.new-label.segment .cancel').on('click', () => { + $(".new-label.segment .cancel").on("click", () => { $newLabelPanel.hide(); }); - $('.color-picker').each(function () { + $(".color-picker").each(function () { $(this).minicolors(); }); - $('.precolors .color').on('click', function () { - const color_hex = $(this).data('color-hex'); - $('.color-picker').val(color_hex); - $('.minicolors-swatch-color').css('background-color', color_hex); + $(".precolors .color").on("click", function () { + const color_hex = $(this).data("color-hex"); + $(".color-picker").val(color_hex); + $(".minicolors-swatch-color").css("background-color", color_hex); }); - $('.edit-label-button').on('click', function () { - $('#label-modal-id').val($(this).data('id')); - $('.edit-label .new-label-input').val($(this).data('title')); - $('.edit-label .new-label-desc-input').val($(this).data('description')); - $('.edit-label .color-picker').val($(this).data('color')); - $('.minicolors-swatch-color').css( - 'background-color', - $(this).data('color') + $(".edit-label-button").on("click", function () { + $("#label-modal-id").val($(this).data("id")); + $(".edit-label .new-label-input").val($(this).data("title")); + $(".edit-label .new-label-desc-input").val($(this).data("description")); + $(".edit-label .color-picker").val($(this).data("color")); + $(".minicolors-swatch-color").css( + "background-color", + $(this).data("color") ); - $('.edit-label.modal') + $(".edit-label.modal") .modal({ onApprove() { - $('.edit-label.form').trigger('submit'); - } + $(".edit-label.form").trigger("submit"); + }, }) - .modal('show'); + .modal("show"); return false; }); } @@ -235,7 +234,7 @@ function initLabelEdit() { function updateIssuesMeta(url, action, issueIds, elementId, isAdd) { return new Promise((resolve) => { $.ajax({ - type: 'POST', + type: "POST", url, data: { _csrf: csrf, @@ -244,25 +243,24 @@ function updateIssuesMeta(url, action, issueIds, elementId, isAdd) { id: elementId, is_add: isAdd, }, - success: resolve + success: resolve, }); }); } - function initRepoStatusChecker() { - const migrating = $('#repo_migrating'); - $('#repo_migrating_failed').hide(); + const migrating = $("#repo_migrating"); + $("#repo_migrating_failed").hide(); if (migrating) { - const repo_name = migrating.attr('repo'); - if (typeof repo_name === 'undefined') { + const repo_name = migrating.attr("repo"); + if (typeof repo_name === "undefined") { return; } $.ajax({ - type: 'GET', + type: "GET", url: `${AppSubUrl}/${repo_name}/status`, data: { - _csrf: csrf + _csrf: csrf, }, complete(xhr) { if (xhr.status === 200) { @@ -278,65 +276,63 @@ function initRepoStatusChecker() { return; } } - $('#repo_migrating_progress').hide(); - $('#repo_migrating_failed').show(); - } + $("#repo_migrating_progress").hide(); + $("#repo_migrating_failed").show(); + }, }); } } function initReactionSelector(parent) { - let reactions = ''; + let reactions = ""; if (!parent) { parent = $(document); - reactions = '.reactions > '; + reactions = ".reactions > "; } parent.find(`${reactions}a.label`).popup({ - position: 'bottom left', - metadata: { content: 'title', title: 'none' } + position: "bottom left", + metadata: { content: "title", title: "none" }, }); parent .find(`.select-reaction > .menu > .item, ${reactions}a.label`) - .on('click', function (e) { + .on("click", function (e) { const vm = this; e.preventDefault(); - if ($(this).hasClass('disabled')) return; + if ($(this).hasClass("disabled")) return; - const actionURL = $(this).hasClass('item') ? - $(this) - .closest('.select-reaction') - .data('action-url') : - $(this).data('action-url'); + const actionURL = $(this).hasClass("item") + ? $(this).closest(".select-reaction").data("action-url") + : $(this).data("action-url"); const url = `${actionURL}/${ - $(this).hasClass('blue') ? 'unreact' : 'react' - }`; + $(this).hasClass("blue") ? "unreact" : "react" + }`; $.ajax({ - type: 'POST', + type: "POST", url, data: { _csrf: csrf, - content: $(this).data('content') - } + content: $(this).data("content"), + }, }).done((resp) => { if (resp && (resp.html || resp.empty)) { - const content = $(vm).closest('.content'); - let react = content.find('.segment.reactions'); + const content = $(vm).closest(".content"); + let react = content.find(".segment.reactions"); if (!resp.empty && react.length > 0) { react.remove(); } if (!resp.empty) { react = $('
'); - const attachments = content.find('.segment.bottom:first'); + const attachments = content.find(".segment.bottom:first"); if (attachments.length > 0) { react.insertBefore(attachments); } else { react.appendTo(content); } react.html(resp.html); - react.find('.dropdown').dropdown(); + react.find(".dropdown").dropdown(); initReactionSelector(react); } } @@ -377,15 +373,15 @@ function retrieveImageFromClipboardAsBlob(pasteEvent, callback) { } const { items } = pasteEvent.clipboardData; - if (typeof items === 'undefined') { + if (typeof items === "undefined") { return; } for (let i = 0; i < items.length; i++) { - if (!items[i].type.includes('image')) continue; + if (!items[i].type.includes("image")) continue; const blob = items[i].getAsFile(); - if (typeof callback === 'function') { + if (typeof callback === "function") { pasteEvent.preventDefault(); pasteEvent.stopPropagation(); callback(blob); @@ -396,16 +392,16 @@ function retrieveImageFromClipboardAsBlob(pasteEvent, callback) { function uploadFile(file, callback) { const xhr = new XMLHttpRequest(); - xhr.addEventListener('load', () => { + xhr.addEventListener("load", () => { if (xhr.status === 200) { callback(xhr.responseText); } }); - xhr.open('post', `${AppSubUrl}/attachments`, true); - xhr.setRequestHeader('X-Csrf-Token', csrf); + xhr.open("post", `${AppSubUrl}/attachments`, true); + xhr.setRequestHeader("X-Csrf-Token", csrf); const formData = new FormData(); - formData.append('file', file, file.name); + formData.append("file", file, file.name); xhr.send(formData); } @@ -417,10 +413,10 @@ function initImagePaste(target) { target.each(function () { const field = this; field.addEventListener( - 'paste', + "paste", (event) => { retrieveImageFromClipboardAsBlob(event, (img) => { - const name = img.name.substr(0, img.name.lastIndexOf('.')); + const name = img.name.substr(0, img.name.lastIndexOf(".")); insertAtCursor(field, `![${name}]()`); uploadFile(img, (res) => { const data = JSON.parse(res); @@ -432,7 +428,7 @@ function initImagePaste(target) { const input = $( `` ).val(data.uuid); - $('.files').append(input); + $(".files").append(input); }); }); }, @@ -442,9 +438,9 @@ function initImagePaste(target) { } function initSimpleMDEImagePaste(simplemde, files) { - simplemde.codemirror.on('paste', (_, event) => { + simplemde.codemirror.on("paste", (_, event) => { retrieveImageFromClipboardAsBlob(event, (img) => { - const name = img.name.substr(0, img.name.lastIndexOf('.')); + const name = img.name.substr(0, img.name.lastIndexOf(".")); uploadFile(img, (res) => { const data = JSON.parse(res); const pos = simplemde.codemirror.getCursor(); @@ -464,38 +460,38 @@ function initSimpleMDEImagePaste(simplemde, files) { let autoSimpleMDE; function initCommentForm() { - if ($('.comment.form').length === 0) { + if ($(".comment.form").length === 0) { return; } autoSimpleMDE = setCommentSimpleMDE( - $('.comment.form textarea:not(.review-textarea)') + $(".comment.form textarea:not(.review-textarea)") ); initBranchSelector(); - initCommentPreviewTab($('.comment.form')); - initImagePaste($('.comment.form textarea')); + initCommentPreviewTab($(".comment.form")); + initImagePaste($(".comment.form textarea")); // Listsubmit function initListSubmits(selector, outerSelector) { const $list = $(`.ui.${outerSelector}.list`); - const $noSelect = $list.find('.no-select'); + const $noSelect = $list.find(".no-select"); const $listMenu = $(`.${selector} .menu`); - let hasLabelUpdateAction = $listMenu.data('action') === 'update'; + let hasLabelUpdateAction = $listMenu.data("action") === "update"; const labels = {}; - $(`.${selector}`).dropdown('setting', 'onHide', () => { - hasLabelUpdateAction = $listMenu.data('action') === 'update'; // Update the var + $(`.${selector}`).dropdown("setting", "onHide", () => { + hasLabelUpdateAction = $listMenu.data("action") === "update"; // Update the var if (hasLabelUpdateAction) { const promises = []; Object.keys(labels).forEach((elementId) => { const label = labels[elementId]; - console.log("label:", label) + console.log("label:", label); const promise = updateIssuesMeta( - label['update-url'], + label["update-url"], label.action, - label['issue-id'], + label["issue-id"], elementId, - label['is-checked'], + label["is-checked"] ); promises.push(promise); }); @@ -503,74 +499,66 @@ function initCommentForm() { } }); - $listMenu.find('.item:not(.no-select)').on('click', function () { + $listMenu.find(".item:not(.no-select)").on("click", function () { // we don't need the action attribute when updating assignees if ( - selector === 'select-assignees-modify' || - selector === 'select-reviewers-modify' + selector === "select-assignees-modify" || + selector === "select-reviewers-modify" ) { // UI magic. We need to do this here, otherwise it would destroy the functionality of // adding/removing labels - if ($(this).data('can-change') === 'block') { + if ($(this).data("can-change") === "block") { return false; } - if ($(this).hasClass('checked')) { - $(this).removeClass('checked'); - $(this) - .find('.octicon-check') - .addClass('invisible'); - $(this).data('is-checked', 'remove'); + if ($(this).hasClass("checked")) { + $(this).removeClass("checked"); + $(this).find(".octicon-check").addClass("invisible"); + $(this).data("is-checked", "remove"); } else { - $(this).addClass('checked'); - $(this) - .find('.octicon-check') - .removeClass('invisible'); - $(this).data('is-checked', 'add'); + $(this).addClass("checked"); + $(this).find(".octicon-check").removeClass("invisible"); + $(this).data("is-checked", "add"); } updateIssuesMeta( - $listMenu.data('update-url'), - '', - $listMenu.data('issue-id'), - $(this).data('id'), - $(this).data('is-checked'), + $listMenu.data("update-url"), + "", + $listMenu.data("issue-id"), + $(this).data("id"), + $(this).data("is-checked") ); - $listMenu.data('action', 'update'); // Update to reload the page when we updated items + $listMenu.data("action", "update"); // Update to reload the page when we updated items return false; } - if ($(this).hasClass('checked')) { - $(this).removeClass('checked'); - $(this) - .find('.octicon-check') - .addClass('invisible'); + if ($(this).hasClass("checked")) { + $(this).removeClass("checked"); + $(this).find(".octicon-check").addClass("invisible"); if (hasLabelUpdateAction) { - if (!($(this).data('id') in labels)) { - labels[$(this).data('id')] = { - 'update-url': $listMenu.data('update-url'), - action: 'detach', - 'issue-id': $listMenu.data('issue-id') + if (!($(this).data("id") in labels)) { + labels[$(this).data("id")] = { + "update-url": $listMenu.data("update-url"), + action: "detach", + "issue-id": $listMenu.data("issue-id"), }; } else { - delete labels[$(this).data('id')]; + delete labels[$(this).data("id")]; } } } else { - $(this).addClass('checked'); - $(this) - .find('.octicon-check') - .removeClass('invisible'); + $(this).addClass("checked"); + $(this).find(".octicon-check").removeClass("invisible"); if (hasLabelUpdateAction) { - if (!($(this).data('id') in labels)) { - labels[$(this).data('id')] = { - 'update-url': $listMenu.data('update-url'), - action: 'attach', - 'issue-id': $listMenu.data('issue-id') + if (!($(this).data("id") in labels)) { + labels[$(this).data("id")] = { + "update-url": $listMenu.data("update-url"), + action: "attach", + "issue-id": $listMenu.data("issue-id"), }; } else { - delete labels[$(this).data('id')]; + delete labels[$(this).data("id")]; } } } @@ -578,88 +566,77 @@ function initCommentForm() { const listIds = []; $(this) .parent() - .find('.item') + .find(".item") .each(function () { - if ($(this).hasClass('checked')) { - listIds.push($(this).data('id')); - $($(this).data('id-selector')).removeClass('hide'); + if ($(this).hasClass("checked")) { + listIds.push($(this).data("id")); + $($(this).data("id-selector")).removeClass("hide"); } else { - $($(this).data('id-selector')).addClass('hide'); + $($(this).data("id-selector")).addClass("hide"); } }); if (listIds.length === 0) { - $noSelect.removeClass('hide'); + $noSelect.removeClass("hide"); } else { - $noSelect.addClass('hide'); + $noSelect.addClass("hide"); } - $( - $(this) - .parent() - .data('id') - ).val(listIds.join(',')); + $($(this).parent().data("id")).val(listIds.join(",")); return false; }); - $listMenu.find('.no-select.item').on('click', function () { - if (hasLabelUpdateAction || selector === 'select-assignees-modify') { + $listMenu.find(".no-select.item").on("click", function () { + if (hasLabelUpdateAction || selector === "select-assignees-modify") { updateIssuesMeta( - $listMenu.data('update-url'), - 'clear', - $listMenu.data('issue-id'), - '', - '' - + $listMenu.data("update-url"), + "clear", + $listMenu.data("issue-id"), + "", + "" ).then(reload); } $(this) .parent() - .find('.item') + .find(".item") .each(function () { - $(this).removeClass('checked'); - $(this) - .find('.octicon') - .addClass('invisible'); - $(this).data('is-checked', 'remove'); + $(this).removeClass("checked"); + $(this).find(".octicon").addClass("invisible"); + $(this).data("is-checked", "remove"); }); - $list.find('.item').each(function () { - $(this).addClass('hide'); + $list.find(".item").each(function () { + $(this).addClass("hide"); }); - $noSelect.removeClass('hide'); - $( - $(this) - .parent() - .data('id') - ).val(''); + $noSelect.removeClass("hide"); + $($(this).parent().data("id")).val(""); }); } // Init labels and assignees - initListSubmits('select-label', 'labels'); - initListSubmits('select-assignees', 'assignees'); - initListSubmits('select-assignees-modify', 'assignees'); - initListSubmits('select-reviewers-modify', 'assignees'); + initListSubmits("select-label", "labels"); + initListSubmits("select-assignees", "assignees"); + initListSubmits("select-assignees-modify", "assignees"); + initListSubmits("select-reviewers-modify", "assignees"); function selectItem(select_id, input_id) { let $menu; - if (select_id == '.select-branch') { + if (select_id == ".select-branch") { $menu = $(`${select_id} .menu`).eq(1); } else { $menu = $(`${select_id} .menu`); } const $list = $(`.ui${select_id}.list`); - const hasUpdateAction = $menu.data('action') === 'update'; + const hasUpdateAction = $menu.data("action") === "update"; - $menu.find('.item:not(.no-select)').on('click', function () { + $menu.find(".item:not(.no-select)").on("click", function () { $(this) .parent() - .find('.item') + .find(".item") .each(function () { - $(this).removeClass('selected active'); + $(this).removeClass("selected active"); }); - $(this).addClass('selected active'); + $(this).addClass("selected active"); if (hasUpdateAction) { //let ref = '' //if (select_id=='.select-branch'){ @@ -667,176 +644,176 @@ function initCommentForm() { // } updateIssuesMeta( - $menu.data('update-url'), - '', - $menu.data('issue-id'), - $(this).data('id'), - $(this).data('is-checked'), + $menu.data("update-url"), + "", + $menu.data("issue-id"), + $(this).data("id"), + $(this).data("is-checked") ).then(reload); } switch (input_id) { - case '#milestone_id': + case "#milestone_id": $list - .find('.selected') + .find(".selected") .html( - `${htmlEncode( + `${htmlEncode( $(this).text() )}` ); break; - case '#assignee_id': + case "#assignee_id": $list - .find('.selected') + .find(".selected") .html( - `` + - `${htmlEncode($(this).text())}` + `` + + `${htmlEncode($(this).text())}` ); } - $(`.ui${select_id}.list .no-select`).addClass('hide'); - $(input_id).val($(this).data('id')); + $(`.ui${select_id}.list .no-select`).addClass("hide"); + $(input_id).val($(this).data("id")); }); - $menu.find('.no-select.item').on('click', function () { + $menu.find(".no-select.item").on("click", function () { $(this) .parent() - .find('.item:not(.no-select)') + .find(".item:not(.no-select)") .each(function () { - $(this).removeClass('selected active'); + $(this).removeClass("selected active"); }); if (hasUpdateAction) { updateIssuesMeta( - $menu.data('update-url'), - '', - $menu.data('issue-id'), - $(this).data('id'), - $(this).data('is-checked') + $menu.data("update-url"), + "", + $menu.data("issue-id"), + $(this).data("id"), + $(this).data("is-checked") ).then(reload); } - $list.find('.selected').html(''); - $list.find('.no-select').removeClass('hide'); - $(input_id).val(''); + $list.find(".selected").html(""); + $list.find(".no-select").removeClass("hide"); + $(input_id).val(""); }); } // Milestone and assignee - selectItem('.select-milestone', '#milestone_id'); - selectItem('.select-assignee', '#assignee_id'); - selectItem('.select-branch', ''); + selectItem(".select-milestone", "#milestone_id"); + selectItem(".select-assignee", "#assignee_id"); + selectItem(".select-branch", ""); } function initInstall() { - if ($('.install').length === 0) { + if ($(".install").length === 0) { return; } - if ($('#db_host').val() === '') { - $('#db_host').val('127.0.0.1:3306'); - $('#db_user').val('gitea'); - $('#db_name').val('gitea'); + if ($("#db_host").val() === "") { + $("#db_host").val("127.0.0.1:3306"); + $("#db_user").val("gitea"); + $("#db_name").val("gitea"); } // Database type change detection. - $('#db_type').on('change', function () { - const sqliteDefault = 'data/gitea.db'; - const tidbDefault = 'data/gitea_tidb'; + $("#db_type").on("change", function () { + const sqliteDefault = "data/gitea.db"; + const tidbDefault = "data/gitea_tidb"; const dbType = $(this).val(); - if (dbType === 'SQLite3') { - $('#sql_settings').hide(); - $('#pgsql_settings').hide(); - $('#mysql_settings').hide(); - $('#sqlite_settings').show(); - - if (dbType === 'SQLite3' && $('#db_path').val() === tidbDefault) { - $('#db_path').val(sqliteDefault); + if (dbType === "SQLite3") { + $("#sql_settings").hide(); + $("#pgsql_settings").hide(); + $("#mysql_settings").hide(); + $("#sqlite_settings").show(); + + if (dbType === "SQLite3" && $("#db_path").val() === tidbDefault) { + $("#db_path").val(sqliteDefault); } return; } const dbDefaults = { - MySQL: '127.0.0.1:3306', - PostgreSQL: '127.0.0.1:5432', - MSSQL: '127.0.0.1:1433' + MySQL: "127.0.0.1:3306", + PostgreSQL: "127.0.0.1:5432", + MSSQL: "127.0.0.1:1433", }; - $('#sqlite_settings').hide(); - $('#sql_settings').show(); + $("#sqlite_settings").hide(); + $("#sql_settings").show(); - $('#pgsql_settings').toggle(dbType === 'PostgreSQL'); - $('#mysql_settings').toggle(dbType === 'MySQL'); + $("#pgsql_settings").toggle(dbType === "PostgreSQL"); + $("#mysql_settings").toggle(dbType === "MySQL"); $.each(dbDefaults, (_type, defaultHost) => { - if ($('#db_host').val() === defaultHost) { - $('#db_host').val(dbDefaults[dbType]); + if ($("#db_host").val() === defaultHost) { + $("#db_host").val(dbDefaults[dbType]); return false; } }); }); // TODO: better handling of exclusive relations. - $('#offline-mode input').on('change', function () { - if ($(this).is(':checked')) { - $('#disable-gravatar').checkbox('check'); - $('#federated-avatar-lookup').checkbox('uncheck'); + $("#offline-mode input").on("change", function () { + if ($(this).is(":checked")) { + $("#disable-gravatar").checkbox("check"); + $("#federated-avatar-lookup").checkbox("uncheck"); } }); - $('#disable-gravatar input').on('change', function () { - if ($(this).is(':checked')) { - $('#federated-avatar-lookup').checkbox('uncheck'); + $("#disable-gravatar input").on("change", function () { + if ($(this).is(":checked")) { + $("#federated-avatar-lookup").checkbox("uncheck"); } else { - $('#offline-mode').checkbox('uncheck'); + $("#offline-mode").checkbox("uncheck"); } }); - $('#federated-avatar-lookup input').on('change', function () { - if ($(this).is(':checked')) { - $('#disable-gravatar').checkbox('uncheck'); - $('#offline-mode').checkbox('uncheck'); + $("#federated-avatar-lookup input").on("change", function () { + if ($(this).is(":checked")) { + $("#disable-gravatar").checkbox("uncheck"); + $("#offline-mode").checkbox("uncheck"); } }); - $('#enable-openid-signin input').on('change', function () { - if ($(this).is(':checked')) { - if (!$('#disable-registration input').is(':checked')) { - $('#enable-openid-signup').checkbox('check'); + $("#enable-openid-signin input").on("change", function () { + if ($(this).is(":checked")) { + if (!$("#disable-registration input").is(":checked")) { + $("#enable-openid-signup").checkbox("check"); } } else { - $('#enable-openid-signup').checkbox('uncheck'); + $("#enable-openid-signup").checkbox("uncheck"); } }); - $('#disable-registration input').on('change', function () { - if ($(this).is(':checked')) { - $('#enable-captcha').checkbox('uncheck'); - $('#enable-openid-signup').checkbox('uncheck'); + $("#disable-registration input").on("change", function () { + if ($(this).is(":checked")) { + $("#enable-captcha").checkbox("uncheck"); + $("#enable-openid-signup").checkbox("uncheck"); } else { - $('#enable-openid-signup').checkbox('check'); + $("#enable-openid-signup").checkbox("check"); } }); - $('#enable-captcha input').on('change', function () { - if ($(this).is(':checked')) { - $('#disable-registration').checkbox('uncheck'); + $("#enable-captcha input").on("change", function () { + if ($(this).is(":checked")) { + $("#disable-registration").checkbox("uncheck"); } }); } function initIssueComments() { - if ($('.repository.view.issue .timeline').length === 0) return; + if ($(".repository.view.issue .timeline").length === 0) return; - $('.re-request-review').on('click', function (event) { - const url = $(this).data('update-url'); - const issueId = $(this).data('issue-id'); - const id = $(this).data('id'); - const isChecked = $(this).data('is-checked'); + $(".re-request-review").on("click", function (event) { + const url = $(this).data("update-url"); + const issueId = $(this).data("issue-id"); + const id = $(this).data("id"); + const isChecked = $(this).data("is-checked"); //const ref = $(this).data('name'); event.preventDefault(); - updateIssuesMeta(url, '', issueId, id, isChecked).then(reload); + updateIssuesMeta(url, "", issueId, id, isChecked).then(reload); }); - $(document).on('click', (event) => { - const urlTarget = $(':target'); + $(document).on("click", (event) => { + const urlTarget = $(":target"); if (urlTarget.length === 0) return; - const urlTargetId = urlTarget.attr('id'); + const urlTargetId = urlTarget.attr("id"); if (!urlTargetId) return; if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return; @@ -844,15 +821,15 @@ function initIssueComments() { if ($target.closest(`#${urlTargetId}`).length === 0) { const scrollPosition = $(window).scrollTop(); - window.location.hash = ''; + window.location.hash = ""; $(window).scrollTop(scrollPosition); - window.history.pushState(null, null, ' '); + window.history.pushState(null, null, " "); } }); } async function initRepository() { - if ($('.repository').length === 0) { + if ($(".repository").length === 0) { return; } @@ -862,105 +839,105 @@ async function initRepository() { fullTextSearch: true, selectOnKeydown: false, onChange(_text, _value, $choice) { - if ($choice.data('url')) { - window.location.href = $choice.data('url'); + if ($choice.data("url")) { + window.location.href = $choice.data("url"); } }, - message: { noResults: $dropdown.data('no-results') } + message: { noResults: $dropdown.data("no-results") }, }); } // File list and commits if ( - $('.repository.file.list').length > 0 || - '.repository.commits'.length > 0 + $(".repository.file.list").length > 0 || + ".repository.commits".length > 0 ) { - initFilterBranchTagDropdown('.choose.reference .dropdown'); + initFilterBranchTagDropdown(".choose.reference .dropdown"); } // Wiki - if ($('.repository.wiki.view').length > 0) { - initFilterSearchDropdown('.choose.page .dropdown'); + if ($(".repository.wiki.view").length > 0) { + initFilterSearchDropdown(".choose.page .dropdown"); } // Options - if ($('.repository.settings.options').length > 0) { + if ($(".repository.settings.options").length > 0) { // Enable or select internal/external wiki system and issue tracker. - $('.enable-system').on('change', function () { + $(".enable-system").on("change", function () { if (this.checked) { - $($(this).data('target')).removeClass('disabled'); - if (!$(this).data('context')) { - $($(this).data('context')).addClass('disabled'); + $($(this).data("target")).removeClass("disabled"); + if (!$(this).data("context")) { + $($(this).data("context")).addClass("disabled"); } } else { - $($(this).data('target')).addClass('disabled'); - if (!$(this).data('context')) { - $($(this).data('context')).removeClass('disabled'); + $($(this).data("target")).addClass("disabled"); + if (!$(this).data("context")) { + $($(this).data("context")).removeClass("disabled"); } } }); - $('.enable-system-radio').on('change', function () { - if (this.value === 'false') { - $($(this).data('target')).addClass('disabled'); - if (typeof $(this).data('context') !== 'undefined') { - $($(this).data('context')).removeClass('disabled'); + $(".enable-system-radio").on("change", function () { + if (this.value === "false") { + $($(this).data("target")).addClass("disabled"); + if (typeof $(this).data("context") !== "undefined") { + $($(this).data("context")).removeClass("disabled"); } - } else if (this.value === 'true') { - $($(this).data('target')).removeClass('disabled'); - if (typeof $(this).data('context') !== 'undefined') { - $($(this).data('context')).addClass('disabled'); + } else if (this.value === "true") { + $($(this).data("target")).removeClass("disabled"); + if (typeof $(this).data("context") !== "undefined") { + $($(this).data("context")).addClass("disabled"); } } }); } // Labels - if ($('.repository.labels').length > 0) { + if ($(".repository.labels").length > 0) { initLabelEdit(); } // Milestones - if ($('.repository.new.milestone').length > 0) { - const $datepicker = $('.milestone.datepicker'); + if ($(".repository.new.milestone").length > 0) { + const $datepicker = $(".milestone.datepicker"); - await initDateTimePicker($datepicker.data('lang')); + await initDateTimePicker($datepicker.data("lang")); $datepicker.datetimepicker({ inline: true, timepicker: false, - startDate: $datepicker.data('start-date'), + startDate: $datepicker.data("start-date"), onSelectDate(date) { - $('#deadline').val(date.toISOString().substring(0, 10)); - } + $("#deadline").val(date.toISOString().substring(0, 10)); + }, }); - $('#clear-date').on('click', () => { - $('#deadline').val(''); + $("#clear-date").on("click", () => { + $("#deadline").val(""); return false; }); } // Issues - if ($('.repository.view.issue').length > 0) { + if ($(".repository.view.issue").length > 0) { // Edit issue title - const $issueTitle = $('#issue-title'); - const $editInput = $('#edit-title-input input'); + const $issueTitle = $("#issue-title"); + const $editInput = $("#edit-title-input input"); const editTitleToggle = function () { $issueTitle.toggle(); - $('.not-in-edit').toggle(); - $('#edit-title-input').toggle(); - $('#pull-desc').toggle(); - $('#pull-desc-edit').toggle(); - $('.in-edit').toggle(); + $(".not-in-edit").toggle(); + $("#edit-title-input").toggle(); + $("#pull-desc").toggle(); + $("#pull-desc-edit").toggle(); + $(".in-edit").toggle(); $editInput.focus(); return false; }; const changeBranchSelect = function () { - const selectionTextField = $('#pull-target-branch'); + const selectionTextField = $("#pull-target-branch"); - const baseName = selectionTextField.data('basename'); - const branchNameNew = $(this).data('branch'); - const branchNameOld = selectionTextField.data('branch'); + const baseName = selectionTextField.data("basename"); + const branchNameNew = $(this).data("branch"); + const branchNameOld = selectionTextField.data("branch"); // Replace branch name to keep translation from HTML template selectionTextField.html( @@ -971,24 +948,24 @@ async function initRepository() { `${baseName}:${branchNameNew}` ) ); - selectionTextField.data('branch', branchNameNew); // update branch name in setting + selectionTextField.data("branch", branchNameNew); // update branch name in setting }; - $('#branch-select > .item').on('click', changeBranchSelect); + $("#branch-select > .item").on("click", changeBranchSelect); - $('#edit-title').on('click', editTitleToggle); - $('#cancel-edit-title').on('click', editTitleToggle); - $('#save-edit-title') - .on('click', editTitleToggle) - .on('click', function () { + $("#edit-title").on("click", editTitleToggle); + $("#cancel-edit-title").on("click", editTitleToggle); + $("#save-edit-title") + .on("click", editTitleToggle) + .on("click", function () { const pullrequest_targetbranch_change = function (update_url) { - const targetBranch = $('#pull-target-branch').data('branch'); - const $branchTarget = $('#branch_target'); + const targetBranch = $("#pull-target-branch").data("branch"); + const $branchTarget = $("#branch_target"); if (targetBranch === $branchTarget.text()) { return false; } $.post(update_url, { _csrf: csrf, - target_branch: targetBranch + target_branch: targetBranch, }) .done((data) => { $branchTarget.text(data.base_branch); @@ -998,7 +975,7 @@ async function initRepository() { }); }; - const pullrequest_target_update_url = $(this).data('target-update-url'); + const pullrequest_target_update_url = $(this).data("target-update-url"); if ( $editInput.val().length === 0 || $editInput.val() === $issueTitle.text() @@ -1007,10 +984,10 @@ async function initRepository() { pullrequest_targetbranch_change(pullrequest_target_update_url); } else { $.post( - $(this).data('update-url'), + $(this).data("update-url"), { _csrf: csrf, - title: $editInput.val() + title: $editInput.val(), }, (data) => { $editInput.val(data.title); @@ -1027,35 +1004,30 @@ async function initRepository() { initIssueComments(); // Issue/PR Context Menus - $('.context-dropdown').dropdown({ - action: 'hide' + $(".context-dropdown").dropdown({ + action: "hide", }); // Quote reply - $('.quote-reply').on('click', function (event) { - $(this) - .closest('.dropdown') - .find('.menu') - .toggle('visible'); - const target = $(this).data('target'); - const quote = $(`#comment-${target}`) - .text() - .replace(/\n/g, '\n> '); + $(".quote-reply").on("click", function (event) { + $(this).closest(".dropdown").find(".menu").toggle("visible"); + const target = $(this).data("target"); + const quote = $(`#comment-${target}`).text().replace(/\n/g, "\n> "); const content = `> ${quote}\n\n`; let $content; - if ($(this).hasClass('quote-reply-diff')) { - const $parent = $(this).closest('.comment-code-cloud'); - $parent.find('button.comment-form-reply').trigger('click'); + if ($(this).hasClass("quote-reply-diff")) { + const $parent = $(this).closest(".comment-code-cloud"); + $parent.find("button.comment-form-reply").trigger("click"); $content = $parent.find('[name="content"]'); - if ($content.val() !== '') { + if ($content.val() !== "") { $content.val(`${$content.val()}\n\n${content}`); } else { $content.val(`${content}`); } $content.focus(); } else if (autoSimpleMDE !== null) { - if (autoSimpleMDE.value() !== '') { + if (autoSimpleMDE.value() !== "") { autoSimpleMDE.value(`${autoSimpleMDE.value()}\n\n${content}`); } else { autoSimpleMDE.value(`${content}`); @@ -1065,99 +1037,94 @@ async function initRepository() { }); // Edit issue or comment content - $('.edit-content').on('click', async function (event) { - $(this) - .closest('.dropdown') - .find('.menu') - .toggle('visible'); - const $segment = $(this) - .closest('.header') - .next(); - const $editContentZone = $segment.find('.edit-content-zone'); - const $renderContent = $segment.find('.render-content'); - const $rawContent = $segment.find('.raw-content'); + $(".edit-content").on("click", async function (event) { + $(this).closest(".dropdown").find(".menu").toggle("visible"); + const $segment = $(this).closest(".header").next(); + const $editContentZone = $segment.find(".edit-content-zone"); + const $renderContent = $segment.find(".render-content"); + const $rawContent = $segment.find(".raw-content"); let $textarea; let $simplemde; // Setup new form if ($editContentZone.html().length === 0) { - $editContentZone.html($('#edit-content-form').html()); - $textarea = $editContentZone.find('textarea'); + $editContentZone.html($("#edit-content-form").html()); + $textarea = $editContentZone.find("textarea"); issuesTribute.attach($textarea.get()); emojiTribute.attach($textarea.get()); let dz; - const $dropzone = $editContentZone.find('.dropzone'); - const $files = $editContentZone.find('.comment-files'); + const $dropzone = $editContentZone.find(".dropzone"); + const $files = $editContentZone.find(".comment-files"); if ($dropzone.length > 0) { - $dropzone.data('saved', false); + $dropzone.data("saved", false); const filenameDict = {}; dz = await createDropzone($dropzone[0], { - url: $dropzone.data('upload-url'), - headers: { 'X-Csrf-Token': csrf }, - maxFiles: $dropzone.data('max-file'), - maxFilesize: $dropzone.data('max-size'), + url: $dropzone.data("upload-url"), + headers: { "X-Csrf-Token": csrf }, + maxFiles: $dropzone.data("max-file"), + maxFilesize: $dropzone.data("max-size"), acceptedFiles: - $dropzone.data('accepts') === '*/*' ? - null : - $dropzone.data('accepts'), + $dropzone.data("accepts") === "*/*" + ? null + : $dropzone.data("accepts"), addRemoveLinks: true, - dictDefaultMessage: $dropzone.data('default-message'), - dictInvalidFileType: $dropzone.data('invalid-input-type'), - dictFileTooBig: $dropzone.data('file-too-big'), - dictRemoveFile: $dropzone.data('remove-file'), + dictDefaultMessage: $dropzone.data("default-message"), + dictInvalidFileType: $dropzone.data("invalid-input-type"), + dictFileTooBig: $dropzone.data("file-too-big"), + dictRemoveFile: $dropzone.data("remove-file"), init() { - this.on('success', (file, data) => { + this.on("success", (file, data) => { filenameDict[file.name] = { uuid: data.uuid, - submitted: false + submitted: false, }; const input = $( `` ).val(data.uuid); $files.append(input); }); - this.on('removedfile', (file) => { + this.on("removedfile", (file) => { if (!(file.name in filenameDict)) { return; } $(`#${filenameDict[file.name].uuid}`).remove(); if ( - $dropzone.data('remove-url') && - $dropzone.data('csrf') && + $dropzone.data("remove-url") && + $dropzone.data("csrf") && !filenameDict[file.name].submitted ) { - $.post($dropzone.data('remove-url'), { + $.post($dropzone.data("remove-url"), { file: filenameDict[file.name].uuid, - _csrf: $dropzone.data('csrf') + _csrf: $dropzone.data("csrf"), }); } }); - this.on('submit', () => { + this.on("submit", () => { $.each(filenameDict, (name) => { filenameDict[name].submitted = true; }); }); - this.on('reload', () => { - $.getJSON($editContentZone.data('attachment-url'), (data) => { + this.on("reload", () => { + $.getJSON($editContentZone.data("attachment-url"), (data) => { dz.removeAllFiles(true); $files.empty(); $.each(data, function () { - const imgSrc = `${$dropzone.data('upload-url')}/${ + const imgSrc = `${$dropzone.data("upload-url")}/${ this.uuid - }`; - dz.emit('addedfile', this); - dz.emit('thumbnail', this, imgSrc); - dz.emit('complete', this); + }`; + dz.emit("addedfile", this); + dz.emit("thumbnail", this, imgSrc); + dz.emit("complete", this); dz.files.push(this); filenameDict[this.name] = { submitted: true, - uuid: this.uuid + uuid: this.uuid, }; $dropzone .find(`img[src='${imgSrc}']`) - .css('max-width', '100%'); + .css("max-width", "100%"); const input = $( `` ).val(this.uuid); @@ -1165,92 +1132,90 @@ async function initRepository() { }); }); }); - } + }, }); - dz.emit('reload'); + dz.emit("reload"); } // Give new write/preview data-tab name to distinguish from others - const $editContentForm = $editContentZone.find('.ui.comment.form'); - const $tabMenu = $editContentForm.find('.tabular.menu'); - $tabMenu.attr('data-write', $editContentZone.data('write')); - $tabMenu.attr('data-preview', $editContentZone.data('preview')); + const $editContentForm = $editContentZone.find(".ui.comment.form"); + const $tabMenu = $editContentForm.find(".tabular.menu"); + $tabMenu.attr("data-write", $editContentZone.data("write")); + $tabMenu.attr("data-preview", $editContentZone.data("preview")); $tabMenu - .find('.write.item') - .attr('data-tab', $editContentZone.data('write')); + .find(".write.item") + .attr("data-tab", $editContentZone.data("write")); $tabMenu - .find('.preview.item') - .attr('data-tab', $editContentZone.data('preview')); + .find(".preview.item") + .attr("data-tab", $editContentZone.data("preview")); $editContentForm - .find('.write') - .attr('data-tab', $editContentZone.data('write')); + .find(".write") + .attr("data-tab", $editContentZone.data("write")); $editContentForm - .find('.preview') - .attr('data-tab', $editContentZone.data('preview')); + .find(".preview") + .attr("data-tab", $editContentZone.data("preview")); $simplemde = setCommentSimpleMDE($textarea); - commentMDEditors[$editContentZone.data('write')] = $simplemde; + commentMDEditors[$editContentZone.data("write")] = $simplemde; initCommentPreviewTab($editContentForm); initSimpleMDEImagePaste($simplemde, $files); - $editContentZone.find('.cancel.button').on('click', () => { + $editContentZone.find(".cancel.button").on("click", () => { $renderContent.show(); $editContentZone.hide(); - dz.emit('reload'); + dz.emit("reload"); }); - $editContentZone.find('.save.button').on('click', () => { + $editContentZone.find(".save.button").on("click", () => { $renderContent.show(); $editContentZone.hide(); const $attachments = $files - .find('[name=files]') + .find("[name=files]") .map(function () { return $(this).val(); }) .get(); $.post( - $editContentZone.data('update-url'), + $editContentZone.data("update-url"), { _csrf: csrf, content: $textarea.val(), - context: $editContentZone.data('context'), - files: $attachments + context: $editContentZone.data("context"), + files: $attachments, }, (data) => { - if (data.length === 0 || data.content === '') { - $renderContent.html($('#no-content').html()); + if (data.length === 0 || data.content === "") { + $renderContent.html($("#no-content").html()); } else { $renderContent.html(data.content); - $('pre code', $renderContent[0]).each(function () { + $("pre code", $renderContent[0]).each(function () { highlight(this); }); } - let imageShow = '' + let imageShow = ""; const $content = $segment.parent(); - if (!$content.find('.ui.small.images').length) { - if (data.attachments !== '' && data.attachments) { - if ($content.find('.ui.middle.aligned').length === 0) { - imageShow += '
' - imageShow += '
' - imageShow += data.attachments - imageShow += '
' - $content.find('.ui.attached.segment').append(imageShow) + if (!$content.find(".ui.small.images").length) { + if (data.attachments !== "" && data.attachments) { + if ($content.find(".ui.middle.aligned").length === 0) { + imageShow += '
'; + imageShow += '
'; + imageShow += data.attachments; + imageShow += "
"; + $content.find(".ui.attached.segment").append(imageShow); + } else { + $content.find(".ui.middle.aligned").html(data.attachments); } - else { $content.find('.ui.middle.aligned').html(data.attachments) } } - } else if (data.attachments === '') { - $content - .find('.ui.small.images') - .parent() - .remove(); + } else if (data.attachments === "") { + $content.find(".ui.small.images").parent().remove(); } else { - $content.find('.ui.small.images').html(data.attachments); + $content.find(".ui.small.images").html(data.attachments); } - dz.emit('submit'); - dz.emit('reload'); + dz.emit("submit"); + dz.emit("reload"); } ); }); } else { - $textarea = $segment.find('textarea'); - $simplemde = commentMDEditors[$editContentZone.data('write')]; + $textarea = $segment.find("textarea"); + $simplemde = commentMDEditors[$editContentZone.data("write")]; } // Show write/preview tab and copy raw content as needed @@ -1266,390 +1231,367 @@ async function initRepository() { }); // Delete comment - $('.delete-comment').on('click', function () { + $(".delete-comment").on("click", function () { const $this = $(this); - if (window.confirm($this.data('locale'))) { - $.post($this.data('url'), { - _csrf: csrf + if (window.confirm($this.data("locale"))) { + $.post($this.data("url"), { + _csrf: csrf, }).done(() => { - $(`#${$this.data('comment-id')}`).remove(); + $(`#${$this.data("comment-id")}`).remove(); }); } return false; }); // Change status - const $statusButton = $('#status-button'); - $('#comment-form .edit_area').on('keyup', function () { + const $statusButton = $("#status-button"); + $("#comment-form .edit_area").on("keyup", function () { if ($(this).val().length === 0) { - $statusButton.text($statusButton.data('status')); + $statusButton.text($statusButton.data("status")); } else { - $statusButton.text($statusButton.data('status-and-comment')); + $statusButton.text($statusButton.data("status-and-comment")); } }); - $statusButton.on('click', () => { - $('#status').val($statusButton.data('status-val')); - $('#comment-form').trigger('submit'); + $statusButton.on("click", () => { + $("#status").val($statusButton.data("status-val")); + $("#comment-form").trigger("submit"); }); // Pull Request merge button - const $mergeButton = $('.merge-button > button'); - $mergeButton.on('click', function (e) { + const $mergeButton = $(".merge-button > button"); + $mergeButton.on("click", function (e) { e.preventDefault(); - $(`.${$(this).data('do')}-fields`).show(); - $(this) - .parent() - .hide(); + $(`.${$(this).data("do")}-fields`).show(); + $(this).parent().hide(); }); - $('.merge-button > .dropdown').dropdown({ + $(".merge-button > .dropdown").dropdown({ onChange(_text, _value, $choice) { - if ($choice.data('do')) { - $mergeButton.find('.button-text').text($choice.text()); - $mergeButton.data('do', $choice.data('do')); + if ($choice.data("do")) { + $mergeButton.find(".button-text").text($choice.text()); + $mergeButton.data("do", $choice.data("do")); } - } + }, }); - $('.merge-cancel').on('click', function (e) { + $(".merge-cancel").on("click", function (e) { e.preventDefault(); - $(this) - .closest('.form') - .hide(); + $(this).closest(".form").hide(); $mergeButton.parent().show(); }); initReactionSelector(); } // Datasets - if ($('.repository.dataset-list.view').length > 0) { + if ($(".repository.dataset-list.view").length > 0) { const editContentToggle = function () { - $('#dataset-content').toggle(); - $('#dataset-content-edit').toggle(); - $('#dataset-content input').focus(); + $("#dataset-content").toggle(); + $("#dataset-content-edit").toggle(); + $("#dataset-content input").focus(); return false; }; - $('[data-dataset-status]').on('click', function () { + $("[data-dataset-status]").on("click", function () { const $this = $(this); - const $private = $this.data('private'); - const $is_private = $this.data('is-private'); + const $private = $this.data("private"); + const $is_private = $this.data("is-private"); if ($is_private === $private) { return; } - const $uuid = $this.data('uuid'); - $.post($this.data('url'), { - _csrf: $this.data('csrf'), + const $uuid = $this.data("uuid"); + $.post($this.data("url"), { + _csrf: $this.data("csrf"), file: $uuid, - is_private: $private + is_private: $private, }) .done((_data) => { - $(`[data-uuid='${$uuid}']`).removeClass('positive active'); - $(`[data-uuid='${$uuid}']`).data('is-private', $private); - $this.addClass('positive active'); + $(`[data-uuid='${$uuid}']`).removeClass("positive active"); + $(`[data-uuid='${$uuid}']`).data("is-private", $private); + $this.addClass("positive active"); }) .fail(() => { window.location.reload(); }); }); - $('[data-dataset-delete]').on('click', function () { + $("[data-dataset-delete]").on("click", function () { const $this = $(this); - $('#data-dataset-delete-modal') + $("#data-dataset-delete-modal") .modal({ closable: false, onApprove() { - $.post($this.data('remove-url'), { - _csrf: $this.data('csrf'), - file: $this.data('uuid') + $.post($this.data("remove-url"), { + _csrf: $this.data("csrf"), + file: $this.data("uuid"), }) .done((_data) => { - $(`#${$this.data('uuid')}`).hide(); + $(`#${$this.data("uuid")}`).hide(); }) .fail(() => { window.location.reload(); }); - } + }, }) - .modal('show'); + .modal("show"); }); - $('[data-category-id]').on('click', function () { - const category = $(this).data('category-id'); - $('#category').val(category); - $('#submit').click(); + $("[data-category-id]").on("click", function () { + const category = $(this).data("category-id"); + $("#category").val(category); + $("#submit").click(); }); - $('[data-task-id]').on('click', function () { - const task = $(this).data('task-id'); - $('#task').val(task); - $('#submit').click(); + $("[data-task-id]").on("click", function () { + const task = $(this).data("task-id"); + $("#task").val(task); + $("#submit").click(); }); - $('[data-license-id]').on('click', function () { - const license = $(this).data('license-id'); - $('#license').val(license); - $('#submit').click(); + $("[data-license-id]").on("click", function () { + const license = $(this).data("license-id"); + $("#license").val(license); + $("#submit").click(); }); - $('#dataset-edit').on('click', editContentToggle); - $('#cancel').on('click', editContentToggle); + $("#dataset-edit").on("click", editContentToggle); + $("#cancel").on("click", editContentToggle); } // Diff - if ($('.repository.diff').length > 0) { - $('.diff-counter').each(function () { + if ($(".repository.diff").length > 0) { + $(".diff-counter").each(function () { const $item = $(this); - const addLine = $item.find('span[data-line].add').data('line'); - const delLine = $item.find('span[data-line].del').data('line'); + const addLine = $item.find("span[data-line].add").data("line"); + const delLine = $item.find("span[data-line].del").data("line"); const addPercent = (parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine))) * 100; - $item.find('.bar .add').css('width', `${addPercent}%`); + $item.find(".bar .add").css("width", `${addPercent}%`); }); } // Quick start and repository home - $('#repo-clone-ssh').on('click', function () { - $('.clone-url').text($(this).data('link')); - $('#repo-clone-url').val($(this).data('link')); - $(this).addClass('blue'); - $('#repo-clone-https').removeClass('blue'); - localStorage.setItem('repo-clone-protocol', 'ssh'); + $("#repo-clone-ssh").on("click", function () { + $(".clone-url").text($(this).data("link")); + $("#repo-clone-url").val($(this).data("link")); + $(this).addClass("blue"); + $("#repo-clone-https").removeClass("blue"); + localStorage.setItem("repo-clone-protocol", "ssh"); }); - $('#repo-clone-https').on('click', function () { - $('.clone-url').text($(this).data('link')); - $('#repo-clone-url').val($(this).data('link')); - $(this).addClass('blue'); - $('#repo-clone-ssh').removeClass('blue'); - localStorage.setItem('repo-clone-protocol', 'https'); + $("#repo-clone-https").on("click", function () { + $(".clone-url").text($(this).data("link")); + $("#repo-clone-url").val($(this).data("link")); + $(this).addClass("blue"); + $("#repo-clone-ssh").removeClass("blue"); + localStorage.setItem("repo-clone-protocol", "https"); }); - $('#repo-clone-url').on('click', function () { + $("#repo-clone-url").on("click", function () { $(this).select(); }); // Pull request - const $repoComparePull = $('.repository.compare.pull'); + const $repoComparePull = $(".repository.compare.pull"); if ($repoComparePull.length > 0) { - initFilterSearchDropdown('.choose.branch .dropdown'); + initFilterSearchDropdown(".choose.branch .dropdown"); // show pull request form - $repoComparePull.find('button.show-form').on('click', function (e) { + $repoComparePull.find("button.show-form").on("click", function (e) { e.preventDefault(); - $repoComparePull.find('.pullrequest-form').show(); + $repoComparePull.find(".pullrequest-form").show(); autoSimpleMDE.codemirror.refresh(); - $(this) - .parent() - .hide(); + $(this).parent().hide(); }); } // Branches - if ($('.repository.settings.branches').length > 0) { - initFilterSearchDropdown('.protected-branches .dropdown'); - $('.enable-protection, .enable-whitelist, .enable-statuscheck').on( - 'change', + if ($(".repository.settings.branches").length > 0) { + initFilterSearchDropdown(".protected-branches .dropdown"); + $(".enable-protection, .enable-whitelist, .enable-statuscheck").on( + "change", function () { if (this.checked) { - $($(this).data('target')).removeClass('disabled'); + $($(this).data("target")).removeClass("disabled"); } else { - $($(this).data('target')).addClass('disabled'); + $($(this).data("target")).addClass("disabled"); } } ); - $('.disable-whitelist').on('change', function () { + $(".disable-whitelist").on("change", function () { if (this.checked) { - $($(this).data('target')).addClass('disabled'); + $($(this).data("target")).addClass("disabled"); } }); } // Language stats - if ($('.language-stats').length > 0) { - $('.language-stats').on('click', (e) => { + if ($(".language-stats").length > 0) { + $(".language-stats").on("click", (e) => { e.preventDefault(); - $('.language-stats-details, .repository-menu').slideToggle(); + $(".language-stats-details, .repository-menu").slideToggle(); }); } } function initMigration() { const toggleMigrations = function () { - const authUserName = $('#auth_username').val(); - const cloneAddr = $('#clone_addr').val(); + const authUserName = $("#auth_username").val(); + const cloneAddr = $("#clone_addr").val(); if ( - !$('#mirror').is(':checked') && + !$("#mirror").is(":checked") && authUserName && authUserName.length > 0 && cloneAddr !== undefined && - (cloneAddr.startsWith('https://github.com') || - cloneAddr.startsWith('http://github.com') || - cloneAddr.startsWith('http://gitlab.com') || - cloneAddr.startsWith('https://gitlab.com')) + (cloneAddr.startsWith("https://github.com") || + cloneAddr.startsWith("http://github.com") || + cloneAddr.startsWith("http://gitlab.com") || + cloneAddr.startsWith("https://gitlab.com")) ) { - $('#migrate_items').show(); + $("#migrate_items").show(); } else { - $('#migrate_items').hide(); + $("#migrate_items").hide(); } }; toggleMigrations(); - $('#clone_addr').on('input', toggleMigrations); - $('#auth_username').on('input', toggleMigrations); - $('#mirror').on('change', toggleMigrations); + $("#clone_addr").on("input", toggleMigrations); + $("#auth_username").on("input", toggleMigrations); + $("#mirror").on("change", toggleMigrations); } function initPullRequestReview() { - $('.show-outdated').on('click', function (e) { + $(".show-outdated").on("click", function (e) { e.preventDefault(); - const id = $(this).data('comment'); - $(this).addClass('hide'); - $(`#code-comments-${id}`).removeClass('hide'); - $(`#code-preview-${id}`).removeClass('hide'); - $(`#hide-outdated-${id}`).removeClass('hide'); + const id = $(this).data("comment"); + $(this).addClass("hide"); + $(`#code-comments-${id}`).removeClass("hide"); + $(`#code-preview-${id}`).removeClass("hide"); + $(`#hide-outdated-${id}`).removeClass("hide"); }); - $('.hide-outdated').on('click', function (e) { + $(".hide-outdated").on("click", function (e) { e.preventDefault(); - const id = $(this).data('comment'); - $(this).addClass('hide'); - $(`#code-comments-${id}`).addClass('hide'); - $(`#code-preview-${id}`).addClass('hide'); - $(`#show-outdated-${id}`).removeClass('hide'); + const id = $(this).data("comment"); + $(this).addClass("hide"); + $(`#code-comments-${id}`).addClass("hide"); + $(`#code-preview-${id}`).addClass("hide"); + $(`#show-outdated-${id}`).removeClass("hide"); }); - $('button.comment-form-reply').on('click', function (e) { + $("button.comment-form-reply").on("click", function (e) { e.preventDefault(); $(this).hide(); - const form = $(this) - .parent() - .find('.comment-form'); - form.removeClass('hide'); - assingMenuAttributes(form.find('.menu')); + const form = $(this).parent().find(".comment-form"); + form.removeClass("hide"); + assingMenuAttributes(form.find(".menu")); }); // The following part is only for diff views - if ($('.repository.pull.diff').length === 0) { + if ($(".repository.pull.diff").length === 0) { return; } - $('.diff-detail-box.ui.sticky').sticky(); + $(".diff-detail-box.ui.sticky").sticky(); - $('.btn-review') - .on('click', function (e) { + $(".btn-review") + .on("click", function (e) { e.preventDefault(); - $(this) - .closest('.dropdown') - .find('.menu') - .toggle('visible'); + $(this).closest(".dropdown").find(".menu").toggle("visible"); }) - .closest('.dropdown') - .find('.link.close') - .on('click', function (e) { + .closest(".dropdown") + .find(".link.close") + .on("click", function (e) { e.preventDefault(); - $(this) - .closest('.menu') - .toggle('visible'); + $(this).closest(".menu").toggle("visible"); }); - $('.code-view .lines-code,.code-view .lines-num') - .on('mouseenter', function () { - const parent = $(this).closest('td'); + $(".code-view .lines-code,.code-view .lines-num") + .on("mouseenter", function () { + const parent = $(this).closest("td"); $(this) - .closest('tr') + .closest("tr") .addClass( - parent.hasClass('lines-num-old') || parent.hasClass('lines-code-old') ? - 'focus-lines-old' : - 'focus-lines-new' + parent.hasClass("lines-num-old") || parent.hasClass("lines-code-old") + ? "focus-lines-old" + : "focus-lines-new" ); }) - .on('mouseleave', function () { - $(this) - .closest('tr') - .removeClass('focus-lines-new focus-lines-old'); + .on("mouseleave", function () { + $(this).closest("tr").removeClass("focus-lines-new focus-lines-old"); }); - $('.add-code-comment').on('click', function (e) { + $(".add-code-comment").on("click", function (e) { // https://github.com/go-gitea/gitea/issues/4745 - if ($(e.target).hasClass('btn-add-single')) { + if ($(e.target).hasClass("btn-add-single")) { return; } e.preventDefault(); - const isSplit = $(this) - .closest('.code-diff') - .hasClass('code-diff-split'); - const side = $(this).data('side'); - const idx = $(this).data('idx'); - const path = $(this).data('path'); - const form = $('#pull_review_add_comment').html(); - const tr = $(this).closest('tr'); + const isSplit = $(this).closest(".code-diff").hasClass("code-diff-split"); + const side = $(this).data("side"); + const idx = $(this).data("idx"); + const path = $(this).data("path"); + const form = $("#pull_review_add_comment").html(); + const tr = $(this).closest("tr"); let ntr = tr.next(); - if (!ntr.hasClass('add-comment')) { + if (!ntr.hasClass("add-comment")) { ntr = $( `${ - isSplit ? - '' : - '' + isSplit + ? '' + : '' }` ); tr.after(ntr); } const td = ntr.find(`.add-comment-${side}`); - let commentCloud = td.find('.comment-code-cloud'); + let commentCloud = td.find(".comment-code-cloud"); if (commentCloud.length === 0) { td.html(form); - commentCloud = td.find('.comment-code-cloud'); - assingMenuAttributes(commentCloud.find('.menu')); + commentCloud = td.find(".comment-code-cloud"); + assingMenuAttributes(commentCloud.find(".menu")); td.find("input[name='line']").val(idx); td.find("input[name='side']").val( - side === 'left' ? 'previous' : 'proposed' + side === "left" ? "previous" : "proposed" ); td.find("input[name='path']").val(path); } - commentCloud.find('textarea').focus(); + commentCloud.find("textarea").focus(); }); } function assingMenuAttributes(menu) { const id = Math.floor(Math.random() * Math.floor(1000000)); - menu.attr('data-write', menu.attr('data-write') + id); - menu.attr('data-preview', menu.attr('data-preview') + id); - menu.find('.item').each(function () { - const tab = $(this).attr('data-tab') + id; - $(this).attr('data-tab', tab); + menu.attr("data-write", menu.attr("data-write") + id); + menu.attr("data-preview", menu.attr("data-preview") + id); + menu.find(".item").each(function () { + const tab = $(this).attr("data-tab") + id; + $(this).attr("data-tab", tab); }); - menu - .parent() - .find("*[data-tab='write']") - .attr('data-tab', `write${id}`); - menu - .parent() - .find("*[data-tab='preview']") - .attr('data-tab', `preview${id}`); - initCommentPreviewTab(menu.parent('.form')); + menu.parent().find("*[data-tab='write']").attr("data-tab", `write${id}`); + menu.parent().find("*[data-tab='preview']").attr("data-tab", `preview${id}`); + initCommentPreviewTab(menu.parent(".form")); return id; } function initRepositoryCollaboration() { // Change collaborator access mode - $('.access-mode.menu .item').on('click', function () { + $(".access-mode.menu .item").on("click", function () { const $menu = $(this).parent(); - $.post($menu.data('url'), { + $.post($menu.data("url"), { _csrf: csrf, - uid: $menu.data('uid'), - mode: $(this).data('value') + uid: $menu.data("uid"), + mode: $(this).data("value"), }); }); } function initTeamSettings() { // Change team access mode - $('.organization.new.team input[name=permission]').on('change', () => { + $(".organization.new.team input[name=permission]").on("change", () => { const val = $( - 'input[name=permission]:checked', - '.organization.new.team' + "input[name=permission]:checked", + ".organization.new.team" ).val(); - if (val === 'admin') { - $('.organization.new.team .team-units').hide(); + if (val === "admin") { + $(".organization.new.team .team-units").hide(); } else { - $('.organization.new.team .team-units').show(); + $(".organization.new.team .team-units").show(); } }); } function initWikiForm() { - const $editArea = $('.repository.wiki textarea#edit_area'); + const $editArea = $(".repository.wiki textarea#edit_area"); let sideBySideChanges = 0; let sideBySideTimeout = null; if ($editArea.length > 0) { @@ -1668,17 +1610,17 @@ function initWikiForm() { sideBySideTimeout = null; } $.post( - $editArea.data('url'), + $editArea.data("url"), { _csrf: csrf, - mode: 'gfm', - context: $editArea.data('context'), - text: plainText + mode: "gfm", + context: $editArea.data("context"), + text: plainText, }, (data) => { preview.innerHTML = `
${data}
`; $(preview) - .find('pre code') + .find("pre code") .each((_, e) => { highlight(e); }); @@ -1702,29 +1644,29 @@ function initWikiForm() { } }, 0); if (!simplemde.isSideBySideActive()) { - return 'Loading...'; + return "Loading..."; } return preview.innerHTML; }, renderingConfig: { - singleLineBreaks: false + singleLineBreaks: false, }, indentWithTabs: false, tabSize: 4, spellChecker: false, toolbar: [ - 'bold', - 'italic', - 'strikethrough', - '|', - 'heading-1', - 'heading-2', - 'heading-3', - 'heading-bigger', - 'heading-smaller', - '|', + "bold", + "italic", + "strikethrough", + "|", + "heading-1", + "heading-2", + "heading-3", + "heading-bigger", + "heading-smaller", + "|", { - name: 'code-inline', + name: "code-inline", action(e) { const cm = e.codemirror; const selection = cm.getSelection(); @@ -1735,96 +1677,96 @@ function initWikiForm() { } cm.focus(); }, - className: 'fa fa-angle-right', - title: 'Add Inline Code' + className: "fa fa-angle-right", + title: "Add Inline Code", }, - 'code', - 'quote', - '|', + "code", + "quote", + "|", { - name: 'checkbox-empty', + name: "checkbox-empty", action(e) { const cm = e.codemirror; cm.replaceSelection(`\n- [ ] ${cm.getSelection()}`); cm.focus(); }, - className: 'fa fa-square-o', - title: 'Add Checkbox (empty)' + className: "fa fa-square-o", + title: "Add Checkbox (empty)", }, { - name: 'checkbox-checked', + name: "checkbox-checked", action(e) { const cm = e.codemirror; cm.replaceSelection(`\n- [x] ${cm.getSelection()}`); cm.focus(); }, - className: 'fa fa-check-square-o', - title: 'Add Checkbox (checked)' + className: "fa fa-check-square-o", + title: "Add Checkbox (checked)", }, - '|', - 'unordered-list', - 'ordered-list', - '|', - 'link', - 'image', - 'table', - 'horizontal-rule', - '|', - 'clean-block', - 'preview', - 'fullscreen', - 'side-by-side', - '|', + "|", + "unordered-list", + "ordered-list", + "|", + "link", + "image", + "table", + "horizontal-rule", + "|", + "clean-block", + "preview", + "fullscreen", + "side-by-side", + "|", { - name: 'revert-to-textarea', + name: "revert-to-textarea", action(e) { e.toTextArea(); }, - className: 'fa fa-file', - title: 'Revert to simple textarea' - } - ] + className: "fa fa-file", + title: "Revert to simple textarea", + }, + ], }); - $(simplemde.codemirror.getInputField()).addClass('js-quick-submit'); + $(simplemde.codemirror.getInputField()).addClass("js-quick-submit"); setTimeout(() => { const $bEdit = $('.repository.wiki.new .previewtabs a[data-tab="write"]'); const $bPrev = $( '.repository.wiki.new .previewtabs a[data-tab="preview"]' ); - const $toolbar = $('.editor-toolbar'); - const $bPreview = $('.editor-toolbar a.fa-eye'); - const $bSideBySide = $('.editor-toolbar a.fa-columns'); - $bEdit.on('click', () => { - if ($toolbar.hasClass('disabled-for-preview')) { - $bPreview.trigger('click'); + const $toolbar = $(".editor-toolbar"); + const $bPreview = $(".editor-toolbar a.fa-eye"); + const $bSideBySide = $(".editor-toolbar a.fa-columns"); + $bEdit.on("click", () => { + if ($toolbar.hasClass("disabled-for-preview")) { + $bPreview.trigger("click"); } }); - $bPrev.on('click', () => { - if (!$toolbar.hasClass('disabled-for-preview')) { - $bPreview.trigger('click'); + $bPrev.on("click", () => { + if (!$toolbar.hasClass("disabled-for-preview")) { + $bPreview.trigger("click"); } }); - $bPreview.on('click', () => { + $bPreview.on("click", () => { setTimeout(() => { - if ($toolbar.hasClass('disabled-for-preview')) { - if ($bEdit.hasClass('active')) { - $bEdit.removeClass('active'); + if ($toolbar.hasClass("disabled-for-preview")) { + if ($bEdit.hasClass("active")) { + $bEdit.removeClass("active"); } - if (!$bPrev.hasClass('active')) { - $bPrev.addClass('active'); + if (!$bPrev.hasClass("active")) { + $bPrev.addClass("active"); } } else { - if (!$bEdit.hasClass('active')) { - $bEdit.addClass('active'); + if (!$bEdit.hasClass("active")) { + $bEdit.addClass("active"); } - if ($bPrev.hasClass('active')) { - $bPrev.removeClass('active'); + if ($bPrev.hasClass("active")) { + $bPrev.removeClass("active"); } } }, 0); }); - $bSideBySide.on('click', () => { + $bSideBySide.on("click", () => { sideBySideChanges = 10; }); }, 0); @@ -1835,13 +1777,13 @@ function initWikiForm() { $.fn.getCursorPosition = function () { const el = $(this).get(0); let pos = 0; - if ('selectionStart' in el) { + if ("selectionStart" in el) { pos = el.selectionStart; - } else if ('selection' in document) { + } else if ("selection" in document) { el.focus(); const Sel = document.selection.createRange(); const SelLength = document.selection.createRange().text.length; - Sel.moveStart('character', -el.value.length); + Sel.moveStart("character", -el.value.length); pos = Sel.text.length - SelLength; } return pos; @@ -1853,47 +1795,47 @@ function setCommentSimpleMDE($editArea) { element: $editArea[0], forceSync: true, renderingConfig: { - singleLineBreaks: false + singleLineBreaks: false, }, indentWithTabs: false, tabSize: 4, spellChecker: false, toolbar: [ - 'bold', - 'italic', - 'strikethrough', - '|', - 'heading-1', - 'heading-2', - 'heading-3', - 'heading-bigger', - 'heading-smaller', - '|', - 'code', - 'quote', - '|', - 'unordered-list', - 'ordered-list', - '|', - 'link', - 'image', - 'table', - 'horizontal-rule', - '|', - 'clean-block', - '|', + "bold", + "italic", + "strikethrough", + "|", + "heading-1", + "heading-2", + "heading-3", + "heading-bigger", + "heading-smaller", + "|", + "code", + "quote", + "|", + "unordered-list", + "ordered-list", + "|", + "link", + "image", + "table", + "horizontal-rule", + "|", + "clean-block", + "|", { - name: 'revert-to-textarea', + name: "revert-to-textarea", action(e) { e.toTextArea(); }, - className: 'fa fa-file', - title: 'Revert to simple textarea' - } - ] + className: "fa fa-file", + title: "Revert to simple textarea", + }, + ], }); - $(simplemde.codemirror.getInputField()).addClass('js-quick-submit'); - simplemde.codemirror.setOption('extraKeys', { + $(simplemde.codemirror.getInputField()).addClass("js-quick-submit"); + simplemde.codemirror.setOption("extraKeys", { Enter: () => { if (!(issuesTribute.isActive || emojiTribute.isActive)) { return CodeMirror.Pass; @@ -1901,10 +1843,10 @@ function setCommentSimpleMDE($editArea) { }, Backspace: (cm) => { if (cm.getInputField().trigger) { - cm.getInputField().trigger('input'); + cm.getInputField().trigger("input"); } - cm.execCommand('delCharBefore'); - } + cm.execCommand("delCharBefore"); + }, }); issuesTribute.attach(simplemde.codemirror.getInputField()); emojiTribute.attach(simplemde.codemirror.getInputField()); @@ -1912,32 +1854,29 @@ function setCommentSimpleMDE($editArea) { } async function initEditor() { - $('.js-quick-pull-choice-option').on('change', function () { - if ($(this).val() === 'commit-to-new-branch') { - $('.quick-pull-branch-name').show(); - $('.quick-pull-branch-name input').prop('required', true); + $(".js-quick-pull-choice-option").on("change", function () { + if ($(this).val() === "commit-to-new-branch") { + $(".quick-pull-branch-name").show(); + $(".quick-pull-branch-name input").prop("required", true); } else { - $('.quick-pull-branch-name').hide(); - $('.quick-pull-branch-name input').prop('required', false); + $(".quick-pull-branch-name").hide(); + $(".quick-pull-branch-name input").prop("required", false); } - $('#commit-button').text($(this).attr('button_text')); + $("#commit-button").text($(this).attr("button_text")); }); - const $editFilename = $('#file-name'); + const $editFilename = $("#file-name"); $editFilename - .on('keyup', function (e) { - const $section = $('.breadcrumb span.section'); - const $divider = $('.breadcrumb div.divider'); + .on("keyup", function (e) { + const $section = $(".breadcrumb span.section"); + const $divider = $(".breadcrumb div.divider"); let value; let parts; if (e.keyCode === 8) { if ($(this).getCursorPosition() === 0) { if ($section.length > 0) { - value = $section - .last() - .find('a') - .text(); + value = $section.last().find("a").text(); $(this).val(value + $(this).val()); $(this)[0].setSelectionRange(value.length, value.length); $section.last().remove(); @@ -1946,9 +1885,7 @@ async function initEditor() { } } if (e.keyCode === 191) { - parts = $(this) - .val() - .split('/'); + parts = $(this).val().split("/"); for (let i = 0; i < parts.length; ++i) { value = parts[i]; if (i < parts.length - 1) { @@ -1965,77 +1902,71 @@ async function initEditor() { } } parts = []; - $('.breadcrumb span.section').each(function () { + $(".breadcrumb span.section").each(function () { const element = $(this); - if (element.find('a').length) { - parts.push(element.find('a').text()); + if (element.find("a").length) { + parts.push(element.find("a").text()); } else { parts.push(element.text()); } }); if ($(this).val()) parts.push($(this).val()); - $('#tree_path').val(parts.join('/')); + $("#tree_path").val(parts.join("/")); }) - .trigger('keyup'); + .trigger("keyup"); - const $editArea = $('.repository.editor textarea#edit_area'); + const $editArea = $(".repository.editor textarea#edit_area"); if (!$editArea.length) return; await createCodeEditor($editArea[0], $editFilename[0], previewFileModes); // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage // to enable or disable the commit button - const $commitButton = $('#commit-button'); - const $editForm = $('.ui.edit.form'); - const dirtyFileClass = 'dirty-file'; + const $commitButton = $("#commit-button"); + const $editForm = $(".ui.edit.form"); + const dirtyFileClass = "dirty-file"; // Disabling the button at the start - $commitButton.prop('disabled', true); + $commitButton.prop("disabled", true); // Registering a custom listener for the file path and the file content $editForm.areYouSure({ silent: true, dirtyClass: dirtyFileClass, - fieldSelector: ':input:not(.commit-form-wrapper :input)', + fieldSelector: ":input:not(.commit-form-wrapper :input)", change() { const dirty = $(this).hasClass(dirtyFileClass); - $commitButton.prop('disabled', !dirty); - } + $commitButton.prop("disabled", !dirty); + }, }); - $commitButton.on('click', (event) => { + $commitButton.on("click", (event) => { // A modal which asks if an empty file should be committed if ($editArea.val().length === 0) { - $('#edit-empty-content-modal') + $("#edit-empty-content-modal") .modal({ onApprove() { - $('.edit.form').trigger('submit'); - } + $(".edit.form").trigger("submit"); + }, }) - .modal('show'); + .modal("show"); event.preventDefault(); } }); } function initOrganization() { - if ($('.organization').length === 0) { + if ($(".organization").length === 0) { return; } // Options - if ($('.organization.settings.options').length > 0) { - $('#org_name').on('keyup', function () { - const $prompt = $('#org-name-change-prompt'); + if ($(".organization.settings.options").length > 0) { + $("#org_name").on("keyup", function () { + const $prompt = $("#org-name-change-prompt"); if ( - $(this) - .val() - .toString() - .toLowerCase() !== - $(this) - .data('org-name') - .toString() - .toLowerCase() + $(this).val().toString().toLowerCase() !== + $(this).data("org-name").toString().toLowerCase() ) { $prompt.show(); } else { @@ -2045,25 +1976,19 @@ function initOrganization() { } // Labels - if ($('.organization.settings.labels').length > 0) { + if ($(".organization.settings.labels").length > 0) { initLabelEdit(); } } function initUserSettings() { // Options - if ($('.user.settings.profile').length > 0) { - $('#username').on('keyup', function () { - const $prompt = $('#name-change-prompt'); + if ($(".user.settings.profile").length > 0) { + $("#username").on("keyup", function () { + const $prompt = $("#name-change-prompt"); if ( - $(this) - .val() - .toString() - .toLowerCase() !== - $(this) - .data('name') - .toString() - .toLowerCase() + $(this).val().toString().toLowerCase() !== + $(this).data("name").toString().toLowerCase() ) { $prompt.show(); } else { @@ -2074,307 +1999,294 @@ function initUserSettings() { } function initGithook() { - if ($('.edit.githook').length === 0) { + if ($(".edit.githook").length === 0) { return; } CodeMirror.autoLoadMode( - CodeMirror.fromTextArea($('#content')[0], { + CodeMirror.fromTextArea($("#content")[0], { lineNumbers: true, - mode: 'shell' + mode: "shell", }), - 'shell' + "shell" ); } function initWebhook() { - if ($('.new.webhook').length === 0) { + if ($(".new.webhook").length === 0) { return; } - $('.events.checkbox input').on('change', function () { - if ($(this).is(':checked')) { - $('.events.fields').show(); + $(".events.checkbox input").on("change", function () { + if ($(this).is(":checked")) { + $(".events.fields").show(); } }); - $('.non-events.checkbox input').on('change', function () { - if ($(this).is(':checked')) { - $('.events.fields').hide(); + $(".non-events.checkbox input").on("change", function () { + if ($(this).is(":checked")) { + $(".events.fields").hide(); } }); const updateContentType = function () { - const visible = $('#http_method').val() === 'POST'; - $('#content_type') - .parent() - .parent() - [visible ? 'show' : 'hide'](); + const visible = $("#http_method").val() === "POST"; + $("#content_type").parent().parent()[visible ? "show" : "hide"](); }; updateContentType(); - $('#http_method').on('change', () => { + $("#http_method").on("change", () => { updateContentType(); }); // Test delivery - $('#test-delivery').on('click', function () { + $("#test-delivery").on("click", function () { const $this = $(this); - $this.addClass('loading disabled'); - $.post($this.data('link'), { - _csrf: csrf + $this.addClass("loading disabled"); + $.post($this.data("link"), { + _csrf: csrf, }).done( setTimeout(() => { - window.location.href = $this.data('redirect'); + window.location.href = $this.data("redirect"); }, 5000) ); }); } function initAdmin() { - if ($('.admin').length === 0) { + if ($(".admin").length === 0) { return; } // New user - if ($('.admin.new.user').length > 0 || $('.admin.edit.user').length > 0) { - $('#login_type').on('change', function () { - if ( - $(this) - .val() - .substring(0, 1) === '0' - ) { - $('#login_name').removeAttr('required'); - $('.non-local').hide(); - $('.local').show(); - $('#user_name').focus(); - - if ($(this).data('password') === 'required') { - $('#password').attr('required', 'required'); + if ($(".admin.new.user").length > 0 || $(".admin.edit.user").length > 0) { + $("#login_type").on("change", function () { + if ($(this).val().substring(0, 1) === "0") { + $("#login_name").removeAttr("required"); + $(".non-local").hide(); + $(".local").show(); + $("#user_name").focus(); + + if ($(this).data("password") === "required") { + $("#password").attr("required", "required"); } } else { - $('#login_name').attr('required', 'required'); - $('.non-local').show(); - $('.local').hide(); - $('#login_name').focus(); + $("#login_name").attr("required", "required"); + $(".non-local").show(); + $(".local").hide(); + $("#login_name").focus(); - $('#password').removeAttr('required'); + $("#password").removeAttr("required"); } }); } function onSecurityProtocolChange() { - if ($('#security_protocol').val() > 0) { - $('.has-tls').show(); + if ($("#security_protocol").val() > 0) { + $(".has-tls").show(); } else { - $('.has-tls').hide(); + $(".has-tls").hide(); } } function onUsePagedSearchChange() { - if ($('#use_paged_search').prop('checked')) { - $('.search-page-size') - .show() - .find('input') - .attr('required', 'required'); + if ($("#use_paged_search").prop("checked")) { + $(".search-page-size").show().find("input").attr("required", "required"); } else { - $('.search-page-size') - .hide() - .find('input') - .removeAttr('required'); + $(".search-page-size").hide().find("input").removeAttr("required"); } } function onOAuth2Change() { - $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide(); - $('.open_id_connect_auto_discovery_url input[required]').removeAttr( - 'required' + $(".open_id_connect_auto_discovery_url, .oauth2_use_custom_url").hide(); + $(".open_id_connect_auto_discovery_url input[required]").removeAttr( + "required" ); - const provider = $('#oauth2_provider').val(); + const provider = $("#oauth2_provider").val(); switch (provider) { - case 'github': - case 'gitlab': - case 'gitea': - case 'nextcloud': - $('.oauth2_use_custom_url').show(); + case "github": + case "gitlab": + case "gitea": + case "nextcloud": + $(".oauth2_use_custom_url").show(); break; - case 'openidConnect': - $('.open_id_connect_auto_discovery_url input').attr( - 'required', - 'required' + case "openidConnect": + $(".open_id_connect_auto_discovery_url input").attr( + "required", + "required" ); - $('.open_id_connect_auto_discovery_url').show(); + $(".open_id_connect_auto_discovery_url").show(); break; } onOAuth2UseCustomURLChange(); } function onOAuth2UseCustomURLChange() { - const provider = $('#oauth2_provider').val(); - $('.oauth2_use_custom_url_field').hide(); - $('.oauth2_use_custom_url_field input[required]').removeAttr('required'); + const provider = $("#oauth2_provider").val(); + $(".oauth2_use_custom_url_field").hide(); + $(".oauth2_use_custom_url_field input[required]").removeAttr("required"); - if ($('#oauth2_use_custom_url').is(':checked')) { - $('#oauth2_token_url').val($(`#${provider}_token_url`).val()); - $('#oauth2_auth_url').val($(`#${provider}_auth_url`).val()); - $('#oauth2_profile_url').val($(`#${provider}_profile_url`).val()); - $('#oauth2_email_url').val($(`#${provider}_email_url`).val()); + if ($("#oauth2_use_custom_url").is(":checked")) { + $("#oauth2_token_url").val($(`#${provider}_token_url`).val()); + $("#oauth2_auth_url").val($(`#${provider}_auth_url`).val()); + $("#oauth2_profile_url").val($(`#${provider}_profile_url`).val()); + $("#oauth2_email_url").val($(`#${provider}_email_url`).val()); switch (provider) { - case 'github': + case "github": $( - '.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input' - ).attr('required', 'required'); + ".oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input" + ).attr("required", "required"); $( - '.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url' + ".oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url" ).show(); break; - case 'nextcloud': - case 'gitea': - case 'gitlab': + case "nextcloud": + case "gitea": + case "gitlab": $( - '.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input' - ).attr('required', 'required'); - $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show(); - $('#oauth2_email_url').val(''); + ".oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input" + ).attr("required", "required"); + $(".oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url").show(); + $("#oauth2_email_url").val(""); break; } } } // New authentication - if ($('.admin.new.authentication').length > 0) { - $('#auth_type').on('change', function () { + if ($(".admin.new.authentication").length > 0) { + $("#auth_type").on("change", function () { $( - '.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls, .search-page-size, .sspi' + ".ldap, .dldap, .smtp, .pam, .oauth2, .has-tls, .search-page-size, .sspi" ).hide(); $( - '.ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required], .sspi input[required]' - ).removeAttr('required'); - $('.binddnrequired').removeClass('required'); + ".ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required], .sspi input[required]" + ).removeAttr("required"); + $(".binddnrequired").removeClass("required"); const authType = $(this).val(); switch (authType) { - case '2': // LDAP - $('.ldap').show(); - $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr( - 'required', - 'required' + case "2": // LDAP + $(".ldap").show(); + $(".binddnrequired input, .ldap div.required:not(.dldap) input").attr( + "required", + "required" ); - $('.binddnrequired').addClass('required'); + $(".binddnrequired").addClass("required"); break; - case '3': // SMTP - $('.smtp').show(); - $('.has-tls').show(); - $('.smtp div.required input, .has-tls').attr('required', 'required'); + case "3": // SMTP + $(".smtp").show(); + $(".has-tls").show(); + $(".smtp div.required input, .has-tls").attr("required", "required"); break; - case '4': // PAM - $('.pam').show(); - $('.pam input').attr('required', 'required'); + case "4": // PAM + $(".pam").show(); + $(".pam input").attr("required", "required"); break; - case '5': // LDAP - $('.dldap').show(); - $('.dldap div.required:not(.ldap) input').attr( - 'required', - 'required' + case "5": // LDAP + $(".dldap").show(); + $(".dldap div.required:not(.ldap) input").attr( + "required", + "required" ); break; - case '6': // OAuth2 - $('.oauth2').show(); + case "6": // OAuth2 + $(".oauth2").show(); $( - '.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input' - ).attr('required', 'required'); + ".oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input" + ).attr("required", "required"); onOAuth2Change(); break; - case '7': // SSPI - $('.sspi').show(); - $('.sspi div.required input').attr('required', 'required'); + case "7": // SSPI + $(".sspi").show(); + $(".sspi div.required input").attr("required", "required"); break; } - if (authType === '2' || authType === '5') { + if (authType === "2" || authType === "5") { onSecurityProtocolChange(); } - if (authType === '2') { + if (authType === "2") { onUsePagedSearchChange(); } }); - $('#auth_type').trigger('change'); - $('#security_protocol').on('change', onSecurityProtocolChange); - $('#use_paged_search').on('change', onUsePagedSearchChange); - $('#oauth2_provider').on('change', onOAuth2Change); - $('#oauth2_use_custom_url').on('change', onOAuth2UseCustomURLChange); + $("#auth_type").trigger("change"); + $("#security_protocol").on("change", onSecurityProtocolChange); + $("#use_paged_search").on("change", onUsePagedSearchChange); + $("#oauth2_provider").on("change", onOAuth2Change); + $("#oauth2_use_custom_url").on("change", onOAuth2UseCustomURLChange); } // Edit authentication - if ($('.admin.edit.authentication').length > 0) { - const authType = $('#auth_type').val(); - if (authType === '2' || authType === '5') { - $('#security_protocol').on('change', onSecurityProtocolChange); - if (authType === '2') { - $('#use_paged_search').on('change', onUsePagedSearchChange); + if ($(".admin.edit.authentication").length > 0) { + const authType = $("#auth_type").val(); + if (authType === "2" || authType === "5") { + $("#security_protocol").on("change", onSecurityProtocolChange); + if (authType === "2") { + $("#use_paged_search").on("change", onUsePagedSearchChange); } - } else if (authType === '6') { - $('#oauth2_provider').on('change', onOAuth2Change); - $('#oauth2_use_custom_url').on('change', onOAuth2UseCustomURLChange); + } else if (authType === "6") { + $("#oauth2_provider").on("change", onOAuth2Change); + $("#oauth2_use_custom_url").on("change", onOAuth2UseCustomURLChange); onOAuth2Change(); } } // Notice - if ($('.admin.notice')) { - const $detailModal = $('#detail-modal'); + if ($(".admin.notice")) { + const $detailModal = $("#detail-modal"); // Attach view detail modals - $('.view-detail').on('click', function () { - $detailModal.find('.content pre').text($(this).data('content')); - $detailModal.modal('show'); + $(".view-detail").on("click", function () { + $detailModal.find(".content pre").text($(this).data("content")); + $detailModal.modal("show"); return false; }); // Select actions - const $checkboxes = $('.select.table .ui.checkbox'); - $('.select.action').on('click', function () { - switch ($(this).data('action')) { - case 'select-all': - $checkboxes.checkbox('check'); + const $checkboxes = $(".select.table .ui.checkbox"); + $(".select.action").on("click", function () { + switch ($(this).data("action")) { + case "select-all": + $checkboxes.checkbox("check"); break; - case 'deselect-all': - $checkboxes.checkbox('uncheck'); + case "deselect-all": + $checkboxes.checkbox("uncheck"); break; - case 'inverse': - $checkboxes.checkbox('toggle'); + case "inverse": + $checkboxes.checkbox("toggle"); break; } }); - $('#delete-selection').on('click', function () { + $("#delete-selection").on("click", function () { const $this = $(this); - $this.addClass('loading disabled'); + $this.addClass("loading disabled"); const ids = []; $checkboxes.each(function () { - if ($(this).checkbox('is checked')) { - ids.push($(this).data('id')); + if ($(this).checkbox("is checked")) { + ids.push($(this).data("id")); } }); - $.post($this.data('link'), { + $.post($this.data("link"), { _csrf: csrf, - ids + ids, }).done(() => { - window.location.href = $this.data('redirect'); + window.location.href = $this.data("redirect"); }); }); } } function buttonsClickOnEnter() { - $('.ui.button').on('keypress', function (e) { + $(".ui.button").on("keypress", function (e) { if (e.keyCode === 13 || e.keyCode === 32) { // enter key or space bar - $(this).trigger('click'); + $(this).trigger("click"); } }); } function searchUsers() { - const $searchUserBox = $('#search-user-box'); + const $searchUserBox = $("#search-user-box"); $searchUserBox.search({ minCharacters: 2, apiSettings: { @@ -2388,135 +2300,135 @@ function searchUsers() { } items.push({ title, - image: item.avatar_url + image: item.avatar_url, }); }); return { results: items }; - } + }, }, - searchFields: ['login', 'full_name'], - showNoResults: false + searchFields: ["login", "full_name"], + showNoResults: false, }); } function searchTeams() { - const $searchTeamBox = $('#search-team-box'); + const $searchTeamBox = $("#search-team-box"); $searchTeamBox.search({ minCharacters: 2, apiSettings: { url: `${AppSubUrl}/api/v1/orgs/${$searchTeamBox.data( - 'org' + "org" )}/teams/search?q={query}`, - headers: { 'X-Csrf-Token': csrf }, + headers: { "X-Csrf-Token": csrf }, onResponse(response) { const items = []; $.each(response.data, (_i, item) => { const title = `${item.name} (${item.permission} access)`; items.push({ - title + title, }); }); return { results: items }; - } + }, }, - searchFields: ['name', 'description'], - showNoResults: false + searchFields: ["name", "description"], + showNoResults: false, }); } function searchRepositories() { - const $searchRepoBox = $('#search-repo-box'); + const $searchRepoBox = $("#search-repo-box"); $searchRepoBox.search({ minCharacters: 2, apiSettings: { url: `${AppSubUrl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data( - 'uid' + "uid" )}`, onResponse(response) { const items = []; $.each(response.data, (_i, item) => { items.push({ - title: item.full_display_name.split('/')[1], - description: item.full_display_name + title: item.full_display_name.split("/")[1], + description: item.full_display_name, }); }); return { results: items }; - } + }, }, - searchFields: ['full_name'], - showNoResults: false + searchFields: ["full_name"], + showNoResults: false, }); } function initCodeView() { - if ($('.code-view .linenums').length > 0) { - $(document).on('click', '.lines-num span', function (e) { + if ($(".code-view .linenums").length > 0) { + $(document).on("click", ".lines-num span", function (e) { const $select = $(this); const $list = $select .parent() - .siblings('.lines-code') - .find('ol.linenums > li'); + .siblings(".lines-code") + .find("ol.linenums > li"); selectRange( $list, - $list.filter(`[rel=${$select.attr('id')}]`), - e.shiftKey ? $list.filter('.active').eq(0) : null + $list.filter(`[rel=${$select.attr("id")}]`), + e.shiftKey ? $list.filter(".active").eq(0) : null ); deSelect(); }); $(window) - .on('hashchange', () => { + .on("hashchange", () => { let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/); - const $list = $('.code-view ol.linenums > li'); + const $list = $(".code-view ol.linenums > li"); let $first; if (m) { $first = $list.filter(`.${m[1]}`); selectRange($list, $first, $list.filter(`.${m[2]}`)); - $('html, body').scrollTop($first.offset().top - 200); + $("html, body").scrollTop($first.offset().top - 200); return; } m = window.location.hash.match(/^#(L|n)(\d+)$/); if (m) { $first = $list.filter(`.L${m[2]}`); selectRange($list, $first); - $('html, body').scrollTop($first.offset().top - 200); + $("html, body").scrollTop($first.offset().top - 200); } }) - .trigger('hashchange'); + .trigger("hashchange"); } - $('.fold-code').on('click', ({ target }) => { - const box = target.closest('.file-content'); - const folded = box.dataset.folded !== 'true'; - target.classList.add(`fa-chevron-${folded ? 'right' : 'down'}`); - target.classList.remove(`fa-chevron-${folded ? 'down' : 'right'}`); + $(".fold-code").on("click", ({ target }) => { + const box = target.closest(".file-content"); + const folded = box.dataset.folded !== "true"; + target.classList.add(`fa-chevron-${folded ? "right" : "down"}`); + target.classList.remove(`fa-chevron-${folded ? "down" : "right"}`); box.dataset.folded = String(folded); }); function insertBlobExcerpt(e) { const $blob = $(e.target); const $row = $blob.parent().parent(); $.get( - `${$blob.data('url')}?${$blob.data('query')}&anchor=${$blob.data( - 'anchor' + `${$blob.data("url")}?${$blob.data("query")}&anchor=${$blob.data( + "anchor" )}`, (blob) => { $row.replaceWith(blob); - $(`[data-anchor="${$blob.data('anchor')}"]`).on('click', (e) => { + $(`[data-anchor="${$blob.data("anchor")}"]`).on("click", (e) => { insertBlobExcerpt(e); }); - $('.diff-detail-box.ui.sticky').sticky(); + $(".diff-detail-box.ui.sticky").sticky(); } ); } - $('.ui.blob-excerpt').on('click', (e) => { + $(".ui.blob-excerpt").on("click", (e) => { insertBlobExcerpt(e); }); } function initU2FAuth() { - if ($('#wait-for-key').length === 0) { + if ($("#wait-for-key").length === 0) { return; } u2fApi @@ -2543,10 +2455,10 @@ function initU2FAuth() { function u2fSigned(resp) { $.ajax({ url: `${AppSubUrl}/user/u2f/sign`, - type: 'POST', - headers: { 'X-Csrf-Token': csrf }, + type: "POST", + headers: { "X-Csrf-Token": csrf }, data: JSON.stringify(resp), - contentType: 'application/json; charset=utf-8' + contentType: "application/json; charset=utf-8", }) .done((res) => { window.location.replace(res); @@ -2562,21 +2474,21 @@ function u2fRegistered(resp) { } $.ajax({ url: `${AppSubUrl}/user/settings/security/u2f/register`, - type: 'POST', - headers: { 'X-Csrf-Token': csrf }, + type: "POST", + headers: { "X-Csrf-Token": csrf }, data: JSON.stringify(resp), - contentType: 'application/json; charset=utf-8', + contentType: "application/json; charset=utf-8", success() { reload(); }, fail() { u2fError(1); - } + }, }); } function checkError(resp) { - if (!('errorCode' in resp)) { + if (!("errorCode" in resp)) { return false; } if (resp.errorCode === 0) { @@ -2588,33 +2500,33 @@ function checkError(resp) { function u2fError(errorType) { const u2fErrors = { - browser: $('#unsupported-browser'), - 1: $('#u2f-error-1'), - 2: $('#u2f-error-2'), - 3: $('#u2f-error-3'), - 4: $('#u2f-error-4'), - 5: $('.u2f-error-5') + browser: $("#unsupported-browser"), + 1: $("#u2f-error-1"), + 2: $("#u2f-error-2"), + 3: $("#u2f-error-3"), + 4: $("#u2f-error-4"), + 5: $(".u2f-error-5"), }; - u2fErrors[errorType].removeClass('hide'); + u2fErrors[errorType].removeClass("hide"); Object.keys(u2fErrors).forEach((type) => { if (type !== errorType) { - u2fErrors[type].addClass('hide'); + u2fErrors[type].addClass("hide"); } }); - $('#u2f-error').modal('show'); + $("#u2f-error").modal("show"); } function initU2FRegister() { - $('#register-device').modal({ allowMultiple: false }); - $('#u2f-error').modal({ allowMultiple: false }); - $('#register-security-key').on('click', (e) => { + $("#register-device").modal({ allowMultiple: false }); + $("#u2f-error").modal({ allowMultiple: false }); + $("#register-security-key").on("click", (e) => { e.preventDefault(); u2fApi .ensureSupport() .then(u2fRegisterRequest) .catch(() => { - u2fError('browser'); + u2fError("browser"); }); }); } @@ -2622,13 +2534,11 @@ function initU2FRegister() { function u2fRegisterRequest() { $.post(`${AppSubUrl}/user/settings/security/u2f/request_register`, { _csrf: csrf, - name: $('#nickname').val() + name: $("#nickname").val(), }) .done((req) => { - $('#nickname') - .closest('div.field') - .removeClass('error'); - $('#register-device').modal('show'); + $("#nickname").closest("div.field").removeClass("error"); + $("#register-device").modal("show"); if (req.registeredKeys === null) { req.registeredKeys = []; } @@ -2645,23 +2555,18 @@ function u2fRegisterRequest() { }) .fail((xhr) => { if (xhr.status === 409) { - $('#nickname') - .closest('div.field') - .addClass('error'); + $("#nickname").closest("div.field").addClass("error"); } }); } function initWipTitle() { - $('.title_wip_desc > a').on('click', (e) => { + $(".title_wip_desc > a").on("click", (e) => { e.preventDefault(); - const $issueTitle = $('#issue_title'); + const $issueTitle = $("#issue_title"); $issueTitle.focus(); - const value = $issueTitle - .val() - .trim() - .toUpperCase(); + const value = $issueTitle.val().trim().toUpperCase(); for (const i in wipPrefixes) { if (value.startsWith(wipPrefixes[i].toUpperCase())) { @@ -2674,11 +2579,11 @@ function initWipTitle() { } function initTemplateSearch() { - const $repoTemplate = $('#repo_template'); + const $repoTemplate = $("#repo_template"); const checkTemplate = function () { - const $templateUnits = $('#template_units'); - const $nonTemplate = $('#non_template'); - if ($repoTemplate.val() !== '' && $repoTemplate.val() !== '0') { + const $templateUnits = $("#template_units"); + const $nonTemplate = $("#non_template"); + if ($repoTemplate.val() !== "" && $repoTemplate.val() !== "0") { $templateUnits.show(); $nonTemplate.hide(); } else { @@ -2686,92 +2591,92 @@ function initTemplateSearch() { $nonTemplate.show(); } }; - $repoTemplate.on('change', checkTemplate); + $repoTemplate.on("change", checkTemplate); checkTemplate(); const changeOwner = function () { - $('#repo_template_search').dropdown({ + $("#repo_template_search").dropdown({ apiSettings: { url: `${AppSubUrl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$( - '#uid' + "#uid" ).val()}`, onResponse(response) { const filteredResponse = { success: true, results: [] }; filteredResponse.results.push({ - name: '', - value: '' + name: "", + value: "", }); // Parse the response from the api to work with our dropdown $.each(response.data, (_r, repo) => { filteredResponse.results.push({ name: htmlEncode(repo.full_display_name), - value: repo.id + value: repo.id, }); }); return filteredResponse; }, - cache: false + cache: false, }, - fullTextSearch: true + fullTextSearch: true, }); }; - $('#uid').on('change', changeOwner); + $("#uid").on("change", changeOwner); changeOwner(); } $(document).ready(async () => { // Show exact time - $('.time-since').each(function () { + $(".time-since").each(function () { $(this) - .addClass('poping up') - .attr('data-content', $(this).attr('title')) - .attr('data-variation', 'inverted tiny') - .attr('title', ''); + .addClass("poping up") + .attr("data-content", $(this).attr("title")) + .attr("data-variation", "inverted tiny") + .attr("title", ""); }); // Semantic UI modules. - $('.dropdown:not(.custom)').dropdown(); - $('.jump.dropdown').dropdown({ - action: 'hide', + $(".dropdown:not(.custom)").dropdown(); + $(".jump.dropdown").dropdown({ + action: "hide", onShow() { - $('.poping.up').popup('hide'); - } + $(".poping.up").popup("hide"); + }, }); - $('.slide.up.dropdown').dropdown({ - transition: 'slide up' + $(".slide.up.dropdown").dropdown({ + transition: "slide up", }); - $('.upward.dropdown').dropdown({ - direction: 'upward' + $(".upward.dropdown").dropdown({ + direction: "upward", }); - $('.ui.accordion').accordion(); - $('.ui.checkbox').checkbox(); - $('.ui.progress').progress({ - showActivity: false + $(".ui.accordion").accordion(); + $(".ui.checkbox").checkbox(); + $(".ui.progress").progress({ + showActivity: false, }); - $('.poping.up').popup(); - $('.top.menu .poping.up').popup({ + $(".poping.up").popup(); + $(".top.menu .poping.up").popup({ onShow() { - if ($('.top.menu .menu.transition').hasClass('visible')) { + if ($(".top.menu .menu.transition").hasClass("visible")) { return false; } - } + }, }); - $('.tabular.menu .item').tab(); - $('.tabable.menu .item').tab(); + $(".tabular.menu .item").tab(); + $(".tabable.menu .item").tab(); - $('.toggle.button').on('click', function () { - $($(this).data('target')).slideToggle(100); + $(".toggle.button").on("click", function () { + $($(this).data("target")).slideToggle(100); }); // make table element clickable like a link - $('tr[data-href]').on('click', function () { - window.location = $(this).data('href'); + $("tr[data-href]").on("click", function () { + window.location = $(this).data("href"); }); // make table element clickable like a link - $('td[data-href]').click(function () { - window.location = $(this).data('href'); + $("td[data-href]").click(function () { + window.location = $(this).data("href"); }); // 在String原型对象上添加format方法 String.prototype.format = function () { @@ -2780,156 +2685,161 @@ $(document).ready(async () => { return str; } else { Object.keys(arguments).forEach((item, index) => { - str = str.replace(/\?/, arguments[item]) - }) - return str + str = str.replace(/\?/, arguments[item]); + }); + return str; } - } + }; // Dropzone - const $dropzone = $('#dropzone'); + const $dropzone = $("#dropzone"); if ($dropzone.length > 0) { const filenameDict = {}; - let maxFileTooltips - let maxSizeTooltips - if ($dropzone.data('max-file-tooltips') && $dropzone.data('max-size-tooltips')) { - maxFileTooltips = $dropzone.data('max-file-tooltips').format($dropzone.data('max-file'), $dropzone.data('max-size')) - maxSizeTooltips = $dropzone.data('max-size-tooltips').format($dropzone.data('max-file')) + let maxFileTooltips; + let maxSizeTooltips; + if ( + $dropzone.data("max-file-tooltips") && + $dropzone.data("max-size-tooltips") + ) { + maxFileTooltips = $dropzone + .data("max-file-tooltips") + .format($dropzone.data("max-file"), $dropzone.data("max-size")); + maxSizeTooltips = $dropzone + .data("max-size-tooltips") + .format($dropzone.data("max-file")); } - await createDropzone('#dropzone', { - url: $dropzone.data('upload-url'), - headers: { 'X-Csrf-Token': csrf }, - maxFiles: $dropzone.data('max-file'), - maxFilesize: $dropzone.data('max-size'), + await createDropzone("#dropzone", { + url: $dropzone.data("upload-url"), + headers: { "X-Csrf-Token": csrf }, + maxFiles: $dropzone.data("max-file"), + maxFilesize: $dropzone.data("max-size"), acceptedFiles: - $dropzone.data('accepts') === '*/*' ? null : $dropzone.data('accepts'), + $dropzone.data("accepts") === "*/*" ? null : $dropzone.data("accepts"), addRemoveLinks: true, - dictDefaultMessage: $dropzone.data('default-message'), - dictInvalidFileType: $dropzone.data('invalid-input-type'), - dictFileTooBig: $dropzone.data('file-too-big'), - dictRemoveFile: $dropzone.data('remove-file'), + dictDefaultMessage: $dropzone.data("default-message"), + dictInvalidFileType: $dropzone.data("invalid-input-type"), + dictFileTooBig: $dropzone.data("file-too-big"), + dictRemoveFile: $dropzone.data("remove-file"), init() { - this.on('success', (file, data) => { + this.on("success", (file, data) => { filenameDict[file.name] = data.uuid; const input = $( `` ).val(data.uuid); - $('.files').append(input); + $(".files").append(input); }); - this.on('removedfile', (file) => { + this.on("removedfile", (file) => { if (file.name in filenameDict) { $(`#${filenameDict[file.name]}`).remove(); } - if ($dropzone.data('remove-url') && $dropzone.data('csrf')) { - $.post($dropzone.data('remove-url'), { + if ($dropzone.data("remove-url") && $dropzone.data("csrf")) { + $.post($dropzone.data("remove-url"), { file: filenameDict[file.name], - _csrf: $dropzone.data('csrf') + _csrf: $dropzone.data("csrf"), }); } }); - this.on('addedfile', (file) => { - if (file.size / (1000 * 1000) > $dropzone.data('max-size')) { - this.removeFile(file) + this.on("addedfile", (file) => { + if (file.size / (1000 * 1000) > $dropzone.data("max-size")) { + this.removeFile(file); if (maxFileTooltips) { - $('.maxfilesize.ui.red.message').text(maxFileTooltips) - $('.maxfilesize.ui.red.message').css('display', 'block') + $(".maxfilesize.ui.red.message").text(maxFileTooltips); + $(".maxfilesize.ui.red.message").css("display", "block"); } } else { if (maxFileTooltips) { - $('.maxfilesize.ui.red.message').css('display', 'none') + $(".maxfilesize.ui.red.message").css("display", "none"); } } - }); - this.on('maxfilesexceeded', (file) => { - this.removeFile(file) + this.on("maxfilesexceeded", (file) => { + this.removeFile(file); if (maxSizeTooltips) { - $('.maxfilesize.ui.red.message').text(maxSizeTooltips) - $('.maxfilesize.ui.red.message').css('display', 'block') + $(".maxfilesize.ui.red.message").text(maxSizeTooltips); + $(".maxfilesize.ui.red.message").css("display", "block"); } - }) - - } + }); + }, }); } // Helpers. - $('.delete-button').on('click', showDeletePopup); - $('.add-all-button').on('click', showAddAllPopup); - $('.link-action').on('click', linkAction); - $('.link-email-action').on('click', linkEmailAction); + $(".delete-button").on("click", showDeletePopup); + $(".add-all-button").on("click", showAddAllPopup); + $(".link-action").on("click", linkAction); + $(".link-email-action").on("click", linkEmailAction); - $('.delete-branch-button').on('click', showDeletePopup); + $(".delete-branch-button").on("click", showDeletePopup); - $('.undo-button').on('click', function () { + $(".undo-button").on("click", function () { const $this = $(this); - $.post($this.data('url'), { + $.post($this.data("url"), { _csrf: csrf, - id: $this.data('id') + id: $this.data("id"), }).done((data) => { window.location.href = data.redirect; }); }); - $('.show-panel.button').on('click', function () { - $($(this).data('panel')).show(); + $(".show-panel.button").on("click", function () { + $($(this).data("panel")).show(); }); - $('.show-modal.button').on('click', function () { - $($(this).data('modal')).modal('show'); + $(".show-modal.button").on("click", function () { + $($(this).data("modal")).modal("show"); }); - $('.delete-post.button').on('click', function () { + $(".delete-post.button").on("click", function () { const $this = $(this); - $.post($this.data('request-url'), { - _csrf: csrf + $.post($this.data("request-url"), { + _csrf: csrf, }).done(() => { - window.location.href = $this.data('done-url'); + window.location.href = $this.data("done-url"); }); }); // Set anchor. - $('.markdown').each(function () { + $(".markdown").each(function () { $(this) - .find('h1, h2, h3, h4, h5, h6') + .find("h1, h2, h3, h4, h5, h6") .each(function () { let node = $(this); node = node.wrap('
'); node.append( `${svg('octicon-link', 16)}` + node.attr("id") + )}">${svg("octicon-link", 16)}` ); }); }); - $('.issue-checkbox').on('click', () => { - const numChecked = $('.issue-checkbox').children('input:checked').length; + $(".issue-checkbox").on("click", () => { + const numChecked = $(".issue-checkbox").children("input:checked").length; if (numChecked > 0) { - $('#issue-filters').addClass('hide'); - $('#issue-actions').removeClass('hide'); + $("#issue-filters").addClass("hide"); + $("#issue-actions").removeClass("hide"); } else { - $('#issue-filters').removeClass('hide'); - $('#issue-actions').addClass('hide'); + $("#issue-filters").removeClass("hide"); + $("#issue-actions").addClass("hide"); } }); - $('.issue-action').on('click', function () { + $(".issue-action").on("click", function () { let { action } = this.dataset; let { elementId } = this.dataset; - const issueIDs = $('.issue-checkbox') - .children('input:checked') + const issueIDs = $(".issue-checkbox") + .children("input:checked") .map(function () { return this.dataset.issueId; }) .get() .join(); - console.log("this:", this) + console.log("this:", this); const { url } = this.dataset; - if (elementId === '0' && url.substr(-9) === '/assignee') { - elementId = ''; - action = 'clear'; + if (elementId === "0" && url.substr(-9) === "/assignee") { + elementId = ""; + action = "clear"; } - updateIssuesMeta(url, action, issueIDs, elementId, '').then(() => { + updateIssuesMeta(url, action, issueIDs, elementId, "").then(() => { // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload - if (action === 'close' || action === 'open') { + if (action === "close" || action === "open") { // uncheck all checkboxes $('.issue-checkbox input[type="checkbox"]').each((_, e) => { e.checked = false; @@ -2945,19 +2855,19 @@ $(document).ready(async () => { .first() .each((_, e) => { e.checked = false; - $(e).trigger('click'); + $(e).trigger("click"); }); - $('.resolve-conversation').on('click', function (e) { + $(".resolve-conversation").on("click", function (e) { e.preventDefault(); - const id = $(this).data('comment-id'); - const action = $(this).data('action'); - const url = $(this).data('update-url'); + const id = $(this).data("comment-id"); + const action = $(this).data("action"); + const url = $(this).data("update-url"); $.post(url, { _csrf: csrf, action, - comment_id: id + comment_id: id, }).then(reload); }); @@ -2988,10 +2898,11 @@ $(document).ready(async () => { initVueModel(); initVueDataAnalysis(); initVueWxAutorize(); + initVueselectDataset(); initTeamSettings(); initCtrlEnterSubmit(); initNavbarContentToggle(); - // initTopicbar();vim + // initTopicbar();vim // closeTopicbar(); initU2FAuth(); initU2FRegister(); @@ -3010,22 +2921,22 @@ $(document).ready(async () => { initContextMenu(); // Repo clone url. - if ($('#repo-clone-url').length > 0) { - switch (localStorage.getItem('repo-clone-protocol')) { - case 'ssh': - if ($('#repo-clone-ssh').length === 0) { - $('#repo-clone-https').trigger('click'); + if ($("#repo-clone-url").length > 0) { + switch (localStorage.getItem("repo-clone-protocol")) { + case "ssh": + if ($("#repo-clone-ssh").length === 0) { + $("#repo-clone-https").trigger("click"); } break; default: - $('#repo-clone-https').trigger('click'); + $("#repo-clone-https").trigger("click"); break; } } const routes = { - 'div.user.settings': initUserSettings, - 'div.repository.settings.collaboration': initRepositoryCollaboration + "div.user.settings": initUserSettings, + "div.repository.settings.collaboration": initRepositoryCollaboration, }; let selector; @@ -3036,32 +2947,38 @@ $(document).ready(async () => { } } - const $cloneAddr = $('#clone_addr'); - $cloneAddr.on('change', () => { - const $repoName = $('#alias'); - const $owner = $('#ownerDropdown div.text').attr("title") - const $urlAdd = location.href.split('/')[0] + '//' + location.href.split('/')[2] + const $cloneAddr = $("#clone_addr"); + $cloneAddr.on("change", () => { + const $repoName = $("#alias"); + const $owner = $("#ownerDropdown div.text").attr("title"); + const $urlAdd = + location.href.split("/")[0] + "//" + location.href.split("/")[2]; if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) { // Only modify if repo_name input is blank - const repoValue = $cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3] + const repoValue = $cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]; $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]); - $.get(`${window.config.AppSubUrl}/repo/check_name?q=${repoValue}&owner=${$owner}`, (data) => { - const repo_name = data.name - $('#repo_name').val(repo_name) - repo_name && $('#repo_name').parent().removeClass('error') - $('#repoAdress').css("display", "flex") - $('#repoAdress span').text($urlAdd + '/' + $owner + '/' + $('#repo_name').val() + '.git') - $('#repo_name').attr("placeholder", "") - }) + $.get( + `${window.config.AppSubUrl}/repo/check_name?q=${repoValue}&owner=${$owner}`, + (data) => { + const repo_name = data.name; + $("#repo_name").val(repo_name); + repo_name && $("#repo_name").parent().removeClass("error"); + $("#repoAdress").css("display", "flex"); + $("#repoAdress span").text( + $urlAdd + "/" + $owner + "/" + $("#repo_name").val() + ".git" + ); + $("#repo_name").attr("placeholder", ""); + } + ); } }); // parallel init of lazy-loaded features await Promise.all([ - highlight(document.querySelectorAll('pre code')), + highlight(document.querySelectorAll("pre code")), initGitGraph(), initClipboard(), - initUserHeatmap() + initUserHeatmap(), ]); }); @@ -3082,10 +2999,10 @@ function deSelect() { } function selectRange($list, $select, $from) { - $list.removeClass('active'); + $list.removeClass("active"); if ($from) { - let a = parseInt($select.attr('rel').substr(1)); - let b = parseInt($from.attr('rel').substr(1)); + let a = parseInt($select.attr("rel").substr(1)); + let b = parseInt($from.attr("rel").substr(1)); let c; if (a !== b) { if (a > b) { @@ -3097,29 +3014,27 @@ function selectRange($list, $select, $from) { for (let i = a; i <= b; i++) { classes.push(`.L${i}`); } - $list.filter(classes.join(',')).addClass('active'); + $list.filter(classes.join(",")).addClass("active"); changeHash(`#L${a}-L${b}`); return; } } - $select.addClass('active'); - changeHash(`#${$select.attr('rel')}`); + $select.addClass("active"); + changeHash(`#${$select.attr("rel")}`); } $(() => { // Warn users that try to leave a page after entering data into a form. // Except on sign-in pages, and for forms marked as 'ignore-dirty'. - if ($('.user.signin').length === 0) { - $('form:not(.ignore-dirty)').areYouSure(); + if ($(".user.signin").length === 0) { + $("form:not(.ignore-dirty)").areYouSure(); } // Parse SSH Key - $('#ssh-key-content').on('change paste keyup', function () { - const arrays = $(this) - .val() - .split(' '); - const $title = $('#ssh-key-title'); - if ($title.val() === '' && arrays.length === 3 && arrays[2] !== '') { + $("#ssh-key-content").on("change paste keyup", function () { + const arrays = $(this).val().split(" "); + const $title = $("#ssh-key-title"); + if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") { $title.val(arrays[2]); } }); @@ -3127,72 +3042,72 @@ $(() => { function showDeletePopup() { const $this = $(this); - let filter = ''; - if ($this.attr('id')) { - filter += `#${$this.attr('id')}`; + let filter = ""; + if ($this.attr("id")) { + filter += `#${$this.attr("id")}`; } const dialog = $(`.delete.modal${filter}`); - dialog.find('.name').text($this.data('name')); + dialog.find(".name").text($this.data("name")); dialog .modal({ closable: false, onApprove() { - if ($this.data('type') === 'form') { - $($this.data('form')).trigger('submit'); + if ($this.data("type") === "form") { + $($this.data("form")).trigger("submit"); return; } - $.post($this.data('url'), { + $.post($this.data("url"), { _csrf: csrf, - id: $this.data('id') + id: $this.data("id"), }).done((data) => { window.location.href = data.redirect; }); - } + }, }) - .modal('show'); + .modal("show"); return false; } function showAddAllPopup() { const $this = $(this); - let filter = ''; - if ($this.attr('id')) { - filter += `#${$this.attr('id')}`; + let filter = ""; + if ($this.attr("id")) { + filter += `#${$this.attr("id")}`; } const dialog = $(`.addall.modal${filter}`); - dialog.find('.name').text($this.data('name')); + dialog.find(".name").text($this.data("name")); dialog .modal({ closable: false, onApprove() { - if ($this.data('type') === 'form') { - $($this.data('form')).trigger('submit'); + if ($this.data("type") === "form") { + $($this.data("form")).trigger("submit"); return; } - $.post($this.data('url'), { + $.post($this.data("url"), { _csrf: csrf, - id: $this.data('id') + id: $this.data("id"), }).done((data) => { window.location.href = data.redirect; }); - } + }, }) - .modal('show'); + .modal("show"); return false; } function linkAction(e) { e.preventDefault(); const $this = $(this); - const redirect = $this.data('redirect'); - $.post($this.data('url'), { - _csrf: csrf + const redirect = $this.data("redirect"); + $.post($this.data("url"), { + _csrf: csrf, }).done((data) => { if (data.redirect) { window.location.href = data.redirect; @@ -3206,87 +3121,87 @@ function linkAction(e) { function linkEmailAction(e) { const $this = $(this); - $('#form-uid').val($this.data('uid')); - $('#form-email').val($this.data('email')); - $('#form-primary').val($this.data('primary')); - $('#form-activate').val($this.data('activate')); - $('#form-uid').val($this.data('uid')); - $('#change-email-modal').modal('show'); + $("#form-uid").val($this.data("uid")); + $("#form-email").val($this.data("email")); + $("#form-primary").val($this.data("primary")); + $("#form-activate").val($this.data("activate")); + $("#form-uid").val($this.data("uid")); + $("#change-email-modal").modal("show"); e.preventDefault(); } function initVueComponents() { - const vueDelimeters = ['${', '}']; + const vueDelimeters = ["${", "}"]; - Vue.component('repo-search', { + Vue.component("repo-search", { delimiters: vueDelimeters, props: { searchLimit: { type: Number, - default: 10 + default: 10, }, suburl: { type: String, - required: true + required: true, }, uid: { type: Number, - required: true + required: true, }, organizations: { type: Array, - default: [] + default: [], }, isOrganization: { type: Boolean, - default: true + default: true, }, canCreateOrganization: { type: Boolean, - default: false + default: false, }, organizationsTotalCount: { type: Number, - default: 0 + default: 0, }, moreReposLink: { type: String, - default: '' - } + default: "", + }, }, data() { const params = new URLSearchParams(window.location.search); - let tab = params.get('repo-search-tab'); + let tab = params.get("repo-search-tab"); if (!tab) { - tab = 'repos'; + tab = "repos"; } - let reposFilter = params.get('repo-search-filter'); + let reposFilter = params.get("repo-search-filter"); if (!reposFilter) { - reposFilter = 'all'; + reposFilter = "all"; } - let privateFilter = params.get('repo-search-private'); + let privateFilter = params.get("repo-search-private"); if (!privateFilter) { - privateFilter = 'both'; + privateFilter = "both"; } - let archivedFilter = params.get('repo-search-archived'); + let archivedFilter = params.get("repo-search-archived"); if (!archivedFilter) { - archivedFilter = 'unarchived'; + archivedFilter = "unarchived"; } - let searchQuery = params.get('repo-search-query'); + let searchQuery = params.get("repo-search-query"); if (!searchQuery) { - searchQuery = ''; + searchQuery = ""; } let page = 1; try { - page = parseInt(params.get('repo-search-page')); + page = parseInt(params.get("repo-search-page")); } catch { // noop } @@ -3309,21 +3224,21 @@ function initVueComponents() { counts: {}, repoTypes: { all: { - searchMode: '' + searchMode: "", }, forks: { - searchMode: 'fork' + searchMode: "fork", }, mirrors: { - searchMode: 'mirror' + searchMode: "mirror", }, sources: { - searchMode: 'source' + searchMode: "source", }, collaborative: { - searchMode: 'collaborative' - } - } + searchMode: "collaborative", + }, + }, }; }, @@ -3332,39 +3247,35 @@ function initVueComponents() { return ( this.repos.length > 0 && this.repos.length < - this.counts[ - `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}` - ] + this.counts[ + `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}` + ] ); }, searchURL() { return `${ this.suburl - }/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=${ + }/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=${ this.searchQuery - }&page=${this.page}&limit=${this.searchLimit}&mode=${ + }&page=${this.page}&limit=${this.searchLimit}&mode=${ this.repoTypes[this.reposFilter].searchMode - }${this.reposFilter !== 'all' ? '&exclusive=1' : ''}${ - this.archivedFilter === 'archived' ? '&archived=true' : '' - }${this.archivedFilter === 'unarchived' ? '&archived=false' : ''}${ - this.privateFilter === 'private' ? '&onlyPrivate=true' : '' - }${this.privateFilter === 'public' ? '&private=false' : ''}`; + }${this.reposFilter !== "all" ? "&exclusive=1" : ""}${ + this.archivedFilter === "archived" ? "&archived=true" : "" + }${this.archivedFilter === "unarchived" ? "&archived=false" : ""}${ + this.privateFilter === "private" ? "&onlyPrivate=true" : "" + }${this.privateFilter === "public" ? "&private=false" : ""}`; }, repoTypeCount() { return this.counts[ `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}` ]; - } + }, }, mounted() { this.searchRepos(this.reposFilter); - $(this.$el) - .find('.poping.up') - .popup(); - $(this.$el) - .find('.dropdown') - .dropdown(); + $(this.$el).find(".poping.up").popup(); + $(this.$el).find(".dropdown").dropdown(); this.setCheckboxes(); const self = this; Vue.nextTick(() => { @@ -3379,33 +3290,33 @@ function initVueComponents() { setCheckboxes() { switch (this.archivedFilter) { - case 'unarchived': - $('#archivedFilterCheckbox').checkbox('set unchecked'); + case "unarchived": + $("#archivedFilterCheckbox").checkbox("set unchecked"); break; - case 'archived': - $('#archivedFilterCheckbox').checkbox('set checked'); + case "archived": + $("#archivedFilterCheckbox").checkbox("set checked"); break; - case 'both': - $('#archivedFilterCheckbox').checkbox('set indeterminate'); + case "both": + $("#archivedFilterCheckbox").checkbox("set indeterminate"); break; default: - this.archivedFilter = 'unarchived'; - $('#archivedFilterCheckbox').checkbox('set unchecked'); + this.archivedFilter = "unarchived"; + $("#archivedFilterCheckbox").checkbox("set unchecked"); break; } switch (this.privateFilter) { - case 'public': - $('#privateFilterCheckbox').checkbox('set unchecked'); + case "public": + $("#privateFilterCheckbox").checkbox("set unchecked"); break; - case 'private': - $('#privateFilterCheckbox').checkbox('set checked'); + case "private": + $("#privateFilterCheckbox").checkbox("set checked"); break; - case 'both': - $('#privateFilterCheckbox').checkbox('set indeterminate'); + case "both": + $("#privateFilterCheckbox").checkbox("set indeterminate"); break; default: - this.privateFilter = 'both'; - $('#privateFilterCheckbox').checkbox('set indeterminate'); + this.privateFilter = "both"; + $("#privateFilterCheckbox").checkbox("set indeterminate"); break; } }, @@ -3425,58 +3336,58 @@ function initVueComponents() { updateHistory() { const params = new URLSearchParams(window.location.search); - if (this.tab === 'repos') { - params.delete('repo-search-tab'); + if (this.tab === "repos") { + params.delete("repo-search-tab"); } else { - params.set('repo-search-tab', this.tab); + params.set("repo-search-tab", this.tab); } - if (this.reposFilter === 'all') { - params.delete('repo-search-filter'); + if (this.reposFilter === "all") { + params.delete("repo-search-filter"); } else { - params.set('repo-search-filter', this.reposFilter); + params.set("repo-search-filter", this.reposFilter); } - if (this.privateFilter === 'both') { - params.delete('repo-search-private'); + if (this.privateFilter === "both") { + params.delete("repo-search-private"); } else { - params.set('repo-search-private', this.privateFilter); + params.set("repo-search-private", this.privateFilter); } - if (this.archivedFilter === 'unarchived') { - params.delete('repo-search-archived'); + if (this.archivedFilter === "unarchived") { + params.delete("repo-search-archived"); } else { - params.set('repo-search-archived', this.archivedFilter); + params.set("repo-search-archived", this.archivedFilter); } - if (this.searchQuery === '') { - params.delete('repo-search-query'); + if (this.searchQuery === "") { + params.delete("repo-search-query"); } else { - params.set('repo-search-query', this.searchQuery); + params.set("repo-search-query", this.searchQuery); } if (this.page === 1) { - params.delete('repo-search-page'); + params.delete("repo-search-page"); } else { - params.set('repo-search-page', `${this.page}`); + params.set("repo-search-page", `${this.page}`); } - window.history.replaceState({}, '', `?${params.toString()}`); + window.history.replaceState({}, "", `?${params.toString()}`); }, toggleArchivedFilter() { switch (this.archivedFilter) { - case 'both': - this.archivedFilter = 'unarchived'; + case "both": + this.archivedFilter = "unarchived"; break; - case 'unarchived': - this.archivedFilter = 'archived'; + case "unarchived": + this.archivedFilter = "archived"; break; - case 'archived': - this.archivedFilter = 'both'; + case "archived": + this.archivedFilter = "both"; break; default: - this.archivedFilter = 'unarchived'; + this.archivedFilter = "unarchived"; break; } this.page = 1; @@ -3492,17 +3403,17 @@ function initVueComponents() { togglePrivateFilter() { switch (this.privateFilter) { - case 'both': - this.privateFilter = 'public'; + case "both": + this.privateFilter = "public"; break; - case 'public': - this.privateFilter = 'private'; + case "public": + this.privateFilter = "private"; break; - case 'private': - this.privateFilter = 'both'; + case "private": + this.privateFilter = "both"; break; default: - this.privateFilter = 'both'; + this.privateFilter = "both"; break; } this.page = 1; @@ -3535,11 +3446,11 @@ function initVueComponents() { showArchivedRepo(repo) { switch (this.archivedFilter) { - case 'both': + case "both": return true; - case 'unarchived': + case "unarchived": return !repo.archived; - case 'archived': + case "archived": return repo.archived; default: return !repo.archived; @@ -3548,11 +3459,11 @@ function initVueComponents() { showPrivateRepo(repo) { switch (this.privateFilter) { - case 'both': + case "both": return true; - case 'public': + case "public": return !repo.private; - case 'private': + case "private": return repo.private; default: return true; @@ -3561,13 +3472,13 @@ function initVueComponents() { showFilteredRepo(repo) { switch (this.reposFilter) { - case 'sources': + case "sources": return repo.owner.id === this.uid && !repo.mirror && !repo.fork; - case 'forks': + case "forks": return repo.owner.id === this.uid && !repo.mirror && repo.fork; - case 'mirrors': + case "mirrors": return repo.mirror; - case 'collaborative': + case "collaborative": return repo.owner.id !== this.uid && !repo.mirror; default: return true; @@ -3594,11 +3505,11 @@ function initVueComponents() { $.getJSON(searchedURL, (result, _textStatus, request) => { if (searchedURL === self.searchURL) { self.repos = result.data; - const count = request.getResponseHeader('X-Total-Count'); + const count = request.getResponseHeader("X-Total-Count"); if ( - searchedQuery === '' && - searchedMode === '' && - self.archivedFilter === 'both' + searchedQuery === "" && + searchedMode === "" && + self.archivedFilter === "both" ) { self.reposTotalCount = count; } @@ -3619,38 +3530,36 @@ function initVueComponents() { repoClass(repo) { if (repo.fork) { - return 'octicon-repo-forked'; + return "octicon-repo-forked"; } if (repo.mirror) { - return 'octicon-repo-clone'; + return "octicon-repo-clone"; } if (repo.template) { - return `octicon-repo-template${repo.private ? '-private' : ''}`; + return `octicon-repo-template${repo.private ? "-private" : ""}`; } if (repo.private) { - return 'octicon-lock'; + return "octicon-lock"; } - return 'octicon-repo'; - } - } + return "octicon-repo"; + }, + }, }); } function initCtrlEnterSubmit() { - $('.js-quick-submit').on('keydown', function (e) { + $(".js-quick-submit").on("keydown", function (e) { if ( ((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode === 13 || e.keyCode === 10) ) { - $(this) - .closest('form') - .trigger('submit'); + $(this).closest("form").trigger("submit"); } }); } function initVueApp() { - const el = document.getElementById('app'); + const el = document.getElementById("app"); if (!el) { return; } @@ -3658,198 +3567,223 @@ function initVueApp() { initVueComponents(); new Vue({ - delimiters: ['${', '}'], + delimiters: ["${", "}"], el, data: { - page: parseInt(new URLSearchParams(window.location.search).get('page')), + page: parseInt(new URLSearchParams(window.location.search).get("page")), searchLimit: Number( - (document.querySelector('meta[name=_search_limit]') || {}).content + (document.querySelector("meta[name=_search_limit]") || {}).content ), page: 1, suburl: AppSubUrl, uid: Number( - (document.querySelector('meta[name=_context_uid]') || {}).content + (document.querySelector("meta[name=_context_uid]") || {}).content ), activityTopAuthors: window.ActivityTopAuthors || [], - localHref: '' + localHref: "", }, components: { - ActivityTopAuthors + ActivityTopAuthors, }, mounted() { - this.page = parseInt(new URLSearchParams(window.location.search).get('page')) - this.localHref = location.href - + this.page = parseInt( + new URLSearchParams(window.location.search).get("page") + ); + this.localHref = location.href; }, methods: { handleCurrentChange: function (val) { - const searchParams = new URLSearchParams(window.location.search) + const searchParams = new URLSearchParams(window.location.search); if (!window.location.search) { - window.location.href = this.localHref + '?page=' + val - } else if (searchParams.has('page')) { - window.location.href = this.localHref.replace(/page=[0-9]+/g, 'page=' + val) + window.location.href = this.localHref + "?page=" + val; + } else if (searchParams.has("page")) { + window.location.href = this.localHref.replace( + /page=[0-9]+/g, + "page=" + val + ); } else { - window.location.href = location.href + '&page=' + val + window.location.href = location.href + "&page=" + val; } - this.page = val - } - } + this.page = val; + }, + }, }); } function initVueUploader() { - const el = document.getElementById('minioUploader'); + const el = document.getElementById("minioUploader"); if (!el) { return; } new Vue({ - el: '#minioUploader', + el: "#minioUploader", components: { MinioUploader }, - template: '' + template: "", }); } function initVueEditAbout() { - const el = document.getElementById('about-desc'); + const el = document.getElementById("about-desc"); if (!el) { return; } new Vue({ - el: '#about-desc', - render: h => h(EditAboutInfo) + el: "#about-desc", + render: (h) => h(EditAboutInfo), }); } function initVueDataset() { - if ($('#dataset_check').length) { - if (location.search.indexOf('recommend=true') !== -1) { - $('#dataset_check').checkbox('set checked') + if ($("#dataset_check").length) { + if (location.search.indexOf("recommend=true") !== -1) { + $("#dataset_check").checkbox("set checked"); } else { - $('#dataset_check').checkbox('set unchecked') + $("#dataset_check").checkbox("set unchecked"); } - $('#dataset_check').checkbox({ + $("#dataset_check").checkbox({ onChecked: function () { if (location.search) { - const params = new URLSearchParams(location.search) - if (params.has('recommend')) { - params.delete('recommend') - location.href = AppSubUrl + location.pathname + '?' + params.toString() + '&recommend=true' + const params = new URLSearchParams(location.search); + if (params.has("recommend")) { + params.delete("recommend"); + location.href = + AppSubUrl + + location.pathname + + "?" + + params.toString() + + "&recommend=true"; } else { - location.href = `${window.config.AppSubUrl}/admin/datasets${location.search}&recommend=true` + location.href = `${window.config.AppSubUrl}/admin/datasets${location.search}&recommend=true`; } } else { - location.href = `${window.config.AppSubUrl}/admin/datasets?recommend=true` + location.href = `${window.config.AppSubUrl}/admin/datasets?recommend=true`; } }, onUnchecked: function () { - if (location.search == '?recommend=true') { - location.href = AppSubUrl + location.pathname + if (location.search == "?recommend=true") { + location.href = AppSubUrl + location.pathname; } else { - const params = new URLSearchParams(location.search) - params.delete('recommend') - location.href = AppSubUrl + location.pathname + '?' + params.toString() + const params = new URLSearchParams(location.search); + params.delete("recommend"); + location.href = + AppSubUrl + location.pathname + "?" + params.toString(); } }, - }) + }); } - $('.set_dataset').on('click', function () { + $(".set_dataset").on("click", function () { const $this = $(this); - let link = $this.data('url') + let link = $this.data("url"); $.ajax({ url: link, - type: 'PUT', + type: "PUT", success: function (res) { - console.log(res) + console.log(res); if (res.Code == 0) { - window.location.href = '/admin/datasets' + window.location.href = "/admin/datasets"; } else { - $('.ui.negative.message').text(res.Message).show().delay(1500).fadeOut(); + $(".ui.negative.message") + .text(res.Message) + .show() + .delay(1500) + .fadeOut(); } }, error: function (xhr) { // 隐藏 loading // 只有请求不正常(状态码不为200)才会执行 - $('.ui.negative.message').html(xhr.responseText).show().delay(1500).fadeOut(); - console.log(xhr) + $(".ui.negative.message") + .html(xhr.responseText) + .show() + .delay(1500) + .fadeOut(); + console.log(xhr); }, complete: function (xhr) { // $("#mask").css({"display":"none","z-index":"1"}) - } - }) - + }, + }); }); - const el = document.getElementById('dataset-base'); + const el = document.getElementById("dataset-base"); if (!el) { return; } - let link = $('#square-link').data('link') - let repolink = $('.dataset-repolink').data('repolink') - let cloudbrainType = $('.dataset-repolink').data('cloudranin-type') + let link = $("#square-link").data("link"); + let repolink = $(".dataset-repolink").data("repolink"); + let cloudbrainType = $(".dataset-repolink").data("cloudranin-type"); const clearBtn = document.getElementsByClassName("clear_dataset_value"); - const params = new URLSearchParams(location.search) + const params = new URLSearchParams(location.search); for (let i = 0; i < clearBtn.length; i++) { - clearBtn[i].addEventListener('click', function (e) { - let searchType = e.target.getAttribute("data-clear-value") + clearBtn[i].addEventListener("click", function (e) { + let searchType = e.target.getAttribute("data-clear-value"); if (params.has(searchType)) { - params.delete(searchType) - let clearSearch = params.toString() - location.href = link + '?' + clearSearch + params.delete(searchType); + let clearSearch = params.toString(); + location.href = link + "?" + clearSearch; } - }) + }); } - const items = [] - const zipStatus = [] - $('#dataset-range-value').find('.item').each(function () { - items.push($(this).data('private')) - zipStatus.push($(this).data('decompress-state')) - }) - let num_stars = $('#dataset-range-value').data('num-stars') - let star_active = $('#dataset-range-value').data('star-active') - const ruleForm = {} - if (document.getElementById('dataset-edit-value')) { - let $this = $('#dataset-edit-value') - ruleForm.title = $this.data('edit-title') || '' - ruleForm.description = $this.data('edit-description') || '' - ruleForm.category = $this.data('edit-category') || '' - ruleForm.task = $this.data('edit-task') || '' - ruleForm.license = $this.data('edit-license') || '' - ruleForm.id = $this.data('edit-id') || '' - ruleForm._csrf = csrf + const items = []; + const zipStatus = []; + $("#dataset-range-value") + .find(".item") + .each(function () { + items.push($(this).data("private")); + zipStatus.push($(this).data("decompress-state")); + }); + let num_stars = $("#dataset-range-value").data("num-stars"); + let star_active = $("#dataset-range-value").data("star-active"); + const ruleForm = {}; + if (document.getElementById("dataset-edit-value")) { + let $this = $("#dataset-edit-value"); + ruleForm.title = $this.data("edit-title") || ""; + ruleForm.description = $this.data("edit-description") || ""; + ruleForm.category = $this.data("edit-category") || ""; + ruleForm.task = $this.data("edit-task") || ""; + ruleForm.license = $this.data("edit-license") || ""; + ruleForm.id = $this.data("edit-id") || ""; + ruleForm._csrf = csrf; } - const starItems = [] - const starActives = [] - $('#datasets-square-range-value').find('.item').each(function () { - starItems.push($(this).data('num-stars')) - starActives.push($(this).data('star-active')) - }) - const taskLists = [] - const licenseLists = [] - $('#task-square-range-value').find('.item').each(function () { - taskLists.push($(this).data('task')) - }) - $('#task-square-range-value').find('.item').each(function () { - licenseLists.push($(this).data('license')) - }) - let dataset_file_desc - if (document.getElementById('dataset-file-desc')) { - dataset_file_desc = document.getElementById('dataset-file-desc').value + const starItems = []; + const starActives = []; + $("#datasets-square-range-value") + .find(".item") + .each(function () { + starItems.push($(this).data("num-stars")); + starActives.push($(this).data("star-active")); + }); + const taskLists = []; + const licenseLists = []; + $("#task-square-range-value") + .find(".item") + .each(function () { + taskLists.push($(this).data("task")); + }); + $("#task-square-range-value") + .find(".item") + .each(function () { + licenseLists.push($(this).data("license")); + }); + let dataset_file_desc; + if (document.getElementById("dataset-file-desc")) { + dataset_file_desc = document.getElementById("dataset-file-desc").value; } new Vue({ - delimiters: ['${', '}'], + delimiters: ["${", "}"], el, data: { suburl: AppSubUrl, - url: '', + url: "", checked: false, clusterFlag: false, type: 0, - desc: '', - descfile: '', - datasetType: '', + desc: "", + descfile: "", + datasetType: "", privates: [], zipStatus: [], starItems: [], @@ -3863,42 +3797,46 @@ function initVueDataset() { star_active: false, num_stars: 0, dialogVisible: false, - activeName: 'first', - searchDataItem: '', + activeName: "first", + searchDataItem: "", currentRepoDataset: [], myDataset: [], publicDataset: [], myFavoriteDataset: [], page: 1, totalnums: 0, - repolink: '', + repolink: "", cloudbrainType: 0, - dataset_uuid: '', - dataset_name: '', + dataset_uuid: "", + dataset_name: "", loadingDataIndex: false, timer: null, ruleForm: { - title: '', - description: '', - category: '', - task: '', - license: '', + title: "", + description: "", + category: "", + task: "", + license: "", _csrf: csrf, - }, ruleForm1: { - title: '', - description: '', - category: '', - task: '', - license: '', - _csrf: '', - id: '' + title: "", + description: "", + category: "", + task: "", + license: "", + _csrf: "", + id: "", }, rules: { title: [ - { required: true, message: '请输入数据集名称', trigger: 'blur' }, - { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }, + { required: true, message: "请输入数据集名称", trigger: "blur" }, + { + min: 1, + max: 100, + message: "长度在 1 到 100 个字符", + trigger: "blur", + }, // {required:true,message:'test',pattern:'/^[a-zA-Z0-9-_]{1,100}[^-]$/',trigger:'blur'}, { validator: (rule, value, callback) => { @@ -3907,17 +3845,22 @@ function initVueDataset() { } else { callback(); } - }, trigger: 'blur' - } + }, + trigger: "blur", + }, ], description: [ - { required: true, message: '请输入数据集描述详情', trigger: 'blur' } + { required: true, message: "请输入数据集描述详情", trigger: "blur" }, ], category: [ - { required: true, message: '请选择分类', trigger: 'change' } + { required: true, message: "请选择分类", trigger: "change" }, ], task: [ - { required: true, message: '请选择研究方向/应用领域', trigger: 'change' } + { + required: true, + message: "请选择研究方向/应用领域", + trigger: "change", + }, ], // license: [ // { required: true, message: '请选择活动区域', trigger: 'change' } @@ -3925,240 +3868,246 @@ function initVueDataset() { }, }, components: { - MinioUploader + MinioUploader, }, mounted() { - this.getTypeList() + this.getTypeList(); - if (!!document.getElementById('dataset-repolink-init')) { - this.cloudbrainType = location.href.indexOf('cloudbrain') !== -1 ? 0 : 1 - this.getCurrentRepoDataset(this.repolink, this.cloudbrainType) + if (!!document.getElementById("dataset-repolink-init")) { + this.cloudbrainType = + location.href.indexOf("cloudbrain") !== -1 ? 0 : 1; + this.getCurrentRepoDataset(this.repolink, this.cloudbrainType); } - const params = new URLSearchParams(location.search) - if (params.has('recommend') && params.get('recommend') == 'true') { - this.checked = true + const params = new URLSearchParams(location.search); + if (params.has("recommend") && params.get("recommend") == "true") { + this.checked = true; } else { - this.checked = false + this.checked = false; } }, created() { - if (document.getElementById('postPath')) { - this.url = document.getElementById('postPath').value + if (document.getElementById("postPath")) { + this.url = document.getElementById("postPath").value; } - this.privates = items - this.zipStatus = zipStatus - this.num_stars = num_stars - this.star_active = star_active - this.ruleForm1 = ruleForm + this.privates = items; + this.zipStatus = zipStatus; + this.num_stars = num_stars; + this.star_active = star_active; + this.ruleForm1 = ruleForm; // this.getEditInit() - this.starItems = starItems - this.starActives = starActives - this.taskLists = taskLists - this.licenseLists = licenseLists - this.descfile = dataset_file_desc - this.repolink = repolink - this.cloudbrainType = cloudbrainType + this.starItems = starItems; + this.starActives = starActives; + this.taskLists = taskLists; + this.licenseLists = licenseLists; + this.descfile = dataset_file_desc; + this.repolink = repolink; + this.cloudbrainType = cloudbrainType; }, methods: { copyUrl(url) { - const cInput = document.createElement('input') - cInput.value = url - document.body.appendChild(cInput) - cInput.select() - document.execCommand('Copy') - cInput.remove() - $('body') - .toast({ - message: '复制成功!', - showProgress: 'bottom', - showIcon: 'check circle', - class: 'info', - position: 'top right', - }) - ; + const cInput = document.createElement("input"); + cInput.value = url; + document.body.appendChild(cInput); + cInput.select(); + document.execCommand("Copy"); + cInput.remove(); + $("body").toast({ + message: "复制成功!", + showProgress: "bottom", + showIcon: "check circle", + class: "info", + position: "top right", + }); }, handleCurrentChange(val) { - this.page = val + this.page = val; switch (this.activeName) { - case 'first': - this.getCurrentRepoDataset(this.repolink, this.cloudbrainType) - - break - case 'second': - this.getMyDataset(this.repolink, this.cloudbrainType) - break - case 'third': - this.getPublicDataset(this.repolink, this.cloudbrainType) - break - case 'fourth': - this.getStarDataset(this.repolink, this.cloudbrainType) - break - } + case "first": + this.getCurrentRepoDataset(this.repolink, this.cloudbrainType); + break; + case "second": + this.getMyDataset(this.repolink, this.cloudbrainType); + break; + case "third": + this.getPublicDataset(this.repolink, this.cloudbrainType); + break; + case "fourth": + this.getStarDataset(this.repolink, this.cloudbrainType); + break; + } }, handleCheckedChange(val) { if (val) { if (location.search) { - const params = new URLSearchParams(location.search) - if (params.has('recommend')) { - params.delete('recommend') - let search = params.toString() - location.href = `${AppSubUrl}/explore/datasets?${search}&recommend=${val}` + const params = new URLSearchParams(location.search); + if (params.has("recommend")) { + params.delete("recommend"); + let search = params.toString(); + location.href = `${AppSubUrl}/explore/datasets?${search}&recommend=${val}`; } else { - location.href = `${AppSubUrl}/explore/datasets${location.search}&recommend=${val}` + location.href = `${AppSubUrl}/explore/datasets${location.search}&recommend=${val}`; } } else { - location.href = `${AppSubUrl}/explore/datasets?recommend=${val}` + location.href = `${AppSubUrl}/explore/datasets?recommend=${val}`; } } else { - if (location.search == '?recommend=true') { - location.href = AppSubUrl + location.pathname + if (location.search == "?recommend=true") { + location.href = AppSubUrl + location.pathname; } else { - const params = new URLSearchParams(location.search) - params.delete('recommend') - location.href = AppSubUrl + location.pathname + '?' + params.toString() + const params = new URLSearchParams(location.search); + params.delete("recommend"); + location.href = + AppSubUrl + location.pathname + "?" + params.toString(); } } }, createDataset(formName) { - let _this = this + let _this = this; this.$refs[formName].validate((valid) => { if (valid) { - document.getElementById("mask").style.display = "block" - _this.$axios.post(_this.url, _this.qs.stringify(_this.ruleForm)).then((res) => { - if (res.data.Code === 0) { - document.getElementById("mask").style.display = "none" - location.href = _this.url.split('/create')[0] + '?type=-1' - } else { - console.log(res.data.Message) - } - document.getElementById("mask").style.display = "none" - }).catch(error => { - console.log(error) - }) - } - else { - return false + document.getElementById("mask").style.display = "block"; + _this.$axios + .post(_this.url, _this.qs.stringify(_this.ruleForm)) + .then((res) => { + if (res.data.Code === 0) { + document.getElementById("mask").style.display = "none"; + location.href = _this.url.split("/create")[0] + "?type=-1"; + } else { + console.log(res.data.Message); + } + document.getElementById("mask").style.display = "none"; + }) + .catch((error) => { + console.log(error); + }); + } else { + return false; } - }) + }); }, cancelDataset(getpage, attachment) { if (getpage && !attachment) { - if (getpage === 'create') { - location.href = this.url.split('/create')[0] + '?type=-1' - } else if (getpage === 'edit') { - location.href = this.url.split('/edit')[0] + '?type=-1' + if (getpage === "create") { + location.href = this.url.split("/create")[0] + "?type=-1"; + } else if (getpage === "edit") { + location.href = this.url.split("/edit")[0] + "?type=-1"; } else { - location.href = '/' + location.href = "/"; } + } else { + location.href = `${AppSubUrl}${attachment}/datasets`; } - else { - location.href = `${AppSubUrl}${attachment}/datasets` - - } - }, gotoUpload(repolink, datsetId) { // location.href = `${AppSubUrl}${repolink}/datasets/attachments/upload?datasetId=${datsetId}` - window.open(`${AppSubUrl}${repolink}/datasets/attachments/upload?datasetId=${datsetId}`, '_blank') + window.open( + `${AppSubUrl}${repolink}/datasets/attachments/upload?datasetId=${datsetId}`, + "_blank" + ); }, gotoDataset(datsetUrl) { - location.href = datsetUrl + location.href = datsetUrl; }, gotoAnnotate(repolink, uuid, type) { - location.href = `${AppSubUrl}${repolink}/datasets/label/${uuid}?type=${type}` + location.href = `${AppSubUrl}${repolink}/datasets/label/${uuid}?type=${type}`; }, setcluster(val) { - this.clusterFlag = val + this.clusterFlag = val; }, uploadGpu() { - this.type = 0 + this.type = 0; }, uploadNpu() { - this.type = 1 + this.type = 1; }, sortAble(dom) { - const params = new URLSearchParams(location.search) - if (params.toString() === '') { - location.href = `${location.href}?sort=${dom}Asc` - } - else if (!params.get('sort')) { - location.href = `${location.href}&sort=${dom}Asc` - } - else if (params.get('sort') === `${dom}Desc` || params.get('sort').indexOf(`${dom}`) === -1) { - params.set("sort", `${dom}Asc`) - let asc = params.toString() - location.search = asc - } - else { - params.set("sort", `${dom}Desc`) - let desc = params.toString() - location.search = desc + const params = new URLSearchParams(location.search); + if (params.toString() === "") { + location.href = `${location.href}?sort=${dom}Asc`; + } else if (!params.get("sort")) { + location.href = `${location.href}&sort=${dom}Asc`; + } else if ( + params.get("sort") === `${dom}Desc` || + params.get("sort").indexOf(`${dom}`) === -1 + ) { + params.set("sort", `${dom}Asc`); + let asc = params.toString(); + location.search = asc; + } else { + params.set("sort", `${dom}Desc`); + let desc = params.toString(); + location.search = desc; } }, sortIcon(dom, sort) { - const params = new URLSearchParams(location.search) + const params = new URLSearchParams(location.search); if (sort === "up") { - if (params.toString() === '') { - location.href = `${location.href}?sort=${dom}Asc` - } - else if (!params.get('sort')) { - location.href = `${location.href}&sort=${dom}Asc` - } else if (params.get('sort') && params.get('sort').indexOf(`${dom}Asc`) !== -1) { - params.delete('sort') - location.search = params.toString() + if (params.toString() === "") { + location.href = `${location.href}?sort=${dom}Asc`; + } else if (!params.get("sort")) { + location.href = `${location.href}&sort=${dom}Asc`; + } else if ( + params.get("sort") && + params.get("sort").indexOf(`${dom}Asc`) !== -1 + ) { + params.delete("sort"); + location.search = params.toString(); } else { - params.set("sort", `${dom}Asc`) - let asc = params.toString() - location.search = asc - } - } - else if (sort === "down") { - if (params.toString() === '') { - location.href = `${location.href}?sort=${dom}Desc` + params.set("sort", `${dom}Asc`); + let asc = params.toString(); + location.search = asc; } - else if (!params.get('sort')) { - location.href = `${location.href}&sort=${dom}Desc` - } - else if (params.get('sort') && params.get('sort').indexOf(`${dom}Desc`) !== -1) { - params.delete('sort') - location.search = params.toString() + } else if (sort === "down") { + if (params.toString() === "") { + location.href = `${location.href}?sort=${dom}Desc`; + } else if (!params.get("sort")) { + location.href = `${location.href}&sort=${dom}Desc`; + } else if ( + params.get("sort") && + params.get("sort").indexOf(`${dom}Desc`) !== -1 + ) { + params.delete("sort"); + location.search = params.toString(); } else { - params.set("sort", `${dom}Desc`) - let asc = params.toString() - location.search = asc + params.set("sort", `${dom}Desc`); + let asc = params.toString(); + location.search = asc; } - - } - }, setPrivate(uuid, privateFlag, index) { - const params = { _csrf: csrf, file: uuid, is_private: privateFlag } - this.$axios.post('/attachments/private', this.qs.stringify(params)).then((res) => { - this.$set(this.privates, index, privateFlag) - }).catch(error => { - console.log(error) - }) + const params = { _csrf: csrf, file: uuid, is_private: privateFlag }; + this.$axios + .post("/attachments/private", this.qs.stringify(params)) + .then((res) => { + this.$set(this.privates, index, privateFlag); + }) + .catch((error) => { + console.log(error); + }); }, delDataset(uuid) { - let _this = this - const params = { _csrf: csrf, file: uuid } - $('#data-dataset-delete-modal') + let _this = this; + const params = { _csrf: csrf, file: uuid }; + $("#data-dataset-delete-modal") .modal({ closable: false, onApprove() { - _this.$axios.post('/attachments/delete', _this.qs.stringify(params)).then((res) => { - // $('#'+uuid).hide() - location.reload() - }).catch(error => { - console.log(error) - }) - } + _this.$axios + .post("/attachments/delete", _this.qs.stringify(params)) + .then((res) => { + // $('#'+uuid).hide() + location.reload(); + }) + .catch((error) => { + console.log(error); + }); + }, }) - .modal('show'); + .modal("show"); }, // getEditInit(){ // if($('#dataset-edit-value')){ @@ -4172,352 +4121,357 @@ function initVueDataset() { // } // }, editDataset(formName, id) { - let _this = this - this.url = this.url.split(`/${id}`)[0] + let _this = this; + this.url = this.url.split(`/${id}`)[0]; this.$refs[formName].validate((valid) => { if (valid) { - document.getElementById("mask").style.display = "block" - _this.$axios.post(_this.url, _this.qs.stringify(_this.ruleForm1)).then((res) => { - if (res.data.Code === 0) { - document.getElementById("mask").style.display = "none" - location.href = _this.url.split('/edit')[0] + '?type=-1' - } else { - console.log(res.data.Message) - } - document.getElementById("mask").style.display = "none" - }).catch((err) => { - console.log(err) - }) - } - else { - return false + document.getElementById("mask").style.display = "block"; + _this.$axios + .post(_this.url, _this.qs.stringify(_this.ruleForm1)) + .then((res) => { + if (res.data.Code === 0) { + document.getElementById("mask").style.display = "none"; + location.href = _this.url.split("/edit")[0] + "?type=-1"; + } else { + console.log(res.data.Message); + } + document.getElementById("mask").style.display = "none"; + }) + .catch((err) => { + console.log(err); + }); + } else { + return false; } - }) - + }); }, editDatasetFile(id, backurl) { - let url = '/attachments/edit' - const params = { id: id, description: this.descfile, _csrf: csrf } + let url = "/attachments/edit"; + const params = { id: id, description: this.descfile, _csrf: csrf }; // document.getElementById("mask").style.display = "block" - this.$axios.post(url, this.qs.stringify(params)).then((res) => { - if (res.data.Code === 0) { - location.href = `${AppSubUrl}${backurl}/datasets` - } else { - console.log(res.data.Message) - } - }).catch((err) => { - console.log(err) - }) + this.$axios + .post(url, this.qs.stringify(params)) + .then((res) => { + if (res.data.Code === 0) { + location.href = `${AppSubUrl}${backurl}/datasets`; + } else { + console.log(res.data.Message); + } + }) + .catch((err) => { + console.log(err); + }); }, postStar(id, link) { if (this.star_active) { - let url = link + '/' + id + '/unstar' + let url = link + "/" + id + "/unstar"; this.$axios.put(url).then((res) => { if (res.data.Code === 0) { - this.star_active = false - this.num_stars = this.num_stars - 1 + this.star_active = false; + this.num_stars = this.num_stars - 1; } - }) + }); } else { - let url = link + '/' + id + '/star' + let url = link + "/" + id + "/star"; this.$axios.put(url).then((res) => { if (res.data.Code === 0) { - this.star_active = true - this.num_stars = this.num_stars + 1 + this.star_active = true; + this.num_stars = this.num_stars + 1; } - }) + }); } }, postSquareStar(id, link, index) { if (this.starActives[index]) { - let url = link + '/' + id + '/unstar' + let url = link + "/" + id + "/unstar"; this.$axios.put(url).then((res) => { if (res.data.Code === 0) { - this.$set(this.starActives, index, false) - this.$set(this.starItems, index, this.starItems[index] - 1) + this.$set(this.starActives, index, false); + this.$set(this.starItems, index, this.starItems[index] - 1); } - }) + }); } else { - let url = link + '/' + id + '/star' + let url = link + "/" + id + "/star"; this.$axios.put(url).then((res) => { if (res.data.Code === 0) { - this.$set(this.starActives, index, true) - this.$set(this.starItems, index, this.starItems[index] + 1) - + this.$set(this.starActives, index, true); + this.$set(this.starItems, index, this.starItems[index] + 1); } - }) + }); } }, getTypeList() { - const params = new URLSearchParams(window.location.search) - if (window.location.search && params.has('type')) { - if (params.get('type') == 0) { - this.datasetType = '0' + const params = new URLSearchParams(window.location.search); + if (window.location.search && params.has("type")) { + if (params.get("type") == 0) { + this.datasetType = "0"; } - if (params.get('type') == 1) { - this.datasetType = '1' + if (params.get("type") == 1) { + this.datasetType = "1"; } - if (params.get('type') == -1) { - this.datasetType = '-1' + if (params.get("type") == -1) { + this.datasetType = "-1"; } } else { - this.datasetType = '-1' + this.datasetType = "-1"; } }, changeDatasetType(val) { - const searchParams = new URLSearchParams(window.location.search) + const searchParams = new URLSearchParams(window.location.search); if (!window.location.search) { - window.location.href = window.location.href + '?type=' + val - } else if (searchParams.has('type')) { - window.location.href = window.location.href.replace(/type=([0-9]|-[0-9])/g, 'type=' + val) + window.location.href = window.location.href + "?type=" + val; + } else if (searchParams.has("type")) { + window.location.href = window.location.href.replace( + /type=([0-9]|-[0-9])/g, + "type=" + val + ); } else { - window.location.href = window.location.href + '&type=' + val + window.location.href = window.location.href + "&type=" + val; } - - }, gotoDatasetEidt(repolink, id) { - location.href = `${repolink}/datasets/attachments/edit/${id}` - + location.href = `${repolink}/datasets/attachments/edit/${id}`; }, handleClick(repoLink, tabName, type) { if (tabName == "first") { - this.page = 1 - this.searchDataItem = '' - this.getCurrentRepoDataset(repoLink, type) - + this.page = 1; + this.searchDataItem = ""; + this.getCurrentRepoDataset(repoLink, type); } if (tabName == "second") { - this.page = 1 - this.searchDataItem = '' - this.getMyDataset(repoLink, type) + this.page = 1; + this.searchDataItem = ""; + this.getMyDataset(repoLink, type); } if (tabName == "third") { - this.page = 1 - this.searchDataItem = '' - this.getPublicDataset(repoLink, type) + this.page = 1; + this.searchDataItem = ""; + this.getPublicDataset(repoLink, type); } if (tabName == "fourth") { - this.page = 1 - this.searchDataItem = '' - this.getStarDataset(repoLink, type) + this.page = 1; + this.searchDataItem = ""; + this.getStarDataset(repoLink, type); } }, polling(checkStatuDataset, repoLink) { this.timer = window.setInterval(() => { setTimeout(() => { - this.getDatasetStatus(checkStatuDataset, repoLink) - }, 0) - }, 15000) - + this.getDatasetStatus(checkStatuDataset, repoLink); + }, 0); + }, 15000); }, getDatasetStatus(checkStatuDataset, repoLink) { const getmap = checkStatuDataset.map((item) => { - let url = `${AppSubUrl}${repolink}/datasets/status/${item.UUID}` - return this.$axios.get(url) - }) - this.$axios.all(getmap) - .then((res) => { - let flag = res.some((item) => { - return item.data.AttachmentStatus == 1 - }) - flag && clearInterval(this.timer) - flag && this.refreshStatusDataset() - - } - ) - + let url = `${AppSubUrl}${repolink}/datasets/status/${item.UUID}`; + return this.$axios.get(url); + }); + this.$axios.all(getmap).then((res) => { + let flag = res.some((item) => { + return item.data.AttachmentStatus == 1; + }); + flag && clearInterval(this.timer); + flag && this.refreshStatusDataset(); + }); }, refreshStatusDataset() { switch (this.activeName) { - case 'first': - this.getCurrentRepoDataset(this.repolink, this.cloudbrainType) - break - case 'second': - this.getMyDataset(this.repolink, this.cloudbrainType) - break - case 'third': - this.getPublicDataset(this.repolink, this.cloudbrainType) - break - case 'fourth': - this.getStarDataset(this.repolink, this.cloudbrainType) - break + case "first": + this.getCurrentRepoDataset(this.repolink, this.cloudbrainType); + break; + case "second": + this.getMyDataset(this.repolink, this.cloudbrainType); + break; + case "third": + this.getPublicDataset(this.repolink, this.cloudbrainType); + break; + case "fourth": + this.getStarDataset(this.repolink, this.cloudbrainType); + break; } }, getCurrentRepoDataset(repoLink, type) { - - clearInterval(this.timer) - this.loadingDataIndex = true - let url = repoLink + '/datasets/current_repo' - this.$axios.get(url, { - params: { - type: type, - page: this.page, - q: this.searchDataItem - } - }).then((res) => { - if (res.data.result_code == '0') { - this.currentRepoDataset = JSON.parse(res.data.data) - const checkStatuDataset = this.currentRepoDataset.filter(item => item.DecompressState === 2) - if (checkStatuDataset.length > 0) { - this.polling(checkStatuDataset, repoLink) + clearInterval(this.timer); + this.loadingDataIndex = true; + let url = repoLink + "/datasets/current_repo"; + this.$axios + .get(url, { + params: { + type: type, + page: this.page, + q: this.searchDataItem, + }, + }) + .then((res) => { + if (res.data.result_code == "0") { + this.currentRepoDataset = JSON.parse(res.data.data); + const checkStatuDataset = this.currentRepoDataset.filter( + (item) => item.DecompressState === 2 + ); + if (checkStatuDataset.length > 0) { + this.polling(checkStatuDataset, repoLink); + } + this.totalnums = parseInt(res.data.count); + } else { + this.totalnums = 0; } - this.totalnums = parseInt(res.data.count) - } else { - this.totalnums = 0 - } - this.loadingDataIndex = false - }) + this.loadingDataIndex = false; + }); }, getMyDataset(repoLink, type) { - clearInterval(this.timer) - this.loadingDataIndex = true - let url = repoLink + '/datasets/my_datasets' - this.$axios.get(url, { - params: { - type: type, - page: this.page, - q: this.searchDataItem - } - }).then((res) => { - this.myDataset = JSON.parse(res.data.data) - const checkStatuDataset = this.myDataset.filter(item => item.DecompressState === 2) - if (checkStatuDataset.length > 0) { - this.polling(checkStatuDataset, repoLink) - } - this.totalnums = parseInt(res.data.count) - this.loadingDataIndex = false - }) - + clearInterval(this.timer); + this.loadingDataIndex = true; + let url = repoLink + "/datasets/my_datasets"; + this.$axios + .get(url, { + params: { + type: type, + page: this.page, + q: this.searchDataItem, + }, + }) + .then((res) => { + this.myDataset = JSON.parse(res.data.data); + const checkStatuDataset = this.myDataset.filter( + (item) => item.DecompressState === 2 + ); + if (checkStatuDataset.length > 0) { + this.polling(checkStatuDataset, repoLink); + } + this.totalnums = parseInt(res.data.count); + this.loadingDataIndex = false; + }); }, getPublicDataset(repoLink, type) { - clearInterval(this.timer) - this.loadingDataIndex = true - let url = repoLink + '/datasets/public_datasets' - this.$axios.get(url, { - params: { - type: type, - page: this.page, - q: this.searchDataItem - } - }).then((res) => { - this.publicDataset = JSON.parse(res.data.data) - const checkStatuDataset = this.publicDataset.filter(item => item.DecompressState === 2) - if (checkStatuDataset.length > 0) { - this.polling(checkStatuDataset, repoLink) - } - this.totalnums = parseInt(res.data.count) - this.loadingDataIndex = false - }) - + clearInterval(this.timer); + this.loadingDataIndex = true; + let url = repoLink + "/datasets/public_datasets"; + this.$axios + .get(url, { + params: { + type: type, + page: this.page, + q: this.searchDataItem, + }, + }) + .then((res) => { + this.publicDataset = JSON.parse(res.data.data); + const checkStatuDataset = this.publicDataset.filter( + (item) => item.DecompressState === 2 + ); + if (checkStatuDataset.length > 0) { + this.polling(checkStatuDataset, repoLink); + } + this.totalnums = parseInt(res.data.count); + this.loadingDataIndex = false; + }); }, getStarDataset(repoLink, type) { - clearInterval(this.timer) - this.loadingDataIndex = true - let url = repoLink + '/datasets/my_favorite' - this.$axios.get(url, { - params: { - type: type, - page: this.page, - q: this.searchDataItem - } - }).then((res) => { - this.myFavoriteDataset = JSON.parse(res.data.data) - const checkStatuDataset = this.myFavoriteDataset.filter(item => item.DecompressState === 2) - if (checkStatuDataset.length > 0) { - this.polling(checkStatuDataset, repoLink) - } - this.totalnums = parseInt(res.data.count) - this.loadingDataIndex = false - }) - + clearInterval(this.timer); + this.loadingDataIndex = true; + let url = repoLink + "/datasets/my_favorite"; + this.$axios + .get(url, { + params: { + type: type, + page: this.page, + q: this.searchDataItem, + }, + }) + .then((res) => { + this.myFavoriteDataset = JSON.parse(res.data.data); + const checkStatuDataset = this.myFavoriteDataset.filter( + (item) => item.DecompressState === 2 + ); + if (checkStatuDataset.length > 0) { + this.polling(checkStatuDataset, repoLink); + } + this.totalnums = parseInt(res.data.count); + this.loadingDataIndex = false; + }); }, selectDataset(uuid, name) { - this.dataset_uuid = uuid - this.dataset_name = name - this.dialogVisible = false + this.dataset_uuid = uuid; + this.dataset_name = name; + this.dialogVisible = false; }, searchDataset() { switch (this.activeName) { - case 'first': - this.page = 1 - this.getCurrentRepoDataset(this.repolink, this.cloudbrainType) - break - case 'second': - this.page = 1 - this.getMyDataset(this.repolink, this.cloudbrainType) - break - case 'third': - this.page = 1 - this.getPublicDataset(this.repolink, this.cloudbrainType) - break - case 'fourth': - this.page = 1 - this.getStarDataset(this.repolink, this.cloudbrainType) - break + case "first": + this.page = 1; + this.getCurrentRepoDataset(this.repolink, this.cloudbrainType); + break; + case "second": + this.page = 1; + this.getMyDataset(this.repolink, this.cloudbrainType); + break; + case "third": + this.page = 1; + this.getPublicDataset(this.repolink, this.cloudbrainType); + break; + case "fourth": + this.page = 1; + this.getStarDataset(this.repolink, this.cloudbrainType); + break; } - } + }, }, watch: { searchDataItem() { switch (this.activeName) { - case 'first': - this.page = 1 - this.getCurrentRepoDataset(this.repolink, this.cloudbrainType) - break - case 'second': - this.page = 1 - this.getMyDataset(this.repolink, this.cloudbrainType) - break - case 'third': - this.page = 1 - this.getPublicDataset(this.repolink, this.cloudbrainType) - break - case 'fourth': - this.page = 1 - this.getStarDataset(this.repolink, this.cloudbrainType) - break + case "first": + this.page = 1; + this.getCurrentRepoDataset(this.repolink, this.cloudbrainType); + break; + case "second": + this.page = 1; + this.getMyDataset(this.repolink, this.cloudbrainType); + break; + case "third": + this.page = 1; + this.getPublicDataset(this.repolink, this.cloudbrainType); + break; + case "fourth": + this.page = 1; + this.getStarDataset(this.repolink, this.cloudbrainType); + break; } - } - + }, }, }); - } function initVueEditTopic() { - const el = document.getElementById('topic_edit1'); + const el = document.getElementById("topic_edit1"); if (!el) { return; } new Vue({ - el: '#topic_edit1', - render: h => h(EditTopics) - }) + el: "#topic_edit1", + render: (h) => h(EditTopics), + }); } function initVueContributors() { - const el = document.getElementById('Contributors'); + const el = document.getElementById("Contributors"); if (!el) { return; } new Vue({ - el: '#Contributors', - render: h => h(Contributors) - }) + el: "#Contributors", + render: (h) => h(Contributors), + }); } - // function initVueImages() { // const el = document.getElementById('images'); - // if (!el) { // return; // } @@ -4529,8 +4483,7 @@ function initVueContributors() { // }); // } function initVueModel() { - const el = document.getElementById('model_list'); - + const el = document.getElementById("model_list"); if (!el) { return; @@ -4539,91 +4492,100 @@ function initVueModel() { new Vue({ el: el, - render: h => h(Model) + render: (h) => h(Model), }); } function initVueDataAnalysis() { - const el = document.getElementById('data_analysis'); + const el = document.getElementById("data_analysis"); if (!el) { return; } new Vue({ - el: '#data_analysis', + el: "#data_analysis", router, - render: h => h(DataAnalysis) + render: (h) => h(DataAnalysis), }); } function initVueWxAutorize() { - const el = document.getElementById('WxAutorize'); + const el = document.getElementById("WxAutorize"); if (!el) { return; } new Vue({ el: el, - render: h => h(WxAutorize) + render: (h) => h(WxAutorize), + }); +} +function initVueselectDataset() { + const el = document.getElementById("select-multi-dataset"); + if (!el) { + return; + } + new Vue({ + el: el, + render: (h) => h(selectDataset), }); } - window.timeAddManual = function () { - $('.mini.modal') + $(".mini.modal") .modal({ duration: 200, onApprove() { - $('#add_time_manual_form').trigger('submit'); - } + $("#add_time_manual_form").trigger("submit"); + }, }) - .modal('show'); + .modal("show"); }; window.toggleStopwatch = function () { - $('#toggle_stopwatch_form').trigger('submit'); + $("#toggle_stopwatch_form").trigger("submit"); }; window.cancelStopwatch = function () { - $('#cancel_stopwatch_form').trigger('submit'); + $("#cancel_stopwatch_form").trigger("submit"); }; function initFilterBranchTagDropdown(selector) { $(selector).each(function () { const $dropdown = $(this); - const $data = $dropdown.find('.data'); + const $data = $dropdown.find(".data"); const data = { items: [], - mode: $data.data('mode'), - searchTerm: '', - noResults: '', + mode: $data.data("mode"), + searchTerm: "", + noResults: "", canCreateBranch: false, menuVisible: false, - active: 0 + active: 0, }; - $data.find('.item').each(function () { + $data.find(".item").each(function () { data.items.push({ name: $(this).text(), - url: $(this).data('url'), - branch: $(this).hasClass('branch'), - tag: $(this).hasClass('tag'), - selected: $(this).hasClass('selected') + url: $(this).data("url"), + branch: $(this).hasClass("branch"), + tag: $(this).hasClass("tag"), + selected: $(this).hasClass("selected"), }); }); $data.remove(); new Vue({ - delimiters: ['${', '}'], + delimiters: ["${", "}"], el: this, data, beforeMount() { const vm = this; - this.noResults = vm.$el.getAttribute('data-no-results'); + this.noResults = vm.$el.getAttribute("data-no-results"); this.canCreateBranch = - vm.$el.getAttribute('data-can-create-branch') === 'true'; + vm.$el.getAttribute("data-can-create-branch") === "true"; - document.body.addEventListener('click', (event) => { + document.body.addEventListener("click", (event) => { if (vm.$el.contains(event.target)) { return; } if (vm.menuVisible) { - Vue.set(vm, 'menuVisible', false); + Vue.set(vm, "menuVisible", false); } }); }, @@ -4633,7 +4595,7 @@ function initFilterBranchTagDropdown(selector) { if (visible) { this.focusSearchField(); } - } + }, }, computed: { @@ -4642,8 +4604,8 @@ function initFilterBranchTagDropdown(selector) { const items = vm.items.filter((item) => { return ( - ((vm.mode === 'branches' && item.branch) || - (vm.mode === 'tags' && item.tag)) && + ((vm.mode === "branches" && item.branch) || + (vm.mode === "tags" && item.tag)) && (!vm.searchTerm || item.name.toLowerCase().includes(vm.searchTerm.toLowerCase())) ); @@ -4658,7 +4620,7 @@ function initFilterBranchTagDropdown(selector) { }, showCreateNewBranch() { const vm = this; - if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') { + if (!this.canCreateBranch || !vm.searchTerm || vm.mode === "tags") { return false; } @@ -4667,7 +4629,7 @@ function initFilterBranchTagDropdown(selector) { (item) => item.name.toLowerCase() === vm.searchTerm.toLowerCase() ).length === 0 ); - } + }, }, methods: { @@ -4683,7 +4645,7 @@ function initFilterBranchTagDropdown(selector) { if (!this.showCreateNewBranch) { return; } - $(this.$refs.newBranchForm).trigger('submit'); + $(this.$refs.newBranchForm).trigger("submit"); }, focusSearchField() { const vm = this; @@ -4771,111 +4733,107 @@ function initFilterBranchTagDropdown(selector) { event.preventDefault(); vm.menuVisible = false; } - } - } + }, + }, }); }); } -$('.commit-button').on('click', function (e) { +$(".commit-button").on("click", function (e) { e.preventDefault(); - $(this) - .parent() - .find('.commit-body') - .toggle(); + $(this).parent().find(".commit-body").toggle(); }); function initNavbarContentToggle() { - const content = $('#navbar'); - const toggle = $('#navbar-expand-toggle'); + const content = $("#navbar"); + const toggle = $("#navbar-expand-toggle"); let isExpanded = false; - toggle.on('click', () => { + toggle.on("click", () => { isExpanded = !isExpanded; if (isExpanded) { - content.addClass('shown'); - toggle.addClass('active'); + content.addClass("shown"); + toggle.addClass("active"); } else { - content.removeClass('shown'); - toggle.removeClass('active'); + content.removeClass("shown"); + toggle.removeClass("active"); } }); } - window.toggleDeadlineForm = function () { - $('#deadlineForm').fadeToggle(150); + $("#deadlineForm").fadeToggle(150); }; window.setDeadline = function () { - const deadline = $('#deadlineDate').val(); + const deadline = $("#deadlineDate").val(); window.updateDeadline(deadline); }; window.updateDeadline = function (deadlineString) { - $('#deadline-err-invalid-date').hide(); - $('#deadline-loader').addClass('loading'); + $("#deadline-err-invalid-date").hide(); + $("#deadline-loader").addClass("loading"); let realDeadline = null; - if (deadlineString !== '') { + if (deadlineString !== "") { const newDate = Date.parse(deadlineString); if (Number.isNaN(newDate)) { - $('#deadline-loader').removeClass('loading'); - $('#deadline-err-invalid-date').show(); + $("#deadline-loader").removeClass("loading"); + $("#deadline-err-invalid-date").show(); return false; } realDeadline = new Date(newDate); } - $.ajax(`${$('#update-issue-deadline-form').attr('action')}/deadline`, { + $.ajax(`${$("#update-issue-deadline-form").attr("action")}/deadline`, { data: JSON.stringify({ - due_date: realDeadline + due_date: realDeadline, }), headers: { - 'X-Csrf-Token': csrf, - 'X-Remote': true + "X-Csrf-Token": csrf, + "X-Remote": true, }, - contentType: 'application/json', - type: 'POST', + contentType: "application/json", + type: "POST", success() { reload(); }, error() { - $('#deadline-loader').removeClass('loading'); - $('#deadline-err-invalid-date').show(); - } + $("#deadline-loader").removeClass("loading"); + $("#deadline-err-invalid-date").show(); + }, }); }; window.deleteDependencyModal = function (id, type) { - $('.remove-dependency') + $(".remove-dependency") .modal({ closable: false, duration: 200, onApprove() { - $('#removeDependencyID').val(id); - $('#dependencyType').val(type); - $('#removeDependencyForm').trigger('submit'); - } + $("#removeDependencyID").val(id); + $("#dependencyType").val(type); + $("#removeDependencyForm").trigger("submit"); + }, }) - .modal('show'); + .modal("show"); }; function initIssueList() { - const repolink = $('#repolink').val(); - const repoId = $('#repoId').val(); - const crossRepoSearch = $('#crossRepoSearch').val(); - const tp = $('#type').val(); + const repolink = $("#repolink").val(); + const repoId = $("#repoId").val(); + const crossRepoSearch = $("#crossRepoSearch").val(); + const tp = $("#type").val(); let issueSearchUrl = `${AppSubUrl}/api/v1/repos/${repolink}/issues?q={query}&type=${tp}`; - if (crossRepoSearch === 'true') { + if (crossRepoSearch === "true") { issueSearchUrl = `${AppSubUrl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`; } - $('#new-dependency-drop-list').dropdown({ + $("#new-dependency-drop-list").dropdown({ apiSettings: { url: issueSearchUrl, onResponse(response) { const filteredResponse = { success: true, results: [] }; - const currIssueId = $('#new-dependency-drop-list').data('issue-id'); + const currIssueId = $("#new-dependency-drop-list").data("issue-id"); // Parse the response from the api to work with our dropdown $.each(response, (_i, issue) => { // Don't list current issue in the dependency list. @@ -4888,47 +4846,47 @@ function initIssueList() { )}
${htmlEncode( issue.repository.full_name )}
`, - value: issue.id + value: issue.id, }); }); return filteredResponse; }, - cache: false + cache: false, }, - fullTextSearch: true + fullTextSearch: true, }); - $('.menu a.label-filter-item').each(function () { - $(this).on('click', function (e) { + $(".menu a.label-filter-item").each(function () { + $(this).on("click", function (e) { if (e.altKey) { e.preventDefault(); - const href = $(this).attr('href'); - const id = $(this).data('label-id'); + const href = $(this).attr("href"); + const id = $(this).data("label-id"); const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`; - const newStr = 'labels=$1-$2$3&'; + const newStr = "labels=$1-$2$3&"; window.location = href.replace(new RegExp(regStr), newStr); } }); }); - $('.menu .ui.dropdown.label-filter').on('keydown', (e) => { + $(".menu .ui.dropdown.label-filter").on("keydown", (e) => { if (e.altKey && e.keyCode === 13) { const selectedItems = $( - '.menu .ui.dropdown.label-filter .menu .item.selected' + ".menu .ui.dropdown.label-filter .menu .item.selected" ); if (selectedItems.length > 0) { const item = $(selectedItems[0]); - const href = item.attr('href'); - const id = item.data('label-id'); + const href = item.attr("href"); + const id = item.data("label-id"); const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`; - const newStr = 'labels=$1-$2$3&'; + const newStr = "labels=$1-$2$3&"; window.location = href.replace(new RegExp(regStr), newStr); } @@ -4936,36 +4894,33 @@ function initIssueList() { }); } window.cancelCodeComment = function (btn) { - const form = $(btn).closest('form'); - if (form.length > 0 && form.hasClass('comment-form')) { - form.addClass('hide'); - form - .parent() - .find('button.comment-form-reply') - .show(); + const form = $(btn).closest("form"); + if (form.length > 0 && form.hasClass("comment-form")) { + form.addClass("hide"); + form.parent().find("button.comment-form-reply").show(); } else { - form.closest('.comment-code-cloud').remove(); + form.closest(".comment-code-cloud").remove(); } }; window.submitReply = function (btn) { - const form = $(btn).closest('form'); - if (form.length > 0 && form.hasClass('comment-form')) { - form.trigger('submit'); + const form = $(btn).closest("form"); + if (form.length > 0 && form.hasClass("comment-form")) { + form.trigger("submit"); } }; window.onOAuthLoginClick = function () { - const oauthLoader = $('#oauth2-login-loader'); - const oauthNav = $('#oauth2-login-navigator'); + const oauthLoader = $("#oauth2-login-loader"); + const oauthNav = $("#oauth2-login-navigator"); oauthNav.hide(); - oauthLoader.removeClass('disabled'); + oauthLoader.removeClass("disabled"); setTimeout(() => { // recover previous content to let user try again // usually redirection will be performed before this action - oauthLoader.addClass('disabled'); + oauthLoader.addClass("disabled"); oauthNav.show(); }, 5000); }; @@ -4973,24 +4928,29 @@ window.onOAuthLoginClick = function () { // Pull SVGs via AJAX to workaround CORS issues with tags // https://css-tricks.com/ajaxing-svg-sprite/ $.get(`${window.config.StaticUrlPrefix}/img/svg/icons.svg`, (data) => { - const div = document.createElement('div'); - div.style.display = 'none'; + const div = document.createElement("div"); + div.style.display = "none"; div.innerHTML = new XMLSerializer().serializeToString(data.documentElement); document.body.insertBefore(div, document.body.childNodes[0]); }); function initDropDown() { $("#dropdown_PageHome").dropdown({ - on: 'hover',//鼠标悬浮显示,默认值是click + on: "hover", //鼠标悬浮显示,默认值是click }); $("#dropdown_explore").dropdown({ - on: 'hover',//鼠标悬浮显示,默认值是click + on: "hover", //鼠标悬浮显示,默认值是click }); } //云脑提示 -$('.question.circle.icon.cloudbrain-question').hover(function () { - $(this).popup('show') - $('.ui.popup.mini.top.center').css({ "border-color": 'rgba(50, 145, 248, 100)', "color": "rgba(3, 102, 214, 100)", "border-radius": "5px", "border-shadow": "none" }) +$(".question.circle.icon.cloudbrain-question").hover(function () { + $(this).popup("show"); + $(".ui.popup.mini.top.center").css({ + "border-color": "rgba(50, 145, 248, 100)", + color: "rgba(3, 102, 214, 100)", + "border-radius": "5px", + "border-shadow": "none", + }); }); //云脑详情页面跳转回上一个页面 @@ -5000,179 +4960,195 @@ $('.question.circle.icon.cloudbrain-question').hover(function () { function initcreateRepo() { let timeout; - let keydown_flag = false - const urlAdd = location.href.split('/')[0] + '//' + location.href.split('/')[2] - let owner = $('#ownerDropdown div.text').attr("title") + let keydown_flag = false; + const urlAdd = + location.href.split("/")[0] + "//" + location.href.split("/")[2]; + let owner = $("#ownerDropdown div.text").attr("title"); $(document).ready(function () { - $('#ownerDropdown').dropdown({ + $("#ownerDropdown").dropdown({ onChange: function (value, text, $choice) { - owner = $choice[0].getAttribute("title") - $('#repoAdress').css("display", "flex") - $('#repoAdress span').text(urlAdd + '/' + owner + '/' + $('#repo_name').val() + '.git') - } + owner = $choice[0].getAttribute("title"); + $("#repoAdress").css("display", "flex"); + $("#repoAdress span").text( + urlAdd + "/" + owner + "/" + $("#repo_name").val() + ".git" + ); + }, }); - }) - $('#repo_name').keyup(function () { - keydown_flag = $('#repo_name').val() ? true : false + }); + $("#repo_name").keyup(function () { + keydown_flag = $("#repo_name").val() ? true : false; if (keydown_flag) { - $('#repoAdress').css("display", "flex") - $('#repoAdress span').text(urlAdd + '/' + owner + '/' + $('#repo_name').val() + '.git') - } - else { - $('#repoAdress').css("display", "none") - $('#repo_name').attr("placeholder", "") + $("#repoAdress").css("display", "flex"); + $("#repoAdress span").text( + urlAdd + "/" + owner + "/" + $("#repo_name").val() + ".git" + ); + } else { + $("#repoAdress").css("display", "none"); + $("#repo_name").attr("placeholder", ""); } - }) - $("#create_repo_form") - .form({ - on: 'blur', - // inline:true, - fields: { - alias: { - identifier: 'alias', - rules: [ - { - type: 'regExp[/^[\u4E00-\u9FA5A-Za-z0-9_.-]{1,100}$/]', - } - ] - }, - repo_name: { - identifier: 'repo_name', - rules: [ - { - type: 'regExp[/^[A-Za-z0-9_.-]{1,100}$/]', - - } - ] - }, + }); + $("#create_repo_form").form({ + on: "blur", + // inline:true, + fields: { + alias: { + identifier: "alias", + rules: [ + { + type: "regExp[/^[\u4E00-\u9FA5A-Za-z0-9_.-]{1,100}$/]", + }, + ], }, - onFailure: function (e) { - return false; - } - }) - $('#alias').bind('input propertychange', function (event) { - clearTimeout(timeout) + repo_name: { + identifier: "repo_name", + rules: [ + { + type: "regExp[/^[A-Za-z0-9_.-]{1,100}$/]", + }, + ], + }, + }, + onFailure: function (e) { + return false; + }, + }); + $("#alias").bind("input propertychange", function (event) { + clearTimeout(timeout); timeout = setTimeout(() => { //在此处写调用的方法,可以实现仅最后一次操作生效 - const aliasValue = $('#alias').val() + const aliasValue = $("#alias").val(); if (keydown_flag) { - $('#repo_name').attr("placeholder", "") - } - else if (aliasValue) { - $('#repo_name').attr("placeholder", "正在获取路径...") - $.get(`${window.config.AppSubUrl}/repo/check_name?q=${aliasValue}&owner=${owner}`, (data) => { - const repo_name = data.name - $('#repo_name').val(repo_name) - repo_name && $('#repo_name').parent().removeClass('error') - $('#repoAdress').css("display", "flex") - $('#repoAdress span').text(urlAdd + '/' + owner + '/' + $('#repo_name').val() + '.git') - $('#repo_name').attr("placeholder", "") - }) + $("#repo_name").attr("placeholder", ""); + } else if (aliasValue) { + $("#repo_name").attr("placeholder", "正在获取路径..."); + $.get( + `${window.config.AppSubUrl}/repo/check_name?q=${aliasValue}&owner=${owner}`, + (data) => { + const repo_name = data.name; + $("#repo_name").val(repo_name); + repo_name && $("#repo_name").parent().removeClass("error"); + $("#repoAdress").css("display", "flex"); + $("#repoAdress span").text( + urlAdd + "/" + owner + "/" + $("#repo_name").val() + ".git" + ); + $("#repo_name").attr("placeholder", ""); + } + ); } else { - $('#repo_name').val('') - $('#repo_name').attr("placeholder", "") - $('#repoAdress').css("display", "none") + $("#repo_name").val(""); + $("#repo_name").attr("placeholder", ""); + $("#repoAdress").css("display", "none"); } - }, 500) + }, 500); }); } -initcreateRepo() - +initcreateRepo(); function initChartsNpu() { - const url = window.location.href - const urlArr = url.split('/') - let userName = urlArr.slice(-5)[0] - let repoPath = urlArr.slice(-4)[0] - let jobID = urlArr.slice(-1)[0] - + const url = window.location.href; + const urlArr = url.split("/"); + let userName = urlArr.slice(-5)[0]; + let repoPath = urlArr.slice(-4)[0]; + let jobID = urlArr.slice(-1)[0]; let options = { legend: { - data: [] + data: [], }, grid: { - top: '35%', - bottom: '2%', - x: '2%', - containLabel: true + top: "35%", + bottom: "2%", + x: "2%", + containLabel: true, }, tooltip: { - trigger: 'axis', - backgroundColor: 'rgb(51, 56, 84)', - borderColor: 'rgb(51, 51, 51)', + trigger: "axis", + backgroundColor: "rgb(51, 56, 84)", + borderColor: "rgb(51, 51, 51)", borderWidth: 0, textStyle: { - color: '#fff' + color: "#fff", }, axisPointer: { - type: 'line' - } + type: "line", + }, }, xAxis: { - type: 'category', + type: "category", data: [], boundaryGap: false, axisLabel: { - interval: 'auto' + interval: "auto", }, - name: '时间(min)' + name: "时间(min)", }, yAxis: { - show: true, - name: '占有率(%)', + name: "占有率(%)", axisLine: { - show: true + show: true, }, - axisTick: { show: true } + axisTick: { show: true }, }, - series: [] + series: [], }; - const sortBy = (arr, k) => arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0)); - $('.metric_chart').click(function (e) { - let versionName = $(this).data('version') - let myCharts = echarts.init(document.getElementById(`metric-${versionName}`)) - $.get(`${window.config.AppSubUrl}/api/v1/repos/${userName}/${repoPath}/modelarts/train-job/${jobID}/metric_statistics?version_name=${versionName}&statistic_type=each&metrics=`, (res) => { - let filterDta = res.MetricsInfo.filter((item) => { - - return !(['recvBytesRate', 'diskWriteRate', 'sendBytesRate', 'diskReadRate'].includes(item.metric)) - }) - filterDta = sortBy(filterDta, "metric") - let legenData = filterDta.map((item) => { - return item.metric - }) - let seriesData = filterDta.map((item) => { - let value = item.value.map((item) => { return item > 0 ? item : '0' }) - let seriesOption = { - name: item.metric, - type: 'line', - symbol: 'circle', - symbolSize: 10, - smooth: true, - showSymbol: false, - lineStyle: { - width: 2, - shadowColor: 'rgba(0,0,0,0.3)', - shadowBlur: 10, - shadowOffsetY: 8 - }, - data: value - } - return seriesOption - }) - let xLength = res.MetricsInfo[0].value.length - options.xAxis.data = Array.from({ length: xLength }, (_, index) => index) - options.legend.data = legenData - options.series = seriesData - options && myCharts.setOption(options); - - }) + const sortBy = (arr, k) => + arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0)); + $(".metric_chart").click(function (e) { + let versionName = $(this).data("version"); + let myCharts = echarts.init( + document.getElementById(`metric-${versionName}`) + ); + $.get( + `${window.config.AppSubUrl}/api/v1/repos/${userName}/${repoPath}/modelarts/train-job/${jobID}/metric_statistics?version_name=${versionName}&statistic_type=each&metrics=`, + (res) => { + let filterDta = res.MetricsInfo.filter((item) => { + return ![ + "recvBytesRate", + "diskWriteRate", + "sendBytesRate", + "diskReadRate", + ].includes(item.metric); + }); + filterDta = sortBy(filterDta, "metric"); + let legenData = filterDta.map((item) => { + return item.metric; + }); + let seriesData = filterDta.map((item) => { + let value = item.value.map((item) => { + return item > 0 ? item : "0"; + }); + let seriesOption = { + name: item.metric, + type: "line", + symbol: "circle", + symbolSize: 10, + smooth: true, + showSymbol: false, + lineStyle: { + width: 2, + shadowColor: "rgba(0,0,0,0.3)", + shadowBlur: 10, + shadowOffsetY: 8, + }, + data: value, + }; + return seriesOption; + }); + let xLength = res.MetricsInfo[0].value.length; + options.xAxis.data = Array.from( + { length: xLength }, + (_, index) => index + ); + options.legend.data = legenData; + options.series = seriesData; + options && myCharts.setOption(options); + } + ); options && myCharts.setOption(options); - - }) + }); } -initChartsNpu() \ No newline at end of file +initChartsNpu(); -- 2.34.1 From 7dc20ff4b8e23ae97062bb6e7e6bc2f0bb954136 Mon Sep 17 00:00:00 2001 From: Gitea Date: Sat, 25 Jun 2022 19:12:07 +0800 Subject: [PATCH 09/35] fix issue --- .../js/components/dataset/selectDataset.vue | 163 ++++++++++++++---- 1 file changed, 129 insertions(+), 34 deletions(-) diff --git a/web_src/js/components/dataset/selectDataset.vue b/web_src/js/components/dataset/selectDataset.vue index 1ecbf88f81..91266de197 100644 --- a/web_src/js/components/dataset/selectDataset.vue +++ b/web_src/js/components/dataset/selectDataset.vue @@ -76,9 +76,9 @@ > - +
- {{ data.desc }} + {{ data.Description }}
{{ node.label }} @@ -88,11 +88,11 @@ >{{ node.label }} chen/datset{{data.Repo.OwnerName}}/{{data.Repo.Alias}}
{{ node.label }} @@ -132,9 +132,9 @@ > - +
- {{ data.desc }} + {{ data.Description }}
{{ node.label }} @@ -144,11 +144,11 @@ >{{ node.label }} chen/datset{{data.Repo.OwnerName}}/{{data.Repo.Alias}}
{{ node.label }} @@ -192,9 +192,9 @@ > - +
- {{ data.desc }} + {{ data.Description }}
{{ node.label }} @@ -204,11 +204,11 @@ >{{ node.label }} chen/datset{{data.Repo.OwnerName}}/{{data.Repo.Alias}}
{{ node.label }} @@ -252,9 +252,9 @@ > - +
- {{ data.desc }} + {{ data.Description }}
{{ node.label }} @@ -264,11 +264,11 @@ >{{ node.label }} chen/datset{{data.Repo.OwnerName}}/{{data.Repo.Alias}}
{{ node.label }} @@ -320,6 +320,7 @@ v-for="(item, index) in selectDatasetArray" :key="index" :label="item.label" + :title="item.label" @change="(checked) => changeCheckbox(checked, item)" > @@ -530,6 +531,8 @@ export default { selectDatasetArray: [], checkList: [], checkList1: [], + + saveStutusCheck:[], //当前项目数据集页面配置的初始化 initCurrentPage: 1, totalNumCurrent: 0, @@ -648,6 +651,16 @@ export default { this.checkList1 = this.selectDatasetArray.map((item) => { return item.id; }); + console.log() + this.saveStutusCheck = this.selectDatasetArray.reduce((pre,cur)=>{ + let checkedKeys={} + checkedKeys.treeRef = cur.ref + checkedKeys.id=cur.id + checkedKeys.page = cur.page + pre.push(checkedKeys) + return pre + },[]) + console.log("this.saveStutusCheck",this.saveStutusCheck) console.log(this.selectDatasetArray, this.checkList); }, // onMyCheck(data, checkedInfo) { @@ -687,12 +700,49 @@ export default { //已选择数据集checkbox group 勾选事件 changeCheckbox(checked, data) { console.log(checked, data); - if (this.data[0].children.some((item) => item.id === data.id)) { - console.log("----is data-----------"); - this.$refs.currentTree.setChecked(data.id, false, false); - } else if (this.data1[0].children.some((item) => item.id === data.id)) { - console.log("----is data1-----------"); - this.$refs.myTree.setChecked(data.id, false, false); + + // if (this.data[0].children.some((item) => item.id === data.id)) { + // console.log("----is data-----------"); + // this.$refs.currentTree.setChecked(data.id, false, false); + // } else if (this.data1[0].children.some((item) => item.id === data.id)) { + // console.log("----is data1-----------"); + // this.$refs.myTree.setChecked(data.id, false, false); + // } + + switch(data.ref){ + case "currentTree": + { + this.$refs.currentTree.setChecked(data.id, false, false); + let index = this.saveStutusCheck.findIndex((item) => { + return item.id === data.id; + }); + index!==-1&&this.saveStutusCheck.splice(index, 1); + } + case "myTree": + { + this.$refs.myTree.setChecked(data.id, false, false); + let index = this.saveStutusCheck.findIndex((item) => { + return item.id === data.id; + }); + index!==-1&&this.saveStutusCheck.splice(index, 1); + } + case "publicTree": + { + this.$refs.publicTree.setChecked(data.id, false, false); + let index = this.saveStutusCheck.findIndex((item) => { + return item.id === data.id; + }); + index!==-1&&this.saveStutusCheck.splice(index, 1); + } + case "favoriteTree": + { + this.$refs.myTree.setChecked(data.id, false, false); + let index = this.saveStutusCheck.findIndex((item) => { + return item.id === data.id; + }); + index!==-1&&this.saveStutusCheck.splice(index, 1); + } + default: } let index = this.selectDatasetArray.findIndex((item) => { @@ -742,14 +792,22 @@ export default { console.log(data); this.currentDatasetList = this.transformeTreeData( data, - "currentTree" + "currentTree", + this.paramsCurrent.page ); this.initCurrentTreeNode = [this.currentDatasetList[0].id]; console.log("this.initCurrentTreeNode", this.initCurrentTreeNode); this.totalNumCurrent = parseInt(res.data.count); console.log(this.selectDatasetArray); - this.$refs.currentTree.setCheckedKeys(this.checkList1); console.log("this.currentDatasetList:", this.currentDatasetList); + let setCheckedKeysList=this.saveStutusCheck.reduce((pre,cur)=>{ + if(cur.treeRef==='currentTree' && cur.page===this.paramsCurrent.page){ + pre.push(cur.id) + } + return pre + },[]) + console.log("setCheckedKeysList",setCheckedKeysList) + this.$refs.currentTree.setCheckedKeys(setCheckedKeysList); }) .catch(function (error) { this.loadingCurrent = false; @@ -769,13 +827,23 @@ export default { console.log(res); let data = JSON.parse(res.data.data); console.log(data); - this.myDatasetList = this.transformeTreeData(data, "myTree"); + this.myDatasetList = this.transformeTreeData(data, "myTree",this.paramsMy.page); this.initMyTreeNode = [this.myDatasetList[0].id]; this.totalNumMy = parseInt(res.data.count); console.log("this.myDatasetList:", this.myDatasetList); + console.log("this.aveStutusCheck:", this.saveStutusCheck) + let setCheckedKeysList=this.saveStutusCheck.reduce((pre,cur)=>{ + if(cur.treeRef==='myTree' && cur.page===this.paramsMy.page){ + pre.push(cur.id) + } + return pre + },[]) + console.log("setCheckedKeysList",setCheckedKeysList) + this.$refs.myTree.setCheckedKeys(setCheckedKeysList); + }) .catch(function (error) { - this.loadingMy = false; + console.log(error); }); }, @@ -793,10 +861,18 @@ export default { console.log(res); let data = JSON.parse(res.data.data); console.log(data); - this.publicDatasetList = this.transformeTreeData(data, "publicTree"); + this.publicDatasetList = this.transformeTreeData(data, "publicTree",this.paramsPublics.page); this.initPublicTreeNode = [this.publicDatasetList[0].id]; this.totalNumPublic = parseInt(res.data.count); console.log("this.publicDatasetList:", this.publicDatasetList); + let setCheckedKeysList=this.saveStutusCheck.reduce((pre,cur)=>{ + if(cur.treeRef==='publicTree' && cur.page===this.paramsPublics.page){ + pre.push(cur.id) + } + return pre + },[]) + console.log("setCheckedKeysList",setCheckedKeysList) + this.$refs.publicTree.setCheckedKeys(setCheckedKeysList); }) .catch(function (error) { this.loadingPublic = false; @@ -810,7 +886,7 @@ export default { this.paramsFavorite.type = this.type; this.$axios .get(url, { - params: this.paramsCurrent, + params: this.paramsFavorite, }) .then((res) => { this.loadingFavorite = false; @@ -819,7 +895,8 @@ export default { console.log(data); this.MyFavoriteDatasetList = this.transformeTreeData( data, - "favoriteTree" + "favoriteTree", + this.paramsFavorite.page ); this.initFavoriteTreeNode = [this.MyFavoriteDatasetList[0].id]; this.totalNumFavorite = parseInt(res.data.count); @@ -827,13 +904,21 @@ export default { "this.MyFavoriteDatasetList:", this.MyFavoriteDatasetList ); + let setCheckedKeysList=this.saveStutusCheck.reduce((pre,cur)=>{ + if(cur.treeRef==='favoriteTree' && cur.page===this.paramsFavorite.page){ + pre.push(cur.id) + } + return pre + },[]) + console.log("setCheckedKeysList",setCheckedKeysList) + this.$refs.favoriteTree.setCheckedKeys(setCheckedKeysList); }) .catch(function (error) { this.loadingFavorite = false; console.log(error); }); }, - transformeTreeData(data, ref) { + transformeTreeData(data, ref,page) { return data.reduce((preParent, curParent) => { curParent.id = `paraent-${curParent.ID}`; curParent.disabled = true; @@ -843,6 +928,7 @@ export default { (preChild, curchild) => { curchild.id = `chilrden-${ref}-${curchild.ID}`; curchild.ref = ref; + curchild.page = page if (curchild.DecompressState !== 1) { curchild.disabled = true; } @@ -1004,6 +1090,15 @@ export default { line-height: 20px; font-size: 12px; } +/deep/ .el-checkbox-group .el-checkbox{ + max-width: 100%; +} +/deep/ .el-checkbox-group .el-checkbox .el-checkbox__label{ + max-width:100%; + overflow: hidden; + vertical-align: middle; + text-overflow: ellipsis; +} .dataset-nowrap { overflow: hidden; text-overflow: ellipsis; -- 2.34.1 From a3392bb772188f6a6460a28940610c48944646b9 Mon Sep 17 00:00:00 2001 From: lewis <747342561@qq.com> Date: Mon, 27 Jun 2022 11:21:40 +0800 Subject: [PATCH 10/35] gpu debug --- modules/cloudbrain/cloudbrain.go | 111 +++++++++++++++++----------- routers/repo/cloudbrain.go | 123 +++++++++++++++++++++++++++---- 2 files changed, 175 insertions(+), 59 deletions(-) diff --git a/modules/cloudbrain/cloudbrain.go b/modules/cloudbrain/cloudbrain.go index 8fb13ca4c1..bf17619558 100755 --- a/modules/cloudbrain/cloudbrain.go +++ b/modules/cloudbrain/cloudbrain.go @@ -44,6 +44,31 @@ var ( TrainResourceSpecs *models.ResourceSpecs ) +type GenerateCloudBrainTaskReq struct { + Ctx *context.Context + DisplayJobName string + JobName string + Image string + Command string + Uuids string + CodePath string + ModelPath string + BenchmarkPath string + Snn4ImageNetPath string + BrainScorePath string + JobType string + GpuQueue string + Description string + BranchName string + BootFile string + Params string + CommitID string + DataLocalPath string + BenchmarkTypeID int + BenchmarkChildTypeID int + ResourceSpecId int +} + func isAdminOrOwnerOrJobCreater(ctx *context.Context, job *models.Cloudbrain, err error) bool { if !ctx.IsSigned { return false @@ -187,23 +212,23 @@ func AdminOrImageCreaterRight(ctx *context.Context) { } -func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, uuid, codePath, modelPath, benchmarkPath, snn4imagenetPath, brainScorePath, jobType, gpuQueue, description, branchName, bootFile, params, commitID string, benchmarkTypeID, benchmarkChildTypeID, resourceSpecId int) error { +func GenerateTask(req GenerateCloudBrainTaskReq) error { dataActualPath := setting.Attachment.Minio.RealPath + setting.Attachment.Minio.Bucket + "/" + setting.Attachment.Minio.BasePath + - models.AttachmentRelativePath(uuid) + - uuid + models.AttachmentRelativePath(req.Uuids) + + req.Uuids var resourceSpec *models.ResourceSpec var versionCount int - if jobType == string(models.JobTypeTrain) { + if req.JobType == string(models.JobTypeTrain) { versionCount = 1 if TrainResourceSpecs == nil { json.Unmarshal([]byte(setting.TrainResourceSpecs), &TrainResourceSpecs) } for _, spec := range TrainResourceSpecs.ResourceSpec { - if resourceSpecId == spec.Id { + if req.ResourceSpecId == spec.Id { resourceSpec = spec } } @@ -212,7 +237,7 @@ func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, json.Unmarshal([]byte(setting.ResourceSpecs), &ResourceSpecs) } for _, spec := range ResourceSpecs.ResourceSpec { - if resourceSpecId == spec.Id { + if req.ResourceSpecId == spec.Id { resourceSpec = spec } } @@ -220,25 +245,25 @@ func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, } if resourceSpec == nil { - log.Error("no such resourceSpecId(%d)", resourceSpecId, ctx.Data["MsgID"]) + log.Error("no such resourceSpecId(%d)", req.ResourceSpecId, req.Ctx.Data["MsgID"]) return errors.New("no such resourceSpec") } var datasetName string - attach, err := models.GetAttachmentByUUID(uuid) + attach, err := models.GetAttachmentByUUID(req.Uuids) if err != nil { //for benchmark, do not return error - log.Error("GetAttachmentByUUID failed:%v", err) + log.Error("GetAttachmentByUUID failed:%v", err, req.Ctx.Data["MsgID"]) } else { datasetName = attach.Name } createTime := timeutil.TimeStampNow() - jobResult, err := CreateJob(jobName, models.CreateJobParams{ - JobName: jobName, + jobResult, err := CreateJob(req.JobName, models.CreateJobParams{ + JobName: req.JobName, RetryCount: 1, - GpuType: gpuQueue, - Image: image, + GpuType: req.GpuQueue, + Image: req.Image, TaskRoles: []models.TaskRole{ { Name: SubTaskName, @@ -249,7 +274,7 @@ func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, GPUNumber: resourceSpec.GpuNum, MemoryMB: resourceSpec.MemMiB, ShmMB: resourceSpec.ShareMemMiB, - Command: command, + Command: req.Command, NeedIBDevice: false, IsMainRole: false, UseNNI: false, @@ -258,7 +283,7 @@ func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, Volumes: []models.Volume{ { HostPath: models.StHostPath{ - Path: codePath, + Path: req.CodePath, MountPath: CodeMountPath, ReadOnly: false, }, @@ -272,28 +297,28 @@ func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, }, { HostPath: models.StHostPath{ - Path: modelPath, + Path: req.ModelPath, MountPath: ModelMountPath, ReadOnly: false, }, }, { HostPath: models.StHostPath{ - Path: benchmarkPath, + Path: req.BenchmarkPath, MountPath: BenchMarkMountPath, ReadOnly: true, }, }, { HostPath: models.StHostPath{ - Path: snn4imagenetPath, + Path: req.Snn4ImageNetPath, MountPath: Snn4imagenetMountPath, ReadOnly: true, }, }, { HostPath: models.StHostPath{ - Path: brainScorePath, + Path: req.BrainScorePath, MountPath: BrainScoreMountPath, ReadOnly: true, }, @@ -301,42 +326,42 @@ func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, }, }) if err != nil { - log.Error("CreateJob failed:", err.Error(), ctx.Data["MsgID"]) + log.Error("CreateJob failed:", err.Error(), req.Ctx.Data["MsgID"]) return err } if jobResult.Code != Success { - log.Error("CreateJob(%s) failed:%s", jobName, jobResult.Msg, ctx.Data["MsgID"]) + log.Error("CreateJob(%s) failed:%s", req.JobName, jobResult.Msg, req.Ctx.Data["MsgID"]) return errors.New(jobResult.Msg) } var jobID = jobResult.Payload["jobId"].(string) err = models.CreateCloudbrain(&models.Cloudbrain{ Status: string(models.JobWaiting), - UserID: ctx.User.ID, - RepoID: ctx.Repo.Repository.ID, + UserID: req.Ctx.User.ID, + RepoID: req.Ctx.Repo.Repository.ID, JobID: jobID, - JobName: jobName, - DisplayJobName: displayJobName, + JobName: req.JobName, + DisplayJobName: req.DisplayJobName, SubTaskName: SubTaskName, - JobType: jobType, + JobType: req.JobType, Type: models.TypeCloudBrainOne, - Uuid: uuid, - Image: image, - GpuQueue: gpuQueue, - ResourceSpecId: resourceSpecId, + Uuid: req.Uuids, + Image: req.Image, + GpuQueue: req.GpuQueue, + ResourceSpecId: req.ResourceSpecId, ComputeResource: models.GPUResource, - BenchmarkTypeID: benchmarkTypeID, - BenchmarkChildTypeID: benchmarkChildTypeID, - Description: description, + BenchmarkTypeID: req.BenchmarkTypeID, + BenchmarkChildTypeID: req.BenchmarkChildTypeID, + Description: req.Description, IsLatestVersion: "1", VersionCount: versionCount, - BranchName: branchName, - BootFile: bootFile, + BranchName: req.BranchName, + BootFile: req.BootFile, DatasetName: datasetName, - Parameters: params, + Parameters: req.Params, CreatedUnix: createTime, UpdatedUnix: createTime, - CommitID: commitID, + CommitID: req.CommitID, }) if err != nil { @@ -345,17 +370,17 @@ func GenerateTask(ctx *context.Context, displayJobName, jobName, image, command, task, err := models.GetCloudbrainByJobID(jobID) if err != nil { - log.Error("GetCloudbrainByName failed: %v", err.Error()) + log.Error("GetCloudbrainByJobID failed: %v", err.Error()) return err } stringId := strconv.FormatInt(task.ID, 10) - if IsBenchmarkJob(jobType) { - notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, stringId, displayJobName, models.ActionCreateBenchMarkTask) - } else if string(models.JobTypeTrain) == jobType { - notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, jobID, displayJobName, models.ActionCreateGPUTrainTask) + if IsBenchmarkJob(req.JobType) { + notification.NotifyOtherTask(req.Ctx.User, req.Ctx.Repo.Repository, stringId, req.DisplayJobName, models.ActionCreateBenchMarkTask) + } else if string(models.JobTypeTrain) == req.JobType { + notification.NotifyOtherTask(req.Ctx.User, req.Ctx.Repo.Repository, jobID, req.DisplayJobName, models.ActionCreateGPUTrainTask) } else { - notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, stringId, displayJobName, models.ActionCreateDebugGPUTask) + notification.NotifyOtherTask(req.Ctx.User, req.Ctx.Repo.Repository, stringId, req.DisplayJobName, models.ActionCreateDebugGPUTask) } return nil diff --git a/routers/repo/cloudbrain.go b/routers/repo/cloudbrain.go index eb2ddc93b6..479d1076bf 100755 --- a/routers/repo/cloudbrain.go +++ b/routers/repo/cloudbrain.go @@ -207,7 +207,7 @@ func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) { displayJobName := form.DisplayJobName jobName := util.ConvertDisplayJobNameToJobName(displayJobName) image := strings.TrimSpace(form.Image) - uuid := form.Attachment + uuids := form.Attachment jobType := form.JobType gpuQueue := form.GpuType codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath @@ -273,6 +273,13 @@ func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) { } } + if err = checkDatasetLimit(uuids); err != nil { + log.Error("checkDatasetLimit failed: %v", err, ctx.Data["MsgID"]) + cloudBrainNewDataPrepare(ctx) + ctx.RenderWithErr("checkDatasetLimit failed", tpl, &form) + return + } + if branchName == "" { branchName = cloudbrain.DefaultBranchName } @@ -285,11 +292,31 @@ func CloudBrainCreate(ctx *context.Context, form auth.CreateCloudBrainForm) { commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName) - err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, form.Description, branchName, form.BootFile, form.Params, - commitID, 0, 0, resourceSpecId) + req := cloudbrain.GenerateCloudBrainTaskReq{ + Ctx: ctx, + DisplayJobName: displayJobName, + JobName: jobName, + Image: image, + Command: command, + Uuids: uuids, + CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"), + ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"), + BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), + Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"), + BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), + JobType: jobType, + GpuQueue: gpuQueue, + Description: form.Description, + BranchName: branchName, + BootFile: form.BootFile, + Params: form.Params, + CommitID: commitID, + BenchmarkTypeID: 0, + BenchmarkChildTypeID: 0, + ResourceSpecId: resourceSpecId, + } + + err = cloudbrain.GenerateTask(req) if err != nil { cloudBrainNewDataPrepare(ctx) ctx.RenderWithErr(err.Error(), tpl, &form) @@ -1982,11 +2009,31 @@ func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainFo //return } - err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, childInfo.Attachment, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), string(models.JobTypeBenchmark), gpuQueue, form.Description, cloudbrain.DefaultBranchName, "", "", - "", benchmarkTypeID, benchmarkChildTypeID, resourceSpecId) + req := cloudbrain.GenerateCloudBrainTaskReq{ + Ctx: ctx, + DisplayJobName: displayJobName, + JobName: jobName, + Image: image, + Command: command, + Uuids: childInfo.Attachment, + CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"), + ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"), + BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), + Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"), + BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), + JobType: string(models.JobTypeBenchmark), + GpuQueue: gpuQueue, + Description: form.Description, + BranchName: cloudbrain.DefaultBranchName, + BootFile: "", + Params: "", + CommitID: "", + BenchmarkTypeID: benchmarkTypeID, + BenchmarkChildTypeID: benchmarkChildTypeID, + ResourceSpecId: resourceSpecId, + } + + err = cloudbrain.GenerateTask(req) if err != nil { cloudBrainNewDataPrepare(ctx) ctx.RenderWithErr(err.Error(), tplCloudBrainBenchmarkNew, &form) @@ -2080,11 +2127,31 @@ func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, trimSpaceNewlineInString(form.Description)) } - err = cloudbrain.GenerateTask(ctx, displayJobName, jobName, image, command, uuid, storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"), - storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), jobType, gpuQueue, form.Description, branchName, form.BootFile, form.Params, - "", 0, benchmarkChildTypeID, resourceSpecId) + req := cloudbrain.GenerateCloudBrainTaskReq{ + Ctx: ctx, + DisplayJobName: displayJobName, + JobName: jobName, + Image: image, + Command: command, + Uuids: uuid, + CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"), + ModelPath: storage.GetMinioPath(jobName, cloudbrain.ModelMountPath+"/"), + BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"), + Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"), + BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"), + JobType: jobType, + GpuQueue: gpuQueue, + Description: form.Description, + BranchName: branchName, + BootFile: form.BootFile, + Params: form.Params, + CommitID: "", + BenchmarkTypeID: 0, + BenchmarkChildTypeID: benchmarkChildTypeID, + ResourceSpecId: resourceSpecId, + } + + err = cloudbrain.GenerateTask(req) if err != nil { cloudBrainNewDataPrepare(ctx) ctx.RenderWithErr(err.Error(), tpl, &form) @@ -2195,3 +2262,27 @@ func GetBenchmarkTypes(ctx *context.Context) *models.BenchmarkTypes { } return benchmarkTypesMap[lang] } + +func checkDatasetLimit(uuidStr string) error { + uuids := strings.Split(uuidStr, ";") + if len(uuids) > 5 { + log.Error("the dataset count(%d) exceed the limit", len(uuids)) + return errors.New("the dataset count exceed the limit") + } + + attachNames := make(map[string]string) + for _, uuid := range uuids { + attach, err := models.GetAttachmentByUUID(uuid) + if err != nil { + log.Error("GetAttachmentByUUID failed: %v", err) + return err + } + + if _, ok := attachNames[attach.Name]; ok { + log.Error("the dataset name is same: %v", attach.Name) + return errors.New("the dataset name is same") + } + attachNames[attach.Name] = attach.Name + } + return nil +} -- 2.34.1 From c7c241ceff086ca403c513e16eb00136c6b00a01 Mon Sep 17 00:00:00 2001 From: lewis <747342561@qq.com> Date: Mon, 27 Jun 2022 14:37:38 +0800 Subject: [PATCH 11/35] debug --- routers/repo/cloudbrain.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/routers/repo/cloudbrain.go b/routers/repo/cloudbrain.go index 479d1076bf..f3f2fddb0b 100755 --- a/routers/repo/cloudbrain.go +++ b/routers/repo/cloudbrain.go @@ -2009,6 +2009,12 @@ func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainFo //return } + dataActualPath := setting.Attachment.Minio.RealPath + + setting.Attachment.Minio.Bucket + "/" + + setting.Attachment.Minio.BasePath + + models.AttachmentRelativePath(childInfo.Attachment) + + childInfo.Attachment + req := cloudbrain.GenerateCloudBrainTaskReq{ Ctx: ctx, DisplayJobName: displayJobName, @@ -2031,6 +2037,7 @@ func BenchMarkAlgorithmCreate(ctx *context.Context, form auth.CreateCloudBrainFo BenchmarkTypeID: benchmarkTypeID, BenchmarkChildTypeID: benchmarkChildTypeID, ResourceSpecId: resourceSpecId, + DataLocalPath: dataActualPath, } err = cloudbrain.GenerateTask(req) @@ -2127,6 +2134,12 @@ func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) command = fmt.Sprintf(cloudbrain.BrainScoreCommand, getBrainRegion(benchmarkChildTypeID), displayJobName, trimSpaceNewlineInString(form.Description)) } + dataActualPath := setting.Attachment.Minio.RealPath + + setting.Attachment.Minio.Bucket + "/" + + setting.Attachment.Minio.BasePath + + models.AttachmentRelativePath(uuid) + + uuid + req := cloudbrain.GenerateCloudBrainTaskReq{ Ctx: ctx, DisplayJobName: displayJobName, @@ -2149,6 +2162,7 @@ func ModelBenchmarkCreate(ctx *context.Context, form auth.CreateCloudBrainForm) BenchmarkTypeID: 0, BenchmarkChildTypeID: benchmarkChildTypeID, ResourceSpecId: resourceSpecId, + DataLocalPath: dataActualPath, } err = cloudbrain.GenerateTask(req) -- 2.34.1 From 86dc428350e22250dd7640e54f47db88634ea80f Mon Sep 17 00:00:00 2001 From: zhoupzh Date: Mon, 27 Jun 2022 16:15:30 +0800 Subject: [PATCH 12/35] fix issue --- templates/repo/cloudbrain/trainjob/new.tmpl | 79 +- templates/repo/modelarts/trainjob/new.tmpl | 62 +- .../js/components/dataset/selectDataset.vue | 738 ++++---- web_src/js/components/images/selectImages.vue | 917 ++++++---- web_src/less/openi.less | 1565 +++++++++-------- 5 files changed, 1787 insertions(+), 1574 deletions(-) diff --git a/templates/repo/cloudbrain/trainjob/new.tmpl b/templates/repo/cloudbrain/trainjob/new.tmpl index 18a3403985..dbc4dbdd7d 100755 --- a/templates/repo/cloudbrain/trainjob/new.tmpl +++ b/templates/repo/cloudbrain/trainjob/new.tmpl @@ -1,22 +1,12 @@ {{template "base/head" .}} -
-
- +
+ {{if .bootFile}} @@ -213,9 +195,9 @@ 训练脚本存储在/code中,数据集存储在/dataset中,训练输出请存储在/model中以供后续下载。 -
- + style="margin-left: 11.5rem;margin-bottom: 1rem;">训练脚本存储在/code中,数据集存储在/dataset中,训练输出请存储在/model中以供后续下载。 +
+ {{.i18n.Tr "repo.modelarts.train_job.add_run_parameter"}} @@ -242,8 +224,8 @@
-
- +
+
-
+
+ diff --git a/templates/repo/modelarts/trainjob/new.tmpl b/templates/repo/modelarts/trainjob/new.tmpl index cff51c524f..c1a5c8e302 100755 --- a/templates/repo/modelarts/trainjob/new.tmpl +++ b/templates/repo/modelarts/trainjob/new.tmpl @@ -19,6 +19,9 @@ .width{ width:100% !important; } +.width48{ + width: 48.5% !important; +} .width80{ width: 80.7% !important; margin-left: 10px; @@ -49,7 +52,13 @@ text-align: center; color: #C2C7CC; } - +.label-fix-width{ + width: 140px !important; + text-align: right; + font-family: SourceHanSansSC-medium !important; + color: rgba(16, 16, 16, 100) !important; + font-size: 14px !important; + } 训练脚本存储在/code中,数据集存储在/dataset中,训练输出请存储在/model中以供后续下载。 -
+
-
+

{{.i18n.Tr "repo.modelarts.train_job.basic_info"}}:

-
+
-
+
{{.i18n.Tr "cloudbrain.job_name_rule"}}
-
+
@@ -150,7 +122,7 @@

{{.i18n.Tr "repo.modelarts.train_job.parameter_setting"}}:

-
+
@@ -194,7 +166,7 @@
-
+
{{if .bootFile}} @@ -211,7 +183,7 @@
{{.i18n.Tr "cloudbrain.dataset_path_rule"}} -
+
{{.i18n.Tr "repo.modelarts.train_job.add_run_parameter"}} @@ -236,7 +208,7 @@
-