builder.go 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963
  1. package pagebuilder
  2. import (
  3. "errors"
  4. "fmt"
  5. "html/template"
  6. "net/http"
  7. "net/url"
  8. "path"
  9. "reflect"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "github.com/qor5/admin/activity"
  14. "github.com/qor5/admin/l10n"
  15. l10n_view "github.com/qor5/admin/l10n/views"
  16. mediav "github.com/qor5/admin/media/views"
  17. "github.com/qor5/admin/note"
  18. "github.com/qor5/admin/presets"
  19. "github.com/qor5/admin/presets/actions"
  20. "github.com/qor5/admin/presets/gorm2op"
  21. "github.com/qor5/admin/publish"
  22. "github.com/qor5/admin/publish/views"
  23. pv "github.com/qor5/admin/publish/views"
  24. "github.com/qor5/admin/seo"
  25. "github.com/qor5/admin/utils"
  26. . "github.com/qor5/ui/vuetify"
  27. vx "github.com/qor5/ui/vuetifyx"
  28. "github.com/qor5/web"
  29. "github.com/qor5/x/i18n"
  30. "github.com/qor5/x/perm"
  31. "github.com/sunfmin/reflectutils"
  32. h "github.com/theplant/htmlgo"
  33. "goji.io/pat"
  34. "golang.org/x/text/language"
  35. "gorm.io/gorm"
  36. )
  37. type RenderInput struct {
  38. IsEditor bool
  39. IsReadonly bool
  40. Device string
  41. }
  42. type RenderFunc func(obj interface{}, input *RenderInput, ctx *web.EventContext) h.HTMLComponent
  43. type PageLayoutFunc func(body h.HTMLComponent, input *PageLayoutInput, ctx *web.EventContext) h.HTMLComponent
  44. type PageLayoutInput struct {
  45. Page *Page
  46. SeoTags template.HTML
  47. CanonicalLink template.HTML
  48. StructuredData template.HTML
  49. FreeStyleCss []string
  50. FreeStyleTopJs []string
  51. FreeStyleBottomJs []string
  52. Header h.HTMLComponent
  53. Footer h.HTMLComponent
  54. IsEditor bool
  55. EditorCss []h.HTMLComponent
  56. IsPreview bool
  57. }
  58. type Builder struct {
  59. prefix string
  60. wb *web.Builder
  61. db *gorm.DB
  62. containerBuilders []*ContainerBuilder
  63. ps *presets.Builder
  64. mb *presets.ModelBuilder
  65. pageStyle h.HTMLComponent
  66. pageLayoutFunc PageLayoutFunc
  67. preview http.Handler
  68. images http.Handler
  69. imagesPrefix string
  70. defaultDevice string
  71. publishBtnColor string
  72. duplicateBtnColor string
  73. templateEnabled bool
  74. }
  75. const (
  76. openTemplateDialogEvent = "openTemplateDialogEvent"
  77. selectTemplateEvent = "selectTemplateEvent"
  78. // clearTemplateEvent = "clearTemplateEvent"
  79. republishRelatedOnlinePagesEvent = "republish_related_online_pages"
  80. schedulePublishDialogEvent = "schedulePublishDialogEvent"
  81. schedulePublishEvent = "schedulePublishEvent"
  82. createNoteDialogEvent = "createNoteDialogEvent"
  83. createNoteEvent = "createNoteEvent"
  84. editSEODialogEvent = "editSEODialogEvent"
  85. updateSEOEvent = "updateSEOEvent"
  86. selectVersionEvent = "selectVersionEvent"
  87. renameVersionDialogEvent = "renameVersionDialogEvent"
  88. renameVersionEvent = "renameVersionEvent"
  89. deleteVersionDialogEvent = "deleteVersionDialogEvent"
  90. paramOpenFromSharedContainer = "open_from_shared_container"
  91. )
  92. func New(prefix string, db *gorm.DB, i18nB *i18n.Builder) *Builder {
  93. err := db.AutoMigrate(
  94. &Page{},
  95. &Template{},
  96. &Container{},
  97. &DemoContainer{},
  98. &Category{},
  99. )
  100. if err != nil {
  101. panic(err)
  102. }
  103. // https://github.com/go-gorm/sqlite/blob/64917553e84d5482e252c7a0c8f798fb672d7668/ddlmod.go#L16
  104. // fxxk: newline is not allowed
  105. err = db.Exec(`
  106. create unique index if not exists uidx_page_builder_demo_containers_model_name_locale_code on page_builder_demo_containers (model_name, locale_code) where deleted_at is null;
  107. `).Error
  108. if err != nil {
  109. panic(err)
  110. }
  111. r := &Builder{
  112. db: db,
  113. wb: web.New(),
  114. prefix: prefix,
  115. defaultDevice: DeviceComputer,
  116. publishBtnColor: "primary",
  117. duplicateBtnColor: "primary",
  118. templateEnabled: true,
  119. }
  120. r.ps = presets.New().
  121. BrandTitle("Page Builder").
  122. DataOperator(gorm2op.DataOperator(db)).
  123. URIPrefix(prefix).
  124. LayoutFunc(r.pageEditorLayout).
  125. SetI18n(i18nB)
  126. type Editor struct {
  127. }
  128. r.ps.Model(&Editor{}).
  129. Detailing().
  130. PageFunc(r.Editor)
  131. r.ps.GetWebBuilder().RegisterEventFunc(AddContainerDialogEvent, r.AddContainerDialog)
  132. r.ps.GetWebBuilder().RegisterEventFunc(AddContainerEvent, r.AddContainer)
  133. r.ps.GetWebBuilder().RegisterEventFunc(DeleteContainerConfirmationEvent, r.DeleteContainerConfirmation)
  134. r.ps.GetWebBuilder().RegisterEventFunc(DeleteContainerEvent, r.DeleteContainer)
  135. r.ps.GetWebBuilder().RegisterEventFunc(MoveContainerEvent, r.MoveContainer)
  136. r.ps.GetWebBuilder().RegisterEventFunc(ToggleContainerVisibilityEvent, r.ToggleContainerVisibility)
  137. r.ps.GetWebBuilder().RegisterEventFunc(MarkAsSharedContainerEvent, r.MarkAsSharedContainer)
  138. r.ps.GetWebBuilder().RegisterEventFunc(RenameContainerDialogEvent, r.RenameContainerDialog)
  139. r.ps.GetWebBuilder().RegisterEventFunc(RenameContainerEvent, r.RenameContainer)
  140. r.preview = r.ps.GetWebBuilder().Page(r.Preview)
  141. return r
  142. }
  143. func (b *Builder) Prefix(v string) (r *Builder) {
  144. b.ps.URIPrefix(v)
  145. b.prefix = v
  146. return b
  147. }
  148. func (b *Builder) PageStyle(v h.HTMLComponent) (r *Builder) {
  149. b.pageStyle = v
  150. return b
  151. }
  152. func (b *Builder) PageLayout(v PageLayoutFunc) (r *Builder) {
  153. b.pageLayoutFunc = v
  154. return b
  155. }
  156. func (b *Builder) Images(v http.Handler, imagesPrefix string) (r *Builder) {
  157. b.images = v
  158. b.imagesPrefix = imagesPrefix
  159. return b
  160. }
  161. func (b *Builder) DefaultDevice(v string) (r *Builder) {
  162. b.defaultDevice = v
  163. return b
  164. }
  165. func (b *Builder) GetPresetsBuilder() (r *presets.Builder) {
  166. return b.ps
  167. }
  168. func (b *Builder) PublishBtnColor(v string) (r *Builder) {
  169. b.publishBtnColor = v
  170. return b
  171. }
  172. func (b *Builder) DuplicateBtnColor(v string) (r *Builder) {
  173. b.duplicateBtnColor = v
  174. return b
  175. }
  176. func (b *Builder) TemplateEnabled(v bool) (r *Builder) {
  177. b.templateEnabled = v
  178. return b
  179. }
  180. func (b *Builder) Configure(pb *presets.Builder, db *gorm.DB, l10nB *l10n.Builder, activityB *activity.ActivityBuilder, publisher *publish.Builder, seoCollection *seo.Collection) (pm *presets.ModelBuilder) {
  181. pb.I18n().
  182. RegisterForModule(language.English, I18nPageBuilderKey, Messages_en_US).
  183. RegisterForModule(language.SimplifiedChinese, I18nPageBuilderKey, Messages_zh_CN).
  184. RegisterForModule(language.Japanese, I18nPageBuilderKey, Messages_ja_JP)
  185. pm = pb.Model(&Page{})
  186. templateM := presets.NewModelBuilder(pb, &Template{})
  187. if b.templateEnabled {
  188. templateM = b.ConfigTemplate(pb, db)
  189. }
  190. b.mb = pm
  191. pm.Listing("ID", "Online", "Title", "Slug")
  192. dp := pm.Detailing("Overview")
  193. dp.Field("Overview").ComponentFunc(settings(db, pm))
  194. oldDetailLayout := pb.GetDetailLayoutFunc()
  195. pb.DetailLayoutFunc(func(in web.PageFunc, cfg *presets.LayoutConfig) (out web.PageFunc) {
  196. return func(ctx *web.EventContext) (pr web.PageResponse, err error) {
  197. if !strings.Contains(ctx.R.RequestURI, "/"+pm.Info().URIName()+"/") && !strings.Contains(ctx.R.RequestURI, "/"+templateM.Info().URIName()+"/") {
  198. pr, err = oldDetailLayout(in, cfg)(ctx)
  199. return
  200. }
  201. pb.InjectAssets(ctx)
  202. // call createMenus before in(ctx) to fill the menuGroupName for modelBuilders first
  203. menu := pb.CreateMenus(ctx)
  204. var profile h.HTMLComponent
  205. if pb.GetProfileFunc() != nil {
  206. profile = pb.GetProfileFunc()(ctx)
  207. }
  208. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  209. utilsMsgr := i18n.MustGetModuleMessages(ctx.R, utils.I18nUtilsKey, utils.Messages_en_US).(*utils.Messages)
  210. pvMsgr := i18n.MustGetModuleMessages(ctx.R, pv.I18nPublishKey, utils.Messages_en_US).(*pv.Messages)
  211. id := pat.Param(ctx.R, "id")
  212. if id == "" {
  213. return pb.DefaultNotFoundPageFunc(ctx)
  214. }
  215. isPage := strings.Contains(ctx.R.RequestURI, "/"+pm.Info().URIName()+"/")
  216. isTemplate := strings.Contains(ctx.R.RequestURI, "/"+templateM.Info().URIName()+"/")
  217. var obj interface{}
  218. var dmb *presets.ModelBuilder
  219. if isPage {
  220. dmb = pm
  221. } else {
  222. dmb = templateM
  223. }
  224. obj = dmb.NewModel()
  225. if sd, ok := obj.(presets.SlugDecoder); ok {
  226. vs, err := presets.RecoverPrimaryColumnValuesBySlug(sd, id)
  227. if err != nil {
  228. return pb.DefaultNotFoundPageFunc(ctx)
  229. }
  230. if _, err := strconv.Atoi(vs["id"]); err != nil {
  231. return pb.DefaultNotFoundPageFunc(ctx)
  232. }
  233. } else {
  234. if _, err := strconv.Atoi(id); err != nil {
  235. return pb.DefaultNotFoundPageFunc(ctx)
  236. }
  237. }
  238. obj, err = dmb.Detailing().GetFetchFunc()(obj, id, ctx)
  239. if err != nil {
  240. if errors.Is(err, presets.ErrRecordNotFound) {
  241. return pb.DefaultNotFoundPageFunc(ctx)
  242. }
  243. return
  244. }
  245. if l, ok := obj.(l10n.L10nInterface); ok {
  246. locale := ctx.R.FormValue("locale")
  247. if ctx.R.FormValue(web.EventFuncIDName) == "__reload__" && locale != "" && locale != l.GetLocale() {
  248. // redirect to list page when change locale
  249. http.Redirect(ctx.W, ctx.R, dmb.Info().ListingHref(), http.StatusSeeOther)
  250. return
  251. }
  252. }
  253. var tabContent web.PageResponse
  254. tab := ctx.R.FormValue("tab")
  255. isContent := tab == "content"
  256. activeTabIndex := 0
  257. isVersion := false
  258. if _, ok := obj.(publish.VersionInterface); ok {
  259. isVersion = true
  260. }
  261. if isContent {
  262. activeTabIndex = 1
  263. if v, ok := obj.(interface {
  264. GetID() uint
  265. }); ok {
  266. ctx.R.Form.Set("id", strconv.Itoa(int(v.GetID())))
  267. }
  268. if v, ok := obj.(publish.VersionInterface); ok {
  269. ctx.R.Form.Set("version", v.GetVersion())
  270. }
  271. if l, ok := obj.(l10n.L10nInterface); ok {
  272. ctx.R.Form.Set("locale", l.GetLocale())
  273. }
  274. if isTemplate {
  275. ctx.R.Form.Set("tpl", "1")
  276. }
  277. tabContent, err = b.PageContent(ctx)
  278. } else {
  279. tabContent, err = in(ctx)
  280. }
  281. if errors.Is(err, perm.PermissionDenied) {
  282. pr.Body = h.Text(perm.PermissionDenied.Error())
  283. return pr, nil
  284. }
  285. if err != nil {
  286. panic(err)
  287. }
  288. device := ctx.R.FormValue("device")
  289. editAction := web.POST().
  290. EventFunc(actions.Edit).
  291. URL(web.Var("\""+b.prefix+"/\"+arr[0]")).
  292. Query(presets.ParamOverlay, actions.Drawer).
  293. Query(presets.ParamID, web.Var("arr[1]")).
  294. Go()
  295. var publishBtn h.HTMLComponent
  296. var duplicateBtn h.HTMLComponent
  297. var versionSwitch h.HTMLComponent
  298. primarySlug := ""
  299. if v, ok := obj.(presets.SlugEncoder); ok {
  300. primarySlug = v.PrimarySlug()
  301. }
  302. if isVersion {
  303. p := obj.(*Page)
  304. versionCount := versionCount(db, p)
  305. switch p.GetStatus() {
  306. case publish.StatusDraft, publish.StatusOffline:
  307. publishBtn = VBtn(pvMsgr.Publish).Small(true).Color(b.publishBtnColor).Height(40).Attr("@click", fmt.Sprintf(`locals.action="%s";locals.commonConfirmDialog = true`, pv.PublishEvent))
  308. case publish.StatusOnline:
  309. publishBtn = VBtn(pvMsgr.Republish).Small(true).Color(b.publishBtnColor).Height(40).Attr("@click", fmt.Sprintf(`locals.action="%s";locals.commonConfirmDialog = true`, pv.RepublishEvent))
  310. }
  311. duplicateBtn = VBtn(msgr.Duplicate).
  312. Small(true).Color(b.duplicateBtnColor).Height(40).Class("rounded-l-0 mr-3").
  313. Attr("@click", web.Plaid().
  314. EventFunc(pv.DuplicateVersionEvent).
  315. URL(pm.Info().ListingHref()).
  316. Query(presets.ParamID, primarySlug).
  317. Query("tab", tab).
  318. QueryIf("device", device, device != "").
  319. FieldValue("Title", p.Title).FieldValue("Slug", p.Slug).FieldValue("CategoryID", p.CategoryID).
  320. Go(),
  321. )
  322. versionSwitch = VChip(
  323. VChip(h.Text(fmt.Sprintf("%d", versionCount))).Label(true).Color("#E0E0E0").Small(true).Class("px-1 mx-1").TextColor("black").Attr("style", "height:20px"),
  324. h.Text(p.GetVersionName()+" | "),
  325. VChip(h.Text(pv.GetStatusText(p.GetStatus(), pvMsgr))).Label(true).Color(pv.GetStatusColor(p.GetStatus())).Small(true).Class("px-1 mx-1").TextColor("black").Attr("style", "height:20px"),
  326. VIcon("chevron_right"),
  327. ).Label(true).Outlined(true).Class("px-1 ml-8 rounded-r-0").Attr("style", "height:40px;background-color:#FFFFFF!important;").TextColor("black").
  328. Attr("@click", web.Plaid().EventFunc(actions.OpenListingDialog).
  329. URL(b.ps.GetURIPrefix()+"/version-list-dialog").
  330. Query("select_id", primarySlug).
  331. Go())
  332. }
  333. pr.Body = VApp(
  334. VNavigationDrawer(
  335. pb.RunBrandProfileSwitchLanguageDisplayFunc(pb.RunBrandFunc(ctx), profile, pb.RunSwitchLanguageFunc(ctx), ctx),
  336. VDivider(),
  337. menu,
  338. ).App(true).
  339. Fixed(true).
  340. Value(true).
  341. Attr("v-model", "vars.navDrawer").
  342. Attr(web.InitContextVars, `{navDrawer: null}`),
  343. VAppBar(
  344. VAppBarNavIcon().On("click.stop", "vars.navDrawer = !vars.navDrawer"),
  345. VTabs(
  346. VTab(h.Text("{{item.label}}")).Attr("@click", web.Plaid().Query("tab", web.Var("item.query")).PushState(true).Go()).
  347. Attr("v-for", "(item, index) in locals.tabs", ":key", "index"),
  348. ).Centered(true).FixedTabs(true).Attr("v-model", `locals.activeTab`).Attr("style", "width:400px"),
  349. // h.If(isContent, VAppBarNavIcon().On("click.stop", "vars.pbEditorDrawer = !vars.pbEditorDrawer")),
  350. h.If(isVersion, versionSwitch, duplicateBtn, publishBtn),
  351. ).Dark(true).
  352. Color(presets.ColorPrimary).
  353. App(true).
  354. ClippedRight(true).
  355. Fixed(true),
  356. web.Portal().Name(presets.RightDrawerPortalName),
  357. web.Portal().Name(presets.DialogPortalName),
  358. web.Portal().Name(presets.DeleteConfirmPortalName),
  359. web.Portal().Name(presets.DefaultConfirmDialogPortalName),
  360. web.Portal().Name(presets.ListingDialogPortalName),
  361. web.Portal().Name(dialogPortalName),
  362. utils.ConfirmDialog(pvMsgr.Areyousure, web.Plaid().EventFunc(web.Var("locals.action")).
  363. Query(presets.ParamID, primarySlug).Go(),
  364. utilsMsgr),
  365. h.If(isContent, h.Script(`
  366. (function(){
  367. let scrollLeft = 0;
  368. let scrollTop = 0;
  369. function pause(duration) {
  370. return new Promise(res => setTimeout(res, duration));
  371. }
  372. function backoff(retries, fn, delay = 100) {
  373. fn().catch(err => retries > 1
  374. ? pause(delay).then(() => backoff(retries - 1, fn, delay * 2))
  375. : Promise.reject(err));
  376. }
  377. function restoreScroll() {
  378. window.scroll({left: scrollLeft, top: scrollTop, behavior: "auto"});
  379. if (window.scrollX == scrollLeft && window.scrollY == scrollTop) {
  380. return Promise.resolve();
  381. }
  382. return Promise.reject();
  383. }
  384. window.addEventListener('fetchStart', (event) => {
  385. scrollLeft = window.scrollX;
  386. scrollTop = window.scrollY;
  387. });
  388. window.addEventListener('fetchEnd', (event) => {
  389. backoff(5, restoreScroll, 100);
  390. });
  391. })()
  392. `),
  393. vx.VXMessageListener().ListenFunc(fmt.Sprintf(`
  394. function(e){
  395. if (!e.data.split) {
  396. return
  397. }
  398. let arr = e.data.split("_");
  399. if (arr.length != 2) {
  400. console.log(arr);
  401. return
  402. }
  403. %s
  404. }`, editAction))),
  405. VProgressLinear().
  406. Attr(":active", "isFetching").
  407. Attr("style", "position: fixed; z-index: 99").
  408. Indeterminate(true).
  409. Height(2).
  410. Color(pb.GetProgressBarColor()),
  411. h.Template(
  412. VSnackbar(h.Text("{{vars.presetsMessage.message}}")).
  413. Attr("v-model", "vars.presetsMessage.show").
  414. Attr(":color", "vars.presetsMessage.color").
  415. Timeout(1000).
  416. Top(true),
  417. ).Attr("v-if", "vars.presetsMessage"),
  418. VMain(
  419. tabContent.Body.(h.HTMLComponent),
  420. ),
  421. ).Id("vt-app").
  422. Attr(web.InitContextVars, `{presetsRightDrawer: false, presetsDialog: false, dialogPortalName: false, presetsListingDialog: false, presetsMessage: {show: false, color: "success", message: ""}}`).
  423. Attr(web.InitContextLocals, fmt.Sprintf(`{action: "", commonConfirmDialog: false, activeTab:%d, tabs: [{label:"SETTINGS",query:"settings"},{label:"CONTENT",query:"content"}]}`, activeTabIndex))
  424. return
  425. }
  426. })
  427. configureVersionListDialog(db, b.ps, pm)
  428. if b.templateEnabled {
  429. pm.RegisterEventFunc(openTemplateDialogEvent, openTemplateDialog(db, b.prefix))
  430. pm.RegisterEventFunc(selectTemplateEvent, selectTemplate(db))
  431. // pm.RegisterEventFunc(clearTemplateEvent, clearTemplate(db))
  432. }
  433. pm.RegisterEventFunc(schedulePublishDialogEvent, schedulePublishDialog(db, pm))
  434. pm.RegisterEventFunc(schedulePublishEvent, schedulePublish(db, pm))
  435. pm.RegisterEventFunc(createNoteDialogEvent, createNoteDialog(db, pm))
  436. pm.RegisterEventFunc(createNoteEvent, createNote(db, pm))
  437. pm.RegisterEventFunc(editSEODialogEvent, editSEODialog(db, pm, seoCollection))
  438. pm.RegisterEventFunc(updateSEOEvent, updateSEO(db, pm))
  439. eb := pm.Editing("TemplateSelection", "Title", "CategoryID", "Slug")
  440. eb.ValidateFunc(func(obj interface{}, ctx *web.EventContext) (err web.ValidationErrors) {
  441. c := obj.(*Page)
  442. err = pageValidator(c, db, l10nB)
  443. return
  444. })
  445. eb.Field("Slug").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  446. var vErr web.ValidationErrors
  447. if ve, ok := ctx.Flash.(*web.ValidationErrors); ok {
  448. vErr = *ve
  449. }
  450. return VTextField().
  451. FieldName(field.Name).
  452. Prefix("/").
  453. Label(field.Label).Value(strings.TrimPrefix(field.Value(obj).(string), "/")).
  454. ErrorMessages(vErr.GetFieldErrors("Page.Slug")...)
  455. }).SetterFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) (err error) {
  456. m := obj.(*Page)
  457. m.Slug = path.Join("/", m.Slug)
  458. return nil
  459. })
  460. eb.Field("CategoryID").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  461. p := obj.(*Page)
  462. categories := []*Category{}
  463. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  464. if err := db.Model(&Category{}).Where("locale_code = ?", locale).Find(&categories).Error; err != nil {
  465. panic(err)
  466. }
  467. var vErr web.ValidationErrors
  468. if ve, ok := ctx.Flash.(*web.ValidationErrors); ok {
  469. vErr = *ve
  470. }
  471. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  472. return vx.VXAutocomplete().Label(msgr.Category).FieldName(field.Name).
  473. Multiple(false).Chips(false).
  474. Items(categories).Value(p.CategoryID).ItemText("Path").ItemValue("ID").
  475. ErrorMessages(vErr.GetFieldErrors("Page.Category")...)
  476. })
  477. eb.Field("TemplateSelection").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  478. if !b.templateEnabled {
  479. return nil
  480. }
  481. p := obj.(*Page)
  482. selectedID := ctx.R.FormValue(templateSelectedID)
  483. body, err := getTplPortalComp(ctx, db, selectedID)
  484. if err != nil {
  485. panic(err)
  486. }
  487. // Display template selection only when creating a new page
  488. if p.ID == 0 {
  489. return h.Div(
  490. web.Portal().Name(templateSelectPortal),
  491. web.Portal(
  492. body,
  493. ).Name(selectedTemplatePortal),
  494. ).Class("my-2").Attr(web.InitContextVars, `{showTemplateDialog: false}`)
  495. }
  496. return nil
  497. })
  498. eb.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  499. localeCode, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  500. p := obj.(*Page)
  501. if p.Slug != "" {
  502. p.Slug = path.Clean(p.Slug)
  503. }
  504. funcName := ctx.R.FormValue(web.EventFuncIDName)
  505. if funcName == pv.DuplicateVersionEvent {
  506. id := ctx.R.FormValue(presets.ParamID)
  507. var fromPage Page
  508. eb.Fetcher(&fromPage, id, ctx)
  509. p.SEO = fromPage.SEO
  510. }
  511. err = db.Transaction(func(tx *gorm.DB) (inerr error) {
  512. if inerr = gorm2op.DataOperator(tx).Save(obj, id, ctx); inerr != nil {
  513. return
  514. }
  515. if strings.Contains(ctx.R.RequestURI, pv.SaveNewVersionEvent) || strings.Contains(ctx.R.RequestURI, pv.DuplicateVersionEvent) {
  516. if inerr = b.copyContainersToNewPageVersion(tx, int(p.ID), p.GetLocale(), p.ParentVersion, p.GetVersion()); inerr != nil {
  517. return
  518. }
  519. return
  520. }
  521. if v := ctx.R.FormValue(templateSelectedID); v != "" {
  522. var tplID int
  523. tplID, inerr = strconv.Atoi(v)
  524. if inerr != nil {
  525. return
  526. }
  527. if !l10nON {
  528. localeCode = ""
  529. }
  530. if inerr = b.copyContainersToAnotherPage(tx, tplID, templateVersion, localeCode, int(p.ID), p.GetVersion(), localeCode); inerr != nil {
  531. panic(inerr)
  532. return
  533. }
  534. }
  535. if l10nON && strings.Contains(ctx.R.RequestURI, l10n_view.DoLocalize) {
  536. fromID := ctx.R.Context().Value(l10n_view.FromID).(string)
  537. fromVersion := ctx.R.Context().Value(l10n_view.FromVersion).(string)
  538. fromLocale := ctx.R.Context().Value(l10n_view.FromLocale).(string)
  539. var fromIDInt int
  540. fromIDInt, err = strconv.Atoi(fromID)
  541. if err != nil {
  542. return
  543. }
  544. if inerr = b.localizeContainersToAnotherPage(tx, fromIDInt, fromVersion, fromLocale, int(p.ID), p.GetVersion(), p.GetLocale()); inerr != nil {
  545. panic(inerr)
  546. return
  547. }
  548. return
  549. }
  550. return
  551. })
  552. return
  553. })
  554. sharedContainerM := b.ConfigSharedContainer(pb, db)
  555. demoContainerM := b.ConfigDemoContainer(pb, db)
  556. categoryM := b.ConfigCategory(pb, db, l10nB)
  557. if activityB != nil {
  558. activityB.RegisterModels(pm, sharedContainerM, demoContainerM, templateM, categoryM)
  559. }
  560. if l10nB != nil {
  561. l10n_view.Configure(pb, db, l10nB, activityB, pm, demoContainerM, templateM, categoryM)
  562. }
  563. if publisher != nil {
  564. publisher.WithPageBuilder(b)
  565. pv.Configure(pb, db, activityB, publisher, pm)
  566. pm.Editing().SidePanelFunc(nil).ActionsFunc(nil)
  567. }
  568. if seoCollection != nil {
  569. seoCollection.RegisterSEO(&Page{}).RegisterContextVariables(
  570. "Title",
  571. func(object interface{}, _ *seo.Setting, _ *http.Request) string {
  572. if p, ok := object.(Page); ok {
  573. return p.Title
  574. }
  575. return ""
  576. },
  577. )
  578. }
  579. note.Configure(db, pb, pm)
  580. eb.CleanTabsPanels()
  581. dp.CleanTabsPanels()
  582. mediav.Configure(b.GetPresetsBuilder(), db)
  583. return
  584. }
  585. func versionCount(db *gorm.DB, p *Page) (count int64) {
  586. db.Model(&Page{}).Where("id = ? and locale_code = ?", p.ID, p.LocaleCode).Count(&count)
  587. return
  588. }
  589. func configureVersionListDialog(db *gorm.DB, pb *presets.Builder, pm *presets.ModelBuilder) {
  590. mb := pb.Model(&Page{}).
  591. URIName("version-list-dialog").
  592. InMenu(false)
  593. searcher := mb.Listing().Searcher
  594. lb := mb.Listing("Version", "State", "Notes", "Option").
  595. SearchColumns("version", "version_name").
  596. PerPage(10).
  597. SearchFunc(func(model interface{}, params *presets.SearchParams, ctx *web.EventContext) (r interface{}, totalCount int, err error) {
  598. id := ctx.R.FormValue("select_id")
  599. if id == "" {
  600. id = ctx.R.FormValue("f_select_id")
  601. }
  602. if id != "" {
  603. cs := mb.NewModel().(presets.SlugDecoder).PrimaryColumnValuesBySlug(id)
  604. con := presets.SQLCondition{
  605. Query: "id = ? and locale_code = ?",
  606. Args: []interface{}{cs["id"], cs["locale_code"]},
  607. }
  608. params.SQLConditions = append(params.SQLConditions, &con)
  609. }
  610. params.OrderBy = "created_at DESC"
  611. return searcher(model, params, ctx)
  612. })
  613. lb.Field("Version").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  614. versionName := obj.(publish.VersionInterface).GetVersionName()
  615. return h.Td(
  616. h.Text(versionName),
  617. VBtn("").Icon(true).Children(VIcon("edit")).Attr("@click", web.Plaid().
  618. URL(pb.GetURIPrefix()+"/version-list-dialog").
  619. EventFunc(renameVersionDialogEvent).
  620. Queries(ctx.Queries()).
  621. Query(presets.ParamOverlay, actions.Dialog).
  622. Query("rename_id", obj.(presets.SlugEncoder).PrimarySlug()).
  623. Query("version_name", versionName).
  624. Go()),
  625. )
  626. })
  627. lb.Field("State").ComponentFunc(pv.StatusListFunc())
  628. lb.Field("Notes").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  629. p := obj.(*Page)
  630. rt := pm.Info().Label()
  631. ri := p.PrimarySlug()
  632. userID, _ := note.GetUserData(ctx)
  633. count := note.GetUnreadNotesCount(db, userID, rt, ri)
  634. return h.Td(
  635. h.If(count > 0,
  636. VBadge().Content(count).Color("red"),
  637. ).Else(
  638. h.Text(""),
  639. ),
  640. )
  641. }).Label("Unread Notes")
  642. lb.Field("Option").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  643. p := obj.(*Page)
  644. id := ctx.R.FormValue("select_id")
  645. if id == "" {
  646. id = ctx.R.FormValue("f_select_id")
  647. }
  648. versionName := p.GetVersionName()
  649. if p.PrimarySlug() == id {
  650. return h.Td(h.Text("current"))
  651. }
  652. if p.GetStatus() != publish.StatusDraft {
  653. return h.Td()
  654. }
  655. return h.Td(VBtn("").Icon(true).Children(VIcon("delete")).Attr("@click", web.Plaid().
  656. URL(pb.GetURIPrefix()+"/version-list-dialog").
  657. EventFunc(deleteVersionDialogEvent).
  658. Queries(ctx.Queries()).
  659. Query(presets.ParamOverlay, actions.Dialog).
  660. Query("delete_id", obj.(presets.SlugEncoder).PrimarySlug()).
  661. Query("version_name", versionName).
  662. Go()))
  663. })
  664. lb.NewButtonFunc(func(ctx *web.EventContext) h.HTMLComponent { return nil })
  665. lb.RowMenu().Empty()
  666. mb.RegisterEventFunc(selectVersionEvent, func(ctx *web.EventContext) (r web.EventResponse, err error) {
  667. id := ctx.R.FormValue("select_id")
  668. refer, _ := url.Parse(ctx.R.Referer())
  669. newQueries := refer.Query()
  670. r.PushState = web.Location(newQueries).URL(pm.Info().DetailingHref(id))
  671. return
  672. })
  673. mb.RegisterEventFunc(renameVersionDialogEvent, renameVersionDialog(mb))
  674. mb.RegisterEventFunc(renameVersionEvent, renameVersion(mb))
  675. mb.RegisterEventFunc(deleteVersionDialogEvent, deleteVersionDialog(mb))
  676. lb.CellWrapperFunc(func(cell h.MutableAttrHTMLComponent, id string, obj interface{}, dataTableID string) h.HTMLComponent {
  677. cell.SetAttr("@click.self", web.Plaid().
  678. Query("select_id", obj.(*Page).PrimarySlug()).
  679. URL(pb.GetURIPrefix()+"/version-list-dialog").
  680. EventFunc(selectVersionEvent).
  681. Go(),
  682. )
  683. return cell
  684. })
  685. lb.FilterDataFunc(func(ctx *web.EventContext) vx.FilterData {
  686. return []*vx.FilterItem{
  687. {
  688. Key: "all",
  689. Invisible: true,
  690. SQLCondition: ``,
  691. },
  692. {
  693. Key: "online_version",
  694. Invisible: true,
  695. SQLCondition: `status = 'online'`,
  696. },
  697. {
  698. Key: "named_versions",
  699. Invisible: true,
  700. SQLCondition: `version <> version_name`,
  701. },
  702. }
  703. })
  704. lb.FilterTabsFunc(func(ctx *web.EventContext) []*presets.FilterTab {
  705. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  706. id := ctx.R.FormValue("select_id")
  707. if id == "" {
  708. id = ctx.R.FormValue("f_select_id")
  709. }
  710. return []*presets.FilterTab{
  711. {
  712. Label: msgr.FilterTabAllVersions,
  713. ID: "all",
  714. Query: url.Values{"all": []string{"1"}, "select_id": []string{id}},
  715. },
  716. {
  717. Label: msgr.FilterTabOnlineVersion,
  718. ID: "online_version",
  719. Query: url.Values{"online_version": []string{"1"}, "select_id": []string{id}},
  720. },
  721. {
  722. Label: msgr.FilterTabNamedVersions,
  723. ID: "named_versions",
  724. Query: url.Values{"named_versions": []string{"1"}, "select_id": []string{id}},
  725. },
  726. }
  727. })
  728. }
  729. // cats should be ordered by path
  730. func fillCategoryIndentLevels(cats []*Category) {
  731. for i, cat := range cats {
  732. if cat.Path == "/" {
  733. continue
  734. }
  735. for j := i - 1; j >= 0; j-- {
  736. if strings.HasPrefix(cat.Path, cats[j].Path+"/") {
  737. cat.IndentLevel = cats[j].IndentLevel + 1
  738. break
  739. }
  740. }
  741. }
  742. }
  743. func (b *Builder) ConfigCategory(pb *presets.Builder, db *gorm.DB, l10nB *l10n.Builder) (pm *presets.ModelBuilder) {
  744. pm = pb.Model(&Category{}).URIName("page_categories").Label("Categories")
  745. lb := pm.Listing("Name", "Path", "Description")
  746. oldSearcher := lb.Searcher
  747. lb.SearchFunc(func(model interface{}, params *presets.SearchParams, ctx *web.EventContext) (r interface{}, totalCount int, err error) {
  748. r, totalCount, err = oldSearcher(model, params, ctx)
  749. cats := r.([]*Category)
  750. sort.Slice(cats, func(i, j int) bool {
  751. return cats[i].Path < cats[j].Path
  752. })
  753. fillCategoryIndentLevels(cats)
  754. return
  755. })
  756. lb.Field("Name").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  757. cat := obj.(*Category)
  758. icon := "folder"
  759. if cat.IndentLevel != 0 {
  760. icon = "insert_drive_file"
  761. }
  762. return h.Td(
  763. h.Div(
  764. VIcon(icon).Small(true).Class("mb-1"),
  765. h.Text(cat.Name),
  766. ).Style(fmt.Sprintf("padding-left: %dpx;", cat.IndentLevel*32)),
  767. )
  768. })
  769. eb := pm.Editing("Name", "Path", "Description")
  770. eb.Field("Path").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  771. var vErr web.ValidationErrors
  772. if ve, ok := ctx.Flash.(*web.ValidationErrors); ok {
  773. vErr = *ve
  774. }
  775. return VTextField().Label("Path").
  776. Value(strings.TrimPrefix(field.Value(obj).(string), "/")).
  777. FieldName("Path").
  778. Prefix("/").
  779. ErrorMessages(vErr.GetFieldErrors("Category.Category")...)
  780. }).SetterFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) (err error) {
  781. m := obj.(*Category)
  782. p := ctx.R.FormValue(field.Name)
  783. p = path.Join("/", p)
  784. m.Path = p
  785. return nil
  786. })
  787. eb.DeleteFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  788. cs := obj.(presets.SlugDecoder).PrimaryColumnValuesBySlug(id)
  789. ID := cs["id"]
  790. Locale := cs["locale_code"]
  791. var count int64
  792. if err = db.Model(&Page{}).Where("category_id = ? AND locale_code = ?", ID, Locale).Count(&count).Error; err != nil {
  793. return
  794. }
  795. if count > 0 {
  796. err = errors.New(unableDeleteCategoryMsg)
  797. return
  798. }
  799. if err = db.Model(&Category{}).Where("id = ? AND locale_code = ?", ID, Locale).Delete(&Category{}).Error; err != nil {
  800. return
  801. }
  802. return
  803. })
  804. eb.ValidateFunc(func(obj interface{}, ctx *web.EventContext) (err web.ValidationErrors) {
  805. c := obj.(*Category)
  806. err = categoryValidator(c, db, l10nB)
  807. return
  808. })
  809. eb.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  810. c := obj.(*Category)
  811. c.Path = path.Clean(c.Path)
  812. err = db.Save(c).Error
  813. return
  814. })
  815. return
  816. }
  817. const (
  818. templateSelectPortal = "templateSelectPortal"
  819. selectedTemplatePortal = "selectedTemplatePortal"
  820. templateSelectedID = "TemplateSelectedID"
  821. templateID = "TemplateID"
  822. templateBlankVal = "blank"
  823. )
  824. func selectTemplate(db *gorm.DB) web.EventFunc {
  825. return func(ctx *web.EventContext) (er web.EventResponse, err error) {
  826. defer func() {
  827. web.AppendVarsScripts(&er, "vars.showTemplateDialog=false")
  828. }()
  829. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  830. id := ctx.R.FormValue(templateID)
  831. if id == templateBlankVal {
  832. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  833. Name: selectedTemplatePortal,
  834. Body: VRow(
  835. VCol(
  836. h.Input("").Type("hidden").Value("").Attr(web.VFieldName(templateSelectedID)...),
  837. VTextField().Readonly(true).Label(msgr.SelectedTemplateLabel).Value(msgr.Blank).Dense(true).Outlined(true),
  838. ).Cols(5),
  839. VCol(
  840. VBtn(msgr.ChangeTemplate).Color("primary").
  841. Attr("@click", web.Plaid().Query(templateSelectedID, "").EventFunc(openTemplateDialogEvent).Go()),
  842. ).Cols(5),
  843. ),
  844. })
  845. return
  846. }
  847. var body h.HTMLComponent
  848. if body, err = getTplPortalComp(ctx, db, id); err != nil {
  849. return
  850. }
  851. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  852. Name: selectedTemplatePortal,
  853. Body: body,
  854. })
  855. return
  856. }
  857. }
  858. func getTplPortalComp(ctx *web.EventContext, db *gorm.DB, selectedID string) (h.HTMLComponent, error) {
  859. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  860. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  861. name := msgr.Blank
  862. if selectedID != "" {
  863. if err := db.Model(&Template{}).Where("id = ? AND locale_code = ?", selectedID, locale).Pluck("name", &name).Error; err != nil {
  864. return nil, err
  865. }
  866. }
  867. return VRow(
  868. VCol(
  869. h.Input("").Type("hidden").Value(selectedID).Attr(web.VFieldName(templateSelectedID)...),
  870. VTextField().Readonly(true).Label(msgr.SelectedTemplateLabel).Value(name).Dense(true).Outlined(true),
  871. ).Cols(5),
  872. VCol(
  873. VBtn(msgr.ChangeTemplate).Color("primary").
  874. Attr("@click", web.Plaid().Query(templateSelectedID, selectedID).EventFunc(openTemplateDialogEvent).Go()),
  875. ).Cols(5),
  876. ), nil
  877. }
  878. // Unused
  879. func clearTemplate(db *gorm.DB) web.EventFunc {
  880. return func(ctx *web.EventContext) (er web.EventResponse, err error) {
  881. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  882. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  883. Name: selectedTemplatePortal,
  884. Body: VRow(
  885. VCol(
  886. h.Input("").Type("hidden").Value("").Attr(web.VFieldName(templateSelectedID)...),
  887. VTextField().Readonly(true).Label(msgr.SelectedTemplateLabel).Value(msgr.Blank).Dense(true).Outlined(true),
  888. ).Cols(5),
  889. VCol(
  890. VBtn(msgr.ChangeTemplate).Color("primary").
  891. Attr("@click", web.Plaid().Query(templateSelectedID, "").EventFunc(openTemplateDialogEvent).Go()),
  892. ).Cols(5),
  893. ),
  894. })
  895. return
  896. }
  897. }
  898. func openTemplateDialog(db *gorm.DB, prefix string) web.EventFunc {
  899. return func(ctx *web.EventContext) (er web.EventResponse, err error) {
  900. gmsgr := presets.MustGetMessages(ctx.R)
  901. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  902. selectedID := ctx.R.FormValue(templateSelectedID)
  903. tpls := []*Template{}
  904. if err := db.Model(&Template{}).Where("locale_code = ?", locale).Find(&tpls).Error; err != nil {
  905. panic(err)
  906. }
  907. msgrPb := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  908. var tplHTMLComponents []h.HTMLComponent
  909. tplHTMLComponents = append(tplHTMLComponents,
  910. VCol(
  911. VCard(
  912. h.Div(
  913. h.Iframe().
  914. Attr("width", "100%", "height", "150", "frameborder", "no").
  915. Style("transform-origin: left top; transform: scale(1, 1); pointer-events: none;"),
  916. ),
  917. VCardTitle(h.Text(msgrPb.Blank)),
  918. VCardSubtitle(h.Text("")),
  919. h.Div(
  920. h.Input(templateID).Type("radio").
  921. Value(templateBlankVal).
  922. Attr(web.VFieldName(templateID)...).
  923. AttrIf("checked", "checked", selectedID == "").
  924. Style("width: 18px; height: 18px"),
  925. ).Class("mr-4 float-right"),
  926. ).Height(280).Class("text-truncate").Outlined(true),
  927. ).Cols(3),
  928. )
  929. for _, tpl := range tpls {
  930. tplHTMLComponents = append(tplHTMLComponents,
  931. getTplColComponent(ctx, prefix, tpl, selectedID),
  932. )
  933. }
  934. if len(tpls) == 0 {
  935. tplHTMLComponents = append(tplHTMLComponents,
  936. h.Div(h.Text(gmsgr.ListingNoRecordToShow)).Class("pl-4 text-center grey--text text--darken-2"),
  937. )
  938. }
  939. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  940. Name: templateSelectPortal,
  941. Body: VDialog(
  942. VCard(
  943. VCardTitle(
  944. h.Text(msgrPb.CreateFromTemplate),
  945. VSpacer(),
  946. VBtn("").Icon(true).
  947. Children(VIcon("close")).
  948. Large(true).
  949. On("click", fmt.Sprintf("vars.showTemplateDialog=false")),
  950. ),
  951. VCardActions(
  952. VRow(tplHTMLComponents...),
  953. ),
  954. VCardActions(
  955. VSpacer(),
  956. VBtn(gmsgr.Cancel).Attr("@click", "vars.showTemplateDialog=false"),
  957. VBtn(gmsgr.OK).Color("primary").
  958. Attr("@click", web.Plaid().EventFunc(selectTemplateEvent).
  959. Go(),
  960. ),
  961. ).Class("pb-4"),
  962. ).Tile(true),
  963. ).MaxWidth("80%").
  964. Attr("v-model", fmt.Sprintf("vars.showTemplateDialog")).
  965. Attr(web.InitContextVars, fmt.Sprintf(`{showTemplateDialog: false}`)),
  966. })
  967. er.VarsScript = `setTimeout(function(){ vars.showTemplateDialog = true }, 100)`
  968. return
  969. }
  970. }
  971. func getTplColComponent(ctx *web.EventContext, prefix string, tpl *Template, selectedID string) h.HTMLComponent {
  972. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  973. // Avoid layout errors
  974. var name string
  975. var desc string
  976. if tpl.Name == "" {
  977. name = msgr.Unnamed
  978. } else {
  979. name = tpl.Name
  980. }
  981. if tpl.Description == "" {
  982. desc = msgr.NotDescribed
  983. } else {
  984. desc = tpl.Description
  985. }
  986. id := fmt.Sprintf("%d", tpl.ID)
  987. src := fmt.Sprintf("./%s/preview?id=%d&tpl=1&locale=%s", prefix, tpl.ID, tpl.LocaleCode)
  988. return VCol(
  989. VCard(
  990. h.Div(
  991. h.Iframe().Src(src).
  992. Attr("width", "100%", "height", "150", "frameborder", "no").
  993. Style("transform-origin: left top; transform: scale(1, 1); pointer-events: none;"),
  994. ),
  995. VCardTitle(h.Text(name)),
  996. VCardSubtitle(h.Text(desc)),
  997. VBtn(msgr.Preview).Text(true).XSmall(true).Class("ml-2 mb-4").
  998. Href(src).
  999. Target("_blank").Color("primary"),
  1000. h.Div(
  1001. h.Input(templateID).Type("radio").
  1002. Value(id).
  1003. Attr(web.VFieldName(templateID)...).
  1004. AttrIf("checked", "checked", selectedID == id).
  1005. Style("width: 18px; height: 18px"),
  1006. ).Class("mr-4 float-right"),
  1007. ).Height(280).Class("text-truncate").Outlined(true),
  1008. ).Cols(3)
  1009. }
  1010. func schedulePublishDialog(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1011. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1012. paramID := ctx.R.FormValue(presets.ParamID)
  1013. obj := mb.NewModel()
  1014. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1015. if err != nil {
  1016. return
  1017. }
  1018. s, ok := obj.(publish.ScheduleInterface)
  1019. if !ok {
  1020. return
  1021. }
  1022. var start, end string
  1023. if s.GetScheduledStartAt() != nil {
  1024. start = s.GetScheduledStartAt().Format("2006-01-02 15:04")
  1025. }
  1026. if s.GetScheduledEndAt() != nil {
  1027. end = s.GetScheduledEndAt().Format("2006-01-02 15:04")
  1028. }
  1029. msgr := i18n.MustGetModuleMessages(ctx.R, pv.I18nPublishKey, Messages_en_US).(*pv.Messages)
  1030. cmsgr := i18n.MustGetModuleMessages(ctx.R, presets.CoreI18nModuleKey, Messages_en_US).(*presets.Messages)
  1031. updateBtn := VBtn(cmsgr.Update).
  1032. Color("primary").
  1033. Attr(":disabled", "isFetching").
  1034. Attr(":loading", "isFetching").
  1035. Attr("@click", web.Plaid().
  1036. EventFunc(schedulePublishEvent).
  1037. // Queries(queries).
  1038. Query(presets.ParamID, paramID).
  1039. Query(presets.ParamOverlay, actions.Dialog).
  1040. URL(mb.Info().ListingHref()).
  1041. Go())
  1042. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1043. Name: dialogPortalName,
  1044. Body: web.Scope(
  1045. VDialog(
  1046. VCard(
  1047. VCardTitle(h.Text("Schedule Publish Time")),
  1048. VCardText(
  1049. VRow(
  1050. VCol(
  1051. vx.VXDateTimePicker().FieldName("ScheduledStartAt").Label(msgr.ScheduledStartAt).Value(start).
  1052. TimePickerProps(vx.TimePickerProps{Format: "24hr", Scrollable: true}).
  1053. ClearText(msgr.DateTimePickerClearText).OkText(msgr.DateTimePickerOkText),
  1054. // h.RawHTML(fmt.Sprintf(`<vx-datetimepicker label="ScheduledStartAt" value="%s" v-field-name='"ScheduledStartAt"'> </vx-datetimepicker>`, start)),
  1055. ).Cols(6),
  1056. VCol(
  1057. vx.VXDateTimePicker().FieldName("ScheduledEndAt").Label(msgr.ScheduledEndAt).Value(end).
  1058. TimePickerProps(vx.TimePickerProps{Format: "24hr", Scrollable: true}).
  1059. ClearText(msgr.DateTimePickerClearText).OkText(msgr.DateTimePickerOkText),
  1060. // h.RawHTML(fmt.Sprintf(`<vx-datetimepicker label="ScheduledEndAt" value="%s" v-field-name='"ScheduledEndAt"'> </vx-datetimepicker>`, end)),
  1061. ).Cols(6),
  1062. ),
  1063. ),
  1064. VCardActions(
  1065. VSpacer(),
  1066. updateBtn,
  1067. ),
  1068. ),
  1069. ).MaxWidth("480px").
  1070. Attr("v-model", "locals.schedulePublishDialog"),
  1071. ).Init("{schedulePublishDialog:true}").VSlot("{locals}"),
  1072. })
  1073. return
  1074. }
  1075. }
  1076. func schedulePublish(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1077. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1078. paramID := ctx.R.FormValue(presets.ParamID)
  1079. obj := mb.NewModel()
  1080. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1081. if err != nil {
  1082. return
  1083. }
  1084. err = pv.ScheduleEditSetterFunc(obj, nil, ctx)
  1085. if err != nil {
  1086. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1087. return
  1088. }
  1089. err = mb.Editing().Saver(obj, paramID, ctx)
  1090. if err != nil {
  1091. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1092. return
  1093. }
  1094. r.PushState = web.Location(nil)
  1095. return
  1096. }
  1097. }
  1098. func createNoteDialog(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1099. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1100. paramID := ctx.R.FormValue(presets.ParamID)
  1101. okAction := web.Plaid().
  1102. URL(mb.Info().ListingHref()).
  1103. EventFunc(createNoteEvent).
  1104. Query("resource_id", paramID).
  1105. Query("resource_type", mb.Info().Label()).
  1106. Query(presets.ParamOverlay, actions.Dialog).Go()
  1107. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1108. Name: dialogPortalName,
  1109. Body: web.Scope(
  1110. VDialog(
  1111. VCard(
  1112. VCardTitle(h.Text("Note")),
  1113. VCardText(
  1114. VTextField().FieldName("Content").Value(""),
  1115. ),
  1116. VCardActions(
  1117. VSpacer(),
  1118. VBtn("Cancel").
  1119. Depressed(true).
  1120. Class("ml-2").
  1121. On("click", "locals.createNoteDialog = false"),
  1122. VBtn("OK").
  1123. Color("primary").
  1124. Depressed(true).
  1125. Dark(true).
  1126. Attr("@click", okAction),
  1127. ),
  1128. ),
  1129. ).MaxWidth("420px").Attr("v-model", "locals.createNoteDialog"),
  1130. ).Init("{createNoteDialog:true}").VSlot("{locals}"),
  1131. })
  1132. return
  1133. }
  1134. }
  1135. func createNote(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1136. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1137. ri := ctx.R.FormValue("resource_id")
  1138. rt := ctx.R.FormValue("resource_type")
  1139. content := ctx.R.FormValue("Content")
  1140. userID, creator := note.GetUserData(ctx)
  1141. nt := note.QorNote{
  1142. UserID: userID,
  1143. Creator: creator,
  1144. ResourceID: ri,
  1145. ResourceType: rt,
  1146. Content: content,
  1147. }
  1148. if err = db.Save(&nt).Error; err != nil {
  1149. presets.ShowMessage(&r, err.Error(), "error")
  1150. err = nil
  1151. return
  1152. }
  1153. userNote := note.UserNote{UserID: userID, ResourceType: rt, ResourceID: ri}
  1154. db.Where(userNote).FirstOrCreate(&userNote)
  1155. var total int64
  1156. db.Model(&note.QorNote{}).Where("resource_type = ? AND resource_id = ?", rt, ri).Count(&total)
  1157. db.Model(&userNote).UpdateColumn("Number", total)
  1158. r.PushState = web.Location(nil)
  1159. return
  1160. }
  1161. }
  1162. func editSEODialog(db *gorm.DB, mb *presets.ModelBuilder, seoCollection *seo.Collection) web.EventFunc {
  1163. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1164. paramID := ctx.R.FormValue(presets.ParamID)
  1165. obj := mb.NewModel()
  1166. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1167. if err != nil {
  1168. return
  1169. }
  1170. // msgr := i18n.MustGetModuleMessages(ctx.R, pv.I18nPublishKey, Messages_en_US).(*pv.Messages)
  1171. cmsgr := i18n.MustGetModuleMessages(ctx.R, presets.CoreI18nModuleKey, Messages_en_US).(*presets.Messages)
  1172. updateBtn := VBtn(cmsgr.Update).
  1173. Color("primary").
  1174. Attr(":disabled", "isFetching").
  1175. Attr(":loading", "isFetching").
  1176. Attr("@click", web.Plaid().
  1177. EventFunc(updateSEOEvent).
  1178. // Queries(queries).
  1179. Query(presets.ParamID, paramID).
  1180. // Query(presets.ParamOverlay, actions.Dialog).
  1181. URL(mb.Info().ListingHref()).
  1182. Go())
  1183. ctx.R.Form.Set("openCustomizePanel", "0")
  1184. seoForm := seoCollection.EditingComponentFunc(obj, nil, ctx)
  1185. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1186. Name: dialogPortalName,
  1187. Body: web.Scope(
  1188. VDialog(
  1189. VCard(
  1190. VCardTitle(h.Text("")),
  1191. VCardText(
  1192. seoForm,
  1193. ),
  1194. VCardActions(
  1195. VSpacer(),
  1196. updateBtn,
  1197. ),
  1198. ),
  1199. ).MaxWidth("650px").
  1200. Attr("v-model", "locals.editSEODialog"),
  1201. ).Init("{editSEODialog:true}").VSlot("{locals}"),
  1202. })
  1203. return
  1204. }
  1205. }
  1206. func updateSEO(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1207. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1208. paramID := ctx.R.FormValue(presets.ParamID)
  1209. obj := mb.NewModel()
  1210. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1211. if err != nil {
  1212. return
  1213. }
  1214. err = seo.EditSetterFunc(obj, &presets.FieldContext{Name: "SEO"}, ctx)
  1215. if err != nil {
  1216. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1217. return
  1218. }
  1219. err = mb.Editing().Saver(obj, paramID, ctx)
  1220. if err != nil {
  1221. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1222. return
  1223. }
  1224. r.PushState = web.Location(nil)
  1225. return
  1226. }
  1227. }
  1228. func renameVersionDialog(mb *presets.ModelBuilder) web.EventFunc {
  1229. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1230. id := ctx.R.FormValue("rename_id")
  1231. versionName := ctx.R.FormValue("version_name")
  1232. okAction := web.Plaid().
  1233. URL(mb.Info().ListingHref()).
  1234. EventFunc(renameVersionEvent).
  1235. Queries(ctx.Queries()).
  1236. Query("rename_id", id).Go()
  1237. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1238. Name: dialogPortalName,
  1239. Body: web.Scope(
  1240. VDialog(
  1241. VCard(
  1242. VCardTitle(h.Text("Version")),
  1243. VCardText(
  1244. VTextField().FieldName("VersionName").Value(versionName),
  1245. ),
  1246. VCardActions(
  1247. VSpacer(),
  1248. VBtn("Cancel").
  1249. Depressed(true).
  1250. Class("ml-2").
  1251. On("click", "locals.renameVersionDialog = false"),
  1252. VBtn("OK").
  1253. Color("primary").
  1254. Depressed(true).
  1255. Dark(true).
  1256. Attr("@click", "locals.renameVersionDialog = false; "+okAction),
  1257. ),
  1258. ),
  1259. ).MaxWidth("420px").Attr("v-model", "locals.renameVersionDialog"),
  1260. ).Init("{renameVersionDialog:true}").VSlot("{locals}"),
  1261. })
  1262. return
  1263. }
  1264. }
  1265. func renameVersion(mb *presets.ModelBuilder) web.EventFunc {
  1266. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1267. paramID := ctx.R.FormValue("rename_id")
  1268. obj := mb.NewModel()
  1269. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1270. if err != nil {
  1271. return
  1272. }
  1273. name := ctx.R.FormValue("VersionName")
  1274. if err = reflectutils.Set(obj, "Version.VersionName", name); err != nil {
  1275. return
  1276. }
  1277. if err = mb.Editing().Saver(obj, paramID, ctx); err != nil {
  1278. return
  1279. }
  1280. qs := ctx.Queries()
  1281. delete(qs, "version_name")
  1282. delete(qs, "rename_id")
  1283. r.VarsScript = web.Plaid().URL(ctx.R.RequestURI).Queries(qs).EventFunc(actions.UpdateListingDialog).Go()
  1284. return
  1285. }
  1286. }
  1287. func deleteVersionDialog(mb *presets.ModelBuilder) web.EventFunc {
  1288. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1289. id := ctx.R.FormValue("delete_id")
  1290. versionName := ctx.R.FormValue("version_name")
  1291. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1292. Name: presets.DeleteConfirmPortalName,
  1293. Body: VDialog(
  1294. VCard(
  1295. VCardTitle(h.Text(fmt.Sprintf("Are you sure you want to delete %s?", versionName))),
  1296. VCardActions(
  1297. VSpacer(),
  1298. VBtn("Cancel").
  1299. Depressed(true).
  1300. Class("ml-2").
  1301. On("click", "vars.deleteConfirmation = false"),
  1302. VBtn("Delete").
  1303. Color("primary").
  1304. Depressed(true).
  1305. Dark(true).
  1306. Attr("@click", web.Plaid().
  1307. URL(mb.Info().ListingHref()).
  1308. EventFunc(actions.DoDelete).
  1309. Queries(ctx.Queries()).
  1310. Query(presets.ParamInDialog, true).
  1311. Query(presets.ParamID, id).Go()),
  1312. ),
  1313. ),
  1314. ).MaxWidth("580px").
  1315. Attr("v-model", "vars.deleteConfirmation").
  1316. Attr(web.InitContextVars, `{deleteConfirmation: false}`),
  1317. })
  1318. r.VarsScript = "setTimeout(function(){ vars.deleteConfirmation = true }, 100)"
  1319. return
  1320. }
  1321. }
  1322. func (b *Builder) ConfigSharedContainer(pb *presets.Builder, db *gorm.DB) (pm *presets.ModelBuilder) {
  1323. pm = pb.Model(&Container{}).URIName("shared_containers").Label("Shared Containers")
  1324. pm.RegisterEventFunc(republishRelatedOnlinePagesEvent, republishRelatedOnlinePages(b.mb.Info().ListingHref()))
  1325. listing := pm.Listing("DisplayName").SearchColumns("display_name")
  1326. listing.RowMenu("Rename").RowMenuItem("Rename").ComponentFunc(func(obj interface{}, id string, ctx *web.EventContext) h.HTMLComponent {
  1327. c := obj.(*Container)
  1328. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  1329. return VListItem(
  1330. VListItemIcon(VIcon("edit_note")),
  1331. VListItemTitle(h.Text(msgr.Rename)),
  1332. ).Attr("@click",
  1333. web.Plaid().
  1334. URL(b.ContainerByName(c.ModelName).mb.Info().ListingHref()).
  1335. EventFunc(RenameContainerDialogEvent).
  1336. Query(paramContainerID, c.PrimarySlug()).
  1337. Query(paramContainerName, c.DisplayName).
  1338. Query("portal", "presets").
  1339. Go(),
  1340. )
  1341. })
  1342. // ed := pm.Editing("SelectContainer")
  1343. // ed.Field("SelectContainer").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  1344. // var containers []h.HTMLComponent
  1345. // for _, builder := range b.containerBuilders {
  1346. // cover := builder.cover
  1347. // if cover == "" {
  1348. // cover = path.Join(b.prefix, b.imagesPrefix, strings.ReplaceAll(builder.name, " ", "")+".png")
  1349. // }
  1350. // containers = append(containers,
  1351. // VCol(
  1352. // VCard(
  1353. // VImg().Src(cover).Height(200),
  1354. // VCardActions(
  1355. // VCardTitle(h.Text(builder.name)),
  1356. // VSpacer(),
  1357. // VBtn("Select").
  1358. // Text(true).
  1359. // Color("primary").Attr("@click",
  1360. // web.Plaid().
  1361. // EventFunc(actions.New).
  1362. // URL(builder.GetModelBuilder().Info().ListingHref()).
  1363. // Go()),
  1364. // ),
  1365. // ),
  1366. // ).Cols(6),
  1367. // )
  1368. // }
  1369. // return VSheet(
  1370. // VContainer(
  1371. // VRow(
  1372. // containers...,
  1373. // ),
  1374. // ),
  1375. // )
  1376. // })
  1377. if permB := pb.GetPermission(); permB != nil {
  1378. permB.CreatePolicies(
  1379. perm.PolicyFor(perm.Anybody).WhoAre(perm.Denied).ToDo(presets.PermCreate).On("*:shared_containers:*"),
  1380. )
  1381. }
  1382. listing.Field("DisplayName").Label("Name")
  1383. listing.SearchFunc(sharedContainerSearcher(db, pm))
  1384. listing.CellWrapperFunc(func(cell h.MutableAttrHTMLComponent, id string, obj interface{}, dataTableID string) h.HTMLComponent {
  1385. tdbind := cell
  1386. c := obj.(*Container)
  1387. tdbind.SetAttr("@click.self",
  1388. web.Plaid().
  1389. EventFunc(actions.Edit).
  1390. URL(b.ContainerByName(c.ModelName).GetModelBuilder().Info().ListingHref()).
  1391. Query(presets.ParamID, c.ModelID).
  1392. Query(paramOpenFromSharedContainer, 1).
  1393. Go()+fmt.Sprintf(`; vars.currEditingListItemID="%s-%d"`, dataTableID, c.ModelID))
  1394. return tdbind
  1395. })
  1396. return
  1397. }
  1398. func (b *Builder) ConfigDemoContainer(pb *presets.Builder, db *gorm.DB) (pm *presets.ModelBuilder) {
  1399. pm = pb.Model(&DemoContainer{}).URIName("demo_containers").Label("Demo Containers")
  1400. pm.RegisterEventFunc("addDemoContainer", func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1401. modelID := ctx.QueryAsInt(presets.ParamOverlayUpdateID)
  1402. modelName := ctx.R.FormValue("ModelName")
  1403. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  1404. var existID uint
  1405. {
  1406. m := DemoContainer{}
  1407. db.Where("model_name = ?", modelName).First(&m)
  1408. existID = m.ID
  1409. }
  1410. db.Assign(DemoContainer{
  1411. Model: gorm.Model{
  1412. ID: existID,
  1413. },
  1414. ModelID: uint(modelID),
  1415. }).FirstOrCreate(&DemoContainer{}, map[string]interface{}{
  1416. "model_name": modelName,
  1417. "locale_code": locale,
  1418. })
  1419. r.Reload = true
  1420. return
  1421. })
  1422. listing := pm.Listing("ModelName").SearchColumns("ModelName")
  1423. listing.Field("ModelName").Label("Name")
  1424. ed := pm.Editing("SelectContainer").ActionsFunc(func(obj interface{}, ctx *web.EventContext) h.HTMLComponent { return nil })
  1425. ed.Field("ModelName")
  1426. ed.Field("ModelID")
  1427. ed.Field("SelectContainer").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  1428. locale, localizable := l10n.IsLocalizableFromCtx(ctx.R.Context())
  1429. var demoContainers []DemoContainer
  1430. db.Find(&demoContainers)
  1431. var containers []h.HTMLComponent
  1432. for _, builder := range b.containerBuilders {
  1433. cover := builder.cover
  1434. if cover == "" {
  1435. cover = path.Join(b.prefix, b.imagesPrefix, strings.ReplaceAll(builder.name, " ", "")+".png")
  1436. }
  1437. c := VCol(
  1438. VCard(
  1439. VImg().Src(cover).Height(200),
  1440. VCardActions(
  1441. VCardTitle(h.Text(builder.name)),
  1442. VSpacer(),
  1443. VBtn("Select").
  1444. Text(true).
  1445. Color("primary").Attr("@click",
  1446. web.Plaid().
  1447. EventFunc(actions.New).
  1448. URL(builder.GetModelBuilder().Info().ListingHref()).
  1449. Query(presets.ParamOverlayAfterUpdateScript, web.POST().Query("ModelName", builder.name).EventFunc("addDemoContainer").Go()).
  1450. Go()),
  1451. ),
  1452. ),
  1453. ).Cols(6)
  1454. var isExists bool
  1455. var modelID uint
  1456. for _, dc := range demoContainers {
  1457. if dc.ModelName == builder.name {
  1458. if localizable && dc.GetLocale() != locale {
  1459. continue
  1460. }
  1461. isExists = true
  1462. modelID = dc.ModelID
  1463. break
  1464. }
  1465. }
  1466. if isExists {
  1467. c = VCol(
  1468. VCard(
  1469. VImg().Src(cover).Height(200),
  1470. VCardActions(
  1471. VCardTitle(h.Text(builder.name)),
  1472. VSpacer(),
  1473. VBtn("Edit").
  1474. Text(true).
  1475. Color("primary").Attr("@click",
  1476. web.Plaid().
  1477. EventFunc(actions.Edit).
  1478. URL(builder.GetModelBuilder().Info().ListingHref()).
  1479. Query(presets.ParamID, fmt.Sprint(modelID)).
  1480. Go()),
  1481. ),
  1482. ),
  1483. ).Cols(6)
  1484. }
  1485. containers = append(containers, c)
  1486. }
  1487. return VSheet(
  1488. VContainer(
  1489. VRow(
  1490. containers...,
  1491. ),
  1492. ),
  1493. )
  1494. })
  1495. listing.CellWrapperFunc(func(cell h.MutableAttrHTMLComponent, id string, obj interface{}, dataTableID string) h.HTMLComponent {
  1496. tdbind := cell
  1497. c := obj.(*DemoContainer)
  1498. tdbind.SetAttr("@click.self",
  1499. web.Plaid().
  1500. EventFunc(actions.Edit).
  1501. URL(b.ContainerByName(c.ModelName).GetModelBuilder().Info().ListingHref()).
  1502. Query(presets.ParamID, c.ModelID).
  1503. Go()+fmt.Sprintf(`; vars.currEditingListItemID="%s-%d"`, dataTableID, c.ModelID))
  1504. return tdbind
  1505. })
  1506. ed.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  1507. this := obj.(*DemoContainer)
  1508. err = db.Transaction(func(tx *gorm.DB) (inerr error) {
  1509. if l10nON && strings.Contains(ctx.R.RequestURI, l10n_view.DoLocalize) {
  1510. if inerr = b.createModelAfterLocalizeDemoContainer(tx, this); inerr != nil {
  1511. panic(inerr)
  1512. return
  1513. }
  1514. }
  1515. if inerr = gorm2op.DataOperator(tx).Save(this, id, ctx); inerr != nil {
  1516. return
  1517. }
  1518. return
  1519. })
  1520. return
  1521. })
  1522. return
  1523. }
  1524. func (b *Builder) ConfigTemplate(pb *presets.Builder, db *gorm.DB) (pm *presets.ModelBuilder) {
  1525. pm = pb.Model(&Template{}).URIName("page_templates").Label("Templates")
  1526. pm.Listing("ID", "Name", "Description")
  1527. dp := pm.Detailing("Overview")
  1528. dp.Field("Overview").ComponentFunc(templateSettings(db, pm))
  1529. eb := pm.Editing("Name", "Description")
  1530. eb.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  1531. this := obj.(*Template)
  1532. err = db.Transaction(func(tx *gorm.DB) (inerr error) {
  1533. if inerr = gorm2op.DataOperator(tx).Save(obj, id, ctx); inerr != nil {
  1534. return
  1535. }
  1536. if l10nON && strings.Contains(ctx.R.RequestURI, l10n_view.DoLocalize) {
  1537. fromID := ctx.R.Context().Value(l10n_view.FromID).(string)
  1538. fromLocale := ctx.R.Context().Value(l10n_view.FromLocale).(string)
  1539. var fromIDInt int
  1540. fromIDInt, err = strconv.Atoi(fromID)
  1541. if err != nil {
  1542. return
  1543. }
  1544. if inerr = b.localizeContainersToAnotherPage(tx, fromIDInt, "tpl", fromLocale, int(this.ID), "tpl", this.GetLocale()); inerr != nil {
  1545. panic(inerr)
  1546. return
  1547. }
  1548. return
  1549. }
  1550. return
  1551. })
  1552. return
  1553. })
  1554. return
  1555. }
  1556. func sharedContainerSearcher(db *gorm.DB, mb *presets.ModelBuilder) presets.SearchFunc {
  1557. return func(obj interface{}, params *presets.SearchParams, ctx *web.EventContext) (r interface{}, totalCount int, err error) {
  1558. ilike := "ILIKE"
  1559. if db.Dialector.Name() == "sqlite" {
  1560. ilike = "LIKE"
  1561. }
  1562. wh := db.Model(obj)
  1563. if len(params.KeywordColumns) > 0 && len(params.Keyword) > 0 {
  1564. var segs []string
  1565. var args []interface{}
  1566. for _, c := range params.KeywordColumns {
  1567. segs = append(segs, fmt.Sprintf("%s %s ?", c, ilike))
  1568. args = append(args, fmt.Sprintf("%%%s%%", params.Keyword))
  1569. }
  1570. wh = wh.Where(strings.Join(segs, " OR "), args...)
  1571. }
  1572. for _, cond := range params.SQLConditions {
  1573. wh = wh.Where(strings.Replace(cond.Query, " ILIKE ", " "+ilike+" ", -1), cond.Args...)
  1574. }
  1575. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  1576. var c int64
  1577. if err = wh.Select("count(display_name)").Where("shared = true AND locale_code = ?", locale).Group("display_name, model_name, model_id, locale_code").Count(&c).Error; err != nil {
  1578. return
  1579. }
  1580. totalCount = int(c)
  1581. if params.PerPage > 0 {
  1582. wh = wh.Limit(int(params.PerPage))
  1583. page := params.Page
  1584. if page == 0 {
  1585. page = 1
  1586. }
  1587. offset := (page - 1) * params.PerPage
  1588. wh = wh.Offset(int(offset))
  1589. }
  1590. if err = wh.Select("MIN(id) AS id, display_name, model_name, model_id, locale_code").Find(obj).Error; err != nil {
  1591. return
  1592. }
  1593. r = reflect.ValueOf(obj).Elem().Interface()
  1594. return
  1595. }
  1596. }
  1597. func (b *Builder) ContainerByName(name string) (r *ContainerBuilder) {
  1598. for _, cb := range b.containerBuilders {
  1599. if cb.name == name {
  1600. return cb
  1601. }
  1602. }
  1603. panic(fmt.Sprintf("No container: %s", name))
  1604. }
  1605. type ContainerBuilder struct {
  1606. builder *Builder
  1607. name string
  1608. mb *presets.ModelBuilder
  1609. model interface{}
  1610. modelType reflect.Type
  1611. renderFunc RenderFunc
  1612. cover string
  1613. }
  1614. func (b *Builder) RegisterContainer(name string) (r *ContainerBuilder) {
  1615. r = &ContainerBuilder{
  1616. name: name,
  1617. builder: b,
  1618. }
  1619. b.containerBuilders = append(b.containerBuilders, r)
  1620. return
  1621. }
  1622. func (b *ContainerBuilder) Model(m interface{}) *ContainerBuilder {
  1623. b.model = m
  1624. b.mb = b.builder.ps.Model(m)
  1625. val := reflect.ValueOf(m)
  1626. if val.Kind() != reflect.Ptr {
  1627. panic("model pointer type required")
  1628. }
  1629. b.modelType = val.Elem().Type()
  1630. b.configureRelatedOnlinePagesTab()
  1631. return b
  1632. }
  1633. func (b *ContainerBuilder) URIName(uri string) *ContainerBuilder {
  1634. if b.mb == nil {
  1635. return b
  1636. }
  1637. b.mb.URIName(uri)
  1638. return b
  1639. }
  1640. func (b *ContainerBuilder) GetModelBuilder() *presets.ModelBuilder {
  1641. return b.mb
  1642. }
  1643. func (b *ContainerBuilder) RenderFunc(v RenderFunc) *ContainerBuilder {
  1644. b.renderFunc = v
  1645. return b
  1646. }
  1647. func (b *ContainerBuilder) Cover(v string) *ContainerBuilder {
  1648. b.cover = v
  1649. return b
  1650. }
  1651. func (b *ContainerBuilder) NewModel() interface{} {
  1652. return reflect.New(b.modelType).Interface()
  1653. }
  1654. func (b *ContainerBuilder) ModelTypeName() string {
  1655. return b.modelType.String()
  1656. }
  1657. func (b *ContainerBuilder) Editing(vs ...interface{}) *presets.EditingBuilder {
  1658. return b.mb.Editing(vs...)
  1659. }
  1660. func (b *ContainerBuilder) configureRelatedOnlinePagesTab() {
  1661. eb := b.mb.Editing()
  1662. eb.AppendTabsPanelFunc(func(obj interface{}, ctx *web.EventContext) h.HTMLComponent {
  1663. if ctx.R.FormValue(paramOpenFromSharedContainer) != "1" {
  1664. return nil
  1665. }
  1666. pmsgr := i18n.MustGetModuleMessages(ctx.R, presets.CoreI18nModuleKey, Messages_en_US).(*presets.Messages)
  1667. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  1668. id, err := reflectutils.Get(obj, "id")
  1669. if err != nil {
  1670. panic(err)
  1671. }
  1672. pages := []*Page{}
  1673. pageTable := (&Page{}).TableName()
  1674. containerTable := (&Container{}).TableName()
  1675. err = b.builder.db.Model(&Page{}).
  1676. Joins(fmt.Sprintf(`inner join %s on
  1677. %s.id = %s.page_id
  1678. and %s.version = %s.page_version
  1679. and %s.locale_code = %s.locale_code`,
  1680. containerTable,
  1681. pageTable, containerTable,
  1682. pageTable, containerTable,
  1683. pageTable, containerTable,
  1684. )).
  1685. // FIXME: add container locale condition after container supports l10n
  1686. Where(fmt.Sprintf(`%s.status = ? and %s.model_id = ? and %s.model_name = ?`,
  1687. pageTable,
  1688. containerTable,
  1689. containerTable,
  1690. ), publish.StatusOnline, id, b.name).
  1691. Group(fmt.Sprintf(`%s.id,%s.version,%s.locale_code`, pageTable, pageTable, pageTable)).
  1692. Find(&pages).
  1693. Error
  1694. if err != nil {
  1695. panic(err)
  1696. }
  1697. var pageIDs []string
  1698. var pageListComps h.HTMLComponents
  1699. for _, p := range pages {
  1700. pid := p.PrimarySlug()
  1701. pageIDs = append(pageIDs, pid)
  1702. statusVar := fmt.Sprintf(`republish_status_%s`, strings.Replace(pid, "-", "_", -1))
  1703. pageListComps = append(pageListComps, VListItem(
  1704. h.Text(fmt.Sprintf("%s (%s)", p.Title, pid)),
  1705. VSpacer(),
  1706. VIcon(fmt.Sprintf(`{{vars.%s}}`, statusVar)),
  1707. ).
  1708. Dense(true).
  1709. Attr(web.InitContextVars, fmt.Sprintf(`{%s: ""}`, statusVar)))
  1710. }
  1711. return h.Components(
  1712. VTab(h.Text(msgr.RelatedOnlinePages)),
  1713. VTabItem(
  1714. h.If(len(pages) > 0,
  1715. VList(pageListComps),
  1716. h.Div(
  1717. VSpacer(),
  1718. VBtn(msgr.RepublishAllRelatedOnlinePages).
  1719. Color("primary").
  1720. Attr("@click",
  1721. web.Plaid().
  1722. EventFunc(presets.OpenConfirmDialog).
  1723. Query(presets.ConfirmDialogConfirmEvent,
  1724. web.Plaid().
  1725. EventFunc(republishRelatedOnlinePagesEvent).
  1726. Query("ids", strings.Join(pageIDs, ",")).
  1727. Go(),
  1728. ).
  1729. Go(),
  1730. ),
  1731. ).Class("d-flex"),
  1732. ).Else(
  1733. h.Div(h.Text(pmsgr.ListingNoRecordToShow)).Class("text-center grey--text text--darken-2 mt-8"),
  1734. ),
  1735. ),
  1736. )
  1737. })
  1738. }
  1739. func republishRelatedOnlinePages(pageURL string) web.EventFunc {
  1740. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1741. ids := strings.Split(ctx.R.FormValue("ids"), ",")
  1742. for _, id := range ids {
  1743. statusVar := fmt.Sprintf(`republish_status_%s`, strings.Replace(id, "-", "_", -1))
  1744. web.AppendVarsScripts(&r,
  1745. web.Plaid().
  1746. URL(pageURL).
  1747. EventFunc(views.RepublishEvent).
  1748. Query("id", id).
  1749. Query(views.ParamScriptAfterPublish, fmt.Sprintf(`vars.%s = "done"`, statusVar)).
  1750. Query("status_var", statusVar).
  1751. Go(),
  1752. fmt.Sprintf(`vars.%s = "pending"`, statusVar),
  1753. )
  1754. }
  1755. return r, nil
  1756. }
  1757. }
  1758. func (b *Builder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  1759. if strings.Index(r.RequestURI, b.prefix+"/preview") >= 0 {
  1760. b.preview.ServeHTTP(w, r)
  1761. return
  1762. }
  1763. if strings.Index(r.RequestURI, path.Join(b.prefix, b.imagesPrefix)) >= 0 {
  1764. b.images.ServeHTTP(w, r)
  1765. return
  1766. }
  1767. b.ps.ServeHTTP(w, r)
  1768. }