├── .gitignore
├── README.md
├── components
├── index.vue
└── utils.ts
├── dist
├── index.d.ts
└── index.js
├── node
└── index.ts
├── package.json
└── tsconfig.json
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | package-lock.json
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # vitepress-plugin-vue-repl
2 |
3 |
4 | ## install
5 |
6 | ```shell
7 | npm i vitepress-plugin-vue-repl -D
8 | ```
9 |
10 |
11 |
12 | ## config
13 |
14 | ```js
15 | // config.ts
16 | import { VueReplMdPlugin } from 'vitepress-plugin-vue-repl';
17 |
18 | export default defineConfig({
19 | markdown: {
20 | config: (md) => {
21 | md.use(VueReplMdPlugin)
22 | }
23 | },
24 | })
25 | ```
26 |
27 |
28 | ```js
29 | // theme/index.ts
30 | import Playground from 'vitepress-plugin-vue-repl/components/index.vue'
31 | import DefaultTheme from 'vitepress/theme';
32 |
33 | export default {
34 | ...DefaultTheme,
35 | enhanceApp(ctx) {
36 | ctx.app.component('VuePlayground', Playground);
37 | },
38 | };
39 | ```
40 |
41 |
42 | ## Usage
43 |
44 | 
45 |
46 |
47 | 
48 | ## Code Editor Config
49 |
50 | + Monaco
51 | + CodeMirror
52 |
53 | 
54 |
55 |
56 | ## Vue Repl Config & imports
57 | 
--------------------------------------------------------------------------------
/components/index.vue:
--------------------------------------------------------------------------------
1 |
54 |
80 |
81 |
82 |
91 |
92 |
93 |
--------------------------------------------------------------------------------
/components/utils.ts:
--------------------------------------------------------------------------------
1 | import { zlibSync, unzlibSync, strToU8, strFromU8 } from 'fflate'
2 |
3 | export function utoa(data: string): string {
4 | const buffer = strToU8(data)
5 | const zipped = zlibSync(buffer, { level: 9 })
6 | const binary = strFromU8(zipped, true)
7 | return btoa(binary)
8 | }
9 |
10 | export function atou(base64: string): string {
11 | const binary = atob(base64)
12 |
13 | // zlib header (x78), level 9 (xDA)
14 | if (binary.startsWith('\x78\xDA')) {
15 | const buffer = strToU8(binary, true)
16 | const unzipped = unzlibSync(buffer)
17 | return strFromU8(unzipped)
18 | }
19 |
20 | // old unicode hacks for backward compatibility
21 | // https://base64.guru/developers/javascript/examples/unicode-strings
22 | return decodeURIComponent(escape(binary))
23 | }
--------------------------------------------------------------------------------
/dist/index.d.ts:
--------------------------------------------------------------------------------
1 | export declare function VueReplMdPlugin(md: markdownit): void;
2 |
--------------------------------------------------------------------------------
/dist/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
4 | };
5 | Object.defineProperty(exports, "__esModule", { value: true });
6 | exports.VueReplMdPlugin = void 0;
7 | const markdown_it_container_1 = __importDefault(require("markdown-it-container"));
8 | function VueReplMdPlugin(md) {
9 | const defaultRender = md.renderer.rules.fence;
10 | const pattern = /^playground\s*(CodeMirror|Monaco)?\s*$/i;
11 | md.use(markdown_it_container_1.default, 'playground', {
12 | validate: function (params) {
13 | return params.trim().match(pattern);
14 | },
15 | render: function (tokens, idx) {
16 | if (tokens[idx].nesting === 1) {
17 | const editor = tokens[idx].info.toLowerCase().indexOf('monaco') > -1 ? 'Monaco' : 'CodeMirror';
18 | const vueToken = tokens.slice(idx).find(e => e.info === 'vue');
19 | const jsonToken = tokens.slice(idx).find(e => e.info === 'json') || '';
20 | return `${encodeURIComponent(vueToken.content)}\n`;
21 | }
22 | else {
23 | // closing tag
24 | return '\n';
25 | }
26 | }
27 | });
28 | md.renderer.rules.fence = (tokens, idx, options, env, self) => {
29 | const token = tokens[idx];
30 | const prevToken = tokens[idx - 1];
31 | const inPlayground = prevToken && prevToken.nesting === 1 && prevToken.info.trim().match(/^playground\s*(.*)$/);
32 | // 当前token是 ```vue 并且 在 playground 块中, 不去渲染内容
33 | if (token.info === 'vue' && inPlayground) {
34 | return '';
35 | }
36 | if (token.info === 'json' && inPlayground) {
37 | return '';
38 | }
39 | return defaultRender(tokens, idx, options, env, self);
40 | };
41 | }
42 | exports.VueReplMdPlugin = VueReplMdPlugin;
43 |
--------------------------------------------------------------------------------
/node/index.ts:
--------------------------------------------------------------------------------
1 | import MarkdownItContainer from 'markdown-it-container';
2 | export function VueReplMdPlugin(md: markdownit) {
3 | const defaultRender = md.renderer.rules.fence;
4 | const pattern = /^playground\s*(CodeMirror|Monaco)?\s*$/i;
5 | md.use(MarkdownItContainer, 'playground', {
6 | validate: function(params: string) {
7 | return params.trim().match(pattern);
8 | },
9 | render: function (tokens: any[], idx: number) {
10 | if (tokens[idx].nesting === 1) {
11 | const editor = tokens[idx].info.toLowerCase().indexOf('monaco') > -1 ? 'Monaco' : 'CodeMirror';
12 | const vueToken = tokens.slice(idx).find(e => e.info === 'vue');
13 | const jsonToken = tokens.slice(idx).find(e => e.info === 'json') || '';
14 | return `${encodeURIComponent(vueToken.content)}\n`;
15 | } else {
16 | // closing tag
17 | return '\n';
18 | }
19 | }
20 | })
21 |
22 | md.renderer.rules.fence = (tokens: any[], idx: number, options: markdownit.Options, env: any, self: any) => {
23 | const token = tokens[idx];
24 | const prevToken = tokens[idx - 1];
25 | const inPlayground = prevToken && prevToken.nesting === 1 && prevToken.info.trim().match(/^playground\s*(.*)$/);
26 | // 当前token是 ```vue 并且 在 playground 块中, 不去渲染内容
27 | if (token.info === 'vue' && inPlayground) {
28 | return '';
29 | }
30 | if (token.info === 'json' && inPlayground) {
31 | return '';
32 | }
33 | return defaultRender!(tokens, idx, options, env, self);
34 | };
35 | }
36 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vitepress-plugin-vue-repl",
3 | "version": "0.0.9",
4 | "description": "In Vitepress use playground",
5 | "module": "./dist/index.js",
6 | "main": "./dist/index.js",
7 | "homepage": "https://github.com/fyhhub/vitepress-plugin-vue-repl",
8 | "types": "./dist",
9 | "scripts": {
10 | "dev": "tsc --watch",
11 | "build": "tsc"
12 | },
13 | "keywords": [],
14 | "author": "",
15 | "license": "ISC",
16 | "dependencies": {
17 | "@vue/repl": "^2.5.8",
18 | "fflate": "^0.8.0",
19 | "markdown-it": "^13.0.1",
20 | "markdown-it-container": "^3.0.0"
21 | },
22 | "devDependencies": {
23 | "@types/markdown-it": "^13.0.1",
24 | "@types/markdown-it-container": "^2.0.6",
25 | "typescript": "^5.2.2"
26 | },
27 | "files": [
28 | "components",
29 | "node",
30 | "dist"
31 | ]
32 | }
33 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
4 | "module": "commonjs", /* Specify what module code is generated. */
5 | // "rootDir": "./", /* Specify the root folder within your source files. */
6 | // "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
7 | "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
8 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
9 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
10 | // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
11 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */
12 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
13 | // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
14 | // "resolveJsonModule": true, /* Enable importing .json files. */
15 | // "noResolve": true, /* Disallow 'import's, 'require's or ''s from expanding the number of files TypeScript should add to a project. */
16 |
17 | /* JavaScript Support */
18 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
19 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
20 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
21 |
22 | /* Emit */
23 | "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
24 | // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
25 | // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
26 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
27 | "outDir": "./dist", /* Specify an output folder for all emitted files. */
28 | // "removeComments": true, /* Disable emitting comments. */
29 | // "noEmit": true, /* Disable emitting files from a compilation. */
30 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
31 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
32 | // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
33 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
34 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
35 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
36 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
37 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
38 | // "newLine": "crlf", /* Set the newline character for emitting files. */
39 | // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
40 | // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
41 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
42 | // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
43 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
44 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
45 |
46 | /* Interop Constraints */
47 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
48 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
49 | "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
50 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
51 | "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
52 |
53 | /* Type Checking */
54 | "strict": true, /* Enable all strict type-checking options. */
55 | // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
56 | // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
57 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
58 | // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
59 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
60 | // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
61 | // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
62 | // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
63 | // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
64 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
65 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
66 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
67 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
68 | // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
69 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
70 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
71 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
72 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
73 |
74 | /* Completeness */
75 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
76 | "skipLibCheck": true ,
77 | },
78 | "include": ["node/**/*.ts", "node/**/*.vue"]
79 | }
80 |
--------------------------------------------------------------------------------