Skip to content

Commit

Permalink
feat: adds a showCaptions option to disable the current behavior of…
Browse files Browse the repository at this point in the history
… displaying an image's alternate text as a caption when the image is zoomed
  • Loading branch information
HiDeoo committed May 8, 2024
1 parent 47d6c9d commit 7b2a2ea
Show file tree
Hide file tree
Showing 14 changed files with 149 additions and 10 deletions.
6 changes: 6 additions & 0 deletions docs/astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ export default defineConfig({
label: 'Start Here',
items: [
{ label: 'Getting Started', link: '/getting-started/' },
{ label: 'Configuration', link: '/configuration/' },
],
},
{
label: 'Guides',
items: [
{ label: 'Ignoring Images', link: '/ignoring-images/' },
{ label: 'Customization', link: '/customization/' },
],
Expand Down
16 changes: 16 additions & 0 deletions docs/astro.no-caption.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import starlight from '@astrojs/starlight'
import { defineConfig } from 'astro/config'
import starlightImageZoom from 'starlight-image-zoom'

export default defineConfig({
base: '/no-caption/',
integrations: [
starlight({
plugins: [starlightImageZoom({ showCaptions: false })],
title: 'Starlight Image Zoom No Caption Example',
}),
],
server: {
port: 4322,
},
})
1 change: 1 addition & 0 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"type": "module",
"scripts": {
"dev": "astro dev",
"dev:no-caption": "astro dev --config astro.no-caption.config.ts",
"build": "astro build",
"preview": "astro preview",
"lint": "prettier -c --cache . && eslint . --cache --max-warnings=0"
Expand Down
38 changes: 38 additions & 0 deletions docs/src/content/docs/configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
title: Configuration
description: An overview of all the configuration options supported by the Starlight Image Zoom plugin.
---

The Starlight Image Zoom plugin can be configured inside the `astro.config.mjs` configuration file of your project:

```js {11}
// astro.config.mjs
import starlight from '@astrojs/starlight'
import { defineConfig } from 'astro/config'
import starlightImageZoom from 'starlight-image-zoom'

export default defineConfig({
integrations: [
starlight({
plugins: [
starlightImageZoom({
// Configuration options go here.
}),
],
title: 'My Docs',
}),
],
})
```

## Configuration options

The Starlight Image Zoom plugin accepts the following configuration options:

### `showCaptions`

**Type:** `boolean`
**Default:** `true`

Whether an image alternate text should be displayed as a caption when the image is zoomed.
Disabling this options is useful if you are already using another approach to display captions.
2 changes: 2 additions & 0 deletions docs/src/content/docs/getting-started.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,5 @@ import { PackageManagers } from 'starlight-package-managers'
3. [Start the development server](https://starlight.astro.build/getting-started/#start-the-development-server) to see the plugin in action.

</Steps>

The Starlight Image Zoom plugin behavior can be tweaked using various [configuration options](/configuration).
8 changes: 7 additions & 1 deletion packages/starlight-image-zoom/components/ImageZoom.astro
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
<starlight-image-zoom>
---
import config from 'virtual:starlight-image-zoom-config'
---

<starlight-image-zoom data-hide-caption={!config.showCaptions}>
<template>
<dialog class="starlight-image-zoom-dialog">
<button aria-label="Unzoom image" class="starlight-image-zoom-control">
Expand Down Expand Up @@ -334,6 +338,8 @@
}

#setCaption(text: string | null, figure: HTMLElement) {
if (this.hasAttribute('data-hide-caption')) return

text = text?.trim() ?? ''

if (text.length === 0) return
Expand Down
30 changes: 28 additions & 2 deletions packages/starlight-image-zoom/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,31 @@
import type { StarlightPlugin, StarlightUserConfig } from '@astrojs/starlight/types'
import { AstroError } from 'astro/errors'
import { z } from 'astro/zod'

import { starlightImageZoomIntegration } from './libs/integration'

export default function starlightImageZoomPlugin(): StarlightPlugin {
const starlightImageZoomConfigSchema = z
.object({
/**
* Whether an image alternate text should be displayed as a caption when the image is zoomed.
* Disabling this options is useful if you are already using another approach to display captions.
*
* @default true
*/
showCaptions: z.boolean().default(true),
})
.default({})

export default function starlightImageZoomPlugin(userConfig?: StarlightImageZoomUserConfig): StarlightPlugin {
const parsedConfig = starlightImageZoomConfigSchema.safeParse(userConfig)

if (!parsedConfig.success) {
throw new AstroError(
`The provided plugin configuration is invalid.\n${parsedConfig.error.issues.map((issue) => issue.message).join('\n')}`,
`See the error report above for more informations.\n\nIf you believe this is a bug, please file an issue at https://github.com/HiDeoo/starlight-image-zoom/issues/new/choose`,
)
}

return {
name: 'starlight-image-zoom-plugin',
hooks: {
Expand All @@ -24,9 +47,12 @@ export default function starlightImageZoomPlugin(): StarlightPlugin {
updatedConfig.components.MarkdownContent = 'starlight-image-zoom/overrides/MarkdownContent.astro'
}

addIntegration(starlightImageZoomIntegration())
addIntegration(starlightImageZoomIntegration(parsedConfig.data))
updateConfig(updatedConfig)
},
},
}
}

export type StarlightImageZoomUserConfig = z.input<typeof starlightImageZoomConfigSchema>
export type StarlightImageZoomConfig = z.output<typeof starlightImageZoomConfigSchema>
8 changes: 7 additions & 1 deletion packages/starlight-image-zoom/libs/integration.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import type { AstroIntegration } from 'astro'
import rehypeRaw from 'rehype-raw'

import type { StarlightImageZoomConfig } from '..'

import { rehypeStarlightImageZoom } from './rehype'
import { vitePluginStarlightImageZoomConfig } from './vite'

export function starlightImageZoomIntegration(): AstroIntegration {
export function starlightImageZoomIntegration(config: StarlightImageZoomConfig): AstroIntegration {
return {
name: 'starlight-image-zoom-integration',
hooks: {
Expand All @@ -12,6 +15,9 @@ export function starlightImageZoomIntegration(): AstroIntegration {
markdown: {
rehypePlugins: [rehypeRaw, rehypeStarlightImageZoom],
},
vite: {
plugins: [vitePluginStarlightImageZoomConfig(config)],
},
})
},
},
Expand Down
21 changes: 21 additions & 0 deletions packages/starlight-image-zoom/libs/vite.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import type { ViteUserConfig } from 'astro'

import type { StarlightImageZoomConfig } from '..'

export function vitePluginStarlightImageZoomConfig(config: StarlightImageZoomConfig): VitePlugin {
const moduleId = 'virtual:starlight-image-zoom-config'
const resolvedModuleId = `\0${moduleId}`
const moduleContent = `export default ${JSON.stringify(config)}`

return {
name: 'vite-plugin-starlight-image-zoom-config',
load(id) {
return id === resolvedModuleId ? moduleContent : undefined
},
resolveId(id) {
return id === moduleId ? resolvedModuleId : undefined
},
}
}

type VitePlugin = NonNullable<ViteUserConfig['plugins']>[number]
9 changes: 6 additions & 3 deletions packages/starlight-image-zoom/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,18 @@ export default defineConfig({
use: { ...devices['Desktop Chrome'], headless: true },
},
],
use: {
baseURL: 'http://localhost:4321',
},
webServer: [
{
command: 'pnpm run dev',
cwd: '../../docs',
reuseExistingServer: !process.env['CI'],
url: 'http://localhost:4321',
},
{
command: 'pnpm run dev:no-caption',
cwd: '../../docs',
reuseExistingServer: !process.env['CI'],
url: 'http://localhost:4322/no-caption/',
},
],
})
4 changes: 2 additions & 2 deletions packages/starlight-image-zoom/tests/fixtures/TestPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ export class TestPage {

constructor(public readonly page: Page) {}

async goto(slug: string) {
await this.page.goto(`/tests/${slug.replace(/^\//, '')}`)
async goto(slug: string, noCaption = false) {
await this.page.goto(`http://localhost:${noCaption ? '4322/no-caption' : '4321'}/tests/${slug.replace(/^\//, '')}`)
await this.page.waitForLoadState('networkidle')
}

Expand Down
7 changes: 7 additions & 0 deletions packages/starlight-image-zoom/tests/no-caption.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { expect, test } from './test'

test('does not add a caption if the `showCaptions` option is disabled', async ({ testPage }) => {
await testPage.goto('zoom', true)

await expect(testPage.getNthImage(0)).toBeZoomedAfterClick()
})
4 changes: 3 additions & 1 deletion packages/starlight-image-zoom/tests/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ export const expect = baseExpect.extend({
await baseExpect(dialog.locator('.starlight-image-zoom-image')).toBeVisible()

const captionLocator = dialog.locator('figcaption')
// eslint-disable-next-line unicorn/prefer-dom-node-dataset
const noCaption = await page.locator('starlight-image-zoom').getAttribute('data-hide-caption')

if (imageAlt.length === 0) {
if (imageAlt.length === 0 || noCaption !== null) {
// If the image has no alt attribute, the caption should not be visible.
expected = 'hidden'
await baseExpect(captionLocator).not.toBeAttached()
Expand Down
5 changes: 5 additions & 0 deletions packages/starlight-image-zoom/virtual.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
declare module 'virtual:starlight-image-zoom-config' {
const StarlightImageZoomConfig: import('./index').StarlightImageZoomConfig

export default StarlightImageZoomConfig
}

0 comments on commit 7b2a2ea

Please sign in to comment.