diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..a4f4fcc --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# Keep development-only files out of dist installs (Packagist zips). CI and local module work must +# therefore install this module as a PATH repository with symlink: true, or a real checkout - +# a dist install contains no tests at all. +/tests export-ignore +/.github export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/.editorconfig export-ignore +/phpunit.xml.dist export-ignore diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2b60288 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,214 @@ +name: CI + +on: + push: + # master is the repository's current default branch; main is listed too so CI keeps running + # unchanged once the default branch is renamed to the portfolio convention. + branches: [master, main] + pull_request: + workflow_dispatch: + +jobs: + test: + name: SS${{ matrix.silverstripe }} / PHP ${{ matrix.php }} + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + include: + # One job per supported Silverstripe major, at the oldest and newest PHP that major is + # used with here. The module's composer.json is the source of truth for the supported + # range; this matrix must follow it. + - silverstripe: '5' + php: '8.1' + recipe: '^5' + testing: '^3' + - silverstripe: '5' + php: '8.3' + recipe: '^5' + testing: '^3' + - silverstripe: '6' + php: '8.3' + recipe: '^6' + testing: '^4' + - silverstripe: '6' + php: '8.4' + recipe: '^6' + testing: '^4' + + services: + database: + # MariaDB rather than MySQL: it matches both the local dev machines and the Forge + # servers, so a version-specific failure here means something real. + image: mariadb:11.4 + env: + MARIADB_ROOT_PASSWORD: root + MARIADB_DATABASE: ss_ci + ports: + - 3306:3306 + options: >- + --health-cmd="healthcheck.sh --connect --innodb_initialized" + --health-interval=10s --health-timeout=5s --health-retries=10 + + steps: + - name: Check out the module + uses: actions/checkout@v4 + with: + path: module + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: mbstring, intl, pdo_mysql, mysqli, gd, zip, dom, xml, tokenizer, simplexml, ctype, hash, session + tools: composer:v2 + coverage: none + + - name: Build a host project + # The module cannot be tested on its own: it needs a booted Silverstripe app. The host + # composer.json is written by hand; recipe-cms brings in the admin (whose LeftAndMain + # loads the module's script and stylesheet) and the CMS (whose page edit form the suite + # renders the fields in). + # + # The module is pulled in through a PATH repository pointing at the checkout, symlinked + # rather than mirrored: /tests is export-ignore in .gitattributes, so a mirrored + # (dist-style) install would contain no tests at all and the suite would silently pass + # with nothing in it. + run: | + mkdir -p app-host + cd app-host + cat > composer.json <#$1 $1 app/tests$1 $1#' phpunit.xml + grep -q '' phpunit.xml + cat phpunit.xml + + - name: Add a consumer-shape database test + # A module's own suite cannot catch a test fixture that breaks CONSUMING projects: its + # fixtures are loaded by PHPUnit, not registered in the class manifest. This test runs as + # the consumer would, with the module's tests/ in the manifest, and must still build the + # temp database. + run: | + mkdir -p app-host/app/tests + cat > app-host/app/tests/ConsumerDbTest.php <<'PHP' + 'x']); + $m->write(); + $this->assertGreaterThan(0, $m->ID); + } + } + PHP + + - name: Run tests + working-directory: app-host + env: + SS_DATABASE_CLASS: MySQLDatabase + SS_DATABASE_SERVER: 127.0.0.1 + SS_DATABASE_PORT: 3306 + SS_DATABASE_USERNAME: root + SS_DATABASE_PASSWORD: root + SS_DATABASE_NAME: ss_ci + SS_ENVIRONMENT_TYPE: dev + # PHPUnit 11 (SS6) ignores a `flush=1` argument, so the manifest is flushed through + # this instead. It is read only by framework 6: on framework 5 it does nothing and does + # NOT flush, so the SS5 legs flush with a path-first `flush=1` argument below. + SS_PHPUNIT_FLUSH: 1 + # Flush on every run, or a stale test manifest reads as a broken test. On SS5 the flush + # must be a `flush=1` argument AFTER a path: `--testsuite flush=1` silently does + # not flush, so the suites are addressed by their directories there. + # + # Every suite runs with --fail-on-empty-test-suite (PHPUnit 9.6 on SS5 accepts it too, it is + # only missing from its --help), so a suite that silently ran nothing (a file the manifest + # no longer finds, a broken consumer-test heredoc) fails instead of ending green. + # Not a grep for "OK (N tests": PHPUnit exits 0 with "OK, but there were issues!" or + # "OK, but some tests were skipped!", so such a count guard turns a passing suite red on + # the first upstream deprecation notice. + run: | + if [ "${{ matrix.silverstripe }}" = "6" ]; then + vendor/bin/phpunit --fail-on-empty-test-suite --testsuite infofield + vendor/bin/phpunit --fail-on-empty-test-suite --testsuite consumer + else + vendor/bin/phpunit --fail-on-empty-test-suite vendor/restruct/silverstripe-inline-infofield/tests flush=1 + vendor/bin/phpunit --fail-on-empty-test-suite app/tests flush=1 + fi + + - name: Boot the app and build the database + # The suite proves the classes behave; this proves the module does not break a real boot + # or a flush (where an unguarded optional dependency would fatal). + working-directory: app-host + env: + SS_DATABASE_CLASS: MySQLDatabase + SS_DATABASE_SERVER: 127.0.0.1 + SS_DATABASE_PORT: 3306 + SS_DATABASE_USERNAME: root + SS_DATABASE_PASSWORD: root + SS_DATABASE_NAME: ss_ci + SS_ENVIRONMENT_TYPE: dev + run: | + if [ "${{ matrix.silverstripe }}" = "6" ]; then + vendor/bin/sake db:build --flush + else + vendor/bin/sake dev/build flush=1 + fi + + lint: + name: Lint PHP ${{ matrix.php }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # The floor and the ceiling of the module's declared php constraint. + php: ['8.1', '8.4'] + steps: + - uses: actions/checkout@v4 + - uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + coverage: none + - name: Syntax check every PHP file + run: find src tests -name '*.php' -print0 | xargs -0 -n1 php -l diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..c17bf42 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,60 @@ +# Changelog + +## 3.0.0 (2026-09-25) + +Silverstripe 5 and 6. Silverstripe 4 is dropped, which is why this is a major release. See +[UPGRADING.md](UPGRADING.md). + +### Breaking + +- **Silverstripe 4 is no longer supported.** `silverstripe/framework` is now `^5 || ^6` (was + `^4.4`), `silverstripe/vendor-plugin` `^2 || ^3` (was `^1.0`), and PHP `^8.1` (was not declared). + Silverstripe 4 projects keep resolving the `2.x` tags. +- **`silverstripe/admin` (`^2 || ^3`) is now required.** The module's config targets `LeftAndMain` + and both fields exist for CMS forms; it was used but not declared. A framework-only project + now pulls in the admin. +- **`InfoField` now boxes object content too.** Content passed as an object (for example a + `DBHTMLText` from `DBField::create_field()` or `renderWith()`) used to be output bare, without the + info box; it is now wrapped in the same `div.message.info` as string content. If you relied on + the bare output, use a plain `LiteralField` for that content. + +### Fixed + +- `InfoField` dropped its info box for object content (see above). +- `InlineInfoField` wrote the target field name into its `data-target` attribute unescaped; it is + now attribute-escaped. The help text itself is still output as HTML, as documented. + +### Added + +- A behavioural test suite (`tests/`), run in CI against Silverstripe 5 and 6: the markup of both + fields (the contract with the CMS script and stylesheet), the CMS requirements and their + publication, and a real CMS page edit form. +- README: what the module does (the previous text described a different field), requirements, + installation, a version compatibility table, usage of both fields, the assets it loads and where + the inline field works. +- README credits nathancox/silverstripe-helpfield, which `InlineInfoField` is derived from (the + 2.0 README credited it; 2.1 dropped the credit). +- `funding` and PSR-4 `autoload` in `composer.json`. Its description and keywords described a + cookie notice and are corrected. + +### Licence + +- Still no licence declared, as in every `2.x` release: there is no `LICENSE` file and no + `license` key in `composer.json`. + +### Issues + +- No issues or pull requests were open (or had ever been filed) at the time of this release. + +## 2.1.1 + +- Remove a leftover `console.log` from the CMS script. +- (After the tag, on `master`: `silverstripe/vendor-plugin` added as a requirement.) + +## 2.1 + +- Minor fixes. + +## 2.0 + +- Silverstripe 4 vendor module. diff --git a/README.md b/README.md index c439721..e094592 100755 --- a/README.md +++ b/README.md @@ -1,15 +1,154 @@ -SilverStripe Inline Help Field -=================================== +Silverstripe Inline Info Field +============================== -Adds a question mark next to the label of another field that expands to show text when clicked. Can be used to add extra information or instructions without taking up space all the time. +*Maintained by [Restruct](https://github.com/restruct). If this module saves you time, you can +[support ongoing maintenance](https://github.com/sponsors/restruct).* + +Two form fields for putting help text in CMS forms: + +* **`InfoField`** - a block of text or HTML in a styled info box (an info icon on a light + background), between the other fields of a form. +* **`InlineInfoField`** - a small info icon next to **another field's label**. Its text stays hidden + until the editor hovers over the icon (or taps it, on a touch device), so it adds instructions + without taking up space. Requirements ------------ -* SilverStripe 4 -Usage Overview --------------- +* Silverstripe 5 or 6 (`silverstripe/framework`) +* PHP 8.1 or newer +* The CMS admin (`silverstripe/admin` 2 or 3, required): the module configures `LeftAndMain` and + its script and stylesheet are loaded on CMS screens only (see [Assets](#assets)). + +Installation +------------ + +``` +composer require restruct/silverstripe-inline-infofield +``` + +Version compatibility +--------------------- + +| Branch | Module version | Silverstripe | PHP | +|--------|----------------|--------------|-----| +| `master` | `3.x` | `^5 \|\| ^6` | `^8.1` | +| (tags only) | `2.0` - `2.1.1` | `^4.4` | not declared | + +Silverstripe 4 reached end of life in April 2025 and is no longer supported or tested here. Projects +still on it should stay on the `2.x` tags, which remain available. + +The default branch is the only maintained line: it supports every Silverstripe version this module +still targets, so there is no separate maintenance branch. A version branch will be created only when +a change cannot be made compatible across the supported range. + +**`composer.json` is the source of truth** for exact constraints; this table is a quick reference. + +Usage +----- + +Both fields live in the `Restruct\InfoField` namespace. + +### InfoField + +```php +use Restruct\InfoField\InfoField; + +$fields->addFieldToTab( + 'Root.Main', + InfoField::create('LayoutInfo', 'Save the page first, then edit the blocks from their tabs.'), + 'Title' // optional: insert before this field +); +``` + +* **`InfoField::create($name, $content)`** - `$name` is only an identifier (the field holds no + data); `$content` is a string of HTML, or an object such as a `DBHTMLText` from + `DBField::create_field()` or `renderWith()`. +* Renders `
$content
`. Classes added with `addExtraClass()` are + appended to the box. +* **The content is output as HTML, unescaped.** Escape any user-supplied text yourself, for example + with `Convert::raw2xml()`. + +`InfoField` extends `LiteralField`, so everything else a `LiteralField` offers (`setContent()`, +`getContent()`, readonly transformation) applies. + +### InlineInfoField + +```php +use Restruct\InfoField\InlineInfoField; + +$fields->push(InlineInfoField::create('Title', 'Keep titles short: they are also used in the menu.')); +``` + +* **`InlineInfoField::create($targetField, $content)`** - `$targetField` is the **name of the field + whose label gets the info icon** (for example `Title`, `MenuTitle` or `Content`); `$content` is the + help text as a string of HTML, output unescaped. +* The field's own name is `_InlineInfoField`, so use that name to remove or move it. +* Where you add it to the field list does not matter much: in the CMS its script moves the icon into + the target field's label as soon as the form loads. +* It renders ``, with the + help text in an inner `` that the script shows on hover (or toggles on tap on a touch + device). + +**Which forms it works in.** The script finds the target by the holder id +`Form_EditForm__Holder`, or an id ending in that. This matches the CMS edit forms whose +form is named `EditForm`, such as the page editor. A GridField detail form (for example in a +`ModelAdmin`) has ids starting `Form_ItemEditForm_`, which the script does not match, so there the +icon is not moved into the label. Outside the CMS the script is not loaded at all (see below). + +### Assets + +The module adds its script and stylesheet to **every CMS screen** through `LeftAndMain` config +(`_config/config.yml`): + +```yaml +SilverStripe\Admin\LeftAndMain: + extra_requirements_javascript: + - 'restruct/silverstripe-inline-infofield:client/dist/js/InlineInfoField.js' + extra_requirements_css: + - 'restruct/silverstripe-inline-infofield:client/dist/css/InlineInfoField.css' +``` + +Both are published by Composer from the directories listed under `extra.expose` in the module's +`composer.json`. On the front end nothing is loaded, so a front-end form that uses these fields must +include its own styling (and `InlineInfoField` stays where it was placed). + +The stylesheet styles `.message.info` elements in general, not only the ones these fields output, so +other CMS messages with those classes also get the info box look. + +`InlineInfoField::get_module_dir()` returns the module's directory name. It is not used by the module +itself and is kept for code that called it. + +Running the tests +----------------- + +The module cannot be tested on its own: it needs a host Silverstripe project (with +`silverstripe/recipe-cms` and `silverstripe/recipe-testing`). Require it there through a Composer +**path repository with `symlink: true`** - `/tests` is `export-ignore`, so a dist or mirrored install +contains no tests - add `Restruct\InfoField\Tests\` pointing at the module's `tests/` to the host's +`autoload-dev`, copy `phpunit.xml.dist` to the host root as `phpunit.xml`, then: + +```bash +# Silverstripe 5 (PHPUnit 9) - the path must come before flush=1 +vendor/bin/phpunit vendor/restruct/silverstripe-inline-infofield/tests flush=1 + +# Silverstripe 6 (PHPUnit 11) - a flush=1 argument is ignored, use the env var +SS_PHPUNIT_FLUSH=1 vendor/bin/phpunit --testsuite infofield +``` + +The suite checks the rendered markup, the CMS requirements and their publication, and renders a real +CMS page edit form. It does not run the script in a browser. + +CI runs the same suite against Silverstripe 5 and 6 on every push; see `.github/workflows/ci.yml`. + +Credits +------- + +`InlineInfoField` is derived from +[nathancox/silverstripe-helpfield](https://github.com/nathancox/silverstripe-helpfield) by Nathan +Cox, which the 2.0 README credited. + +License +------- -HelpField takes two parameters: -1. The name of the field you want to add help text to (eg, "MenuTitle" or "Content") -2. The help text itself. Should be a string of text/HTML +No licence is declared, as in every `2.x` release. diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..87bc3be --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,26 @@ +# Upgrading + +## 2.x to 3.0 + +3.0 supports Silverstripe 5 and 6 on PHP 8.1+. On Silverstripe 4, keep a `^2` constraint: +Composer will not offer 3.0 there. + +On Silverstripe 5 and 6, change your constraint to `^3`: + +```bash +composer require restruct/silverstripe-inline-infofield:^3 +``` + +3.0 requires `silverstripe/admin` (`^2 || ^3`), which every CMS project already has. + +Class names, the namespace (`Restruct\InfoField`), constructor arguments, the rendered markup and +the CMS config are unchanged. Nothing to edit in `_config` or templates. + +### Behaviour you may notice + +- **`InfoField` with object content.** If you passed an object (a `DBHTMLText` from + `DBField::create_field()` or `renderWith()`, for example) as the content, 2.x output it without + the info box. 3.0 wraps it in the same `div.message.info` box as string content. If you wanted + the bare output, use a `LiteralField` for that content instead. +- **`InlineInfoField` target names** are now attribute-escaped in `data-target`. For ordinary field + names this changes nothing. diff --git a/composer.json b/composer.json index dd109eb..9c50b55 100755 --- a/composer.json +++ b/composer.json @@ -1,23 +1,52 @@ { "name": "restruct/silverstripe-inline-infofield", - "description": "Drop-in configurable notice about cookies", + "description": "CMS form fields for help text: InfoField (a styled info box) and InlineInfoField (an info icon next to another field's label that shows its text on hover or tap)", "type": "silverstripe-vendormodule", - "homepage": "http://github.com/restruct/silverstripe-inline-infofield", + "homepage": "https://github.com/restruct/silverstripe-inline-infofield", "keywords": [ "silverstripe", - "cookies" + "cms", + "forms", + "help", + "info" ], "authors": [ { "name": "Restruct", "email": "dev@restruct.nl", "homepage": "https://restruct.nl" } ], "require": { - "silverstripe/vendor-plugin": "^1.0", - "silverstripe/framework": "^4.4" + "php": "^8.1", + "silverstripe/vendor-plugin": "^2 || ^3", + "silverstripe/framework": "^5 || ^6", + "silverstripe/admin": "^2 || ^3" + }, + "require-dev": { + "silverstripe/recipe-testing": "^3 || ^4" + }, + "autoload": { + "psr-4": { + "Restruct\\InfoField\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "Restruct\\InfoField\\Tests\\": "tests/" + } }, "extra": { "expose": [ "client/dist/js", "client/dist/css", "client/images" - ], - "installer-name": "inline-infofield" - } + ] + }, + "config": { + "allow-plugins": { + "composer/installers": true, + "silverstripe/vendor-plugin": true + } + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/restruct" + } + ] } diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..fb70867 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,12 @@ + + + + + + vendor/restruct/silverstripe-inline-infofield/tests + + + diff --git a/src/InfoField.php b/src/InfoField.php index b21e8e4..2cd5525 100755 --- a/src/InfoField.php +++ b/src/InfoField.php @@ -21,18 +21,23 @@ class InfoField extends LiteralField public function FieldHolder($properties = []) { - if ( is_object($this->content) ) { - $obj = $this->content; + # Object content (eg. a DBHTMLText from DBField::create_field() or renderWith()) is + # rendered first and then boxed like string content. It used to be returned bare, as + # LiteralField does, so the info box this class exists for silently went missing. + $content = $this->content; + if ( is_object($content) ) { + $obj = $content; if ( $properties ) $obj = $obj->customise($properties); - return $obj->forTemplate(); +// return $obj->forTemplate(); + $content = $obj->forTemplate(); } $classes = ''; if ( $this->extraClasses ) $classes = implode(' ', $this->extraClasses); - return "
" . $this->content . '
'; + return "
" . $content . '
'; } } diff --git a/src/InlineInfoField.php b/src/InlineInfoField.php index 5006e47..79ab017 100755 --- a/src/InlineInfoField.php +++ b/src/InlineInfoField.php @@ -2,6 +2,7 @@ namespace Restruct\InfoField { + use SilverStripe\Core\Convert; use SilverStripe\Forms\DatalessField; class InlineInfoField extends DatalessField @@ -30,7 +31,9 @@ function FieldHolder($properties = []) { // self::include_requirements(); - return '' . $this->content . ''; } diff --git a/tests/CmsRenderTest.php b/tests/CmsRenderTest.php new file mode 100644 index 0000000..c5946a5 --- /dev/null +++ b/tests/CmsRenderTest.php @@ -0,0 +1,73 @@ +_Holder` id and a label that the script looks up. + */ +class CmsRenderTest extends FunctionalTest +{ + protected $usesDatabase = true; + + # Filled in setUpBeforeClass() only when the CMS is installed. Declared statically, the stub + # page is built into the temp database in parent::setUpBeforeClass(), before setUp() can skip: + # without silverstripe/cms the stub class does not exist and the table build errors instead of + # the test being skipped. + protected static $extra_dataobjects = []; + + public static function setUpBeforeClass(): void + { + if (class_exists(SiteTree::class)) { + static::$extra_dataobjects = [ + InfoTestPage::class, + ]; + } + + parent::setUpBeforeClass(); + } + + protected function setUp(): void + { + parent::setUp(); + if (!class_exists(SiteTree::class)) { + $this->markTestSkipped('silverstripe/cms is not installed'); + } + } + + public function testCmsEditFormRendersTheFieldsAndLoadsTheirAssets() + { + $page = InfoTestPage::create(['Title' => 'Info test']); + $page->write(); + + $this->logInWithPermission('ADMIN'); + # getCMSEditLink() is the SS6 name (CMSEditLink() is deprecated there); SS5 pages have + # only CMSEditLink() + $editLink = method_exists($page, 'getCMSEditLink') ? $page->getCMSEditLink() : $page->CMSEditLink(); + $response = $this->get($editLink); + + $this->assertSame(200, $response->getStatusCode()); + $body = $response->getBody(); + + # Assets, from LeftAndMain.extra_requirements_* + $this->assertMatchesRegularExpression('#]+src="[^"]*/client/dist/js/InlineInfoField\.js#', $body); + $this->assertMatchesRegularExpression('#]+href="[^"]*/client/dist/css/InlineInfoField\.css#', $body); + + # The two fields + $this->assertStringContainsString( + 'Inline help for the title', + $body + ); + $this->assertStringContainsString('
Boxed help text
', $body); + + # What InlineInfoField.js looks the target label up by + $this->assertMatchesRegularExpression('#
]*>\s*markTestSkipped('silverstripe/admin is not installed'); + } + } + + public function testScriptIsAddedToEveryCmsScreen() + { + $this->assertContains( + self::MODULE . ':client/dist/js/InlineInfoField.js', + LeftAndMain::config()->get('extra_requirements_javascript') + ); + } + + public function testStylesheetIsAddedToEveryCmsScreen() + { + $this->assertContains( + self::MODULE . ':client/dist/css/InlineInfoField.css', + LeftAndMain::config()->get('extra_requirements_css') + ); + } + + public function testEveryConfiguredResourceExistsAndIsExposed() + { + $resources = array_merge( + (array) LeftAndMain::config()->get('extra_requirements_javascript'), + (array) LeftAndMain::config()->get('extra_requirements_css') + ); + $ours = array_filter($resources, fn ($r) => str_starts_with((string) $r, self::MODULE . ':')); + $this->assertCount(2, $ours); + + foreach ($ours as $resource) { + $path = ModuleResourceLoader::singleton()->resolvePath($resource); + $this->assertFileExists(BASE_PATH . '/' . $path, "$resource does not resolve to a file"); + $this->assertExposed(substr($resource, strlen(self::MODULE) + 1)); + } + } + + public function testImagesTheStylesheetReferencesExistAndAreExposed() + { + $module = ModuleLoader::getModule(self::MODULE); + $cssDir = 'client/dist/css'; + $css = file_get_contents($module->getPath() . '/' . $cssDir . '/InlineInfoField.css'); + + preg_match_all('/url\([\'"]?([^\'")]+)[\'"]?\)/', $css, $matches); + $this->assertNotEmpty($matches[1], 'expected the stylesheet to reference its info icon'); + + foreach ($matches[1] as $url) { + # Resolve the url() relative to the stylesheet's own directory, as a browser does + $parts = []; + foreach (explode('/', $cssDir . '/' . $url) as $part) { + if ($part === '..') { + array_pop($parts); + } elseif ($part !== '.' && $part !== '') { + $parts[] = $part; + } + } + $relative = implode('/', $parts); + $this->assertFileExists($module->getPath() . '/' . $relative, "$url in the stylesheet does not exist"); + $this->assertExposed($relative); + } + } + + /** + * Assert a module-relative file lies inside one of the directories composer.json exposes. + */ + private function assertExposed(string $relative): void + { + $module = ModuleLoader::getModule(self::MODULE); + $composer = json_decode(file_get_contents($module->getPath() . '/composer.json'), true); + $exposed = $composer['extra']['expose'] ?? []; + + foreach ($exposed as $dir) { + if (str_starts_with($relative, rtrim($dir, '/') . '/')) { + $this->addToAssertionCount(1); + return; + } + } + $this->fail("$relative is not inside any extra.expose directory of composer.json"); + } +} diff --git a/tests/InfoFieldTest.php b/tests/InfoFieldTest.php new file mode 100644 index 0000000..f517ab4 --- /dev/null +++ b/tests/InfoFieldTest.php @@ -0,0 +1,102 @@ +assertSame('
Some help
', $field->FieldHolder()); + } + + public function testContentIsHtmlAndIsNotEscaped() + { + # The documented contract is "an arbitrary piece of HTML" + $field = InfoField::create('Help', 'bold and a link'); + + $this->assertStringContainsString( + 'bold and a link', + $field->FieldHolder() + ); + } + + public function testExtraClassesAreAddedToTheBox() + { + $field = InfoField::create('Help', 'Some help'); + $field->addExtraClass('warning'); + $field->addExtraClass('wide'); + + $this->assertSame('
Some help
', $field->FieldHolder()); + } + + public function testFieldRendersTheSameAsFieldHolder() + { + # LiteralField::Field() delegates to FieldHolder(), so the box also appears where a form + # template calls $Field instead of $FieldHolder + $field = InfoField::create('Help', 'Some help'); + + $this->assertSame($field->FieldHolder(), $field->Field()); + } + + /** + * Regression: object content (for example a DBHTMLText from DBField::create_field() or + * renderWith()) was returned bare, without the info box the class exists to provide. + */ + public function testObjectContentIsAlsoRenderedInsideAnInfoBox() + { + $field = InfoField::create('Help', DBField::create_field('HTMLFragment', 'rendered')); + $field->addExtraClass('warning'); + + $this->assertSame('
rendered
', $field->FieldHolder()); + } + + /** + * Object content is rendered through its forTemplate(), not cast to a string. DBHTMLText (above) + * renders the same either way, so this uses a stub whose two outputs differ. + */ + public function testObjectContentIsRenderedThroughForTemplate() + { + $field = InfoField::create('Help', new RenderableContentStub()); + + $this->assertSame('
rendered
', $field->FieldHolder()); + } + + public function testFieldHolderPropertiesCustomiseObjectContent() + { + # As LiteralField does: properties passed to FieldHolder() customise object content first + $field = InfoField::create('Help', new RenderableContentStub()); + + $this->assertSame( + '
rendered Tone=calm
', + $field->FieldHolder(['Tone' => 'calm']) + ); + } + + public function testReadonlyTransformationStillRendersTheBox() + { + # A CMS form made readonly (eg. no edit permission) transforms every field + $field = InfoField::create('Help', 'Some help')->performReadonlyTransformation(); + + $this->assertInstanceOf(InfoField::class, $field); + $this->assertSame('
Some help
', $field->FieldHolder()); + } + + public function testRendersInsideAForm() + { + $form = Form::create(null, 'TestForm', FieldList::create(InfoField::create('Help', 'Help in a form')), FieldList::create()); + + $this->assertStringContainsString('
Help in a form
', (string) $form->forTemplate()); + } +} diff --git a/tests/InlineInfoFieldTest.php b/tests/InlineInfoFieldTest.php new file mode 100644 index 0000000..42447e9 --- /dev/null +++ b/tests/InlineInfoFieldTest.php @@ -0,0 +1,83 @@ +assertSame('Title_InlineInfoField', $field->getName()); + } + + public function testFieldHolderRendersTheMarkupTheScriptAndStylesheetExpect() + { + $field = InlineInfoField::create('MenuTitle', 'Shown in the menu'); + + $this->assertSame( + 'Shown in the menu', + $field->FieldHolder() + ); + } + + public function testFieldRendersTheSameAsFieldHolder() + { + $field = InlineInfoField::create('Title', 'Help'); + + $this->assertSame($field->FieldHolder(), $field->Field()); + } + + public function testContentIsHtmlAndIsNotEscaped() + { + $field = InlineInfoField::create('Title', 'Use short titles'); + + $this->assertStringContainsString('Use short titles', $field->FieldHolder()); + } + + public function testTargetFieldNameIsEscapedInTheAttribute() + { + # The target is a field name, but it is written into an HTML attribute: a quote in it must + # not be able to break out of data-target + $field = InlineInfoField::create('Ti"tle', 'Help'); + + $this->assertStringContainsString('data-target="Ti"tle"', $field->FieldHolder()); + } + + public function testRendersInsideAFormAlongsideItsTarget() + { + $form = Form::create( + null, + 'TestForm', + FieldList::create(TextField::create('Title'), InlineInfoField::create('Title', 'Help in a form')), + FieldList::create() + ); + $html = (string) $form->forTemplate(); + + $this->assertStringContainsString('data-target="Title">Help in a form', $html); + # ... and the target holder the script looks the label up by still exists alongside it + $this->assertStringContainsString('id="Form_TestForm_Title_Holder"', $html); + } + + public function testReadonlyFormStillRendersTheInfo() + { + $fields = FieldList::create(TextField::create('Title'), InlineInfoField::create('Title', 'Readonly help')); + $readonly = $fields->makeReadonly(); + + $field = $readonly->dataFieldByName('Title_InlineInfoField') ?: $readonly->fieldByName('Title_InlineInfoField'); + $this->assertNotNull($field); + $this->assertStringContainsString('Readonly help', $field->FieldHolder()); + } +} diff --git a/tests/Stub/InfoTestPage.php b/tests/Stub/InfoTestPage.php new file mode 100644 index 0000000..f1f0156 --- /dev/null +++ b/tests/Stub/InfoTestPage.php @@ -0,0 +1,36 @@ +addFieldToTab('Root.Main', InlineInfoField::create('Title', 'Inline help for the title')); + $fields->addFieldToTab('Root.Main', InfoField::create('BoxInfo', 'Boxed help text'), 'Title'); + + return $fields; + } +} diff --git a/tests/Stub/RenderableContentStub.php b/tests/Stub/RenderableContentStub.php new file mode 100644 index 0000000..f026e0b --- /dev/null +++ b/tests/Stub/RenderableContentStub.php @@ -0,0 +1,44 @@ +customised = array_merge($this->customised, (array) $data); + return $copy; + } + + public function forTemplate(): string + { + $extra = $this->customised ? ' ' . implode(',', array_map( + fn ($key, $value) => "$key=$value", + array_keys($this->customised), + $this->customised + )) : ''; + + return 'rendered' . $extra . ''; + } + + public function __toString(): string + { + # What a plain string cast (or string concatenation) of the object would produce + return 'cast-to-string'; + } +}