Skip to content

Commit

Permalink
feature: External Link (in Action Block) (#234)
Browse files Browse the repository at this point in the history
# Changes

- Adds `ExternalLink` item to `ActionBlock` with required `title` and
`url` field (with validation).
- Matches the `openInNewTab` property also available in the built-in
links in `StructuredText` fields.
- Reuses the same `style` field configuration used for the
`InternalLink` block.
 
# Associated issue

N/A

# How to test

1. Open preview link
2. Navigate to the Action Block demo and scroll down to the "Action
block with External Links" section.
3. Verify the External Links render as primary and secondary
4. Verify the first action opens the external link in the same tab, and
the second action opens a new tab
5. Go the the `external-links` environment and play around with the new
External Link option in Action Blocks
6. Verify changes made are reflected in the web page (note: run locally
as changes are not updated on deploy preview)

# Checklist

- [x] I have performed a self-review of my own code
- [x] I have made sure that my PR is easy to review (not too big,
includes comments)
- ~I have made updated relevant documentation files (in project README,
docs/, etc)~
- ~I have added a decision log entry if the change affects the
architecture or changes a significant technology~
- [x] I have notified a reviewer

<!-- Please strike through and check off all items that do not apply
(rather than removing them) -->
  • Loading branch information
jbmoelker authored Jan 6, 2025
1 parent cccc9c4 commit 8cdbee0
Show file tree
Hide file tree
Showing 7 changed files with 184 additions and 32 deletions.
44 changes: 24 additions & 20 deletions config/datocms/migrations/1734363388_actionBlock.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,26 @@
import { Client } from '@datocms/cli/lib/cma-client-node';
import type { Client, SimpleSchemaTypes } from '@datocms/cli/lib/cma-client-node';

export const actionStyleField: SimpleSchemaTypes.FieldCreateSchema = {
label: 'Style',
field_type: 'string',
api_key: 'style',
validators: {
required: {},
enum: { values: ['default', 'primary', 'secondary'] },
},
appearance: {
addons: [],
editor: 'string_select',
parameters: {
options: [
{ hint: '', label: 'Default action', value: 'default' },
{ hint: '', label: 'Primary action', value: 'primary' },
{ hint: '', label: 'Secondary action', value: 'secondary' },
],
},
},
default_value: 'default',
};

export default async function (client: Client) {
console.log('Create new models/block models');
Expand Down Expand Up @@ -102,25 +124,7 @@ export default async function (client: Client) {
);
await client.fields.create('GWnhoQDqQoGJj4-sQTVttw', {
id: 'S3JQgijhRmalePX3GeugPg',
label: 'Style',
field_type: 'string',
api_key: 'style',
validators: {
required: {},
enum: { values: ['default', 'primary', 'secondary'] },
},
appearance: {
addons: [],
editor: 'string_select',
parameters: {
options: [
{ hint: '', label: 'Default action', value: 'default' },
{ hint: '', label: 'Primary action', value: 'primary' },
{ hint: '', label: 'Secondary action', value: 'secondary' },
],
},
},
default_value: 'default',
...actionStyleField,
});

console.log('Update existing fields/fieldsets');
Expand Down
93 changes: 93 additions & 0 deletions config/datocms/migrations/1735337726_externalLinks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { Client } from '@datocms/cli/lib/cma-client-node';
import { actionStyleField } from './1734363388_actionBlock';

export default async function (client: Client) {
console.log('Create new models/block models');

console.log(
'Create block model "\uD83D\uDD17 External Link" (`external_link`)'
);
await client.itemTypes.create(
{
id: 'Yk1ge9eTTf25Iwph1Dx3_g',
name: '\uD83D\uDD17 External Link',
api_key: 'external_link',
modular_block: true,
inverse_relationships_enabled: false,
},
{
skip_menu_item_creation: true,
schema_menu_item_id: 'OiBwyNPrR82ZWMawg47csg',
}
);

console.log('Creating new fields/fieldsets');

console.log(
'Create Single-line string field "Title" (`title`) in block model "\uD83D\uDD17 External Link" (`external_link`)'
);
await client.fields.create('Yk1ge9eTTf25Iwph1Dx3_g', {
id: 'Epmmtd7MTfeqpiwLP23D1Q',
label: 'Title',
field_type: 'string',
api_key: 'title',
validators: { required: {} },
appearance: {
addons: [],
editor: 'single_line',
parameters: { heading: false, placeholder: null },
},
default_value: '',
});

console.log(
'Create Single-line string field "URL" (`url`) in block model "\uD83D\uDD17 External Link" (`external_link`)'
);
await client.fields.create('Yk1ge9eTTf25Iwph1Dx3_g', {
id: 'bUvYLCENQ3SP_vGhoN07nA',
label: 'URL',
field_type: 'string',
api_key: 'url',
validators: { required: {}, format: { predefined_pattern: 'url' } },
appearance: {
addons: [],
editor: 'single_line',
parameters: { heading: false, placeholder: null },
},
default_value: '',
});

console.log(
'Create Boolean field "Open in new tab" (`open_in_new_tab`) in block model "\uD83D\uDD17 External Link" (`external_link`)'
);
await client.fields.create('Yk1ge9eTTf25Iwph1Dx3_g', {
id: 'AlPRQFQdRlixBp4Tgz5qsQ',
label: 'Open in new tab',
field_type: 'boolean',
api_key: 'open_in_new_tab',
appearance: { addons: [], editor: 'boolean', parameters: {} },
default_value: false,
});

console.log(
'Create Single-line string field "Style" (`style`) in block model "\uD83D\uDD17 External Link" (`external_link`)'
);
await client.fields.create('Yk1ge9eTTf25Iwph1Dx3_g', {
id: 'TNl63OntSe6ZLD3wCYxK-g',
...actionStyleField,
});

console.log('Update existing fields/fieldsets');

console.log(
'Update Modular Content (Multiple blocks) field "Items" (`items`) in block model "\uD83C\uDF9B\uFE0F Action Block" (`action_block`)'
);
await client.fields.update('dAUckF8qR0edf_f7zam6hA', {
validators: {
rich_text_blocks: {
item_types: ['GWnhoQDqQoGJj4-sQTVttw', 'Yk1ge9eTTf25Iwph1Dx3_g'],
},
size: { min: 1 },
},
});
}
2 changes: 1 addition & 1 deletion datocms-environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
* @see docs/getting-started.md on how to use this file
* @see docs/decision-log/2023-10-24-datocms-env-file.md on why file is preferred over env vars
*/
export const datocmsEnvironment = 'action-block';
export const datocmsEnvironment = 'external-links';
export const datocmsBuildTriggerId = '30535';
30 changes: 22 additions & 8 deletions src/blocks/ActionBlock/ActionBlock.astro
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
---
import type { ActionBlockFragment } from '@lib/datocms/types';
import Link from '@components/Link/Link.astro';
import LinkToRecord from '@components/LinkToRecord/LinkToRecord.astro';
export interface Props {
block: ActionBlockFragment;
}
const { block } = Astro.props;
const { items } = block;
const actionClassList = (style: string) => ['action', `action--${style}`];
---

<div class="action-block">
{
items.map((item) => (
<LinkToRecord
record={item.link}
class:list={['action', `action--${item.style}`]}
>
{item.title}
</LinkToRecord>
))
items.map((item) =>
item.__typename === 'InternalLinkRecord' ? (
<LinkToRecord
record={item.link}
class:list={actionClassList(item.style)}
>
{item.title}
</LinkToRecord>
) : item.__typename === 'ExternalLinkRecord' ? (
<Link
href={item.url}
openInNewTab={item.openInNewTab}
class:list={actionClassList(item.style)}
>
{item.title}
</Link>
) : (
<Fragment />
)
)
}
</div>

Expand Down
4 changes: 4 additions & 0 deletions src/blocks/ActionBlock/ActionBlock.fragment.graphql
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#import './InternalLink.fragment.graphql'
#import './ExternalLink.fragment.graphql'

fragment ActionBlock on ActionBlockRecord {
__typename
Expand All @@ -8,5 +9,8 @@ fragment ActionBlock on ActionBlockRecord {
... on InternalLinkRecord {
...InternalLink
}
... on ExternalLinkRecord {
...ExternalLink
}
}
}
35 changes: 32 additions & 3 deletions src/blocks/ActionBlock/ActionBlock.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { renderToFragment } from '@lib/renderer';
import { describe, expect, test } from 'vitest';
import InlineBlock, { type Props } from './ActionBlock.astro';
import type { ActionBlockFragment, InternalLinkFragment, SiteLocale } from '@lib/datocms/types';
import type { ActionBlockFragment, ExternalLinkFragment, InternalLinkFragment, SiteLocale } from '@lib/datocms/types';
import { locales } from '@lib/i18n';

type ActionBlockItem =
| InternalLinkFragment
| ExternalLinkFragment;

const createInternalLinkFragment = (title: string, slug: string, style: string) => ({
'__typename': 'InternalLinkRecord',
'id': `${slug}-123`,
Expand All @@ -19,14 +23,23 @@ const createInternalLinkFragment = (title: string, slug: string, style: string)
}
} satisfies InternalLinkFragment);

const createActionBlockFragment = (items: InternalLinkFragment[]) => ({
const createExternalLinkFragment = (title: string, url: string, style: string) => ({
'__typename': 'ExternalLinkRecord',
'id': `${url}-123`,
'title': title,
'style': style,
'openInNewTab': false,
'url': url
} satisfies ExternalLinkFragment);

const createActionBlockFragment = (items: ActionBlockItem[]) => ({
'__typename': 'ActionBlockRecord',
'id': 'PL9XQGyWQjuyHpdDNsXCNg',
'items': items
} satisfies ActionBlockFragment);

describe('ActionBlock', () => {
test('Block is rendered', async () => {
test('Block is rendered with internal links', async () => {
const blockWithTwoItems = createActionBlockFragment([
createInternalLinkFragment('First item', 'first-item', 'primary'),
createInternalLinkFragment('Second item', 'second-item', 'secondary'),
Expand All @@ -42,4 +55,20 @@ describe('ActionBlock', () => {
expect(fragment.querySelector('a.action--secondary')?.textContent).toBe('Second item');
});

test('Block is rendered with external links', async () => {
const blockWithTwoItems = createActionBlockFragment([
createExternalLinkFragment('First item', 'https://example.com/first', 'primary'),
createExternalLinkFragment('Second item', 'https://example.com/second', 'secondary'),
]);
const fragment = await renderToFragment<Props>(InlineBlock, {
props: {
block: blockWithTwoItems,
}
});

expect(fragment.querySelectorAll('a.action').length).toBe(2);
expect(fragment.querySelector('a.action--primary')?.textContent).toBe('First item');
expect(fragment.querySelector('a.action--secondary')?.textContent).toBe('Second item');
});

});
8 changes: 8 additions & 0 deletions src/blocks/ActionBlock/ExternalLink.fragment.graphql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
fragment ExternalLink on ExternalLinkRecord {
__typename
id
title
url
openInNewTab
style
}

0 comments on commit 8cdbee0

Please sign in to comment.