From 802e6696d01877f14cb2b42a7305909381ca13fb Mon Sep 17 00:00:00 2001 From: sight <1453017105@qq.com> Date: Sun, 26 Jun 2022 17:32:47 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8:=20playground=20hash=20gzip?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package/document-component/package.json | 3 +- .../src/composable/usePlayground.ts | 50 ++++++++++++------- 2 files changed, 34 insertions(+), 19 deletions(-) diff --git a/package/document-component/package.json b/package/document-component/package.json index c252905d..0b9bca94 100644 --- a/package/document-component/package.json +++ b/package/document-component/package.json @@ -28,7 +28,8 @@ "rollup": "^2.70.1", "typescript": "^4.6.3", "vite-plugin-md": "^0.13.1", - "vite": "2.9.8" + "vite": "2.9.8", + "fflate": "^0.7.3" }, "files": [ "lib", diff --git a/package/document-component/src/composable/usePlayground.ts b/package/document-component/src/composable/usePlayground.ts index 42189596..56434073 100644 --- a/package/document-component/src/composable/usePlayground.ts +++ b/package/document-component/src/composable/usePlayground.ts @@ -1,4 +1,5 @@ import type { BuiltInParserName } from "prettier"; +import { zlibSync, unzlibSync, strToU8, strFromU8 } from "fflate"; const scriptRe = /]*>([\s\S]*)<\/script>/; const exportDefaultRe = /export\s*default\s*\{([\s\S]*)\}\;?\s*<\/script>/; @@ -77,24 +78,6 @@ export const usePlayGround = async ( }; }; -/** - * 编码 - * @param data - * @returns - */ -function utoa(data: string): string { - return btoa(unescape(encodeURIComponent(data))); -} - -/** - * 去除字符串两端的空白行 - * @param str - * @returns - */ -function trimBr(str: string): string { - return str.replace(/(^[\r\n]*)|([\r\n]*$)/, ""); -} - /** * * @returns 格式化代码 @@ -131,3 +114,34 @@ async function formatCode(filename: string, data: string) { return code; } + +/** + * 去除字符串两端的空白行 + * @param str + * @returns + */ +function trimBr(str: string): string { + return str.replace(/(^[\r\n]*)|([\r\n]*$)/, ""); +} + +export function utoa(data: string): string { + const buffer = strToU8(data); + const zipped = zlibSync(buffer, { level: 9 }); + const binary = strFromU8(zipped, true); + return btoa(binary); +} + +export function atou(base64: string): string { + const binary = atob(base64); + + // zlib header (x78), level 9 (xDA) + if (binary.startsWith("\x78\xDA")) { + const buffer = strToU8(binary, true); + const unzipped = unzlibSync(buffer); + return strFromU8(unzipped); + } + + // old unicode hacks for backward compatibility + // https://base64.guru/developers/javascript/examples/unicode-strings + return decodeURIComponent(escape(binary)); +}