Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support schema presets block type completion #663

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/stupid-dolphins-cry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@shopify/theme-language-server-browser': minor
'@shopify/theme-language-server-common': minor
'@shopify/theme-language-server-node': minor
'@shopify/theme-check-docs-updater': minor
'@shopify/prettier-plugin-liquid': minor
'@shopify/theme-check-browser': minor
'@shopify/liquid-html-parser': minor
'@shopify/theme-check-common': minor
'@shopify/theme-check-node': minor
'theme-check-vscode': minor
---

Support schema presets block type completion
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { parseJSON, SourceCodeType } from '@shopify/theme-check-common';
import {
AppBlockSchema,
parseJSON,
SectionSchema,
SourceCodeType,
ThemeBlockSchema,
} from '@shopify/theme-check-common';
import {
CompletionsCollector,
JSONPath,
Expand All @@ -8,10 +14,8 @@ import {
import { AugmentedSourceCode, DocumentManager } from '../documents';
import { GetTranslationsForURI } from '../translations';
import { JSONCompletionProvider } from './completions/JSONCompletionProvider';
import {
BlockTypeCompletionProvider,
GetThemeBlockNames,
} from './completions/providers/BlockTypeCompletionProvider';
import { BlockTypeCompletionProvider } from './completions/providers/BlockTypeCompletionProvider';
import { PresetsBlockTypeCompletionProvider } from './completions/providers/PresetsBlockTypeCompletionProvider';
import { SchemaTranslationsCompletionProvider } from './completions/providers/SchemaTranslationCompletionProvider';
import { JSONHoverProvider } from './hover/JSONHoverProvider';
import { SchemaTranslationHoverProvider } from './hover/providers/SchemaTranslationHoverProvider';
Expand All @@ -22,7 +26,11 @@ import { findSchemaNode } from './utils';
/** The getInfoContribution API will only fallback if we return undefined synchronously */
const SKIP_CONTRIBUTION = undefined as any;

export { GetThemeBlockNames };
export type GetThemeBlockSchema = (
uri: string,
name: string,
) => Promise<SectionSchema | ThemeBlockSchema | AppBlockSchema | undefined>;
export type GetThemeBlockNames = (uri: string) => Promise<string[]>;

/**
* I'm not a fan of how json-languageservice does its feature contributions. It's too different
Expand All @@ -39,6 +47,7 @@ export class JSONContributions implements JSONWorkerContribution {
private documentManager: DocumentManager,
getDefaultSchemaTranslations: GetTranslationsForURI,
getThemeBlockNames: GetThemeBlockNames,
getThemeBlockSchema: GetThemeBlockSchema,
) {
this.hoverProviders = [
new TranslationPathHoverProvider(),
Expand All @@ -47,6 +56,7 @@ export class JSONContributions implements JSONWorkerContribution {
this.completionProviders = [
new SchemaTranslationsCompletionProvider(getDefaultSchemaTranslations),
new BlockTypeCompletionProvider(getThemeBlockNames),
new PresetsBlockTypeCompletionProvider(getThemeBlockNames, getThemeBlockSchema),
];
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ describe('Module: JSONLanguageService', () => {
() => Promise.resolve(schemaTranslations),
(uri: string) => Promise.resolve(uri.includes('tae') ? 'app' : 'theme'),
() => Promise.resolve([]),
async () => undefined,
);

await jsonLanguageService.setup({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import {
import { TextDocument } from 'vscode-languageserver-textdocument';
import { DocumentManager } from '../documents';
import { GetTranslationsForURI } from '../translations';
import { JSONContributions, GetThemeBlockNames } from './JSONContributions';
import { JSONContributions, GetThemeBlockNames, GetThemeBlockSchema } from './JSONContributions';

export class JSONLanguageService {
// We index by Mode here because I don't want to reconfigure the service depending on the URI.
Expand All @@ -40,6 +40,7 @@ export class JSONLanguageService {
private getDefaultSchemaTranslations: GetTranslationsForURI,
private getModeForURI: (uri: string) => Promise<Mode>,
private getThemeBlockNames: GetThemeBlockNames,
private getThemeBlockSchema: GetThemeBlockSchema,
) {
this.services = Object.fromEntries(Modes.map((mode) => [mode, null])) as typeof this.services;
this.schemas = {};
Expand Down Expand Up @@ -76,6 +77,7 @@ export class JSONLanguageService {
this.documentManager,
this.getDefaultSchemaTranslations,
this.getThemeBlockNames,
this.getThemeBlockSchema,
),
],
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ describe('Unit: BlockTypeCompletionProvider', () => {
async () => ({}),
async () => 'theme',
async () => blockNames,
async () => undefined,
);

await jsonLanguageService.setup({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ import { CompletionItemKind } from 'vscode-languageserver-protocol';
import { isLiquidRequestContext, RequestContext } from '../../RequestContext';
import { fileMatch } from '../../utils';
import { JSONCompletionProvider } from '../JSONCompletionProvider';

export type GetThemeBlockNames = (uri: string) => Promise<string[]>;
import { GetThemeBlockNames } from '../../JSONContributions';

/**
* The BlockTypeCompletionProvider offers value completions of the
Expand Down Expand Up @@ -54,14 +53,18 @@ export class BlockTypeCompletionProvider implements JSONCompletionProvider {

const blockNames = await this.getThemeBlockNames(doc.uri);

return blockNames.map((name) => ({
kind: CompletionItemKind.Value,
label: `"${name}"`,
insertText: `"${name}"`,
}));
return createBlockNameCompletionItems(blockNames);
}
}

export function createBlockNameCompletionItems(blockNames: string[]) {
return blockNames.map((name) => ({
kind: CompletionItemKind.Value,
label: `"${name}"`,
insertText: `"${name}"`,
}));
}

export function isBlockDefinitionPath(path: JSONPath) {
return path.at(0) === 'blocks';
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
import { describe, it, expect, assert, beforeEach } from 'vitest';
import { JSONLanguageService } from '../../JSONLanguageService';
import { DocumentManager } from '../../../documents';
import { getRequestParams, isCompletionList } from '../../test/test-helpers';
import { SourceCodeType, ThemeBlock } from '@shopify/theme-check-common';

describe('Unit: PresetsBlockTypeCompletionProvider', () => {
const rootUri = 'file:///root/';
let jsonLanguageService: JSONLanguageService;
let documentManager: DocumentManager;

beforeEach(async () => {
documentManager = new DocumentManager(
undefined, // don't need a fs
undefined, // don't need a connection
undefined, // don't need client capabilities
async () => 'theme', // 'theme' mode
async () => false, // schema is invalid for tests
);
jsonLanguageService = new JSONLanguageService(
documentManager,
{
schemas: async () => [
{
uri: 'https://shopify.dev/block-schema.json',
schema: JSON.stringify({
$schema: 'http://json-schema.org/draft-07/schema#',
}),
fileMatch: ['**/{blocks,sections}/*.liquid'],
},
],
},
async () => ({}),
async () => 'theme',
async () => ['block-1', 'block-2', 'custom-block'],
async (_uri: string, name: string) => {
const blockUri = `${rootUri}/blocks/${name}.liquid`;
const doc = documentManager.get(blockUri);
if (!doc || doc.type !== SourceCodeType.LiquidHtml) {
return;
}
return doc.getSchema();
},
);

await jsonLanguageService.setup({
textDocument: {
completion: {
contextSupport: true,
completionItem: {
snippetSupport: true,
commitCharactersSupport: true,
documentationFormat: ['markdown'],
deprecatedSupport: true,
preselectSupport: true,
},
},
},
});
});

const tests = [
{
description: 'select blocks',
configured: [{ type: 'block-1' }],
expected: [`"block-1"`],
},
{
description: '@theme block',
configured: [{ type: '@theme' }],
expected: [`"block-1"`, `"block-2"`, `"custom-block"`],
},
{
description: '@app block',
configured: [{ type: '@app' }],
expected: [],
},
{
description: 'no blocks',
configured: [],
expected: [],
},
];

describe('top-level preset blocks', () => {
for (const test of tests) {
it(`completes preset block type when allowed ${test.description}`, async () => {
const source = `
{% schema %}
{
"blocks": ${JSON.stringify(test.configured)},
"presets": [{
"blocks": [
{ "type": "█" },
]
}]
}
{% endschema %}
`;

const params = getRequestParams(documentManager, 'sections/section.liquid', source);
const completions = await jsonLanguageService.completions(params);

assert(isCompletionList(completions));
expect(completions.items).to.have.lengthOf(test.expected.length);
expect(completions.items.map((item) => item.label)).to.include.members(test.expected);
});
}
});

describe('nested preset blocks', () => {
for (const test of tests) {
it(`completes preset block type when parent block allows ${test.description}`, async () => {
const source = `
{% schema %}
{
"blocks": [{"type": "custom-block"}],
"presets": [{
"blocks": [
{
"type": "custom-block",
"blocks": [{"type": "█"}],
},
]
}]
}
{% endschema %}
`;

documentManager.open(
`${rootUri}/blocks/custom-block.liquid`,
`{% schema %}
{
"blocks": ${JSON.stringify(test.configured)}
}
{% endschema %}`,
1,
);

const params = getRequestParams(documentManager, 'sections/section.liquid', source);
const completions = await jsonLanguageService.completions(params);

assert(isCompletionList(completions));
expect(completions.items).to.have.lengthOf(test.expected.length);
expect(completions.items.map((item) => item.label)).to.include.members(test.expected);
});
}
});

describe('invalid schema', () => {
it('does not complete when schema is invalid', async () => {
const source = `
{% schema %}
typo
{
"blocks": [{"type": "@theme"}],
"presets": [{
"blocks": [
{ "type": "█" },
]
}]
}
{% endschema %}
`;

const params = getRequestParams(documentManager, 'sections/section.liquid', source);
const completions = await jsonLanguageService.completions(params);

assert(isCompletionList(completions));
expect(completions.items).to.have.lengthOf(0);
});

it('does not complete when parent block schema is invalid', async () => {
const source = `
{% schema %}
{
"blocks": [{"type": "custom-block"}],
"presets": [{
"blocks": [
{
"type": "custom-block",
"blocks": [{"type": "█"}],
},
]
}]
}
{% endschema %}
`;

documentManager.open(
`${rootUri}/blocks/custom-block.liquid`,
`{% schema %}
typo
{
"blocks": [{"type": "@theme"}]
}
{% endschema %}`,
1,
);

const params = getRequestParams(documentManager, 'sections/section.liquid', source);
const completions = await jsonLanguageService.completions(params);

assert(isCompletionList(completions));
expect(completions.items).to.have.lengthOf(0);
});
});
});
Loading
Loading