Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation on 01/14/2022 in all areas

  1. This week we have some improvements to the $pages->findRaw() method. Most of these are based on requested improvements in either GitHub (like #427) or the forums: Support for selecting parent properties/fields in the return value, i.e. $pages->findRaw("selector", "parent.title"); // Example 1 $pages->findRaw("selector", [ 'title', 'parent.title', 'parent.parent.title' ]); // Example 2 Support for selecting page 'meta' data in the return value, i.e. $pages->findRaw("selector", "meta"); // example 1 $pages->findRaw("selector", [ "meta.foo", "meta.bar" ]); // example 2 Support for selecting "references" in the return value. References are other pages that reference the found page(s) via Page reference fields, just like the $page->references() method. $pages->findRaw("selector", "references"); // example 1 $pages->findRaw("selector", [ 'references.title', 'references.url' ]); // example 2 If you want the references to be indexed by field name, just include "references.field" in the requested fields: $pages->findRaw("selector", [ 'references.field', 'references.title', 'references.url' ]); Support for selecting title and/or value from options (FieldtypeOptions) fields, i.e. $pages->findRaw("selector", [ 'my_options_field.*' ]); // example 1 $pages->findRaw("selector", [ 'my_options_field.title', 'my_options_field.value' ]); // example 2 Support for a new "flat" option that flattens multidimensional arrays in return value. This is best explained by an example. Let's say we did this: $pages->findRaw("categories.count>0, limit=1", "title, categories.title" ); And it returns an array similar to this for every matching page: [ 'title' => '2-factor authentication coming to ProcessWire', 'categories' => [ 1035 => [ 'title' => 'Security' ], 1288 => [ 'title' => 'Users' ] ] ] Now let's try the flat option: $pages->findRaw("categories.count>0, limit=1", "title, categories.title", [ 'flat' => true ]); (side note: you might already know this, but fields and options can also be bundled in the selector like this below, which is identical to the above): $pages->findRaw("categories.count>0, fields=title|categories.title, flat=1"); It flattens any multi-dimensional arrays in the return value to be indexed in the same way that you requested them in the $fields argument: [ 'title' => '2-factor authentication coming to ProcessWire', 'categories.title' => [ 1035 => 'Security', 1288 => 'Users' ] ] In addition to these updates for the $pages->findRaw() method, this week there have also been updates to the $sanitizer->float() method and InputfieldFloat module. Now both support numbers with E notation such as 1E-2, 10E-14, -1.253E-5, etc. There are also some new values for the getString option on the float sanitizer. I don't work with this kind of stuff very often, so thanks to @MetaTunes on GitHub for helping to figure it out. Lastly, the ProcessTemplate module also went through a refactoring with some minor improvements this week. Thanks for reading, have a great weekend!
    8 points
  2. @ryan, thanks for this week's updates! @MoritzLost has sparked an interesting discussion about using PW with version control and he makes a comparison with Craft CMS. A couple of excerpts from his comments: Ryan, it would be great to get your voice in the discussion. We're at the beginning of the new year so what do you think about putting better compatibility with version control onto a roadmap for 2022?
    4 points
  3. @elabx Craft CMS ? I'm also trying to move towards static site generator and headless and/or git-based CMS (like Forestry or Netlify CMS). My personal websites are built with SSG and hosted for free on Netlify (processwire.dev & mehrlicht.photos) – though those don't use a CMS at all. But most of the tools for the SSG/Jamstack approach are built to accomodate version control from the ground up. I've been eyeing Prismic, hopefully I'll get a project soon where I can try that out. Though it's hard to find clients for static sites + CMS right now, most have never heard of it … @benbyf Drupal 8/9 has that as well, Configuration Synchronization, but it's a pain to use (like Drupal itself). Luckily I migrated the last Drupal project I had to actively support away from Drupal and to Craft CMS last year ? @bernhard Thanks a lot for the detailed explanation and all the code examples! For the next bigger ProcessWire project, if there is one, I'll be sure to use RockMigrations. Sounds like it solves my problem regarding project schema / config well. But there's still a cost associated with this – every developer needs to know how to use it and not shoot themselves in the foot. How does a new developer install and work on the project from the repository? Is it as simple as composer install, php craft install, npm ci, npm run build? Because every additional step is something we don't have to do when using a CMS with first-party git support. For example, how do you install ProcessWire in this case? Manually? That's work I don't have to do if I can just composer install. Sure, I can hook something up to install ProcessWire using composer scripts on install (in fact, I have done something like this for our starter template which is under version control). But now I have a custom script that I need to maintain, fix if it breaks. Or I put the core in my version control, which means I have to litter my version history with core files. (BTW I could use git submodules but somehow nobody knows they're a thing ?) There are more issues like this as I mentioned (e.g. the issue regarding default selected pages in page reference fields; folders containing a mix of files that should and shouldn't be in version control; modules that don't use composer, …). Every one of those can be solved. But every solve either comes with some trade-off (like keeping not project related files in git) or with a maintenance cost and learning curve for a custom solution. And that's a hard sell if there are systems that don't require all that work. Beyond that, I have zero guarantees from the core that all those custom solutions will still work with the next core version (the lack of semantic versioning for the ProcessWire core doesn't help either). There are also side-effects to there not being explicit support from the core regarding those setups – for example, if we want to outsource something to an external developer or train a new hire, we can't just point them to the ProcessWire docs, but have to teach 'the way' to them. For Craft projects, we just follow the standards. Besides the problems I mentioned, there are also advantages that come from the fact that Craft supports version control explicitly and is geared towards it. For example, the production site will not allow any configuration changes (new fields, setting changes, etc) by default. So I have a guarantee that that the configuration will be exactly as I left it so I can deploy with confidence from the repository. With ProcessWire, I don't have a guarantee that nobody has changed some field setting in production while I was on holiday. Of course, not changing stuff in production can be established as a rule, but it's again something to be consciously aware of and enforce, instead of having the system enforce it. I feel like there isn't one single answer to this debate. I hear you – it's easier to complain than work on solutions. Not every project needs a totally 'clean' version control. Trade-offs are acceptable and arguably what we are paid for. I think there's room for multiple CMS with maybe slightly different focus. Right now I'm in the planning stage for a new ProcessWire project that I'm looking forward to. It's just a matter of using different tools depending on the job, no need for a single CMS to rule them all ? Not sure I understand the problem; with Craft, the project config is always the source of truth and the interface is just window dressing to edit the project config. If you're using external modules, they have to be built to support project config, but most plugins are by now. I have said that myself ? After having supported a larger project with regular updates for a while now, which is a bit of a pain. Maybe it would go better if we'd used RockMigrations from the start! Hindsight is 20/20 … @Robin S I'll try to get around to that comparison between Craft CMS and ProcessWire, which would include all the issues regarding version control. But knowing me and my tendency of feature-creep for articles that might take a while ?
    4 points
  4. Hello all! A client asked us to implement a landing page where some content would have to swap in real time when needed. Basically I need to implement a way to select in the backend (via a select dropdown or whatever) which page I want to use as the "replacer", save and then immediately use its html content to swap the old content, in real-time, on the front-end. I've read about htmx and its sse implementation, and also took a look at this simple example on how to dispach an event via php every second. The front-end part looks way easier to implement, but the backend one it's over my knowledge at the time of this writing. I know @netcarver did some test and also @kongondo is playing with those technology a bit lately. This is the first time I came to such a request and I'm looking for some advice from you guys! :)
    2 points
  5. Hi @Andy. Thanks for this. I have seen it before. It was recommended to me by @Jonathan Lahijani a while back. Two reasons why I didn't select it: I needed a simple template for the demo. I am more comfortable with Tailwind compared to UIkit etc ?.
    2 points
  6. @kongondo There is a more elaborate and functional free online shop layout. It is based on UIkit 3 and other technologies. Check it out. Project on github Demo This layout is more suitable for full-featured online shop if you sell something more complicated than shorts and shirts.
    2 points
  7. Thanks to @kongondo's example, I also began to use tailwind.
    1 point
  8. I think @kongondo gives here a super simple example and even refers to it as trivial, haven't tried anything yet tho:
    1 point
  9. Thanks @Andy. I'll have a look at your PR.
    1 point
  10. This would be some kind of a dream for me to have in ProcessWire. ?‍♂️
    1 point
  11. This would be some kind of a dream for me to have in ProcessWire. Wasn't there a Wishlist somewhere for features to include in PW that @ryan takes as a kind of inspiration? If I could I vote for something like that 100 times TBH.
    1 point
  12. Please do, I'd be very interested to read that! It seems like this should be doable via a module in PW. I have a work-in-progress module that does something like this. It's not complete and haven't looked at it a while but it seemed like a promising avenue at the time. I think if the concept could be illustrated in a module then Ryan might see the benefits and then hopefully incorporate the features into the core. Seeing as you've clearly spent some time thinking about these issues, would you mind writing up a wishlist of what things you think PW should handle via files for the sake of version control? Fields and templates are the obvious things but you also mentioned translations which I wouldn't have thought of (I only work on single language websites) so it would be great to have a comprehensive list of problem areas for version control. Thanks in advance! ?
    1 point
  13. ProcessPageAdd preselects the template according to these principles: If there is already one or more child pages under the parent then it preselects the same template as used by the most recently added child page. If there are no child pages it preselects the same template as used by the parent page. But if that template isn't allowed to be used under the parent page then no template is preselected. So probably you recently added a page using the template that is only used in 5% of the cases, or that is the template of the parent page. You can force a particular template to be preselected in a couple of ways. 1. You can add a "template_id" GET variable to the URL of the "Add New" page. Example: "/processwire/page/add/?parent_id=1234&template_id=29" This might be a good approach if you are constructing your own custom link to the "Add New" screen but not so useful if you are just adding a new page via the standard PW admin. 2. You can use a hook in /site/ready.php to set a template_id GET variable to $input: // Before the ProcessPageAdd form is built $wire->addHookBefore('ProcessPageAdd::buildForm', function(HookEvent $event) { $input = $event->wire()->input; // Get the parent page the new page is being added under $parent_id = (int) $input->get('parent_id'); $parent = $event->wire()->pages->get($parent_id); // Return early if a single parent page isn't available or valid if(!$parent->id) return; // Do whatever check you need to identify if this is the parent you want to target if($parent->template == 'home') { // Get the template you want to be preselected $child_template = $event->wire()->templates->get('basic_page'); // Set the template ID to the "template_id" GET variable $input->get->template_id = $child_template->id; } });
    1 point
  14. Sorry I missed your second post... Actually something similar would already be possible using RockMigrations. At least for basic setups. I'm not sure how that can work for more complex setups though. I'll try to explain that by an example: Let's say we created a new blog module. We need a blog page (parent) and several blog-items (children): - home '- blog |- blog entry 1 |- blog entry 2 ... This setup could easily be built into a module using rockmigrations: <?php namespace ProcessWire; class MyBlog extends WireData implements Module { public static function getModuleInfo() { return [ 'title' => 'MyBlog', 'version' => '0.0.1', 'summary' => 'blog module using rockmgirations', 'autoload' => true, 'singular' => true, 'icon' => 'smile-o', 'requires' => [], 'installs' => [], ]; } public function init() { $this->rm()->fireOnRefresh($this, "migrate"); } public function migrate() { $this->rm()->migrate([ 'fiels' => [...], 'templates' => [ 'blog_parent' => [...], 'blog_item' => [...], ], ]); $this->rm()->setParentChild('blog_parent', 'blog_item'); // --> this sets the family settings for both the parent and the child template - how long does that take by hand? ;) It means that all pages having the "blog_parent" template will create a "blog_item" page automatically when you click on "add new page". Basically the stuff that you set on the family tab of the template. } /** * @return RockMigrations */ public function rm() { return $this->wire->modules->get('RockMigrations'); } } That means I'm literally defining my config in the module code. We could also have the config read from a config.yaml - that would really be the same (just less powerful IMHO)! The problem arises when you want to make that config customizable. For example you want a page reference field to select the author for every blog post. Building that into the blog module would probably not be a good idea because not every site might need such a field. What I do in such situations is this: I make the migrate() method hookable and create one module that handles all the project-specific stuff: <?php namespace ProcessWire; class MyProject extends WireData implements Module { public static function getModuleInfo() { return [ 'title' => 'MyProject', 'version' => '0.0.1', 'summary' => 'module that handles site specific stuff', 'autoload' => true, 'singular' => true, 'icon' => 'smile-o', 'requires' => [], 'installs' => [], ]; } public function init() { $this->addHookAfter("MyBlog::migrate", $this, "migrate"); } public function migrate(HookEvent $event) { $this->rm()->createField("author", "page", [ 'label' => 'Select the author', ... ]); $this->rm()->addFieldToTemplate("author", "blog_item", "title"); } /** * @return RockMigrations */ public function rm() { return $this->wire->modules->get('RockMigrations'); } } That means you can have your blog module that you can reuse from project to project (and improve it and just pull changes if you need to) and you can still customize it the ProcessWire way (which we all love I guess). BUT Now we got a new field on the "blog_item", the "author" field. So the config.yaml of the blog module would change, wouldn't it? I'm not sure how CraftCMS handles such situations? And that's one of the reasons why I think that efforts like this are going in a wrong direction. It sounds intriguing for sure to have something like a "migrations recorder". I'm working or at least thinking about that since 2016. But I simply can't imagine a way that could reliably work in all situations. RockMigrations does. And it does it really well. And it does it for almost 3 years now and has evolved a lot. It's still not perfect for sure. But I don't think that This feels wrong. I'dont know how to explain. I think you have a good understanding of composer and such things. Likely a much better understanding than I have. So if it is true what you are saying, I must be doing a lot wrong in my daily work or at least I must be understanding a lot wrong... Because a lot of my workflows do feel very version control friendly. And I've lately started working in a company in vienna where we work on ProcessWire projects with fully automated workflows. We work in a team. We work on different local machines. We deploy to staging and if everything works (which has been the case 100% so far), we deploy to production with a single click. But maybe I'll change my opinion some day and look back and laugh. Maybe I should just try CraftCMS. Maybe many other fancy new tools. At my company they also work (or worked) with another CMS. They said they liked to be able to define fields and templates in code. They said that was one of the (few) things they didn't like about ProcessWire, because they love professional workflows and automated deployments... But they also admitted, that it was somewhat painful to define fields and templates in the other CMS. They said you have to add pieces of config in that file, then change another piece in another file. And end up changing many files for simple changes. Now they like RockMigrations ? And such comments make me think I am on a right track and we as ProcessWire enthusiasts are not that far away from what you seem to be missing. @MoritzLost have you ever heard someone saying "ProcessWire is great for small websites, but not for larger, more complex ones"? We all know how wrong that is, don't we? That's the way I feel when people here on the forum are talking about missing migration / version control features... PS: I tried to keep this post short and not so emotional. I think I failed, sorry ?
    1 point
  15. Yes <?php $rm->migrate([ 'templates' => [ 'car' => [ 'fields' => [ 'title' => [ 'label' => 'Name of the Car', 'columnWidth'=>50, ], 'km' => ['columnWidth'=>50], ], ], ], ]); voila. fields "title" and "km" will be 50% width in the car template context. the title field will have a custom label on the car template. It's really that simple most of the time! Change some properties, commit, push, done! What are you missing? Depends. Both are possible. RockMigrations is really also great if you add it later on a project that did not handle migrations before. It really does not care. For example you could add this in your ready.php: <?php $rm = $modules->get('RockMigrations'); $rm->createField('test', [ 'type' => 'text', 'label' => 'Testing RockMigrations', ]); // add field test to home template after the title field $rm->addFieldToTemplate("test", "home", "title"); You'll have your test field right after the title field of the home template. You can do the same for everything you add to your site. Doing it like this, of course, the migration will run on every page request. The great thing about the migrations is that this will just work! It's not ideal of course, but I just want to show how it works. Add another field? Here we go: <?php $rm = $modules->get('RockMigrations'); $rm->createField('test', [ 'type' => 'text', 'label' => 'Testing RockMigrations', ]); $rm->createField('test2', [ 'type' => 'text', 'label' => 'Testing RockMigrations again', ]); $rm->addFieldToTemplate("test", "home", "title"); $rm->addFieldToTemplate("test2", "home", "test"); Now we got two fields. Ok, we want those fields in a row? Lets refactor this (it would be possible using the syntax from above as well, but I just prefer the array syntax as it has everything in place): <?php $rm = $modules->get('RockMigrations'); $rm->migrate([ 'fields' => [ 'test' => [ 'type' => 'text', 'label' => 'Testing RockMigrations', ], 'test2' => [ 'type' => 'text', 'label' => 'Testing RockMigrations again', ], ], 'templates' => [ 'home' => [ 'fields' => [ 'title' => ['columnWidth'=>33], 'test' => ['columnWidth'=>33], 'test2' => ['columnWidth'=>33], ], ], ], ]); Commit, Push, Done. So do you really think manually creating those fields was quicker? Even if you create those fields remotely first and then pull a DB dump and you have at least semi-automated the process and a dump takes "only 15 seconds or so"... I bet migrations are quicker, more versatile, more powerful. Let's say you want to tidy up your project a little bit. Let's add tags for those two test fields: <?php $rm = $modules->get('RockMigrations'); $rm->migrate([ 'fields' => [ 'test' => [ 'type' => 'text', 'label' => 'Testing RockMigrations', 'tags' => 'RockMigrationsTests', // <----- add this ], 'test2' => [ 'type' => 'text', 'label' => 'Testing RockMigrations again', 'tags' => 'RockMigrationsTests', // <----- add this ], ], 'templates' => [ 'home' => [ 'fields' => [ 'title' => ['columnWidth'=>33], 'test' => ['columnWidth'=>33], 'test2' => ['columnWidth'=>33], ], ], ], ]); Thats it! Both fields live under that new tag: Nice and clean! Ok, now let's remove those changes: The IDE will help you find the right method... So we can do: /** @var RockMigrations $rm */ $rm = $modules->get('RockMigrations'); $rm->deleteFields("tags=RockMigrationsTests"); $rm->setFieldData("title", ["columnWidth"=>100], "home"); How long would it take you to delete those two fields manually? Making sure that all checks are met ("you can't delete this field... it is used by XX templates..." *#*&!), going back to the templates editor, removing the field first, then deleting the field, then going back to the home template and setting the title field back to 100%... I don't know the exact workflow - I haven't done that for a long time now ? Yeah and we are not even talking about doing those changes in a team... Have fun ? Yeah, @adrian, I know Tracy can help. Just trying to show how quick you can get when doing things using RockMigrations. Of course there are some situations where you might not know the properties you need to set. But Tracy can help you. Or you inspect the inputfield and lookup the name in your devtools. The nice side effect: You learn a lot about PW and you will understand it a lot better and improve even more. Well... I don't know what more to say. I feel your pain, but I don't really understand why there are many here "complaining" about those missing features of ProcessWire but nobody seems to be using RockMigrations or seems to have given it an hour or two to simply try it out... ?‍♂️ PS: I know the example runs migrations on every page request, which is not ideal. You can come up with your own strategy to prevent that or you can simply use $rm->fireOnRefresh() so migrations will only fire on modules::refresh I'm maybe similar. There's not a single new project not using RockMigrations and custom PageClasses now. It might be overkill for some, but I think for people that are asking questions that you are asking RockMigrations is just the right tool and you are missing something. That would be a pity. We need more people like you here ? Sometimes life as a developer is hard. But we get paid for that ?? I agree on that. I'm working on it and I wished more were doing so ? Why not? I agree it's not perfect, but I've put hard work into making this possible over the last years. And I think I've come very far. I don't know much other systems though, so I might be on the wrong track. If you know any better systems I'm just as happy to hear about them as @adrian
    1 point
  16. Well in this scenario I was talking about a particular project that is more "app like". But the rest of sites I manage, which might have specific features regarding template/fields, different templates that are for one specific website/design, I handle them the same way, repo and deployment through pipelines. I'd love to hear about what other things you've tried if you'd be keen on sharing. I've seen some folks move to Statamic/Kirby for this purpose. Thinking about this I've thought a "migration recorder" built on field save hooks, would be neat. Like, you're doing your work on PW thinking about the awesome features you wanna build, building repeaters/matrix, changing file widths, show conditions, all those things we love. Then you go into Setup > Migrations and you find all the work you just did on your repeater field recorded. Just a thought for one part of the whole problem. EDIT: I just read about the YAML thing Craft does, thanks for sharing! ?
    1 point
  17. I have had a play and some of the implementation is literally, trivial ?. SSE SSE is so simple it is unbelievable at first. You only need two things: in our case PHP and a modern browser...batteries included! Example adapted from w3schools. More examples at MDN. server-side <?php namespace ProcessWire; header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}\n\n"; flush(); client if(typeof(EventSource) !== "undefined") { var source = new EventSource("/some-processwire/url/"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "<br>"; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } I tested it and it works fine but was getting errors about wrong mime type if I set the headers later, but that is to be expected. Live Preview Refresh - Partial and Full - ajax - htmx I have this working nicely (will try post the demo later today). The premise is: A change happens. The editor client sends the data to the server to save the change (autosave - was just mimicking this part). Server saves and sends back a response including the name of the field that has been saved and the page ID back to the editor client. The editor client communicates with the preview client (a separate window). It sets the page ID and the name of the changed field name in its message to the preview window. The preview window client (htmx) receives the page id and the name of the field that has changed and sends a request to the server to fetch the rendered contents of that field for that page. The server sends back the html for htmx to swap in the DOM. In this simple communication, we have the field name match the html id of the element we are swapping. E.g. <h2 id='headline'>My Headline</h2> This is simple and straightforward and easily achieves partial refresh. However, it will be difficult to handle the more complex cases I mentioned in my previous post. It will also be somewhat dictating how the developer should name their html attributes. In addition, it still leaves the developer's templates with htmx attributes that will not be needed in production. This got me thinking. Live Preview Wrapper - idea #1 In this case, the live preview window would add a wrapper html element around the rendered template file markup. The wrapper html element would have the htmx attributes instead of the template file markup. This idea didn't go very far. It would inevitably lead to broken / incorrect markup in the preview window as the outermost markup of the template file would be <html> tags. In addition, while it solves the problem of unrequired htmx attributes in production, it doesn't solve the problem of selective rendering. It still wouldn't' know what parts of the markup in the preview window to swap. Live Preview Config - idea #2 What if instead of live preview / ProcessWire suggesting things like naming of elements, standard markup, etc. that are needed in a template file in order to get selective markup rendering, we implemented it the other way round? What if the developer instead, via config file(s), passed properties to live preview to implement the htmx attributes needed for a template file / page? The default would be full page refreshes. However, if live preview detected that a partial refresh config was available, it would implement those. This would offer the granularity needed for partial refreshes. If live preview did not receive / detect any configs, the default would kick in. Live preview would remain as agnostic as possible. It could be something like this (assumes use of htmx): A developer places their live preview partial refresh configs in /site/templates/live-previews/basic-page-live-preview.php (or basic-page-live-preview.json). ProcessWire detects that the template file basic-page has a partial refresh config in .../live-previews/basic-page-live-preview.php When ProcessWire loads the preview window, it injects the htmx attributes for each named element in the live preview configs in the corresponding elements in the preview window DOM. Injection is done by a ProcessWire live preview near-agnostic JavaScript script that only runs in the preview window. When the autosave happens in the editor window and the preview window gets informed, htmx kicks in, responding to an event and fires htmx.trigger(elem, event). The element in the markup with the corresponding event listener (hx-trigger='this-element-event-fired') will pick up the event fired by htmx.trigger() and query the server for the changed markup. The attributes set in #3 will ensure only the markup that has a change will fire. Server sends the response back and the element's hx-swap (or even hx-oob) picks it up and swaps the DOM. #6 is still not straightforward though. What will live preview / ProcessWire send back? Here too the config at #1 can help. E.g. it can tell ProcessWire to send <p>My Field Value</p> or just send the value of the field back, i.e. 'My Field Value'. The former is still complicated. Instead of telling ProcessWire I want <p>My Field Value</p>, how about tell it, via the configs at #1 that if requested field is field A, send me back the raw value (e.g. a plain text) but if the request is for field B, use this defined function in basic-page-live-preview.php to send me the rendered partial markup for field B? All ProcessWire would do is pass the value of field B to the said function. This value could be a Pageimages object. The function would iterate the images and send back the 'gallery' markup back to htmx to swap. example live preview config <?php namespace ProcessWire; $livePreviewConfigs = [ [ 'field' => 'headline', 'element_id' => 'my_headline_element_id', 'htmx-attributes' => ['hx-swap' => 'outerHTML', 'hx-trigger' => 'headlineevent'] ], [ 'field' => 'images', 'element_id' => 'gallery', 'handler' => 'renderGallery','htmx-attributes' => ['hx-swap' => 'innerHTML', 'hx-trigger' => 'galleryevent'] ], ]; function renderGallery(Pageimages $images) { // we only need the <li> since we are using innerHTML swap // the target element is <ul id='gallery'></ul> // -------------- $out = ""; foreach ($images as $image) { $thumb = $image->size(200, 200); $out .= "<li><img src='{$thumb->url}' alt='{$image->url}'></li>"; } // --------- // sent back to htmx to swap return $out; } When the preview window loads, ProcessWire sends $livePreviewConfigs to the browser, e.g. ProcessWire.config.LivePreview. The preview window JavaScript would consume it like this: client set htmx attributes @note: JavaScript written in the browser, not tested, could have errors. // get live preview configs const elementsConfigs = ProcessWire.config.LivePreview // loop through configs, find the corresponding element and set their htmx attributes for (const elementConfig of elementsConfigs) { const element = document.getElementById(elementConfig.element_id) if (element) { const htmxAttributes = elementConfig['htmx-attributes'] for (const [prop, value] of Object.entries(htmxAttributes)) { element.setAttribute(prop,value); } } } htmx-ready DOM changes via live preview injection (runtime only in live preview window): <h2 id="my_headline_element_id" hx-swap='outerHTML' hx-trigger='headlineevent' hx-vals='{"field":"headline"}'>My Headline</h2> <!-- gallery --> <ul id="gallery" hx-swap='innerHTML' hx-trigger='galleryevent' hx-vals='{"field":"images"}'> <li><img src='image-1-src' alt='image-1-alt'></li> <li><img src='image-2-src' alt='image-2-alt'></li> </ul> I have partly implement the above (just hard-coded configs for now) and it works nicely. Takeaways ProcessWire's live preview remains as agnostic as possible. Developer give instructions to live preview (via configs) and not the other way round. Live preview ships with minimal defaults, including full page refresh. It seems like a lot of work on the developer's part if they want partial refresh. However, this partly matches the complexity of their template files. Besides, some of the functionality (e.g. renderGallery()) could be something they already use in their template, hence reusable. Developer does not need to have additional markup in their template files in order to see live previews when editing. This means no cleaning up afterwards. Their templates remain clean. Live preview only alters the DOM (of the rendered template) at runtime. Developer can name their markup attributes as they wish. Developer can decide what needs live preview and what doesn't, even on the same page (e.g. hx-select). ProcessWire stays out of the developer's way, as usual.
    1 point
×
×
  • Create New...