builder.go 60 KB

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