diff --git a/README.md b/README.md index e9498dd..d6b1d33 100644 --- a/README.md +++ b/README.md @@ -1,50 +1,82 @@ -# Silverstripe shortcode module +# Shortcodable: a shortcode button for the Silverstripe editor + +Give CMS editors a button for shortcodes in the WYSIWYG editor: they pick a shortcode from a list, +fill in its form, and see it in their content as a placeholder image instead of bracketed code. +Selecting a placeholder and clicking the button again edits it. Developers make any class or +DataObject shortcodable with a line of YAML and a parser method. For Silverstripe 5 and 6. + +![The Content field of a page in the Silverstripe CMS: four shortcodes shown as placeholder images in the text (a current year, a call-to-action button, a full-width newsletter sign-up form and a contact card), with the shortcode button in the editor toolbar](docs/images/editor-placeholders.png) *Maintained by [Restruct](https://github.com/restruct). If this module saves you time, you can [support ongoing maintenance](https://github.com/sponsors/restruct).* -Adds a ![](docs/screens/button.png) button to HTMLEditorField for CMS users to insert Shortcodes in page content.
-Shortcodes can optionally be represented in TinyMCE with a placeholder image. +## Out of the box, editors have to type shortcodes by hand -![](docs/screens/dialog.png) -This module is a partial-to-largely rewrite of sheadawson/silverstripe-shortcodable.
-It depends on [Silverstripe Simpler](https://github.com/restruct/silverstripe-simpler) for some non-react UI functionalities (mainly the modal dialog). +Silverstripe's shortcode parser lets a developer register tags like `[year]` or +`[button label="Book a tour" link="/tours"]` and render them on the page. Editors get no help with +them: they have to know which shortcodes exist, remember each one's attributes and type them +exactly. In the editor a shortcode is plain bracketed text, and a typo is not caught: by default +the parser leaves an unknown shortcode in the page as it is. -## Requirements +This module turns registered shortcodes into something editors can find and use: -* Silverstripe 5 or 6 (`silverstripe/framework ^5 || ^6`) -* PHP 8.1 or newer (Silverstripe 6 itself needs 8.3) -* [restruct/silverstripe-simpler](https://github.com/restruct/silverstripe-simpler), installed automatically: - its `0.x` line (`~0.2`) on Silverstripe 5; on Silverstripe 6 it requires restruct/silverstripe-simpler - 1.0.0 or later -* **Silverstripe 6 only:** `silverstripe/htmleditor-tinymce`. TinyMCE is a separate module on Silverstripe 6 - and `silverstripe/recipe-cms` does not include it. Without it the site still boots, but there is no - TinyMCE editor to add the shortcode button to. +- **A toolbar button** in the HTMLEditorField that opens a dialog listing every shortcode you + registered, by a readable label +- **A form per shortcode**: the attribute fields you define, and for a DataObject a dropdown of its + records +- **Placeholder images in the editor** in place of the bracketed code: a generated default, or your + own image per shortcode +- **Editing**: select a placeholder and click the button, and the dialog opens with its values filled in +- **Block-level shortcodes**: output such as a form or a gallery can close the paragraph around it, + so the page's HTML stays valid -## Installation +This module is a partial-to-largely rewrite of +[sheadawson/silverstripe-shortcodable](https://github.com/sheadawson/silverstripe-shortcodable). It +depends on [Silverstripe Simpler](https://github.com/restruct/silverstripe-simpler) for some +non-React UI functionality (mainly the modal dialog). -``` -composer require restruct/silverstripe-shortcodable -# Silverstripe 6, if your project does not have it yet: -composer require silverstripe/htmleditor-tinymce -``` +## Insert, see and edit shortcodes in the editor -## Version Compatibility +### Picking a shortcode -| Branch | Module Version | Silverstripe | PHP | -|---------|----------------|----------------|----------------| -| `main` | `5.x` (from `5.1.0`) | `^5 \|\| ^6` | `^8.1` | -| `v4` | `4.x` | `^4 \|\| ^5` | `^7.4 \|\| ^8.0` | +The shortcode button sits in the editor toolbar (the `[ ]` icon, "Insert/edit shortcode"). It opens +a dialog with a dropdown of the registered shortcodes: -`main` is the maintained line and supports every Silverstripe version this module still targets. -Silverstripe 4 reached end of life in April 2025 and is no longer supported or tested here; projects -still on it can stay on the `4.x` tags, which remain available. The `5.0.x` tags declared Silverstripe 6 -only, and could not be installed from Packagist (see [CHANGELOG.md](CHANGELOG.md)); use `^5.1`. +![The "Insert/edit shortcode" dialog with its shortcode type dropdown open, listing Current year, Call-to-action button, Contact card and Newsletter sign-up form](docs/images/dialog-types.png) -**Note:** `composer.json` is the source of truth for exact version constraints. +Choosing one loads that shortcode's form: the fields its class defines, and for a DataObject a +dropdown of its records. "Insert shortcode" puts the shortcode at the cursor, or in place of the +selected text; the insert can be undone like any other edit. + +### Editing a shortcode that is already there + +Click a placeholder to select it, then click the shortcode button. The dialog opens on that +shortcode, with its attributes in the form: + +![The shortcode dialog opened on an existing Call-to-action button shortcode, showing its Button text "Book a tour", Link "/tours" and Style "Primary (filled)"](docs/images/dialog-edit.png) + +Inserting replaces the selected shortcode with the edited one. Placeholders are only an editor +view: when the page is saved, every placeholder is turned back into its shortcode text, so the +database holds `[button label="Book a tour" link="/tours" style="primary"]`, not an image. + +### Placeholders + +Every registered shortcode gets a placeholder in the editor. Without anything else, that is a +generated SVG showing the shortcode itself (the blue images above). A class can draw its own, like +the contact card above, with `getShortcodePlaceHolder()`; see +[Shortcode placeholder images](#shortcode-placeholder-images). + +### Block-level shortcodes -## Configuration -Register DataObjects or classes as shortcodable via Yaml config: +Output such as a form, a video or a gallery is block-level HTML, which may not sit inside a `

`. +Set `shortcode_close_parent` on the class and the paragraph around the shortcode is closed before +its output and reopened after it; see [Wrapping](#wrapping-block-level-output) for the exact rules. + +## Making a class shortcodable + +### Register it + +Register DataObjects or other classes as shortcodable via YAML config: ```yml --- @@ -56,31 +88,15 @@ Shortcodable\Shortcodable: shortcodable_classes: - My\Namespaced\Shortcodes\CurrentYearShortcode - My\Namespaced\Shortcodes\SomeOtherShortcode - - ... ---- ``` -### Configuration options +Register through YAML, not programmatically in a `_config.php`: the module's own `_config.php` +reads this list to register the shortcodes with the parser and to tell the editor which shortcodes +have placeholders. -| Option | Default | What it does | -|--------|---------|--------------| -| `Shortcodable\Shortcodable.shortcodable_classes` | `[]` | Classes to register with the shortcode parser and offer in the dialog. | -| `Shortcodable\Shortcodable.htmleditor_names` | `[cms]` | HTMLEditor configs that get the shortcode button. Only TinyMCE configs are changed; others are skipped. | -| `Shortcodable\Controllers\ShortcodableAdminController.default_placeholder` | see class | Size, font and colours of the default SVG placeholder (`width`, `height`, `full_width`, `full_height`, `font`, `fontsize`, `fg`, `bg`). | +### Required methods on shortcodable objects/classes -Per shortcodable class (as `private static` or YAML on that class): - -| Option | Default | What it does | -|--------|---------|--------------| -| `shortcode` | short class name | The shortcode tag, eg `currentyear` for `[currentyear]`. | -| `shortcode_callback` | `parse_shortcode` | Name of the parser method. | -| `shortcode_close_parent` | `false` | Block-level output: close the wrapping element before the shortcode and reopen it after (see below). Also gives the default placeholder the full size. | -| `placeholder_settings` | none | `width`/`height` overriding the default placeholder size for this shortcode. | - - -## Required methods on shortcodable objects/classes - -Implement these methods on your shortcodable classes (may also be added via an Extension): +Implement these methods on your shortcodable classes (they may also be added via an Extension): **(Required) shortcode parser callback:**
`public static function parse_shortcode(...)`
@@ -94,15 +110,74 @@ Implement these methods on your shortcodable classes (may also be added via an E **NOTE: the parser method gets called on a singleton object instance.**
(So there's no `$this->ID` or `$this->owner->ID` etc.) +A registered class without its parser method is a fatal error (`E_USER_ERROR`) when the +shortcodes are registered, on every request. + +A plain class (not a DataObject) needs the `Extensible` trait: the module checks methods with +`hasMethod()`, which comes from that trait (`DataObject` and `ViewableData`/`ModelData` subclasses +have it already). **Optional:** -- `private static $shortcode` (optional, else short ClassName will be used as [ClassName]) -- `getShortcodeLabel()` (optional nice description for in dropdown, `singular_name()` or else `ClassName.Shortname` will be used as fallback) -- `getShortcodeFields()` (optional, attribute-formfields for popup) -- `getShortcodableRecords()` (optional, if applied to DataObject) -- `getShortcodePlaceholder($attributes)` (optional) +- `private static $shortcode` (optional, else the short class name is used, as `[ClassName]`) +- `getShortcodeLabel()` (optional nice description for in the dropdown; `singular_name()` or else + the short class name is used as fallback) +- `getShortcodeFields()` (optional, a `FieldList` of attribute form fields for the dialog; each + field's name becomes the attribute name) +- `getShortcodableRecords()` (optional, if applied to a DataObject: the `ID => title` map for the + record dropdown; default is all records of the class) +- `getShortcodePlaceHolder($attributes)` (optional, see below) + +A minimal shortcode: + +```php +namespace My\Namespaced\Shortcodes; + +use SilverStripe\Core\Config\Configurable; +use SilverStripe\Core\Extensible; +use SilverStripe\Core\Injector\Injectable; +use SilverStripe\Forms\FieldList; +use SilverStripe\Forms\TextField; + +class ButtonShortcode +{ + use Configurable; + use Extensible; + use Injectable; + + private static $shortcode = 'button'; + + public static function parse_shortcode($attrs, $content = null, $parser = null, $shortcode = null, $info = []) + { + return sprintf( + '%s', + htmlspecialchars($attrs['link'] ?? '#'), + htmlspecialchars($attrs['label'] ?? '') + ); + } + + public function getShortcodeLabel() + { + return 'Call-to-action button'; + } + + public function getShortcodeFields() + { + return FieldList::create( + TextField::create('label', 'Button text'), + TextField::create('link', 'Link') + ); + } +} +``` + +For a **DataObject**, the dialog adds a dropdown named `id` with its records, so the shortcode gets +an `id` attribute, eg `[contact id="3"]`. The record ID is also passed to the placeholder (below). + +The dialog form can be changed from an Extension on `Shortcodable\Controllers\ShortcodableAdminController` +through the `updateShortcodeForm($form)` hook. + +### Wrapping (block-level output) -**Wrapping (optional):** In this module, `$shortcodable_is_block` and `$disable_wrapper` have been replaced with `$shortcode_close_parent`:
- `private static $shortcode_close_parent` (optional, set to true if your shortcode output is a block-type html element) @@ -121,24 +196,29 @@ than 8 KB, is left untouched (a guard against pathological markup). Up to 5.1.0 a container on the same line was closed too, so `

[shortcode]
` lost its `
`; since 5.2.0 it is kept. +### Shortcode placeholder images -## Shortcode placeholder images -To display a nice image instead of the raw shortcode in the CMS editor, implement a getShortcodePlaceHolder method on your shortcodable object: +To display a nice image instead of the raw shortcode in the CMS editor, implement a +`getShortcodePlaceHolder()` method on your shortcodable object. The editor loads it as the `src` of +an ``, from `admin/shortcodable/placeholder//?sc=` (CMS +access required). For a DataObject with an `id` attribute the method is called on that record, +otherwise on a singleton. It gets the shortcode's attributes, and whatever it returns is the +response: ```php /** * Redirect to an image OR return image data directly to be displayed as shortcode placeholder in the editor * (getShortcodePlaceHolder gets loaded as/from the 'src' attribute of an tag) * -* @param array $attributes attribute key-value pairs of the shortcode +* @param array|null $attributes attribute key-value pairs of the shortcode * @return \SilverStripe\Control\HTTPResponse **/ public function getShortcodePlaceHolder($attributes) { // Flavour one: redirect to image URL (for this example we're also including the attributes array in the URL) - Controller::curr()->redirect('https://www.silverstripe.org/apple-touch-icon-76x76.png?attrs='.json_encode($attributes)); + return Controller::curr()->redirect('https://www.silverstripe.org/apple-touch-icon-76x76.png?attrs='.json_encode($attributes)); - // Flavour two: output image/svg data directly (any bitmap but may also be SVG) + // Flavour two: return image/svg data directly (any bitmap but may also be SVG) // Hint: process attributes eg to show a set of image thumbnails wrapped in an SVG as gallery-placeholder $response = Controller::curr()->getResponse(); $response->addHeader('Content-Type','image/svg+xml'); @@ -147,18 +227,85 @@ public function getShortcodePlaceHolder($attributes) '); - $response->output(); + return $response; } ``` -### Default placeholder image +#### Default placeholder image Without `getShortcodePlaceHolder()`, the editor shows an SVG generated by `admin/shortcodable/placehold.img` -(CMS access required). It takes `w` and `h` (a positive number of pixels, or `100%`), `bg` and `fg` +(CMS access required), with the shortcode as its text. It is 46 px high and as wide as the text +needs; with `shortcode_close_parent` it is 1000 x 460 px. `placeholder_settings` on the class +(`width`, `height`) overrides that size, and `default_placeholder` sets the defaults and colours +(see [Configuration options](#configuration-options)). + +`placehold.img` takes `w` and `h` (a positive number of pixels, or `100%`), `bg` and `fg` (3 or 6 hex digits, no `#`), `ff` (font family), `txtsize` and `txt`. Invalid values fall back to the -`default_placeholder` config. +`default_placeholder` config. Sizes are capped at `full_width` x `full_height`. + +## Technical + +### Requirements + +* Silverstripe 5 or 6 (`silverstripe/framework ^5 || ^6`) +* PHP 8.1 or newer (Silverstripe 6 itself needs 8.3) +* [restruct/silverstripe-simpler](https://github.com/restruct/silverstripe-simpler) `~0.2 || ^1`, + installed automatically. On Silverstripe 6 that is 1.0.0 or later (0.x does not support 6); a + fresh install gets 1.x on Silverstripe 5 as well, and a Silverstripe 5 project that already has + simpler 0.2 or 0.3 can keep it +* **Silverstripe 6 only:** `silverstripe/htmleditor-tinymce`. TinyMCE is a separate module on Silverstripe 6 + and `silverstripe/recipe-cms` does not include it. Without it the site still boots, but there is no + TinyMCE editor to add the shortcode button to. + +### Installation + +``` +composer require restruct/silverstripe-shortcodable +# Silverstripe 6, if your project does not have it yet: +composer require silverstripe/htmleditor-tinymce +``` + +Then flush (`?flush=1`, or `sake dev/build flush=1` on Silverstripe 5 and `sake db:build --flush` +on 6), and register your shortcodes as above. + +### Version compatibility + +| Branch | Module Version | Silverstripe | PHP | +|---------|----------------|----------------|----------------| +| `main` | `5.x` (from `5.1.0`) | `^5 \|\| ^6` | `^8.1` | +| `v4` | `4.x` | `^4 \|\| ^5` | `^7.4 \|\| ^8.0` | -## Running the tests +`main` is the maintained line and supports every Silverstripe version this module still targets. +Silverstripe 4 reached end of life in April 2025 and is no longer supported or tested here; projects +still on it can stay on the `4.x` tags, which remain available. The `5.0.x` tags declared Silverstripe 6 +only, and could not be installed from Packagist (see [CHANGELOG.md](CHANGELOG.md)); use `^5.1`. +Upgrading from 4.x or 5.0.x: see [UPGRADING.md](UPGRADING.md). + +**Note:** `composer.json` is the source of truth for exact version constraints. + +### Configuration options + +| Option | Default | What it does | +|--------|---------|--------------| +| `Shortcodable\Shortcodable.shortcodable_classes` | `[]` | Classes to register with the shortcode parser and offer in the dialog. | +| `Shortcodable\Shortcodable.htmleditor_names` | `[cms]` | HTMLEditor configs that get the shortcode button. Only TinyMCE configs are changed; others are skipped. | +| `Shortcodable\Controllers\ShortcodableAdminController.default_placeholder` | see below | Size, font and colours of the default SVG placeholder. | + +`default_placeholder` keys and their defaults: `height` 46 (inline shortcodes), `full_width` 1000 and +`full_height` 460 (block shortcodes, and the maximum size), `width` 240 (only when `placehold.img` +is called without `w`), `font` a monospace font stack, `fontsize` 16, `fg` `ffffff` and `bg` +`338dc1` (the CMS blue). + +Per shortcodable class (as `private static` or YAML on that class): + +| Option | Default | What it does | +|--------|---------|--------------| +| `shortcode` | short class name | The shortcode tag, eg `currentyear` for `[currentyear]`. | +| `shortcode_callback` | `parse_shortcode` | Name of the parser method. | +| `shortcode_close_parent` | `false` | Block-level output: close the wrapping element before the shortcode and reopen it after (see [Wrapping](#wrapping-block-level-output)). Also gives the default placeholder the full size. | +| `placeholder_settings` | none | `width`/`height` overriding the default placeholder size for this shortcode. | + +### Running the tests The module cannot be tested on its own: it needs a host Silverstripe project. Require it there through a Composer **path repository with `symlink: true`** - `/tests` is `export-ignore`, so a dist @@ -176,7 +323,14 @@ SS_PHPUNIT_FLUSH=1 vendor/bin/phpunit vendor/restruct/silverstripe-shortcodable/ On Silverstripe 6 the host also needs `silverstripe/htmleditor-tinymce`, or the TinyMCE button test is skipped. CI runs the suite against Silverstripe 5 and 6 on every push; see `.github/workflows/ci.yml`. -## Status +Browser tests (Playwright, against a real CMS: the button, the dialog, placeholders and what is +saved) live in `tests/browser/` and run in `.github/workflows/browser-tests.yml`. The screenshots in +this README are generated from the same harness; see +[tests/browser/screenshots/README.md](tests/browser/screenshots/README.md) to regenerate them. + +### Rewrite status + +Compared to sheadawson/silverstripe-shortcodable: - [x] TinyMCE button/plugin - [x] Shortcode form in popup dialog @@ -190,7 +344,13 @@ skipped. CI runs the suite against Silverstripe 5 and 6 on every push; see `.git - [ ] Check/restore functionality for Uploadfields to load existing value - [ ] Check/implement(?) [wrapping shortcodes](https://github.com/sheadawson/silverstripe-shortcodable/pull/73) +### Further reading -## Refs: - [General shortcode documentation](https://docs.silverstripe.org/en/6/developer_guides/extending/shortcodes/) - [Shortcodable V2 documentation](https://github.com/sheadawson/silverstripe-shortcodable/blob/e2e2f1a2fa981d56e3c8ba63808fbe05da3d20f0/README.md) +- [UPGRADING.md](UPGRADING.md) - upgrading from 4.x or 5.0.x +- [CHANGELOG.md](CHANGELOG.md) - release history + +### License + +See [license.md](license.md). diff --git a/composer.json b/composer.json index 73c7646..6d11b3b 100644 --- a/composer.json +++ b/composer.json @@ -1,10 +1,16 @@ { "name": "restruct/silverstripe-shortcodable", - "description": "Provides a simple button to insert Shortcodes into the HTMLEditorField + an API for developers to define shortcodes", + "description": "A shortcode button and dialog for the Silverstripe WYSIWYG editor: CMS editors pick, fill in and edit shortcodes, shown as placeholder images, and developers make any class or DataObject shortcodable.", "type": "silverstripe-vendormodule", "keywords": [ "silverstripe", - "shortcode" + "silverstripe-module", + "silverstripe-cms", + "shortcode", + "shortcodes", + "tinymce", + "wysiwyg", + "htmleditor" ], "license": "BSD-3-Clause", "authors": [ diff --git a/docs/images/dialog-edit.png b/docs/images/dialog-edit.png new file mode 100644 index 0000000..7ef8cfc Binary files /dev/null and b/docs/images/dialog-edit.png differ diff --git a/docs/images/dialog-types.png b/docs/images/dialog-types.png new file mode 100644 index 0000000..ed3e1ad Binary files /dev/null and b/docs/images/dialog-types.png differ diff --git a/docs/images/editor-placeholders.png b/docs/images/editor-placeholders.png new file mode 100644 index 0000000..99abe92 Binary files /dev/null and b/docs/images/editor-placeholders.png differ diff --git a/tests/browser/fixtures/ScbShowcaseButton.php b/tests/browser/fixtures/ScbShowcaseButton.php new file mode 100644 index 0000000..44f1c2c --- /dev/null +++ b/tests/browser/fixtures/ScbShowcaseButton.php @@ -0,0 +1,52 @@ +%s', + htmlspecialchars($attrs['style'] ?? 'primary'), + htmlspecialchars($attrs['link'] ?? '#'), + htmlspecialchars($attrs['label'] ?? '') + ); + } + + public function getShortcodeLabel(): string + { + return 'Call-to-action button'; + } + + public function getShortcodeFields(): FieldList + { + return FieldList::create( + TextField::create('label', 'Button text'), + TextField::create('link', 'Link'), + DropdownField::create('style', 'Style', [ + 'primary' => 'Primary (filled)', + 'secondary' => 'Secondary (outline)', + ]) + ); + } +} diff --git a/tests/browser/fixtures/ScbShowcaseContact.php b/tests/browser/fixtures/ScbShowcaseContact.php new file mode 100644 index 0000000..03ad8f6 --- /dev/null +++ b/tests/browser/fixtures/ScbShowcaseContact.php @@ -0,0 +1,106 @@ + 'Varchar', + 'Phone' => 'Varchar', + ]; + + private static $shortcode = 'contact'; + + public static function parse_shortcode($attrs, $content = null, $parser = null, $shortcode = null, $info = []) + { + $contact = static::get()->byID((int) ($attrs['id'] ?? 0)); + if (!$contact) { + return ''; + } + $html = '' . htmlspecialchars($contact->Title) . ''; + if (($attrs['show'] ?? 'all') === 'all') { + $html .= ' ' . htmlspecialchars($contact->Phone); + } + return '' . $html . ''; + } + + public function getShortcodeFields(): FieldList + { + return FieldList::create( + DropdownField::create('show', 'Show', [ + 'all' => 'Name and phone number', + 'name' => 'Name only', + ]) + ); + } + + /** + * Its own placeholder: a contact card drawn as SVG, with the record's name. Returned as a + * response, which the placeholder endpoint passes on. + */ + public function getShortcodePlaceHolder($attributes) + { + $name = htmlspecialchars((string) $this->Title, ENT_QUOTES | ENT_XML1, 'UTF-8'); + $detail = ($attributes['show'] ?? 'all') === 'all' + ? htmlspecialchars((string) $this->Phone, ENT_QUOTES | ENT_XML1, 'UTF-8') + : 'name only'; + $svg = << + + + + + {$name} + {$detail} + +SVG; + return HTTPResponse::create($svg)->addHeader('Content-Type', 'image/svg+xml'); + } + + public function requireDefaultRecords() + { + parent::requireDefaultRecords(); + if (!Environment::getEnv('SCB_README_SHOWCASE')) { + return; + } + + $ids = []; + foreach (['Visitor centre' => '555-0142', 'Press office' => '555-0177'] as $title => $phone) { + $contact = static::get()->filter('Title', $title)->first() ?: static::create(['Title' => $title]); + $contact->Phone = $phone; + $contact->write(); + $ids[$title] = $contact->ID; + } + + $page = Page::get()->filter('URLSegment', 'plan-your-visit')->first() + ?: Page::create(['Title' => 'Plan your visit', 'URLSegment' => 'plan-your-visit']); + $page->Content = '

We are open every day of the year. Annual passes run until 31 December [year].

' + . '

Groups of ten or more can book a guided tour: ' + . '[button label="Book a tour" link="/tours" style="primary"]

' + . '

Stay in touch

' + . '

[signup_form]

' + . '

Questions about your visit? Call [contact id="' . $ids['Visitor centre'] . '" show="all"]

'; + $page->write(); + $page->publishRecursive(); + } +} diff --git a/tests/browser/fixtures/ScbShowcaseSignup.php b/tests/browser/fixtures/ScbShowcaseSignup.php new file mode 100644 index 0000000..91da10d --- /dev/null +++ b/tests/browser/fixtures/ScbShowcaseSignup.php @@ -0,0 +1,40 @@ + 560, + 'height' => 80, + ]; + + public static function parse_shortcode($attrs, $content = null, $parser = null, $shortcode = null, $info = []) + { + return ''; + } + + public function getShortcodeLabel(): string + { + return 'Newsletter sign-up form'; + } +} diff --git a/tests/browser/fixtures/ScbShowcaseYear.php b/tests/browser/fixtures/ScbShowcaseYear.php new file mode 100644 index 0000000..241ed45 --- /dev/null +++ b/tests/browser/fixtures/ScbShowcaseYear.php @@ -0,0 +1,31 @@ + pair.trim()) + .filter(Boolean) + .map((pair) => { + const [name, url] = pair.split('='); + return { name, url }; + }); +const target = targets.find((t) => t.name === 'ss6') ?? targets[0]; + +if (!target) { + throw new Error( + 'BROWSER_TARGET_URLS is empty. Run through tools/browser/run.sh (see screenshots/README.md), ' + + 'or set it by hand, e.g. BROWSER_TARGET_URLS="ss6=http://127.0.0.1:8898"', + ); +} + +// The login setup saves the session under tests/browser/.auth/ (it is run from tests/browser/). +const browserDir = path.join(__dirname, '..'); + +export default defineConfig({ + testDir: browserDir, + outputDir: path.join(browserDir, 'test-results'), + retries: 0, + // One admin session, shared; see ../playwright.config.ts for why that means one worker. + workers: 1, + timeout: 60_000, + expect: { timeout: 10_000 }, + reporter: [['list']], + use: { + ...devices['Desktop Chrome'], + // ~1280 wide, at 1x, so the PNGs are the width a README shows them at. + viewport: { width: 1280, height: 800 }, + deviceScaleFactor: 1, + screenshot: 'only-on-failure', + }, + projects: [ + { + name: `${target.name}-login`, + testMatch: /specs\/login\.setup\.ts/, + use: { baseURL: target.url }, + }, + { + name: target.name, + testMatch: /screenshots\/.*\.shot\.ts/, + dependencies: [`${target.name}-login`], + use: { baseURL: target.url, storageState: path.join(browserDir, '.auth', `${target.name}.json`) }, + }, + ], +}); diff --git a/tests/browser/screenshots/readme.shot.ts b/tests/browser/screenshots/readme.shot.ts new file mode 100644 index 0000000..61a1049 --- /dev/null +++ b/tests/browser/screenshots/readme.shot.ts @@ -0,0 +1,116 @@ +import { test, expect, type Locator, type Page } from '@playwright/test'; +import * as path from 'path'; + +// Generates the README screenshots in docs/images/. Not a test suite: run it with +// screenshots/playwright.config.ts (see README.md next to this file). The content comes from the +// showcase fixtures (tests/browser/fixtures/ScbShowcase*.php, registered when SCB_README_SHOWCASE +// is set): four shortcodes and a published "Plan your visit" page that uses all of them. + +const IMAGES = path.join(__dirname, '..', '..', '..', 'docs', 'images'); + +// The shortcode button and the dialog, as the browser specs address them (../specs/support.ts). +const BUTTON = '#Form_EditForm_Content_Holder button[aria-label="Insert/edit shortcode"]'; +const DIALOG = '#simplerAdminModal'; + +/** Open the showcase page in the CMS and wait until all four placeholders have loaded. */ +async function openShowcasePage(page: Page): Promise { + await page.goto('/admin/pages'); + await page.locator('.cms-tree a').filter({ hasText: 'Plan your visit' }).first().click(); + await expect(page.locator(BUTTON)).toBeVisible(); + const placeholders = page.frameLocator('#Form_EditForm_Content_ifr').locator('img.sc-placeholder'); + await expect(placeholders).toHaveCount(4); + await expect + .poll(() => placeholders.evaluateAll((imgs) => imgs.every((i) => (i as HTMLImageElement).complete && (i as HTMLImageElement).naturalWidth > 0)), { + message: 'all placeholders loaded', + }) + .toBe(true); +} + +/** A placeholder image in the editor, by its shortcode name. */ +function placeholder(page: Page, name: string): Locator { + return page.frameLocator('#Form_EditForm_Content_ifr').locator(`img.sc-placeholder[title^="${name} "]`); +} + +/** Open the dialog with the toolbar button and wait for its form (fetched with AJAX). */ +async function openDialog(page: Page): Promise { + await page.locator(BUTTON).click(); + const dialog = page.locator(DIALOG); + await expect(dialog.locator('form#Form_ShortcodeForm')).toBeVisible(); + // Bootstrap's fade-in. + await page.waitForTimeout(600); + return dialog; +} + +/** Clip a screenshot to a box with some margin around it, kept inside the viewport. */ +function around(box: { x: number; y: number; width: number; height: number }, margin: number, page: Page) { + const vp = page.viewportSize()!; + const x = Math.max(0, Math.floor(box.x - margin)); + const y = Math.max(0, Math.floor(box.y - margin)); + return { + x, + y, + width: Math.min(vp.width - x, Math.ceil(box.width + 2 * margin)), + height: Math.min(vp.height - y, Math.ceil(box.height + 2 * margin)), + }; +} + +test.use({ viewport: { width: 1280, height: 900 } }); + +test('Editor: shortcodes shown as placeholders, the shortcode button in the toolbar', async ({ page }) => { + await openShowcasePage(page); + + // Point at the button (its hover state marks it in the toolbar). + await page.locator(BUTTON).hover(); + await page.waitForTimeout(300); + + // From the "Content" label down to the end of the content: the page name and URL segment + // fields above it add nothing (and the URL segment would show the test host's address). + const holder = (await page.locator('#Form_EditForm_Content_Holder').boundingBox())!; + const last = (await placeholder(page, 'contact').boundingBox())!; + await page.screenshot({ + path: path.join(IMAGES, 'editor-placeholders.png'), + clip: { + x: holder.x - 16, + y: holder.y - 8, + width: holder.width + 32, + height: Math.ceil(last.y + last.height + 24 - (holder.y - 8)), + }, + }); +}); + +test('Dialog: editing a selected shortcode', async ({ page }) => { + await openShowcasePage(page); + + // Select the button placeholder, then open the dialog: it opens with that shortcode's values. + await placeholder(page, 'button').click(); + const dialog = await openDialog(page); + await expect(dialog.locator('input[name="label"]')).toHaveValue('Book a tour'); + await page.mouse.move(5, 895); + + await page.screenshot({ + path: path.join(IMAGES, 'dialog-edit.png'), + clip: around((await dialog.locator('.modal-content').boundingBox())!, 24, page), + }); +}); + +test('Dialog: choosing a shortcode type', async ({ page }) => { + await openShowcasePage(page); + + // Cursor at the end of the first paragraph, nothing selected: a new shortcode. + const editorBody = page.frameLocator('#Form_EditForm_Content_ifr').locator('body p').first(); + await editorBody.click({ position: { x: 5, y: 5 } }); + await page.keyboard.press('End'); + const dialog = await openDialog(page); + // The type dropdown is a chosen.js field; open its list. + await dialog.locator('#Form_ShortcodeForm_ShortcodeType_chosen').click(); + await expect(dialog.locator('#Form_ShortcodeForm_ShortcodeType_chosen .chosen-results li')).toHaveCount(5); + await page.waitForTimeout(300); + + const content = (await dialog.locator('.modal-content').boundingBox())!; + const list = (await dialog.locator('#Form_ShortcodeForm_ShortcodeType_chosen .chosen-drop').boundingBox())!; + const bottom = Math.max(content.y + content.height, list.y + list.height); + await page.screenshot({ + path: path.join(IMAGES, 'dialog-types.png'), + clip: around({ x: content.x, y: content.y, width: content.width, height: bottom - content.y }, 24, page), + }); +});