builder.go 59 KB

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