builder.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997
  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.Dialog).
  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.Field("EditContainer").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  499. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  500. p := obj.(*Page)
  501. if p.ID == 0 {
  502. return nil
  503. }
  504. if p.GetStatus() == publish.StatusDraft {
  505. var href = fmt.Sprintf("%s/editors/%d?version=%s", b.prefix, p.ID, p.GetVersion())
  506. if locale, isLocalizable := l10n.IsLocalizableFromCtx(ctx.R.Context()); isLocalizable && l10nON {
  507. href = fmt.Sprintf("%s/editors/%d?version=%s&locale=%s", b.prefix, p.ID, p.GetVersion(), locale)
  508. }
  509. return h.Div(
  510. VBtn(msgr.EditPageContent).
  511. Target("_blank").
  512. Href(href).
  513. Color("secondary"),
  514. )
  515. } else {
  516. var href = fmt.Sprintf("%s/preview?id=%d&version=%s", b.prefix, p.ID, p.GetVersion())
  517. if locale, isLocalizable := l10n.IsLocalizableFromCtx(ctx.R.Context()); isLocalizable && l10nON {
  518. href = fmt.Sprintf("%s/preview?id=%d&version=%s&locale=%s", b.prefix, p.ID, p.GetVersion(), locale)
  519. }
  520. return h.Div(
  521. VBtn(msgr.Preview).
  522. Target("_blank").
  523. Href(href).
  524. Color("secondary"),
  525. )
  526. }
  527. return nil
  528. })
  529. eb.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  530. localeCode, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  531. p := obj.(*Page)
  532. if p.Slug != "" {
  533. p.Slug = path.Clean(p.Slug)
  534. }
  535. funcName := ctx.R.FormValue(web.EventFuncIDName)
  536. if funcName == pv.DuplicateVersionEvent {
  537. id := ctx.R.FormValue(presets.ParamID)
  538. var fromPage Page
  539. eb.Fetcher(&fromPage, id, ctx)
  540. p.SEO = fromPage.SEO
  541. }
  542. err = db.Transaction(func(tx *gorm.DB) (inerr error) {
  543. if inerr = gorm2op.DataOperator(tx).Save(obj, id, ctx); inerr != nil {
  544. return
  545. }
  546. if strings.Contains(ctx.R.RequestURI, pv.SaveNewVersionEvent) || strings.Contains(ctx.R.RequestURI, pv.DuplicateVersionEvent) {
  547. if inerr = b.copyContainersToNewPageVersion(tx, int(p.ID), p.GetLocale(), p.ParentVersion, p.GetVersion()); inerr != nil {
  548. return
  549. }
  550. return
  551. }
  552. if v := ctx.R.FormValue(templateSelectedID); v != "" {
  553. var tplID int
  554. tplID, inerr = strconv.Atoi(v)
  555. if inerr != nil {
  556. return
  557. }
  558. if !l10nON {
  559. localeCode = ""
  560. }
  561. if inerr = b.copyContainersToAnotherPage(tx, tplID, templateVersion, localeCode, int(p.ID), p.GetVersion(), localeCode); inerr != nil {
  562. panic(inerr)
  563. return
  564. }
  565. }
  566. if l10nON && strings.Contains(ctx.R.RequestURI, l10n_view.DoLocalize) {
  567. fromID := ctx.R.Context().Value(l10n_view.FromID).(string)
  568. fromVersion := ctx.R.Context().Value(l10n_view.FromVersion).(string)
  569. fromLocale := ctx.R.Context().Value(l10n_view.FromLocale).(string)
  570. var fromIDInt int
  571. fromIDInt, err = strconv.Atoi(fromID)
  572. if err != nil {
  573. return
  574. }
  575. if inerr = b.localizeContainersToAnotherPage(tx, fromIDInt, fromVersion, fromLocale, int(p.ID), p.GetVersion(), p.GetLocale()); inerr != nil {
  576. panic(inerr)
  577. return
  578. }
  579. return
  580. }
  581. return
  582. })
  583. return
  584. })
  585. sharedContainerM := b.ConfigSharedContainer(pb, db)
  586. demoContainerM := b.ConfigDemoContainer(pb, db)
  587. categoryM := b.ConfigCategory(pb, db, l10nB)
  588. if activityB != nil {
  589. activityB.RegisterModels(pm, sharedContainerM, demoContainerM, templateM, categoryM)
  590. }
  591. if l10nB != nil {
  592. l10n_view.Configure(pb, db, l10nB, activityB, pm, demoContainerM, templateM, categoryM)
  593. }
  594. if publisher != nil {
  595. publisher.WithPageBuilder(b)
  596. pv.Configure(pb, db, activityB, publisher, pm)
  597. pm.Editing().SidePanelFunc(nil).ActionsFunc(nil)
  598. }
  599. if seoCollection != nil {
  600. seoCollection.RegisterSEO(&Page{}).RegisterContextVariables(
  601. "Title",
  602. func(object interface{}, _ *seo.Setting, _ *http.Request) string {
  603. if p, ok := object.(Page); ok {
  604. return p.Title
  605. }
  606. return ""
  607. },
  608. )
  609. }
  610. note.Configure(db, pb, pm)
  611. eb.CleanTabsPanels()
  612. dp.CleanTabsPanels()
  613. mediav.Configure(b.GetPresetsBuilder(), db)
  614. return
  615. }
  616. func versionCount(db *gorm.DB, p *Page) (count int64) {
  617. db.Model(&Page{}).Where("id = ? and locale_code = ?", p.ID, p.LocaleCode).Count(&count)
  618. return
  619. }
  620. func configureVersionListDialog(db *gorm.DB, pb *presets.Builder, pm *presets.ModelBuilder) {
  621. mb := pb.Model(&Page{}).
  622. URIName("version-list-dialog").
  623. InMenu(false)
  624. searcher := mb.Listing().Searcher
  625. lb := mb.Listing("Version", "State", "Notes", "Option").
  626. SearchColumns("version", "version_name").
  627. PerPage(10).
  628. SearchFunc(func(model interface{}, params *presets.SearchParams, ctx *web.EventContext) (r interface{}, totalCount int, err error) {
  629. id := ctx.R.FormValue("select_id")
  630. if id == "" {
  631. id = ctx.R.FormValue("f_select_id")
  632. }
  633. if id != "" {
  634. cs := mb.NewModel().(presets.SlugDecoder).PrimaryColumnValuesBySlug(id)
  635. con := presets.SQLCondition{
  636. Query: "id = ? and locale_code = ?",
  637. Args: []interface{}{cs["id"], cs["locale_code"]},
  638. }
  639. params.SQLConditions = append(params.SQLConditions, &con)
  640. }
  641. params.OrderBy = "created_at DESC"
  642. return searcher(model, params, ctx)
  643. })
  644. lb.Field("Version").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  645. versionName := obj.(publish.VersionInterface).GetVersionName()
  646. return h.Td(
  647. h.Text(versionName),
  648. VBtn("").Icon(true).Children(VIcon("edit")).Attr("@click", web.Plaid().
  649. URL(pb.GetURIPrefix()+"/version-list-dialog").
  650. EventFunc(renameVersionDialogEvent).
  651. Queries(ctx.Queries()).
  652. Query(presets.ParamOverlay, actions.Dialog).
  653. Query("rename_id", obj.(presets.SlugEncoder).PrimarySlug()).
  654. Query("version_name", versionName).
  655. Go()),
  656. )
  657. })
  658. lb.Field("State").ComponentFunc(pv.StatusListFunc())
  659. lb.Field("Notes").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  660. p := obj.(*Page)
  661. rt := pm.Info().Label()
  662. ri := p.PrimarySlug()
  663. userID, _ := note.GetUserData(ctx)
  664. count := note.GetUnreadNotesCount(db, userID, rt, ri)
  665. return h.Td(
  666. h.If(count > 0,
  667. VBadge().Content(count).Color("red"),
  668. ).Else(
  669. h.Text(""),
  670. ),
  671. )
  672. }).Label("Unread Notes")
  673. lb.Field("Option").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  674. p := obj.(*Page)
  675. id := ctx.R.FormValue("select_id")
  676. if id == "" {
  677. id = ctx.R.FormValue("f_select_id")
  678. }
  679. versionName := p.GetVersionName()
  680. if p.PrimarySlug() == id {
  681. return h.Td(h.Text("current"))
  682. }
  683. if p.GetStatus() != publish.StatusDraft {
  684. return h.Td()
  685. }
  686. return h.Td(VBtn("").Icon(true).Children(VIcon("delete")).Attr("@click", web.Plaid().
  687. URL(pb.GetURIPrefix()+"/version-list-dialog").
  688. EventFunc(deleteVersionDialogEvent).
  689. Queries(ctx.Queries()).
  690. Query(presets.ParamOverlay, actions.Dialog).
  691. Query("delete_id", obj.(presets.SlugEncoder).PrimarySlug()).
  692. Query("version_name", versionName).
  693. Go()))
  694. })
  695. lb.NewButtonFunc(func(ctx *web.EventContext) h.HTMLComponent { return nil })
  696. lb.RowMenu().Empty()
  697. mb.RegisterEventFunc(selectVersionEvent, func(ctx *web.EventContext) (r web.EventResponse, err error) {
  698. id := ctx.R.FormValue("select_id")
  699. refer, _ := url.Parse(ctx.R.Referer())
  700. newQueries := refer.Query()
  701. r.PushState = web.Location(newQueries).URL(pm.Info().DetailingHref(id))
  702. return
  703. })
  704. mb.RegisterEventFunc(renameVersionDialogEvent, renameVersionDialog(mb))
  705. mb.RegisterEventFunc(renameVersionEvent, renameVersion(mb))
  706. mb.RegisterEventFunc(deleteVersionDialogEvent, deleteVersionDialog(mb))
  707. lb.CellWrapperFunc(func(cell h.MutableAttrHTMLComponent, id string, obj interface{}, dataTableID string) h.HTMLComponent {
  708. cell.SetAttr("@click.self", web.Plaid().
  709. Query("select_id", obj.(*Page).PrimarySlug()).
  710. URL(pb.GetURIPrefix()+"/version-list-dialog").
  711. EventFunc(selectVersionEvent).
  712. Go(),
  713. )
  714. return cell
  715. })
  716. lb.FilterDataFunc(func(ctx *web.EventContext) vx.FilterData {
  717. return []*vx.FilterItem{
  718. {
  719. Key: "all",
  720. Invisible: true,
  721. SQLCondition: ``,
  722. },
  723. {
  724. Key: "online_version",
  725. Invisible: true,
  726. SQLCondition: `status = 'online'`,
  727. },
  728. {
  729. Key: "named_versions",
  730. Invisible: true,
  731. SQLCondition: `version <> version_name`,
  732. },
  733. }
  734. })
  735. lb.FilterTabsFunc(func(ctx *web.EventContext) []*presets.FilterTab {
  736. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  737. id := ctx.R.FormValue("select_id")
  738. if id == "" {
  739. id = ctx.R.FormValue("f_select_id")
  740. }
  741. return []*presets.FilterTab{
  742. {
  743. Label: msgr.FilterTabAllVersions,
  744. ID: "all",
  745. Query: url.Values{"all": []string{"1"}, "select_id": []string{id}},
  746. },
  747. {
  748. Label: msgr.FilterTabOnlineVersion,
  749. ID: "online_version",
  750. Query: url.Values{"online_version": []string{"1"}, "select_id": []string{id}},
  751. },
  752. {
  753. Label: msgr.FilterTabNamedVersions,
  754. ID: "named_versions",
  755. Query: url.Values{"named_versions": []string{"1"}, "select_id": []string{id}},
  756. },
  757. }
  758. })
  759. }
  760. // cats should be ordered by path
  761. func fillCategoryIndentLevels(cats []*Category) {
  762. for i, cat := range cats {
  763. if cat.Path == "/" {
  764. continue
  765. }
  766. for j := i - 1; j >= 0; j-- {
  767. if strings.HasPrefix(cat.Path, cats[j].Path+"/") {
  768. cat.IndentLevel = cats[j].IndentLevel + 1
  769. break
  770. }
  771. }
  772. }
  773. }
  774. func (b *Builder) ConfigCategory(pb *presets.Builder, db *gorm.DB, l10nB *l10n.Builder) (pm *presets.ModelBuilder) {
  775. pm = pb.Model(&Category{}).URIName("page_categories").Label("Categories")
  776. lb := pm.Listing("Name", "Path", "Description")
  777. oldSearcher := lb.Searcher
  778. lb.SearchFunc(func(model interface{}, params *presets.SearchParams, ctx *web.EventContext) (r interface{}, totalCount int, err error) {
  779. r, totalCount, err = oldSearcher(model, params, ctx)
  780. cats := r.([]*Category)
  781. sort.Slice(cats, func(i, j int) bool {
  782. return cats[i].Path < cats[j].Path
  783. })
  784. fillCategoryIndentLevels(cats)
  785. return
  786. })
  787. lb.Field("Name").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  788. cat := obj.(*Category)
  789. icon := "folder"
  790. if cat.IndentLevel != 0 {
  791. icon = "insert_drive_file"
  792. }
  793. return h.Td(
  794. h.Div(
  795. VIcon(icon).Small(true).Class("mb-1"),
  796. h.Text(cat.Name),
  797. ).Style(fmt.Sprintf("padding-left: %dpx;", cat.IndentLevel*32)),
  798. )
  799. })
  800. eb := pm.Editing("Name", "Path", "Description")
  801. eb.Field("Path").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  802. var vErr web.ValidationErrors
  803. if ve, ok := ctx.Flash.(*web.ValidationErrors); ok {
  804. vErr = *ve
  805. }
  806. return VTextField().Label("Path").
  807. Value(strings.TrimPrefix(field.Value(obj).(string), "/")).
  808. FieldName("Path").
  809. Prefix("/").
  810. ErrorMessages(vErr.GetFieldErrors("Category.Category")...)
  811. }).SetterFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) (err error) {
  812. m := obj.(*Category)
  813. p := ctx.R.FormValue(field.Name)
  814. p = path.Join("/", p)
  815. m.Path = p
  816. return nil
  817. })
  818. eb.DeleteFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  819. cs := obj.(presets.SlugDecoder).PrimaryColumnValuesBySlug(id)
  820. ID := cs["id"]
  821. Locale := cs["locale_code"]
  822. var count int64
  823. if err = db.Model(&Page{}).Where("category_id = ? AND locale_code = ?", ID, Locale).Count(&count).Error; err != nil {
  824. return
  825. }
  826. if count > 0 {
  827. err = errors.New(unableDeleteCategoryMsg)
  828. return
  829. }
  830. if err = db.Model(&Category{}).Where("id = ? AND locale_code = ?", ID, Locale).Delete(&Category{}).Error; err != nil {
  831. return
  832. }
  833. return
  834. })
  835. eb.ValidateFunc(func(obj interface{}, ctx *web.EventContext) (err web.ValidationErrors) {
  836. c := obj.(*Category)
  837. err = categoryValidator(c, db, l10nB)
  838. return
  839. })
  840. eb.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  841. c := obj.(*Category)
  842. c.Path = path.Clean(c.Path)
  843. err = db.Save(c).Error
  844. return
  845. })
  846. return
  847. }
  848. const (
  849. templateSelectPortal = "templateSelectPortal"
  850. selectedTemplatePortal = "selectedTemplatePortal"
  851. templateSelectedID = "TemplateSelectedID"
  852. templateID = "TemplateID"
  853. templateBlankVal = "blank"
  854. )
  855. func selectTemplate(db *gorm.DB) web.EventFunc {
  856. return func(ctx *web.EventContext) (er web.EventResponse, err error) {
  857. defer func() {
  858. web.AppendVarsScripts(&er, "vars.showTemplateDialog=false")
  859. }()
  860. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  861. id := ctx.R.FormValue(templateID)
  862. if id == templateBlankVal {
  863. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  864. Name: selectedTemplatePortal,
  865. Body: VRow(
  866. VCol(
  867. h.Input("").Type("hidden").Value("").Attr(web.VFieldName(templateSelectedID)...),
  868. VTextField().Readonly(true).Label(msgr.SelectedTemplateLabel).Value(msgr.Blank).Dense(true).Outlined(true),
  869. ).Cols(5),
  870. VCol(
  871. VBtn(msgr.ChangeTemplate).Color("primary").
  872. Attr("@click", web.Plaid().Query(templateSelectedID, "").EventFunc(openTemplateDialogEvent).Go()),
  873. ).Cols(5),
  874. ),
  875. })
  876. return
  877. }
  878. var body h.HTMLComponent
  879. if body, err = getTplPortalComp(ctx, db, id); err != nil {
  880. return
  881. }
  882. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  883. Name: selectedTemplatePortal,
  884. Body: body,
  885. })
  886. return
  887. }
  888. }
  889. func getTplPortalComp(ctx *web.EventContext, db *gorm.DB, selectedID string) (h.HTMLComponent, error) {
  890. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  891. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  892. name := msgr.Blank
  893. if selectedID != "" {
  894. if err := db.Model(&Template{}).Where("id = ? AND locale_code = ?", selectedID, locale).Pluck("name", &name).Error; err != nil {
  895. return nil, err
  896. }
  897. }
  898. return VRow(
  899. VCol(
  900. h.Input("").Type("hidden").Value(selectedID).Attr(web.VFieldName(templateSelectedID)...),
  901. VTextField().Readonly(true).Label(msgr.SelectedTemplateLabel).Value(name).Dense(true).Outlined(true),
  902. ).Cols(5),
  903. VCol(
  904. VBtn(msgr.ChangeTemplate).Color("primary").
  905. Attr("@click", web.Plaid().Query(templateSelectedID, selectedID).EventFunc(openTemplateDialogEvent).Go()),
  906. ).Cols(5),
  907. ), nil
  908. }
  909. // Unused
  910. func clearTemplate(db *gorm.DB) web.EventFunc {
  911. return func(ctx *web.EventContext) (er web.EventResponse, err error) {
  912. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  913. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  914. Name: selectedTemplatePortal,
  915. Body: VRow(
  916. VCol(
  917. h.Input("").Type("hidden").Value("").Attr(web.VFieldName(templateSelectedID)...),
  918. VTextField().Readonly(true).Label(msgr.SelectedTemplateLabel).Value(msgr.Blank).Dense(true).Outlined(true),
  919. ).Cols(5),
  920. VCol(
  921. VBtn(msgr.ChangeTemplate).Color("primary").
  922. Attr("@click", web.Plaid().Query(templateSelectedID, "").EventFunc(openTemplateDialogEvent).Go()),
  923. ).Cols(5),
  924. ),
  925. })
  926. return
  927. }
  928. }
  929. func openTemplateDialog(db *gorm.DB, prefix string) web.EventFunc {
  930. return func(ctx *web.EventContext) (er web.EventResponse, err error) {
  931. gmsgr := presets.MustGetMessages(ctx.R)
  932. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  933. selectedID := ctx.R.FormValue(templateSelectedID)
  934. tpls := []*Template{}
  935. if err := db.Model(&Template{}).Where("locale_code = ?", locale).Find(&tpls).Error; err != nil {
  936. panic(err)
  937. }
  938. msgrPb := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  939. var tplHTMLComponents []h.HTMLComponent
  940. tplHTMLComponents = append(tplHTMLComponents,
  941. VCol(
  942. VCard(
  943. h.Div(
  944. h.Iframe().
  945. Attr("width", "100%", "height", "150", "frameborder", "no").
  946. Style("transform-origin: left top; transform: scale(1, 1); pointer-events: none;"),
  947. ),
  948. VCardTitle(h.Text(msgrPb.Blank)),
  949. VCardSubtitle(h.Text("")),
  950. h.Div(
  951. h.Input(templateID).Type("radio").
  952. Value(templateBlankVal).
  953. Attr(web.VFieldName(templateID)...).
  954. AttrIf("checked", "checked", selectedID == "").
  955. Style("width: 18px; height: 18px"),
  956. ).Class("mr-4 float-right"),
  957. ).Height(280).Class("text-truncate").Outlined(true),
  958. ).Cols(3),
  959. )
  960. for _, tpl := range tpls {
  961. tplHTMLComponents = append(tplHTMLComponents,
  962. getTplColComponent(ctx, prefix, tpl, selectedID),
  963. )
  964. }
  965. if len(tpls) == 0 {
  966. tplHTMLComponents = append(tplHTMLComponents,
  967. h.Div(h.Text(gmsgr.ListingNoRecordToShow)).Class("pl-4 text-center grey--text text--darken-2"),
  968. )
  969. }
  970. er.UpdatePortals = append(er.UpdatePortals, &web.PortalUpdate{
  971. Name: templateSelectPortal,
  972. Body: VDialog(
  973. VCard(
  974. VCardTitle(
  975. h.Text(msgrPb.CreateFromTemplate),
  976. VSpacer(),
  977. VBtn("").Icon(true).
  978. Children(VIcon("close")).
  979. Large(true).
  980. On("click", fmt.Sprintf("vars.showTemplateDialog=false")),
  981. ),
  982. VCardActions(
  983. VRow(tplHTMLComponents...),
  984. ),
  985. VCardActions(
  986. VSpacer(),
  987. VBtn(gmsgr.Cancel).Attr("@click", "vars.showTemplateDialog=false"),
  988. VBtn(gmsgr.OK).Color("primary").
  989. Attr("@click", web.Plaid().EventFunc(selectTemplateEvent).
  990. Go(),
  991. ),
  992. ).Class("pb-4"),
  993. ).Tile(true),
  994. ).MaxWidth("80%").
  995. Attr("v-model", fmt.Sprintf("vars.showTemplateDialog")).
  996. Attr(web.InitContextVars, fmt.Sprintf(`{showTemplateDialog: false}`)),
  997. })
  998. er.VarsScript = `setTimeout(function(){ vars.showTemplateDialog = true }, 100)`
  999. return
  1000. }
  1001. }
  1002. func getTplColComponent(ctx *web.EventContext, prefix string, tpl *Template, selectedID string) h.HTMLComponent {
  1003. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  1004. // Avoid layout errors
  1005. var name string
  1006. var desc string
  1007. if tpl.Name == "" {
  1008. name = msgr.Unnamed
  1009. } else {
  1010. name = tpl.Name
  1011. }
  1012. if tpl.Description == "" {
  1013. desc = msgr.NotDescribed
  1014. } else {
  1015. desc = tpl.Description
  1016. }
  1017. id := fmt.Sprintf("%d", tpl.ID)
  1018. src := fmt.Sprintf("./%s/preview?id=%d&tpl=1&locale=%s", prefix, tpl.ID, tpl.LocaleCode)
  1019. return VCol(
  1020. VCard(
  1021. h.Div(
  1022. h.Iframe().Src(src).
  1023. Attr("width", "100%", "height", "150", "frameborder", "no").
  1024. Style("transform-origin: left top; transform: scale(1, 1); pointer-events: none;"),
  1025. ),
  1026. VCardTitle(h.Text(name)),
  1027. VCardSubtitle(h.Text(desc)),
  1028. VBtn(msgr.Preview).Text(true).XSmall(true).Class("ml-2 mb-4").
  1029. Href(src).
  1030. Target("_blank").Color("primary"),
  1031. h.Div(
  1032. h.Input(templateID).Type("radio").
  1033. Value(id).
  1034. Attr(web.VFieldName(templateID)...).
  1035. AttrIf("checked", "checked", selectedID == id).
  1036. Style("width: 18px; height: 18px"),
  1037. ).Class("mr-4 float-right"),
  1038. ).Height(280).Class("text-truncate").Outlined(true),
  1039. ).Cols(3)
  1040. }
  1041. func schedulePublishDialog(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1042. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1043. paramID := ctx.R.FormValue(presets.ParamID)
  1044. obj := mb.NewModel()
  1045. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1046. if err != nil {
  1047. return
  1048. }
  1049. s, ok := obj.(publish.ScheduleInterface)
  1050. if !ok {
  1051. return
  1052. }
  1053. var start, end string
  1054. if s.GetScheduledStartAt() != nil {
  1055. start = s.GetScheduledStartAt().Format("2006-01-02 15:04")
  1056. }
  1057. if s.GetScheduledEndAt() != nil {
  1058. end = s.GetScheduledEndAt().Format("2006-01-02 15:04")
  1059. }
  1060. msgr := i18n.MustGetModuleMessages(ctx.R, pv.I18nPublishKey, Messages_en_US).(*pv.Messages)
  1061. cmsgr := i18n.MustGetModuleMessages(ctx.R, presets.CoreI18nModuleKey, Messages_en_US).(*presets.Messages)
  1062. updateBtn := VBtn(cmsgr.Update).
  1063. Color("primary").
  1064. Attr(":disabled", "isFetching").
  1065. Attr(":loading", "isFetching").
  1066. Attr("@click", web.Plaid().
  1067. EventFunc(schedulePublishEvent).
  1068. // Queries(queries).
  1069. Query(presets.ParamID, paramID).
  1070. Query(presets.ParamOverlay, actions.Dialog).
  1071. URL(mb.Info().ListingHref()).
  1072. Go())
  1073. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1074. Name: dialogPortalName,
  1075. Body: web.Scope(
  1076. VDialog(
  1077. VCard(
  1078. VCardTitle(h.Text("Schedule Publish Time")),
  1079. VCardText(
  1080. VRow(
  1081. VCol(
  1082. vx.VXDateTimePicker().FieldName("ScheduledStartAt").Label(msgr.ScheduledStartAt).Value(start).
  1083. TimePickerProps(vx.TimePickerProps{Format: "24hr", Scrollable: true}).
  1084. ClearText(msgr.DateTimePickerClearText).OkText(msgr.DateTimePickerOkText),
  1085. // h.RawHTML(fmt.Sprintf(`<vx-datetimepicker label="ScheduledStartAt" value="%s" v-field-name='"ScheduledStartAt"'> </vx-datetimepicker>`, start)),
  1086. ).Cols(6),
  1087. VCol(
  1088. vx.VXDateTimePicker().FieldName("ScheduledEndAt").Label(msgr.ScheduledEndAt).Value(end).
  1089. TimePickerProps(vx.TimePickerProps{Format: "24hr", Scrollable: true}).
  1090. ClearText(msgr.DateTimePickerClearText).OkText(msgr.DateTimePickerOkText),
  1091. // h.RawHTML(fmt.Sprintf(`<vx-datetimepicker label="ScheduledEndAt" value="%s" v-field-name='"ScheduledEndAt"'> </vx-datetimepicker>`, end)),
  1092. ).Cols(6),
  1093. ),
  1094. ),
  1095. VCardActions(
  1096. VSpacer(),
  1097. updateBtn,
  1098. ),
  1099. ),
  1100. ).MaxWidth("480px").
  1101. Attr("v-model", "locals.schedulePublishDialog"),
  1102. ).Init("{schedulePublishDialog:true}").VSlot("{locals}"),
  1103. })
  1104. return
  1105. }
  1106. }
  1107. func schedulePublish(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1108. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1109. paramID := ctx.R.FormValue(presets.ParamID)
  1110. obj := mb.NewModel()
  1111. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1112. if err != nil {
  1113. return
  1114. }
  1115. err = pv.ScheduleEditSetterFunc(obj, nil, ctx)
  1116. if err != nil {
  1117. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1118. return
  1119. }
  1120. err = mb.Editing().Saver(obj, paramID, ctx)
  1121. if err != nil {
  1122. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1123. return
  1124. }
  1125. r.PushState = web.Location(nil)
  1126. return
  1127. }
  1128. }
  1129. func createNoteDialog(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1130. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1131. paramID := ctx.R.FormValue(presets.ParamID)
  1132. okAction := web.Plaid().
  1133. URL(mb.Info().ListingHref()).
  1134. EventFunc(createNoteEvent).
  1135. Query("resource_id", paramID).
  1136. Query("resource_type", mb.Info().Label()).
  1137. Query(presets.ParamOverlay, actions.Dialog).Go()
  1138. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1139. Name: dialogPortalName,
  1140. Body: web.Scope(
  1141. VDialog(
  1142. VCard(
  1143. VCardTitle(h.Text("Note")),
  1144. VCardText(
  1145. VTextField().FieldName("Content").Value(""),
  1146. ),
  1147. VCardActions(
  1148. VSpacer(),
  1149. VBtn("Cancel").
  1150. Depressed(true).
  1151. Class("ml-2").
  1152. On("click", "locals.createNoteDialog = false"),
  1153. VBtn("OK").
  1154. Color("primary").
  1155. Depressed(true).
  1156. Dark(true).
  1157. Attr("@click", okAction),
  1158. ),
  1159. ),
  1160. ).MaxWidth("420px").Attr("v-model", "locals.createNoteDialog"),
  1161. ).Init("{createNoteDialog:true}").VSlot("{locals}"),
  1162. })
  1163. return
  1164. }
  1165. }
  1166. func createNote(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1167. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1168. ri := ctx.R.FormValue("resource_id")
  1169. rt := ctx.R.FormValue("resource_type")
  1170. content := ctx.R.FormValue("Content")
  1171. userID, creator := note.GetUserData(ctx)
  1172. nt := note.QorNote{
  1173. UserID: userID,
  1174. Creator: creator,
  1175. ResourceID: ri,
  1176. ResourceType: rt,
  1177. Content: content,
  1178. }
  1179. if err = db.Save(&nt).Error; err != nil {
  1180. presets.ShowMessage(&r, err.Error(), "error")
  1181. err = nil
  1182. return
  1183. }
  1184. userNote := note.UserNote{UserID: userID, ResourceType: rt, ResourceID: ri}
  1185. db.Where(userNote).FirstOrCreate(&userNote)
  1186. var total int64
  1187. db.Model(&note.QorNote{}).Where("resource_type = ? AND resource_id = ?", rt, ri).Count(&total)
  1188. db.Model(&userNote).UpdateColumn("Number", total)
  1189. r.PushState = web.Location(nil)
  1190. return
  1191. }
  1192. }
  1193. func editSEODialog(db *gorm.DB, mb *presets.ModelBuilder, seoCollection *seo.Collection) web.EventFunc {
  1194. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1195. paramID := ctx.R.FormValue(presets.ParamID)
  1196. obj := mb.NewModel()
  1197. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1198. if err != nil {
  1199. return
  1200. }
  1201. // msgr := i18n.MustGetModuleMessages(ctx.R, pv.I18nPublishKey, Messages_en_US).(*pv.Messages)
  1202. cmsgr := i18n.MustGetModuleMessages(ctx.R, presets.CoreI18nModuleKey, Messages_en_US).(*presets.Messages)
  1203. updateBtn := VBtn(cmsgr.Update).
  1204. Color("primary").
  1205. Attr(":disabled", "isFetching").
  1206. Attr(":loading", "isFetching").
  1207. Attr("@click", web.Plaid().
  1208. EventFunc(updateSEOEvent).
  1209. // Queries(queries).
  1210. Query(presets.ParamID, paramID).
  1211. // Query(presets.ParamOverlay, actions.Dialog).
  1212. URL(mb.Info().ListingHref()).
  1213. Go())
  1214. ctx.R.Form.Set("openCustomizePanel", "0")
  1215. seoForm := seoCollection.EditingComponentFunc(obj, nil, ctx)
  1216. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1217. Name: dialogPortalName,
  1218. Body: web.Scope(
  1219. VDialog(
  1220. VCard(
  1221. VCardTitle(h.Text("")),
  1222. VCardText(
  1223. seoForm,
  1224. ),
  1225. VCardActions(
  1226. VSpacer(),
  1227. updateBtn,
  1228. ),
  1229. ),
  1230. ).MaxWidth("650px").
  1231. Attr("v-model", "locals.editSEODialog"),
  1232. ).Init("{editSEODialog:true}").VSlot("{locals}"),
  1233. })
  1234. return
  1235. }
  1236. }
  1237. func updateSEO(db *gorm.DB, mb *presets.ModelBuilder) web.EventFunc {
  1238. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1239. paramID := ctx.R.FormValue(presets.ParamID)
  1240. obj := mb.NewModel()
  1241. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1242. if err != nil {
  1243. return
  1244. }
  1245. err = seo.EditSetterFunc(obj, &presets.FieldContext{Name: "SEO"}, ctx)
  1246. if err != nil {
  1247. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1248. return
  1249. }
  1250. err = mb.Editing().Saver(obj, paramID, ctx)
  1251. if err != nil {
  1252. mb.Editing().UpdateOverlayContent(ctx, &r, obj, "", err)
  1253. return
  1254. }
  1255. r.PushState = web.Location(nil)
  1256. return
  1257. }
  1258. }
  1259. func renameVersionDialog(mb *presets.ModelBuilder) web.EventFunc {
  1260. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1261. id := ctx.R.FormValue("rename_id")
  1262. versionName := ctx.R.FormValue("version_name")
  1263. okAction := web.Plaid().
  1264. URL(mb.Info().ListingHref()).
  1265. EventFunc(renameVersionEvent).
  1266. Queries(ctx.Queries()).
  1267. Query("rename_id", id).Go()
  1268. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1269. Name: dialogPortalName,
  1270. Body: web.Scope(
  1271. VDialog(
  1272. VCard(
  1273. VCardTitle(h.Text("Version")),
  1274. VCardText(
  1275. VTextField().FieldName("VersionName").Value(versionName),
  1276. ),
  1277. VCardActions(
  1278. VSpacer(),
  1279. VBtn("Cancel").
  1280. Depressed(true).
  1281. Class("ml-2").
  1282. On("click", "locals.renameVersionDialog = false"),
  1283. VBtn("OK").
  1284. Color("primary").
  1285. Depressed(true).
  1286. Dark(true).
  1287. Attr("@click", "locals.renameVersionDialog = false; "+okAction),
  1288. ),
  1289. ),
  1290. ).MaxWidth("420px").Attr("v-model", "locals.renameVersionDialog"),
  1291. ).Init("{renameVersionDialog:true}").VSlot("{locals}"),
  1292. })
  1293. return
  1294. }
  1295. }
  1296. func renameVersion(mb *presets.ModelBuilder) web.EventFunc {
  1297. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1298. paramID := ctx.R.FormValue("rename_id")
  1299. obj := mb.NewModel()
  1300. obj, err = mb.Editing().Fetcher(obj, paramID, ctx)
  1301. if err != nil {
  1302. return
  1303. }
  1304. name := ctx.R.FormValue("VersionName")
  1305. if err = reflectutils.Set(obj, "Version.VersionName", name); err != nil {
  1306. return
  1307. }
  1308. if err = mb.Editing().Saver(obj, paramID, ctx); err != nil {
  1309. return
  1310. }
  1311. qs := ctx.Queries()
  1312. delete(qs, "version_name")
  1313. delete(qs, "rename_id")
  1314. r.VarsScript = web.Plaid().URL(ctx.R.RequestURI).Queries(qs).EventFunc(actions.UpdateListingDialog).Go()
  1315. return
  1316. }
  1317. }
  1318. func deleteVersionDialog(mb *presets.ModelBuilder) web.EventFunc {
  1319. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1320. id := ctx.R.FormValue("delete_id")
  1321. versionName := ctx.R.FormValue("version_name")
  1322. r.UpdatePortals = append(r.UpdatePortals, &web.PortalUpdate{
  1323. Name: presets.DeleteConfirmPortalName,
  1324. Body: VDialog(
  1325. VCard(
  1326. VCardTitle(h.Text(fmt.Sprintf("Are you sure you want to delete %s?", versionName))),
  1327. VCardActions(
  1328. VSpacer(),
  1329. VBtn("Cancel").
  1330. Depressed(true).
  1331. Class("ml-2").
  1332. On("click", "vars.deleteConfirmation = false"),
  1333. VBtn("Delete").
  1334. Color("primary").
  1335. Depressed(true).
  1336. Dark(true).
  1337. Attr("@click", web.Plaid().
  1338. URL(mb.Info().ListingHref()).
  1339. EventFunc(actions.DoDelete).
  1340. Queries(ctx.Queries()).
  1341. Query(presets.ParamInDialog, true).
  1342. Query(presets.ParamID, id).Go()),
  1343. ),
  1344. ),
  1345. ).MaxWidth("580px").
  1346. Attr("v-model", "vars.deleteConfirmation").
  1347. Attr(web.InitContextVars, `{deleteConfirmation: false}`),
  1348. })
  1349. r.VarsScript = "setTimeout(function(){ vars.deleteConfirmation = true }, 100)"
  1350. return
  1351. }
  1352. }
  1353. func (b *Builder) ConfigSharedContainer(pb *presets.Builder, db *gorm.DB) (pm *presets.ModelBuilder) {
  1354. pm = pb.Model(&Container{}).URIName("shared_containers").Label("Shared Containers")
  1355. pm.RegisterEventFunc(republishRelatedOnlinePagesEvent, republishRelatedOnlinePages(b.mb.Info().ListingHref()))
  1356. listing := pm.Listing("DisplayName").SearchColumns("display_name")
  1357. listing.RowMenu("").Empty()
  1358. // ed := pm.Editing("SelectContainer")
  1359. // ed.Field("SelectContainer").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  1360. // var containers []h.HTMLComponent
  1361. // for _, builder := range b.containerBuilders {
  1362. // cover := builder.cover
  1363. // if cover == "" {
  1364. // cover = path.Join(b.prefix, b.imagesPrefix, strings.ReplaceAll(builder.name, " ", "")+".png")
  1365. // }
  1366. // containers = append(containers,
  1367. // VCol(
  1368. // VCard(
  1369. // VImg().Src(cover).Height(200),
  1370. // VCardActions(
  1371. // VCardTitle(h.Text(builder.name)),
  1372. // VSpacer(),
  1373. // VBtn("Select").
  1374. // Text(true).
  1375. // Color("primary").Attr("@click",
  1376. // web.Plaid().
  1377. // EventFunc(actions.New).
  1378. // URL(builder.GetModelBuilder().Info().ListingHref()).
  1379. // Go()),
  1380. // ),
  1381. // ),
  1382. // ).Cols(6),
  1383. // )
  1384. // }
  1385. // return VSheet(
  1386. // VContainer(
  1387. // VRow(
  1388. // containers...,
  1389. // ),
  1390. // ),
  1391. // )
  1392. // })
  1393. if permB := pb.GetPermission(); permB != nil {
  1394. permB.CreatePolicies(
  1395. perm.PolicyFor(perm.Anybody).WhoAre(perm.Denied).ToDo(presets.PermCreate).On("*:shared_containers:*"),
  1396. )
  1397. }
  1398. listing.Field("DisplayName").Label("Name")
  1399. listing.SearchFunc(sharedContainerSearcher(db, pm))
  1400. listing.CellWrapperFunc(func(cell h.MutableAttrHTMLComponent, id string, obj interface{}, dataTableID string) h.HTMLComponent {
  1401. tdbind := cell
  1402. c := obj.(*Container)
  1403. tdbind.SetAttr("@click.self",
  1404. web.Plaid().
  1405. EventFunc(actions.Edit).
  1406. URL(b.ContainerByName(c.ModelName).GetModelBuilder().Info().ListingHref()).
  1407. Query(presets.ParamID, c.ModelID).
  1408. Query(paramOpenFromSharedContainer, 1).
  1409. Go()+fmt.Sprintf(`; vars.currEditingListItemID="%s-%d"`, dataTableID, c.ModelID))
  1410. return tdbind
  1411. })
  1412. return
  1413. }
  1414. func (b *Builder) ConfigDemoContainer(pb *presets.Builder, db *gorm.DB) (pm *presets.ModelBuilder) {
  1415. pm = pb.Model(&DemoContainer{}).URIName("demo_containers").Label("Demo Containers")
  1416. pm.RegisterEventFunc("addDemoContainer", func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1417. modelID := ctx.QueryAsInt(presets.ParamOverlayUpdateID)
  1418. modelName := ctx.R.FormValue("ModelName")
  1419. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  1420. var existID uint
  1421. {
  1422. m := DemoContainer{}
  1423. db.Where("model_name = ?", modelName).First(&m)
  1424. existID = m.ID
  1425. }
  1426. db.Assign(DemoContainer{
  1427. Model: gorm.Model{
  1428. ID: existID,
  1429. },
  1430. ModelID: uint(modelID),
  1431. }).FirstOrCreate(&DemoContainer{}, map[string]interface{}{
  1432. "model_name": modelName,
  1433. "locale_code": locale,
  1434. })
  1435. r.Reload = true
  1436. return
  1437. })
  1438. listing := pm.Listing("ModelName").SearchColumns("ModelName")
  1439. listing.Field("ModelName").Label("Name")
  1440. ed := pm.Editing("SelectContainer").ActionsFunc(func(obj interface{}, ctx *web.EventContext) h.HTMLComponent { return nil })
  1441. ed.Field("ModelName")
  1442. ed.Field("ModelID")
  1443. ed.Field("SelectContainer").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  1444. locale, localizable := l10n.IsLocalizableFromCtx(ctx.R.Context())
  1445. var demoContainers []DemoContainer
  1446. db.Find(&demoContainers)
  1447. var containers []h.HTMLComponent
  1448. for _, builder := range b.containerBuilders {
  1449. cover := builder.cover
  1450. if cover == "" {
  1451. cover = path.Join(b.prefix, b.imagesPrefix, strings.ReplaceAll(builder.name, " ", "")+".png")
  1452. }
  1453. c := VCol(
  1454. VCard(
  1455. VImg().Src(cover).Height(200),
  1456. VCardActions(
  1457. VCardTitle(h.Text(builder.name)),
  1458. VSpacer(),
  1459. VBtn("Select").
  1460. Text(true).
  1461. Color("primary").Attr("@click",
  1462. web.Plaid().
  1463. EventFunc(actions.New).
  1464. URL(builder.GetModelBuilder().Info().ListingHref()).
  1465. Query(presets.ParamOverlayAfterUpdateScript, web.POST().Query("ModelName", builder.name).EventFunc("addDemoContainer").Go()).
  1466. Go()),
  1467. ),
  1468. ),
  1469. ).Cols(6)
  1470. var isExists bool
  1471. var modelID uint
  1472. for _, dc := range demoContainers {
  1473. if dc.ModelName == builder.name {
  1474. if localizable && dc.GetLocale() != locale {
  1475. continue
  1476. }
  1477. isExists = true
  1478. modelID = dc.ModelID
  1479. break
  1480. }
  1481. }
  1482. if isExists {
  1483. c = VCol(
  1484. VCard(
  1485. VImg().Src(cover).Height(200),
  1486. VCardActions(
  1487. VCardTitle(h.Text(builder.name)),
  1488. VSpacer(),
  1489. VBtn("Edit").
  1490. Text(true).
  1491. Color("primary").Attr("@click",
  1492. web.Plaid().
  1493. EventFunc(actions.Edit).
  1494. URL(builder.GetModelBuilder().Info().ListingHref()).
  1495. Query(presets.ParamID, fmt.Sprint(modelID)).
  1496. Go()),
  1497. ),
  1498. ),
  1499. ).Cols(6)
  1500. }
  1501. containers = append(containers, c)
  1502. }
  1503. return VSheet(
  1504. VContainer(
  1505. VRow(
  1506. containers...,
  1507. ),
  1508. ),
  1509. )
  1510. })
  1511. listing.CellWrapperFunc(func(cell h.MutableAttrHTMLComponent, id string, obj interface{}, dataTableID string) h.HTMLComponent {
  1512. tdbind := cell
  1513. c := obj.(*DemoContainer)
  1514. tdbind.SetAttr("@click.self",
  1515. web.Plaid().
  1516. EventFunc(actions.Edit).
  1517. URL(b.ContainerByName(c.ModelName).GetModelBuilder().Info().ListingHref()).
  1518. Query(presets.ParamID, c.ModelID).
  1519. Go()+fmt.Sprintf(`; vars.currEditingListItemID="%s-%d"`, dataTableID, c.ModelID))
  1520. return tdbind
  1521. })
  1522. ed.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  1523. this := obj.(*DemoContainer)
  1524. err = db.Transaction(func(tx *gorm.DB) (inerr error) {
  1525. if l10nON && strings.Contains(ctx.R.RequestURI, l10n_view.DoLocalize) {
  1526. if inerr = b.createModelAfterLocalizeDemoContainer(tx, this); inerr != nil {
  1527. panic(inerr)
  1528. return
  1529. }
  1530. }
  1531. if inerr = gorm2op.DataOperator(tx).Save(this, id, ctx); inerr != nil {
  1532. return
  1533. }
  1534. return
  1535. })
  1536. return
  1537. })
  1538. return
  1539. }
  1540. func (b *Builder) ConfigTemplate(pb *presets.Builder, db *gorm.DB) (pm *presets.ModelBuilder) {
  1541. pm = pb.Model(&Template{}).URIName("page_templates").Label("Templates")
  1542. pm.Listing("ID", "Name", "Description")
  1543. dp := pm.Detailing("Overview")
  1544. dp.Field("Overview").ComponentFunc(templateSettings(db, pm))
  1545. eb := pm.Editing("Name", "Description")
  1546. eb.Field("EditContainer").ComponentFunc(func(obj interface{}, field *presets.FieldContext, ctx *web.EventContext) h.HTMLComponent {
  1547. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  1548. m := obj.(*Template)
  1549. if m.ID == 0 {
  1550. return nil
  1551. }
  1552. var href = fmt.Sprintf("%s/editors/%d?tpl=1", b.prefix, m.ID)
  1553. if locale, isLocalizable := l10n.IsLocalizableFromCtx(ctx.R.Context()); isLocalizable && l10nON {
  1554. href = fmt.Sprintf("%s/editors/%d?tpl=1&locale=%s", b.prefix, m.ID, locale)
  1555. }
  1556. return h.Div(
  1557. VBtn(msgr.EditPageContent).
  1558. Target("_blank").
  1559. Href(href).
  1560. Color("secondary"),
  1561. )
  1562. })
  1563. eb.SaveFunc(func(obj interface{}, id string, ctx *web.EventContext) (err error) {
  1564. this := obj.(*Template)
  1565. err = db.Transaction(func(tx *gorm.DB) (inerr error) {
  1566. if inerr = gorm2op.DataOperator(tx).Save(obj, id, ctx); inerr != nil {
  1567. return
  1568. }
  1569. if l10nON && strings.Contains(ctx.R.RequestURI, l10n_view.DoLocalize) {
  1570. fromID := ctx.R.Context().Value(l10n_view.FromID).(string)
  1571. fromLocale := ctx.R.Context().Value(l10n_view.FromLocale).(string)
  1572. var fromIDInt int
  1573. fromIDInt, err = strconv.Atoi(fromID)
  1574. if err != nil {
  1575. return
  1576. }
  1577. if inerr = b.localizeContainersToAnotherPage(tx, fromIDInt, "tpl", fromLocale, int(this.ID), "tpl", this.GetLocale()); inerr != nil {
  1578. panic(inerr)
  1579. return
  1580. }
  1581. return
  1582. }
  1583. return
  1584. })
  1585. return
  1586. })
  1587. return
  1588. }
  1589. func sharedContainerSearcher(db *gorm.DB, mb *presets.ModelBuilder) presets.SearchFunc {
  1590. return func(obj interface{}, params *presets.SearchParams, ctx *web.EventContext) (r interface{}, totalCount int, err error) {
  1591. ilike := "ILIKE"
  1592. if db.Dialector.Name() == "sqlite" {
  1593. ilike = "LIKE"
  1594. }
  1595. wh := db.Model(obj)
  1596. if len(params.KeywordColumns) > 0 && len(params.Keyword) > 0 {
  1597. var segs []string
  1598. var args []interface{}
  1599. for _, c := range params.KeywordColumns {
  1600. segs = append(segs, fmt.Sprintf("%s %s ?", c, ilike))
  1601. args = append(args, fmt.Sprintf("%%%s%%", params.Keyword))
  1602. }
  1603. wh = wh.Where(strings.Join(segs, " OR "), args...)
  1604. }
  1605. for _, cond := range params.SQLConditions {
  1606. wh = wh.Where(strings.Replace(cond.Query, " ILIKE ", " "+ilike+" ", -1), cond.Args...)
  1607. }
  1608. locale, _ := l10n.IsLocalizableFromCtx(ctx.R.Context())
  1609. var c int64
  1610. if err = wh.Select("count(display_name)").Where("shared = true AND locale_code = ?", locale).Group("display_name,model_name,model_id").Count(&c).Error; err != nil {
  1611. return
  1612. }
  1613. totalCount = int(c)
  1614. if params.PerPage > 0 {
  1615. wh = wh.Limit(int(params.PerPage))
  1616. page := params.Page
  1617. if page == 0 {
  1618. page = 1
  1619. }
  1620. offset := (page - 1) * params.PerPage
  1621. wh = wh.Offset(int(offset))
  1622. }
  1623. if err = wh.Select("display_name,model_name,model_id").Find(obj).Error; err != nil {
  1624. return
  1625. }
  1626. r = reflect.ValueOf(obj).Elem().Interface()
  1627. return
  1628. }
  1629. }
  1630. func (b *Builder) ContainerByName(name string) (r *ContainerBuilder) {
  1631. for _, cb := range b.containerBuilders {
  1632. if cb.name == name {
  1633. return cb
  1634. }
  1635. }
  1636. panic(fmt.Sprintf("No container: %s", name))
  1637. }
  1638. type ContainerBuilder struct {
  1639. builder *Builder
  1640. name string
  1641. mb *presets.ModelBuilder
  1642. model interface{}
  1643. modelType reflect.Type
  1644. renderFunc RenderFunc
  1645. cover string
  1646. }
  1647. func (b *Builder) RegisterContainer(name string) (r *ContainerBuilder) {
  1648. r = &ContainerBuilder{
  1649. name: name,
  1650. builder: b,
  1651. }
  1652. b.containerBuilders = append(b.containerBuilders, r)
  1653. return
  1654. }
  1655. func (b *ContainerBuilder) Model(m interface{}) *ContainerBuilder {
  1656. b.model = m
  1657. b.mb = b.builder.ps.Model(m)
  1658. val := reflect.ValueOf(m)
  1659. if val.Kind() != reflect.Ptr {
  1660. panic("model pointer type required")
  1661. }
  1662. b.modelType = val.Elem().Type()
  1663. b.configureRelatedOnlinePagesTab()
  1664. return b
  1665. }
  1666. func (b *ContainerBuilder) URIName(uri string) *ContainerBuilder {
  1667. if b.mb == nil {
  1668. return b
  1669. }
  1670. b.mb.URIName(uri)
  1671. return b
  1672. }
  1673. func (b *ContainerBuilder) GetModelBuilder() *presets.ModelBuilder {
  1674. return b.mb
  1675. }
  1676. func (b *ContainerBuilder) RenderFunc(v RenderFunc) *ContainerBuilder {
  1677. b.renderFunc = v
  1678. return b
  1679. }
  1680. func (b *ContainerBuilder) Cover(v string) *ContainerBuilder {
  1681. b.cover = v
  1682. return b
  1683. }
  1684. func (b *ContainerBuilder) NewModel() interface{} {
  1685. return reflect.New(b.modelType).Interface()
  1686. }
  1687. func (b *ContainerBuilder) ModelTypeName() string {
  1688. return b.modelType.String()
  1689. }
  1690. func (b *ContainerBuilder) Editing(vs ...interface{}) *presets.EditingBuilder {
  1691. return b.mb.Editing(vs...)
  1692. }
  1693. func (b *ContainerBuilder) configureRelatedOnlinePagesTab() {
  1694. eb := b.mb.Editing()
  1695. eb.AppendTabsPanelFunc(func(obj interface{}, ctx *web.EventContext) h.HTMLComponent {
  1696. if ctx.R.FormValue(paramOpenFromSharedContainer) != "1" {
  1697. return nil
  1698. }
  1699. pmsgr := i18n.MustGetModuleMessages(ctx.R, presets.CoreI18nModuleKey, Messages_en_US).(*presets.Messages)
  1700. msgr := i18n.MustGetModuleMessages(ctx.R, I18nPageBuilderKey, Messages_en_US).(*Messages)
  1701. id, err := reflectutils.Get(obj, "id")
  1702. if err != nil {
  1703. panic(err)
  1704. }
  1705. pages := []*Page{}
  1706. pageTable := (&Page{}).TableName()
  1707. containerTable := (&Container{}).TableName()
  1708. err = b.builder.db.Model(&Page{}).
  1709. Joins(fmt.Sprintf(`inner join %s on
  1710. %s.id = %s.page_id
  1711. and %s.version = %s.page_version
  1712. and %s.locale_code = %s.locale_code`,
  1713. containerTable,
  1714. pageTable, containerTable,
  1715. pageTable, containerTable,
  1716. pageTable, containerTable,
  1717. )).
  1718. // FIXME: add container locale condition after container supports l10n
  1719. Where(fmt.Sprintf(`%s.status = ? and %s.model_id = ? and %s.model_name = ?`,
  1720. pageTable,
  1721. containerTable,
  1722. containerTable,
  1723. ), publish.StatusOnline, id, b.name).
  1724. Group(fmt.Sprintf(`%s.id,%s.version,%s.locale_code`, pageTable, pageTable, pageTable)).
  1725. Find(&pages).
  1726. Error
  1727. if err != nil {
  1728. panic(err)
  1729. }
  1730. var pageIDs []string
  1731. var pageListComps h.HTMLComponents
  1732. for _, p := range pages {
  1733. pid := p.PrimarySlug()
  1734. pageIDs = append(pageIDs, pid)
  1735. statusVar := fmt.Sprintf(`republish_status_%s`, strings.Replace(pid, "-", "_", -1))
  1736. pageListComps = append(pageListComps, VListItem(
  1737. h.Text(fmt.Sprintf("%s (%s)", p.Title, pid)),
  1738. VSpacer(),
  1739. VIcon(fmt.Sprintf(`{{vars.%s}}`, statusVar)),
  1740. ).
  1741. Dense(true).
  1742. Attr(web.InitContextVars, fmt.Sprintf(`{%s: ""}`, statusVar)))
  1743. }
  1744. return h.Components(
  1745. VTab(h.Text(msgr.RelatedOnlinePages)),
  1746. VTabItem(
  1747. h.If(len(pages) > 0,
  1748. VList(pageListComps),
  1749. h.Div(
  1750. VSpacer(),
  1751. VBtn(msgr.RepublishAllRelatedOnlinePages).
  1752. Color("primary").
  1753. Attr("@click",
  1754. web.Plaid().
  1755. EventFunc(presets.OpenConfirmDialog).
  1756. Query(presets.ConfirmDialogConfirmEvent,
  1757. web.Plaid().
  1758. EventFunc(republishRelatedOnlinePagesEvent).
  1759. Query("ids", strings.Join(pageIDs, ",")).
  1760. Go(),
  1761. ).
  1762. Go(),
  1763. ),
  1764. ).Class("d-flex"),
  1765. ).Else(
  1766. h.Div(h.Text(pmsgr.ListingNoRecordToShow)).Class("text-center grey--text text--darken-2 mt-8"),
  1767. ),
  1768. ),
  1769. )
  1770. })
  1771. }
  1772. func republishRelatedOnlinePages(pageURL string) web.EventFunc {
  1773. return func(ctx *web.EventContext) (r web.EventResponse, err error) {
  1774. ids := strings.Split(ctx.R.FormValue("ids"), ",")
  1775. for _, id := range ids {
  1776. statusVar := fmt.Sprintf(`republish_status_%s`, strings.Replace(id, "-", "_", -1))
  1777. web.AppendVarsScripts(&r,
  1778. web.Plaid().
  1779. URL(pageURL).
  1780. EventFunc(views.RepublishEvent).
  1781. Query("id", id).
  1782. Query(views.ParamScriptAfterPublish, fmt.Sprintf(`vars.%s = "done"`, statusVar)).
  1783. Query("status_var", statusVar).
  1784. Go(),
  1785. fmt.Sprintf(`vars.%s = "pending"`, statusVar),
  1786. )
  1787. }
  1788. return r, nil
  1789. }
  1790. }
  1791. func (b *Builder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  1792. if strings.Index(r.RequestURI, b.prefix+"/preview") >= 0 {
  1793. b.preview.ServeHTTP(w, r)
  1794. return
  1795. }
  1796. if strings.Index(r.RequestURI, path.Join(b.prefix, b.imagesPrefix)) >= 0 {
  1797. b.images.ServeHTTP(w, r)
  1798. return
  1799. }
  1800. b.ps.ServeHTTP(w, r)
  1801. }