config.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package views
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/url"
  6. "reflect"
  7. "time"
  8. "github.com/qor5/admin/activity"
  9. "github.com/qor5/admin/l10n"
  10. "github.com/qor5/admin/presets"
  11. "github.com/qor5/admin/utils"
  12. v "github.com/qor5/ui/vuetify"
  13. vx "github.com/qor5/ui/vuetifyx"
  14. "github.com/qor5/web"
  15. "github.com/sunfmin/reflectutils"
  16. h "github.com/theplant/htmlgo"
  17. "golang.org/x/text/language"
  18. "gorm.io/gorm"
  19. )
  20. const WrapHandlerKey = "l10nWrapHandlerKey"
  21. const MenuTopItemFunc = "l10nMenuTopItemFunc"
  22. func Configure(b *presets.Builder, db *gorm.DB, lb *l10n.Builder, ab *activity.ActivityBuilder, models ...*presets.ModelBuilder) {
  23. for _, m := range models {
  24. obj := m.NewModel()
  25. _ = obj.(presets.SlugEncoder)
  26. _ = obj.(presets.SlugDecoder)
  27. _ = obj.(l10n.L10nInterface)
  28. if l10nONModel, exist := obj.(l10n.L10nONInterface); exist {
  29. l10nONModel.L10nON()
  30. }
  31. m.Listing().Field("Locale")
  32. m.Editing().Field("Locale")
  33. searcher := m.Listing().Searcher
  34. m.Listing().SearchFunc(func(model interface{}, params *presets.SearchParams, ctx *web.EventContext) (r interface{}, totalCount int, err error) {
  35. if localeCode := ctx.R.Context().Value(l10n.LocaleCode); localeCode != nil {
  36. con := presets.SQLCondition{
  37. Query: "locale_code = ?",
  38. Args: []interface{}{localeCode},
  39. }
  40. params.SQLConditions = append(params.SQLConditions, &con)
  41. }
  42. return searcher(model, params, ctx)
  43. })
  44. setter := m.Editing().Setter
  45. m.Editing().SetterFunc(func(obj interface{}, ctx *web.EventContext) {
  46. if ctx.R.FormValue(presets.ParamID) == "" {
  47. if localeCode := ctx.R.Context().Value(l10n.LocaleCode); localeCode != nil {
  48. if err := reflectutils.Set(obj, "LocaleCode", localeCode); err != nil {
  49. return
  50. }
  51. }
  52. }
  53. if setter != nil {
  54. setter(obj, ctx)
  55. }
  56. })
  57. deleter := m.Editing().Deleter
  58. m.Editing().DeleteFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  59. if err = deleter(obj, id, ctx); err != nil {
  60. return
  61. }
  62. Locale := obj.(presets.SlugDecoder).PrimaryColumnValuesBySlug(id)["locale_code"]
  63. Locale = fmt.Sprintf("%s(del:%d)", Locale, time.Now().UnixMilli())
  64. withoutKeys := []string{}
  65. if ctx.R.URL.Query().Get("all_versions") == "true" {
  66. withoutKeys = append(withoutKeys, "version")
  67. }
  68. if err = utils.PrimarySluggerWhere(db.Unscoped(), obj, id, withoutKeys...).Update("locale_code", Locale).Error; err != nil {
  69. return
  70. }
  71. return
  72. })
  73. rmb := m.Listing().RowMenu()
  74. rmb.RowMenuItem("Localize").ComponentFunc(localizeRowMenuItemFunc(m.Info(), "", url.Values{}))
  75. registerEventFuncs(db, m, lb, ab)
  76. }
  77. b.FieldDefaults(presets.LIST).
  78. FieldType(l10n.Locale{}).
  79. ComponentFunc(localeListFunc(db, lb))
  80. b.FieldDefaults(presets.WRITE).
  81. FieldType(l10n.Locale{}).
  82. ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  83. return h.Input("").Type("hidden").Value(field.Value(obj).(l10n.Locale).GetLocale()).Attr(web.VFieldName("LocaleCode")...)
  84. }).
  85. SetterFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) (err error) {
  86. value := field.Value(obj).(l10n.Locale).GetLocale()
  87. if !utils.Contains(lb.GetSupportLocaleCodesFromRequest(ctx.R), value) {
  88. return errors.New("Incorrect locale.")
  89. }
  90. return nil
  91. })
  92. b.AddWrapHandler(WrapHandlerKey, lb.EnsureLocale)
  93. b.AddMenuTopItemFunc(MenuTopItemFunc, runSwitchLocaleFunc(lb))
  94. b.I18n().
  95. RegisterForModule(language.English, I18nLocalizeKey, Messages_en_US).
  96. RegisterForModule(language.SimplifiedChinese, I18nLocalizeKey, Messages_zh_CN).
  97. RegisterForModule(language.Japanese, I18nLocalizeKey, Messages_ja_JP)
  98. }
  99. func localeListFunc(db *gorm.DB, lb *l10n.Builder) func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  100. return func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  101. id, err := reflectutils.Get(obj, "ID")
  102. if err != nil {
  103. return nil
  104. }
  105. fromLocale := lb.GetCorrectLocaleCode(ctx.R)
  106. objs := reflect.New(reflect.SliceOf(reflect.TypeOf(obj).Elem())).Interface()
  107. err = db.Distinct("locale_code").Where("id = ? AND locale_code <> ?", id, fromLocale).Find(objs).Error
  108. if err != nil {
  109. return nil
  110. }
  111. vo := reflect.ValueOf(objs).Elem()
  112. var existLocales []string
  113. for i := 0; i < vo.Len(); i++ {
  114. existLocales = append(existLocales, vo.Index(i).FieldByName("LocaleCode").String())
  115. }
  116. allLocales := lb.GetSupportLocaleCodesFromRequest(ctx.R)
  117. var otherLocales []string
  118. for _, locale := range allLocales {
  119. if utils.Contains(existLocales, locale) {
  120. otherLocales = append(otherLocales, locale)
  121. }
  122. }
  123. var chips []h.HTMLComponent
  124. chips = append(chips, v.VChip(h.Text(MustGetTranslation(ctx.R, lb.GetLocaleLabel(fromLocale)))).Color("green").TextColor("white").Label(true).Small(true))
  125. for _, locale := range otherLocales {
  126. chips = append(chips, v.VChip(h.Text(MustGetTranslation(ctx.R, lb.GetLocaleLabel(locale)))).Label(true).Small(true))
  127. }
  128. return h.Td(
  129. chips...,
  130. )
  131. }
  132. }
  133. func runSwitchLocaleFunc(lb *l10n.Builder) func(ctx *web.EventContext) (r h.HTMLComponent) {
  134. return func(ctx *web.EventContext) (r h.HTMLComponent) {
  135. var supportLocales = lb.GetSupportLocaleCodesFromRequest(ctx.R)
  136. if len(lb.GetSupportLocaleCodes()) <= 1 || len(supportLocales) == 0 {
  137. return nil
  138. }
  139. localeQueryName := lb.GetQueryName()
  140. if len(supportLocales) == 1 {
  141. return h.Template().Children(
  142. h.Div(
  143. v.VList(
  144. v.VListItem(
  145. v.VListItemIcon(
  146. v.VIcon("language").Small(true).Class("ml-1"),
  147. ).Attr("style", "margin-right: 16px"),
  148. v.VListItemContent(
  149. v.VListItemTitle(
  150. h.Div(h.Text(fmt.Sprintf("%s%s %s", MustGetTranslation(ctx.R, "Location"), MustGetTranslation(ctx.R, "Colon"), MustGetTranslation(ctx.R, lb.GetLocaleLabel(supportLocales[0]))))).Role("button"),
  151. ),
  152. ),
  153. ).Class("pa-0").Dense(true),
  154. ).Class("pa-0 ma-n4 mt-n6"),
  155. ).Attr("@click", web.Plaid().Query(localeQueryName, supportLocales[0]).Go()),
  156. )
  157. }
  158. locale := lb.GetCorrectLocaleCode(ctx.R)
  159. var locales []h.HTMLComponent
  160. for _, contry := range supportLocales {
  161. locales = append(locales,
  162. h.Div(
  163. v.VListItem(
  164. v.VListItemContent(
  165. v.VListItemTitle(
  166. h.Div(h.Text(MustGetTranslation(ctx.R, lb.GetLocaleLabel(contry)))),
  167. ),
  168. ),
  169. ).Attr("@click", web.Plaid().Query(localeQueryName, contry).Go()),
  170. ),
  171. )
  172. }
  173. return v.VMenu().OffsetY(true).Children(
  174. h.Template().Attr("v-slot:activator", "{on, attrs}").Children(
  175. h.Div(
  176. v.VList(
  177. v.VListItem(
  178. v.VListItemIcon(
  179. v.VIcon("language").Small(true).Class("ml-1"),
  180. ).Attr("style", "margin-right: 16px"),
  181. v.VListItemContent(
  182. v.VListItemTitle(
  183. h.Text(fmt.Sprintf("%s%s %s", MustGetTranslation(ctx.R, "Location"), MustGetTranslation(ctx.R, "Colon"), MustGetTranslation(ctx.R, lb.GetLocaleLabel(locale)))),
  184. ),
  185. ),
  186. v.VListItemIcon(
  187. v.VIcon("arrow_drop_down").Small(false).Class("mr-1"),
  188. ),
  189. ).Class("pa-0").Dense(true),
  190. ).Class("pa-0 ma-n4 mt-n6"),
  191. ).Attr("v-bind", "attrs").Attr("v-on", "on"),
  192. ),
  193. v.VList(
  194. locales...,
  195. ).Dense(true),
  196. )
  197. }
  198. }
  199. func localizeRowMenuItemFunc(mi *presets.ModelInfo, url string, editExtraParams url.Values) vx.RowMenuItemFunc {
  200. return func(obj interface{}, id string, ctx *web.EventContext) h.HTMLComponent {
  201. if mi.Verifier().Do(presets.PermUpdate).ObjectOn(obj).WithReq(ctx.R).IsAllowed() != nil {
  202. return nil
  203. }
  204. return v.VListItem(
  205. v.VListItemIcon(v.VIcon("language")),
  206. v.VListItemTitle(h.Text(MustGetTranslation(ctx.R, "Localize"))),
  207. ).Attr("@click", web.Plaid().
  208. EventFunc(Localize).
  209. Queries(editExtraParams).
  210. Query(presets.ParamID, id).
  211. URL(url).
  212. Go())
  213. }
  214. }