Browse Source

chore(playground): support unicode in sfc playground (#3662)

atob/btoa only supports ASCII string which makes playground fails
to save unicode source. This patch add unicode support by combining
escape/encodeURIComponent. `escape` is chosen for backward
compatibility.
Herrington Darkholme 4 years ago
parent
commit
9a5bdb15df
2 changed files with 13 additions and 2 deletions
  1. 3 2
      packages/sfc-playground/src/store.ts
  2. 10 0
      packages/sfc-playground/src/utils.ts

+ 3 - 2
packages/sfc-playground/src/store.ts

@@ -1,5 +1,6 @@
 import { reactive, watchEffect } from 'vue'
 import { compileFile, MAIN_FILE } from './sfcCompiler'
+import { utoa, atou } from './utils'
 
 const welcomeCode = `
 <template>
@@ -38,7 +39,7 @@ let files: Store['files'] = {}
 
 const savedFiles = location.hash.slice(1)
 if (savedFiles) {
-  const saved = JSON.parse(atob(savedFiles))
+  const saved = JSON.parse(atou(savedFiles))
   for (const filename in saved) {
     files[filename] = new File(filename, saved[filename])
   }
@@ -70,7 +71,7 @@ for (const file in store.files) {
 }
 
 watchEffect(() => {
-  history.replaceState({}, '', '#' + btoa(JSON.stringify(exportFiles())))
+  history.replaceState({}, '', '#' + utoa(JSON.stringify(exportFiles())))
 })
 
 export function exportFiles() {

+ 10 - 0
packages/sfc-playground/src/utils.ts

@@ -7,3 +7,13 @@ export function debounce(fn: Function, n = 100) {
     }, n)
   }
 }
+
+// prefer old unicode hacks for backward compatibility
+// https://base64.guru/developers/javascript/examples/unicode-strings
+export function utoa(data: string): string {
+  return btoa(unescape(encodeURIComponent(data)))
+}
+
+export function atou(base64: string): string {
+  return decodeURIComponent(escape(atob(base64)))
+}