diff --git a/README.md b/README.md index 76a87c2..f2fd0cd 100644 --- a/README.md +++ b/README.md @@ -1,46 +1,34 @@ -silverstripe-copybutton -======================= +# Copy button for Silverstripe GridFields -Adds a copy/duplicate button to GridFields +Give every row of a GridField a Copy action: one click duplicates the record, and the copy shows up +in the list right away, or opens straight in its edit form. Put it in the row's action menu or show +it as an icon button. For Silverstripe 5 and 6. + +![A ModelAdmin GridField of events in the Silverstripe CMS, with a row's action menu open showing Copy above Edit and Delete](docs/images/menu-mode.png) *Maintained by [Restruct](https://github.com/restruct). If this module saves you time, you can [support ongoing maintenance](https://github.com/sponsors/restruct).* -## Original author - -Elvinas Liutkevičius -(Forked from dhensby's SS4-updated fork for quick maintenance & updates/tags) - -## Requirements - -* Silverstripe 5 or 6 (`silverstripe/framework`) -* PHP 8.1 or newer (Silverstripe 6 itself needs 8.3) - -## Installation - -``` -composer require restruct/silverstripe-copybutton -``` - -## Version compatibility +## A GridField row cannot be copied out of the box -| Branch | Module version | Silverstripe | PHP | -|--------|----------------|--------------|-----| -| `main` | `3.x` | `^5 \|\| ^6` | `^8.1` | -| `v2` | `2.0.x` | `^4 \|\| ^5 \|\| ^6` (see note) | not declared | -| `1`, `1.0` | `1.x` | `^3` | not declared | +Silverstripe can duplicate a record: `DataObject::duplicate()` does it, relations included where the +model asks for that. The CMS uses it for pages, in the site tree. A GridField, though, has no copy +action: the core row actions view, edit, delete or unlink a record, but none copies it. So an editor who needs a second +event, ticket type or newsletter much like an existing one starts from an empty form and types it +all in again. -`2.0.1` declares Silverstripe 4, 5 and 6 but throws a Silverstripe 6-only exception class when a -user without create permission triggers a copy, so on 4 and 5 that path fatals (issue #3). `3.x` -and the `2.0.2` hotfix fix it. Silverstripe 4 reached end of life in April 2025 and is no longer supported or tested here; -projects still on it should stay on `2.0.x`. +This module adds that missing action: -`main` is the maintained line: it supports every Silverstripe version this module still targets. -The `v2` branch exists only for hotfixes to projects that stay on `^2.0` (such as `2.0.2`). +- **Copy in the row's action menu** (the "..." dropdown), next to Edit and Delete, or as an **icon + button** in the Actions column +- **The copy is written at once** and the GridField re-renders with it in the list +- **Optionally opens the copy's edit form** straight after copying +- **Only offered to users who may create the record** (`canCreate()`), and only for records in the + GridField's own list -**`composer.json` is the source of truth** for exact constraints; this table is a quick reference. +## Copy a row in one click -## Usage +### In the action menu, or as a button The component is `Unisolutions\GridField\CopyButton`. Add it to a GridField's config: @@ -59,6 +47,8 @@ $config->addComponent(CopyButton::create(true), GridFieldEditButton::class); The one constructor argument is `$useAsColumn` (default `false`): `false` puts "Copy" in the row's action menu, `true` renders an icon button in the Actions column instead. +![A GridField of ticket types with a copy icon button on every row; the "Family" ticket type is listed twice, the copy right below its original](docs/images/column-mode.png) + Pass the class name, not a short string, as the second `addComponent()` argument: GridFieldConfig places the component before the first existing component that is an `instanceof` it, and silently appends it at the end when nothing matches. @@ -82,10 +72,11 @@ class MyAdmin extends ModelAdmin } ``` -## What a copy does +### What a copy does Clicking Copy calls `DataObject::duplicate()` on the record and writes the copy; the GridField then -re-renders with the copy in the list. No edit form is opened, unless you turn on +re-renders with the copy in the list. The copy has the same field values as its original, title +included. No edit form is opened, unless you turn on [open after copy](#open-the-copy-after-copying). * **Relations are copied only where the model says so.** `duplicate()` follows the model's @@ -97,8 +88,8 @@ re-renders with the copy in the list. No edit form is opened, unless you turn on the record's `canCreate()` is true. A copy request from anyone else is refused with a `ValidationException` ("No create permissions") and nothing is written. -To act on the copy - say, to clear some relations - implement `onAfterDuplicate()` on the model or -in an extension. It runs on the **copy**, after it was written: +To act on the copy - say, to clear some relations, or to mark its title as a copy - implement +`onAfterDuplicate()` on the model or in an extension. It runs on the **copy**, after it was written: ```php use SilverStripe\Core\Extension; @@ -112,7 +103,7 @@ class SomeObjectExtension extends Extension } ``` -## Open the copy after copying +### Open the copy after copying From 3.1, the button can open the copy's edit form straight away instead of re-rendering the list. It is off by default: @@ -124,6 +115,8 @@ use Unisolutions\GridField\CopyButton; $config->addComponent(CopyButton::create()->setOpenAfterCopy(true), GridFieldEditButton::class); ``` +![The edit form of a newsletter in the Silverstripe CMS, opened right after Copy was clicked on its original in the list](docs/images/open-after-copy.png) + The copy opens in the GridField's own detail form (`GridFieldDetailForm`), at the same URL the row's edit button links to. That works for a GridField in a ModelAdmin and for one nested in a record's edit form. In the CMS the redirect is answered with an `X-ControllerURL` header, and the admin loads @@ -140,9 +133,42 @@ error: This replaces redirecting from the model's `onAfterDuplicate()`, which fires on every `duplicate()` call, not only on a click of this button. +## Requirements + +* Silverstripe 5 or 6 (`silverstripe/framework`) +* PHP 8.1 or newer (Silverstripe 6 itself needs 8.3) + +## Installation + +``` +composer require restruct/silverstripe-copybutton +``` + +## Version compatibility + +| Branch | Module version | Silverstripe | PHP | +|--------|----------------|--------------|-----| +| `main` | `3.x` | `^5 \|\| ^6` | `^8.1` | +| `v2` | `2.0.x` | `^4 \|\| ^5 \|\| ^6` (see note) | not declared | +| `1`, `1.0` | `1.x` | `^3` | not declared | + +`2.0.1` declares Silverstripe 4, 5 and 6 but throws a Silverstripe 6-only exception class when a +user without create permission triggers a copy, so on 4 and 5 that path fatals (issue #3). `3.x` +and the `2.0.2` hotfix fix it. Silverstripe 4 reached end of life in April 2025 and is no longer supported or tested here; +projects still on it should stay on `2.0.x`. + +`main` is the maintained line: it supports every Silverstripe version this module still targets. +The `v2` branch exists only for hotfixes to projects that stay on `^2.0` (such as `2.0.2`). + +**`composer.json` is the source of truth** for exact constraints; this table is a quick reference. + +Upgrading from 2.x: see [UPGRADING.md](UPGRADING.md). What changed in each release: +[CHANGELOG.md](CHANGELOG.md). + ## Configuration -The module's only configuration adds its stylesheet to the CMS: +The module's only configuration adds its stylesheet to the CMS (it draws the column-mode icon +button): ```yaml SilverStripe\Admin\LeftAndMain: @@ -170,6 +196,11 @@ SS_PHPUNIT_FLUSH=1 vendor/bin/phpunit vendor/restruct/silverstripe-copybutton/te CI runs the same suite against Silverstripe 5 and 6 on pushes to `main` and on pull requests; see `.github/workflows/ci.yml`. +Playwright browser tests in `tests/browser/` click the copy button in a real CMS, on Silverstripe 5 +and 6, in CI (`.github/workflows/browser-tests.yml`). The screenshots in this README are generated +the same way, from neutral demo content; see +[tests/browser/screenshots/README.md](tests/browser/screenshots/README.md) to regenerate them. + ## Relation to dhensby/silverstripe-copybutton This package `replace`s `dhensby/silverstripe-copybutton` (and `unisolutions/silverstripe-copybutton`): @@ -177,6 +208,11 @@ all three ship the same class, so only one of them can be installed. Upstream pu Silverstripe 6-only 3.0.0; this package's 3.x covers Silverstripe 5 and 6 and differs in behaviour (see [CHANGELOG.md](CHANGELOG.md)). +## Original author + +Elvinas Liutkevičius +(Forked from dhensby's SS4-updated fork for quick maintenance & updates/tags) + ## Licence BSD-3-Clause, see [LICENSE](LICENSE). diff --git a/composer.json b/composer.json index f3f6cb8..ca7834b 100644 --- a/composer.json +++ b/composer.json @@ -2,12 +2,14 @@ "name": "restruct/silverstripe-copybutton", "type": "silverstripe-vendormodule", "license": "BSD-3-Clause", - "description": "Adds copy/duplicate button to the GridField.", + "description": "A Copy action for Silverstripe GridField rows: duplicate a record in one click, from the row action menu or an icon button, and optionally open the copy.", "keywords": [ "silverstripe", - "copy", - "button", + "silverstripe-module", + "silverstripe-cms", "gridfield", + "modeladmin", + "copy", "duplicate" ], "authors": [ diff --git a/docs/images/column-mode.png b/docs/images/column-mode.png new file mode 100644 index 0000000..31145eb Binary files /dev/null and b/docs/images/column-mode.png differ diff --git a/docs/images/menu-mode.png b/docs/images/menu-mode.png new file mode 100644 index 0000000..b2efaf6 Binary files /dev/null and b/docs/images/menu-mode.png differ diff --git a/docs/images/open-after-copy.png b/docs/images/open-after-copy.png new file mode 100644 index 0000000..735d1c9 Binary files /dev/null and b/docs/images/open-after-copy.png differ diff --git a/tests/browser/playwright.screenshots.config.ts b/tests/browser/playwright.screenshots.config.ts new file mode 100644 index 0000000..c9240c5 --- /dev/null +++ b/tests/browser/playwright.screenshots.config.ts @@ -0,0 +1,56 @@ +import { defineConfig, devices } from '@playwright/test'; + +// README screenshots, NOT tests: writes docs/images/*.png from a Silverstripe 6 host with the +// screenshot fixtures (screenshots/fixtures/) loaded. Kept apart from playwright.config.ts on +// purpose: the browser tests (and CI) run that config, and must never rewrite docs/images/. +// How to run: screenshots/README.md. + +// The same BROWSER_TARGET_URLS format the runner uses, but only ONE target is used: two targets +// would overwrite each other's images. ss6 when present, else the first one. +const targets = (process.env.BROWSER_TARGET_URLS ?? '') + .split(',') + .map((pair) => 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. See screenshots/README.md, e.g. ' + + 'BROWSER_TARGET_URLS="ss6=http://127.0.0.1:8958"', + ); +} + +export default defineConfig({ + testDir: '.', + outputDir: './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: 720 }, + 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: `.auth/${target.name}.json` }, + }, + ], +}); diff --git a/tests/browser/screenshots/README.md b/tests/browser/screenshots/README.md new file mode 100644 index 0000000..bb17651 --- /dev/null +++ b/tests/browser/screenshots/README.md @@ -0,0 +1,35 @@ +# README screenshots + +`readme.shot.ts` writes the PNGs in `docs/images/` that the module README shows. It is not a test +suite: it runs with its own config, `playwright.screenshots.config.ts`, which the browser tests and +CI never load, so a normal test run never rewrites the images. Never edit the PNGs by hand; +regenerate them. + +The content is neutral demo data, not the browser-test fixtures: the PHP classes in `fixtures/` +here add an "Events" ModelAdmin (`/admin/events`) with one tab per copy-button setup, re-seeded on +every database build: + +- Events: menu mode, `CopyButton::create()` +- Ticket types: column mode, `CopyButton::create(true)` +- Newsletters: menu mode with `setOpenAfterCopy(true)` + +What it needs: + +- a Silverstripe 6 host with this module installed as a symlinked path repository (the browser-test + runner's host works, or any scratch project), with the PHP files from `fixtures/` here copied into + its `app/src/`, then `vendor/bin/sake db:build --flush`. Build the database again before every + run: the script makes copies, and the column-mode shot expects exactly one; +- the host served (PHP's built-in server with a router that passes static files through, such as + `../router.php`), with a default admin `admin` / `admin`, which `specs/login.setup.ts` logs in as; +- `BROWSER_TARGET_URLS` pointing at that host (only the `ss6` target is used, else the first). + +Then, from `tests/browser/`: + +```bash +npm ci +BROWSER_TARGET_URLS="ss6=http://127.0.0.1:8958" npx playwright test --config=playwright.screenshots.config.ts +``` + +The shared runner's helpers in the maintainers' workspace (`tools/browser/lib.sh`: `host_ensure`, +`host_link_module`, `host_sync_fixtures` with this `fixtures/` directory, `host_build_db`, +`host_start`) build and serve such a host. diff --git a/tests/browser/screenshots/fixtures/ShotAdmin.php b/tests/browser/screenshots/fixtures/ShotAdmin.php new file mode 100644 index 0000000..853f83d --- /dev/null +++ b/tests/browser/screenshots/fixtures/ShotAdmin.php @@ -0,0 +1,48 @@ +, one tab per copy-button setup, configured the way the README tells a + * project to. + */ +class ShotAdmin extends ModelAdmin +{ + private static $url_segment = 'events'; + + private static $menu_title = 'Events'; + + private static $menu_icon_class = 'font-icon-calendar'; + + # Keyed managed_models: the key becomes the URL segment and the GridField's name. + private static $managed_models = [ + 'events' => ['dataClass' => ShotEvent::class, 'title' => 'Events'], + 'tickets' => ['dataClass' => ShotTicketType::class, 'title' => 'Ticket types'], + 'newsletters' => ['dataClass' => ShotNewsletter::class, 'title' => 'Newsletters'], + ]; + + protected function getGridFieldConfig(): GridFieldConfig + { + $config = parent::getGridFieldConfig(); + + switch ($this->modelClass) { + case ShotEvent::class: + $config->addComponent(CopyButton::create(), GridFieldEditButton::class); + break; + case ShotTicketType::class: + $config->addComponent(CopyButton::create(true), GridFieldEditButton::class); + break; + case ShotNewsletter::class: + $config->addComponent(CopyButton::create()->setOpenAfterCopy(true), GridFieldEditButton::class); + break; + } + + return $config; + } +} diff --git a/tests/browser/screenshots/fixtures/ShotEvent.php b/tests/browser/screenshots/fixtures/ShotEvent.php new file mode 100644 index 0000000..4803987 --- /dev/null +++ b/tests/browser/screenshots/fixtures/ShotEvent.php @@ -0,0 +1,69 @@ + 'Varchar(255)', + 'StartDate' => 'Date', + 'Venue' => 'Varchar(255)', + ]; + + # The copy keeps the Title, so sorting on it puts a copy right below its original; ID breaks + # the tie, so the original stays first. + private static $default_sort = '"Title" ASC, "ID" ASC'; + + private static $summary_fields = [ + 'Title' => 'Title', + 'StartDate.Nice' => 'Date', + 'Venue' => 'Venue', + ]; + + /** Seeded on every dev/build: title => [field => value]. */ + protected const SEEDS = [ + 'Autumn lecture series' => ['StartDate' => '2026-10-06', 'Venue' => 'Main hall'], + 'Open day' => ['StartDate' => '2026-04-18', 'Venue' => 'Visitor centre'], + 'Summer workshop: watercolour' => ['StartDate' => '2026-07-09', 'Venue' => 'Studio 2'], + 'Winter concert' => ['StartDate' => '2026-12-12', 'Venue' => 'Main hall'], + ]; + + public function requireDefaultRecords() + { + parent::requireDefaultRecords(); + + # Wipe and re-seed each class's own rows, so every run starts from the same list and the + # copies an earlier run made are gone. + if (!static::SEEDS) { + return; + } + foreach (static::get()->filter('ClassName', static::class) as $old) { + $old->delete(); + } + foreach (static::SEEDS as $title => $fields) { + static::create(['Title' => $title] + $fields)->write(); + } + } +} diff --git a/tests/browser/screenshots/fixtures/ShotNewsletter.php b/tests/browser/screenshots/fixtures/ShotNewsletter.php new file mode 100644 index 0000000..25b2c1a --- /dev/null +++ b/tests/browser/screenshots/fixtures/ShotNewsletter.php @@ -0,0 +1,57 @@ + 'Varchar(255)', + 'SendDate' => 'Date', + 'Intro' => 'Text', + ]; + + # See ShotEvent: a copy lands right below its original. + private static $default_sort = '"Title" ASC, "ID" ASC'; + + private static $summary_fields = [ + 'Title' => 'Title', + 'SendDate.Nice' => 'Send date', + ]; + + public function requireDefaultRecords() + { + parent::requireDefaultRecords(); + + foreach (static::get() as $old) { + $old->delete(); + } + $seeds = [ + 'April newsletter' => '2026-04-01', + 'March newsletter' => '2026-03-02', + 'May newsletter' => '2026-05-04', + ]; + foreach ($seeds as $title => $date) { + static::create([ + 'Title' => $title, + 'SendDate' => $date, + 'Intro' => 'News from the visitor centre, the programme for the coming weeks and how to book.', + ])->write(); + } + } +} diff --git a/tests/browser/screenshots/fixtures/ShotTicketType.php b/tests/browser/screenshots/fixtures/ShotTicketType.php new file mode 100644 index 0000000..04e3064 --- /dev/null +++ b/tests/browser/screenshots/fixtures/ShotTicketType.php @@ -0,0 +1,47 @@ + 'Varchar(255)', + 'Price' => 'Currency', + ]; + + # See ShotEvent: a copy lands right below its original. + private static $default_sort = '"Title" ASC, "ID" ASC'; + + private static $summary_fields = [ + 'Title' => 'Title', + 'Price.Nice' => 'Price', + ]; + + public function requireDefaultRecords() + { + parent::requireDefaultRecords(); + + foreach (static::get() as $old) { + $old->delete(); + } + $seeds = ['Adult' => 12.5, 'Child (under 12)' => 6, 'Family (2 adults, 2 children)' => 32, 'Student' => 8]; + foreach ($seeds as $title => $price) { + static::create(['Title' => $title, 'Price' => $price])->write(); + } + } +} diff --git a/tests/browser/screenshots/readme.shot.ts b/tests/browser/screenshots/readme.shot.ts new file mode 100644 index 0000000..aaa5838 --- /dev/null +++ b/tests/browser/screenshots/readme.shot.ts @@ -0,0 +1,82 @@ +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 +// playwright.screenshots.config.ts (see README.md next to this file). The content comes from the +// screenshot fixtures in ./fixtures/: an "Events" ModelAdmin with one tab per copy-button setup +// (Events: menu mode, Ticket types: column mode, Newsletters: menu mode with open-after-copy), +// re-seeded on every dev/build. + +const IMAGES = path.join(__dirname, '..', '..', '..', 'docs', 'images'); + +/** The GridField of a ShotAdmin tab (its name is the managed_models key). */ +async function openTab(page: Page, tab: string): Promise { + await page.goto(`/admin/events/${tab}`); + const grid = page.locator(`#Form_EditForm_${tab}`); + await expect(grid.locator('tr.ss-gridfield-item').first()).toBeVisible(); + return grid; +} + +/** The rows of a GridField whose Title cell is exactly this title. */ +function rowsTitled(grid: Locator, title: string): Locator { + const exact = new RegExp(`^\\s*${title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*$`); + return grid.locator('tr.ss-gridfield-item').filter({ has: grid.page().locator('td.col-Title', { hasText: exact }) }); +} + +/** Wait until the GridField POST that a copy sends has been answered. */ +function copyPosted(page: Page, gridName: string): Promise { + const url = new RegExp(`/field/${gridName}(\\?|$)`); + return page.waitForResponse((r) => r.request().method() === 'POST' && url.test(r.url()) && r.status() === 200); +} + +/** No hover or focus highlight left on what was just clicked. */ +async function settle(page: Page): Promise { + await page.mouse.move(1270, 710); + await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur()); + await page.waitForTimeout(400); +} + +/** The window from the top down to just below `bottom` (the empty panel underneath adds nothing). */ +async function clipTo(page: Page, bottom: Locator, extra = 24) { + const box = (await bottom.boundingBox())!; + return { x: 0, y: 0, width: 1280, height: Math.min(720, Math.ceil(box.y + box.height + extra)) }; +} + +test('Menu mode: "Copy" in a row\'s action menu', async ({ page }) => { + const grid = await openTab(page, 'events'); + const row = rowsTitled(grid, 'Summer workshop: watercolour'); + await row.locator('.action-menu__toggle').click(); + const menu = row.locator('.action-menu__dropdown'); + await expect(menu.locator('.dropdown-item').filter({ hasText: /^Copy$/ })).toBeVisible(); + // Keep the menu open: move the pointer onto the Copy item, as a user about to click it would. + await menu.locator('.dropdown-item').filter({ hasText: /^Copy$/ }).hover(); + await page.waitForTimeout(400); + + await page.screenshot({ path: path.join(IMAGES, 'menu-mode.png'), clip: await clipTo(page, menu) }); +}); + +test('Column mode: the copy icon button, and the copy below its original', async ({ page }) => { + const grid = await openTab(page, 'tickets'); + const posted = copyPosted(page, 'tickets'); + await rowsTitled(grid, 'Family (2 adults, 2 children)').locator('button.gridfield-button-copy').click(); + await posted; + await expect(rowsTitled(grid, 'Family (2 adults, 2 children)')).toHaveCount(2); + await settle(page); + + await page.screenshot({ path: path.join(IMAGES, 'column-mode.png'), clip: await clipTo(page, grid) }); +}); + +test('Open after copy: the copy\'s edit form', async ({ page }) => { + const grid = await openTab(page, 'newsletters'); + const row = rowsTitled(grid, 'May newsletter'); + await row.locator('.action-menu__toggle').click(); + await row.locator('.action-menu__dropdown .dropdown-item').filter({ hasText: /^Copy$/ }).click(); + // The admin loads the copy's edit form into the panel (X-ControllerURL), at .../item//edit. + const form = page.locator('#Form_ItemEditForm'); + await expect(form).toBeVisible(); + await expect(page).toHaveURL(/\/admin\/events\/newsletters\/.*item\/\d+\/edit/); + await expect(form.locator('input[name="Title"]')).toHaveValue('May newsletter'); + await settle(page); + + await page.screenshot({ path: path.join(IMAGES, 'open-after-copy.png'), clip: await clipTo(page, form.locator('#Form_ItemEditForm_Intro_Holder')) }); +});