config.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. var value string
  84. id, err := reflectutils.Get(obj, "ID")
  85. if err == nil && len(fmt.Sprint(id)) > 0 && fmt.Sprint(id) != "0" {
  86. value = field.Value(obj).(l10n.Locale).GetLocale()
  87. } else {
  88. value = lb.GetCorrectLocaleCode(ctx.R)
  89. }
  90. return h.Input("").Type("hidden").Value(value).Attr(web.VFieldName("LocaleCode")...)
  91. }).
  92. SetterFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) (err error) {
  93. value := field.Value(obj).(l10n.Locale).GetLocale()
  94. if !utils.Contains(lb.GetSupportLocaleCodesFromRequest(ctx.R), value) {
  95. return errors.New("Incorrect locale.")
  96. }
  97. return nil
  98. })
  99. b.AddWrapHandler(WrapHandlerKey, lb.EnsureLocale)
  100. b.AddMenuTopItemFunc(MenuTopItemFunc, runSwitchLocaleFunc(lb))
  101. b.I18n().
  102. RegisterForModule(language.English, I18nLocalizeKey, Messages_en_US).
  103. RegisterForModule(language.SimplifiedChinese, I18nLocalizeKey, Messages_zh_CN).
  104. RegisterForModule(language.Japanese, I18nLocalizeKey, Messages_ja_JP)
  105. }
  106. func localeListFunc(db *gorm.DB, lb *l10n.Builder) func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  107. return func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  108. id, err := reflectutils.Get(obj, "ID")
  109. if err != nil {
  110. return nil
  111. }
  112. fromLocale := lb.GetCorrectLocaleCode(ctx.R)
  113. objs := reflect.New(reflect.SliceOf(reflect.TypeOf(obj).Elem())).Interface()
  114. err = db.Distinct("locale_code").Where("id = ? AND locale_code <> ?", id, fromLocale).Find(objs).Error
  115. if err != nil {
  116. return nil
  117. }
  118. vo := reflect.ValueOf(objs).Elem()
  119. var existLocales []string
  120. for i := 0; i < vo.Len(); i++ {
  121. existLocales = append(existLocales, vo.Index(i).FieldByName("LocaleCode").String())
  122. }
  123. allLocales := lb.GetSupportLocaleCodesFromRequest(ctx.R)
  124. var otherLocales []string
  125. for _, locale := range allLocales {
  126. if utils.Contains(existLocales, locale) {
  127. otherLocales = append(otherLocales, locale)
  128. }
  129. }
  130. var chips []h.HTMLComponent
  131. chips = append(chips, v.VChip(h.Text(MustGetTranslation(ctx.R, lb.GetLocaleLabel(fromLocale)))).Color("green").TextColor("white").Label(true).Small(true))
  132. for _, locale := range otherLocales {
  133. chips = append(chips, v.VChip(h.Text(MustGetTranslation(ctx.R, lb.GetLocaleLabel(locale)))).Label(true).Small(true))
  134. }
  135. return h.Td(
  136. chips...,
  137. )
  138. }
  139. }
  140. func runSwitchLocaleFunc(lb *l10n.Builder) func(ctx *web.EventContext) (r h.HTMLComponent) {
  141. return func(ctx *web.EventContext) (r h.HTMLComponent) {
  142. var supportLocales = lb.GetSupportLocaleCodesFromRequest(ctx.R)
  143. if len(lb.GetSupportLocaleCodes()) <= 1 || len(supportLocales) == 0 {
  144. return nil
  145. }
  146. localeQueryName := lb.GetQueryName()
  147. if len(supportLocales) == 1 {
  148. return h.Template().Children(
  149. h.Div(
  150. v.VList(
  151. v.VListItem(
  152. v.VListItemIcon(
  153. v.VIcon("language").Small(true).Class("ml-1"),
  154. ).Attr("style", "margin-right: 16px"),
  155. v.VListItemContent(
  156. v.VListItemTitle(
  157. 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"),
  158. ),
  159. ),
  160. ).Class("pa-0").Dense(true),
  161. ).Class("pa-0 ma-n4 mt-n6"),
  162. ).Attr("@click", web.Plaid().Query(localeQueryName, supportLocales[0]).Go()),
  163. )
  164. }
  165. locale := lb.GetCorrectLocaleCode(ctx.R)
  166. var locales []h.HTMLComponent
  167. for _, contry := range supportLocales {
  168. locales = append(locales,
  169. h.Div(
  170. v.VListItem(
  171. v.VListItemContent(
  172. v.VListItemTitle(
  173. h.Div(h.Text(MustGetTranslation(ctx.R, lb.GetLocaleLabel(contry)))),
  174. ),
  175. ),
  176. ).Attr("@click", web.Plaid().Query(localeQueryName, contry).Go()),
  177. ),
  178. )
  179. }
  180. return v.VMenu().OffsetY(true).Children(
  181. h.Template().Attr("v-slot:activator", "{on, attrs}").Children(
  182. h.Div(
  183. v.VList(
  184. v.VListItem(
  185. v.VListItemIcon(
  186. v.VIcon("language").Small(true).Class("ml-1"),
  187. ).Attr("style", "margin-right: 16px"),
  188. v.VListItemContent(
  189. v.VListItemTitle(
  190. h.Text(fmt.Sprintf("%s%s %s", MustGetTranslation(ctx.R, "Location"), MustGetTranslation(ctx.R, "Colon"), MustGetTranslation(ctx.R, lb.GetLocaleLabel(locale)))),
  191. ),
  192. ),
  193. v.VListItemIcon(
  194. v.VIcon("arrow_drop_down").Small(false).Class("mr-1"),
  195. ),
  196. ).Class("pa-0").Dense(true),
  197. ).Class("pa-0 ma-n4 mt-n6"),
  198. ).Attr("v-bind", "attrs").Attr("v-on", "on"),
  199. ),
  200. v.VList(
  201. locales...,
  202. ).Dense(true),
  203. )
  204. }
  205. }
  206. func localizeRowMenuItemFunc(mi *presets.ModelInfo, url string, editExtraParams url.Values) vx.RowMenuItemFunc {
  207. return func(obj interface{}, id string, ctx *web.EventContext) h.HTMLComponent {
  208. if mi.Verifier().Do(presets.PermUpdate).ObjectOn(obj).WithReq(ctx.R).IsAllowed() != nil {
  209. return nil
  210. }
  211. return v.VListItem(
  212. v.VListItemIcon(v.VIcon("language")),
  213. v.VListItemTitle(h.Text(MustGetTranslation(ctx.R, "Localize"))),
  214. ).Attr("@click", web.Plaid().
  215. EventFunc(Localize).
  216. Queries(editExtraParams).
  217. Query(presets.ParamID, id).
  218. URL(url).
  219. Go())
  220. }
  221. }