Skip to content

feat(extension): metadata autocompletion #143

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

Merged
merged 12 commits into from
Jul 25, 2024
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ Navigating to a lesson that specifies `autoReload` will always reload the previe
<PropertyTable inherited type="boolean" />

##### `template`
Specified which folder from the `src/templates/` directory should be used as the basis for the code. See the "[Code templates](/guides/creating-content/#code-templates)" guide for a detailed explainer.
Specifies which folder from the `src/templates/` directory should be used as the basis for the code. See the "[Code templates](/guides/creating-content/#code-templates)" guide for a detailed explainer.
<PropertyTable inherited type="string" />

#### `editPageLink`
Expand Down
70 changes: 0 additions & 70 deletions extensions/vscode/build.mjs

This file was deleted.

38 changes: 31 additions & 7 deletions extensions/vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -102,29 +102,53 @@
"when": "view == tutorialkit-lessons-tree && viewItem == part"
}
]
}
},
"languages": [
{
"id": "markdown",
"extensions": [
".md"
]
},
{
"id": "mdx",
"extensions": [
".mdx"
]
}
]
},
"scripts": {
"__esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=dist/extension.js --external:vscode --format=cjs --platform=node",
"__dev": "pnpm run esbuild-base -- --sourcemap --watch",
"__vscode:prepublish": "pnpm run esbuild-base -- --minify",
"__build": "vsce package",
"dev": "node build.mjs --watch",
"build": "pnpm run check-types && node build.mjs",
"dev": "node scripts/build.mjs --watch",
"build": "pnpm run check-types && node scripts/build.mjs",
"check-types": "tsc --noEmit",
"vscode:prepublish": "pnpm run package",
"package": "pnpm run check-types && node build.mjs --production"
"package": "pnpm run check-types && node scripts/build.mjs --production"
},
"dependencies": {
"@volar/language-core": "2.3.4",
"@volar/language-server": "2.3.4",
"@volar/language-service": "2.3.4",
"@volar/vscode": "2.3.4",
"case-anything": "^3.1.0",
"gray-matter": "^4.0.3"
"gray-matter": "^4.0.3",
"volar-service-yaml": "volar-2.3",
"vscode-languageclient": "^9.0.1",
"vscode-uri": "^3.0.8",
"yaml-language-server": "1.15.0"
},
"devDependencies": {
"@types/mocha": "^10.0.6",
"@tutorialkit/types": "workspace:*",
"@types/node": "20.14.11",
"@types/vscode": "^1.80.0",
"chokidar": "3.6.0",
"esbuild": "^0.21.5",
"execa": "^9.2.0",
"typescript": "^5.4.5"
"typescript": "^5.4.5",
"zod-to-json-schema": "3.23.1"
}
}
117 changes: 117 additions & 0 deletions extensions/vscode/scripts/build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { watch } from 'chokidar';
import * as esbuild from 'esbuild';
import { execa } from 'execa';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { join, dirname } from 'path';
import { Worker } from 'node:worker_threads';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
const production = process.argv.includes('--production');
const isWatch = process.argv.includes('--watch');

async function main() {
const ctx = await esbuild.context({
entryPoints: {
extension: 'src/extension.ts',
server: './src/language-server/index.ts',
},
bundle: true,
format: 'cjs',
minify: production,
sourcemap: !production,
sourcesContent: false,
tsconfig: './tsconfig.json',
platform: 'node',
outdir: 'dist',
define: { 'process.env.NODE_ENV': production ? '"production"' : '"development"' },
external: ['vscode'],
plugins: [esbuildUMD2ESMPlugin],
});

if (isWatch) {
const buildMetadataSchemaDebounced = debounce(buildMetadataSchema, 100);
const dependencyPath = dirname(require.resolve('@tutorialkit/types'));

watch(dependencyPath).on('all', (eventName, path) => {
if (eventName !== 'change' && eventName !== 'add' && eventName !== 'unlink') {
return;
}

buildMetadataSchemaDebounced();
});

await Promise.all([
ctx.watch(),
execa('tsc', ['--noEmit', '--watch', '--preserveWatchOutput', '--project', 'tsconfig.json'], {
stdio: 'inherit',
preferLocal: true,
}),
]);
} else {
await ctx.rebuild();
await ctx.dispose();

await buildMetadataSchema();

if (production) {
// rename name in `package.json` to match extension name on store
const pkgJSON = JSON.parse(fs.readFileSync('./package.json', { encoding: 'utf8' }));

pkgJSON.name = 'tutorialkit';

fs.writeFileSync('./package.json', JSON.stringify(pkgJSON, undefined, 2), 'utf8');
}
}
}

async function buildMetadataSchema() {
const schema = await new Promise((resolve) => {
const worker = new Worker(join(__dirname, './load-schema-worker.mjs'));
worker.on('message', (value) => resolve(value));
});

fs.mkdirSync('./dist', { recursive: true });
fs.writeFileSync('./dist/schema.json', JSON.stringify(schema, undefined, 2), 'utf-8');

console.log('Updated schema.json');
}

/**
* @type {import('esbuild').Plugin}
*/
const esbuildUMD2ESMPlugin = {
name: 'umd2esm',
setup(build) {
build.onResolve({ filter: /^(vscode-.*-languageservice|jsonc-parser)/ }, (args) => {
const pathUmdMay = require.resolve(args.path, { paths: [args.resolveDir] });
const pathEsm = pathUmdMay.replace('/umd/', '/esm/').replace('\\umd\\', '\\esm\\');

return { path: pathEsm };
});
},
};

main().catch((error) => {
console.error(error);
process.exit(1);
});

/**
* Debounce the provided function.
*
* @param {Function} fn Function to debounce
* @param {number} duration Duration of the debounce
* @returns {Function} Debounced function
*/
function debounce(fn, duration) {
let timeoutId = 0;

return function () {
clearTimeout(timeoutId);

timeoutId = setTimeout(fn.bind(this), duration, ...arguments);
};
}
5 changes: 5 additions & 0 deletions extensions/vscode/scripts/load-schema-worker.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { parentPort } from 'node:worker_threads';
import { zodToJsonSchema } from 'zod-to-json-schema';
import { contentSchema } from '@tutorialkit/types';

parentPort.postMessage(zodToJsonSchema(contentSchema));
40 changes: 38 additions & 2 deletions extensions/vscode/src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,52 @@
import * as serverProtocol from '@volar/language-server/protocol';
import { createLabsInfo } from '@volar/vscode';
import * as vscode from 'vscode';
import { useCommands } from './commands';
import { useLessonTree } from './views/lessonsTree';
import * as lsp from 'vscode-languageclient/node';

export let extContext: vscode.ExtensionContext;

export function activate(context: vscode.ExtensionContext) {
let client: lsp.BaseLanguageClient;

export async function activate(context: vscode.ExtensionContext) {
extContext = context;

useCommands();
useLessonTree();

const serverModule = vscode.Uri.joinPath(context.extensionUri, 'dist', 'server.js');
const runOptions = { execArgv: <string[]>[] };
const debugOptions = { execArgv: ['--nolazy', '--inspect=' + 6009] };

const serverOptions: lsp.ServerOptions = {
run: {
module: serverModule.fsPath,
transport: lsp.TransportKind.ipc,
options: runOptions,
},
debug: {
module: serverModule.fsPath,
transport: lsp.TransportKind.ipc,
options: debugOptions,
},
};

const clientOptions: lsp.LanguageClientOptions = {
documentSelector: [{ language: 'markdown' }, { language: 'mdx' }],
initializationOptions: {},
};

client = new lsp.LanguageClient('tutorialkit-language-server', 'TutorialKit', serverOptions, clientOptions);

await client.start();

const labsInfo = createLabsInfo(serverProtocol);
labsInfo.addLanguageClient(client);

return labsInfo.extensionExports;
}

export function deactivate() {
// do nothing
return client?.stop();
}
54 changes: 54 additions & 0 deletions extensions/vscode/src/language-server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { createConnection, createServer, createSimpleProject } from '@volar/language-server/node';
import { create as createYamlService } from 'volar-service-yaml';
import { SchemaPriority } from 'yaml-language-server';
import { frontmatterPlugin } from './languagePlugin';
import { readSchema } from './schema';

const connection = createConnection();
const server = createServer(connection);

connection.listen();

connection.onInitialize((params) => {
const yamlService = createYamlService({
getLanguageSettings(_context) {
const schema = readSchema();

return {
completion: true,
validate: true,
hover: true,
format: true,
yamlVersion: '1.2',
isKubernetes: false,
schemas: [
{
uri: 'https://tutorialkit.dev/reference/configuration',
schema,
fileMatch: [
'**/*',

// TODO: these don't work
'src/content/*.md',
'src/content/**/*.md',
'src/content/**/*.mdx',
],
priority: SchemaPriority.Settings,
},
],
};
},
});

delete yamlService.capabilities.codeLensProvider;
Copy link
Member Author

@Nemikolh Nemikolh Jul 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I removed that because otherwise the schema was popping up on each file metadata. It wasn't a really great UX.


return server.initialize(
params,
createSimpleProject([frontmatterPlugin(connection.console.debug.bind(connection.console.debug))]),
[yamlService],
);
});

connection.onInitialized(server.initialized);

connection.onShutdown(server.shutdown);
Loading