Browse Source

Prepare for Publishing VS Code Extension (#227)

* Changed Wardlt use back to Tldraw. Added some VS Code marketplace categories

* Missed removing one Wardlt mention

* Initial support for esbuild based vscode extension workflow.

* Hacky start of vs code extension build script

* Fixed categories of extension

* Added script for generating VS Code extension installer

* Temp fix for file format change affecting VS Code extension

* Temp fix for file format change issue

* Cleanup, prevent changes from saving pagestates

* Remove logic around saving pageState

* standardize capitalization

* v0.1.8

* Edit readme, scripts

* Update .eslintignore

* v0.1.9

* v0.1.10

* cleans up build scripts, adds publishing notes

* Added VS Code extension implementation references links. start:vscode now auto opens the extension folder in VS Code

* Removed step from VS Code README to manually open the extensions folder

* Removed file

* v0.1.11

* v0.1.12

* Fix empty file

* v0.1.13

* README cleanup

* v0.1.14

* Update TLDrawEditorProvider.ts

* v0.1.15

* Fix types for file extension (sort of) build script for extension

Co-authored-by: Steve Ruiz <steveruizok@gmail.com>
main
Francois Laberge 3 years ago
parent
commit
a95b581e07
No account linked to committer's email address
42 changed files with 2506 additions and 1479 deletions
  1. 0
    4
      .eslintignore
  2. 15
    0
      .eslintrc
  3. 0
    15
      .eslintrc.js
  4. 6
    0
      .prettierrc
  5. 4
    7
      package.json
  6. 1
    2
      packages/tldraw/package.json
  7. 2
    2
      packages/tldraw/src/TLDraw.tsx
  8. 48
    8
      vscode/README.md
  9. 7
    4
      vscode/editor/README.md
  10. BIN
      vscode/editor/card-repo.png
  11. 1
    2
      vscode/editor/scripts/dev.mjs
  12. 20
    8
      vscode/editor/src/app.tsx
  13. 1
    1
      vscode/editor/src/types.ts
  14. 3
    1
      vscode/editor/src/utils/defaultDocument.ts
  15. 0
    4
      vscode/editor/src/utils/eventsRegex.ts
  16. 17
    0
      vscode/editor/src/utils/sanitizeDocument.ts
  17. 1
    1
      vscode/extension/.gitignore
  18. 2
    4
      vscode/extension/.vscode/launch.json
  19. 0
    10
      vscode/extension/.vscode/tasks.json
  20. 3
    0
      vscode/extension/CHANGELOG.md
  21. 0
    110
      vscode/extension/CONTRIBUTING.md
  22. 21
    0
      vscode/extension/LICENSE.md
  23. 29
    8
      vscode/extension/README.md
  24. 1015
    1012
      vscode/extension/examples/2.tldr
  25. 4
    5
      vscode/extension/examples/3.tldr
  26. BIN
      vscode/extension/examples/smiley-image.png
  27. 0
    0
      vscode/extension/examples/test.drawio
  28. BIN
      vscode/extension/icon.png
  29. 41
    27
      vscode/extension/package.json
  30. 53
    0
      vscode/extension/scripts/build.js
  31. 54
    0
      vscode/extension/scripts/dev.js
  32. 37
    0
      vscode/extension/scripts/package.js
  33. 38
    39
      vscode/extension/src/TLDrawEditorProvider.ts
  34. 2
    2
      vscode/extension/src/extension.ts
  35. 10
    4
      vscode/extension/src/getHtmlForWebview.ts
  36. 8
    0
      vscode/extension/src/types.ts
  37. 21
    0
      vscode/extension/src/utils.ts
  38. 0
    29
      vscode/extension/src/web/test/suite/index.ts
  39. 0
    12
      vscode/extension/src/web/types.ts
  40. 0
    9
      vscode/extension/src/web/util.ts
  41. 0
    67
      vscode/extension/webpack.config.js
  42. 1042
    82
      yarn.lock

+ 0
- 4
.eslintignore View File

@@ -1,7 +1,3 @@
1 1
 **/node_modules/*
2 2
 **/out/*
3 3
 **/.next/*
4
-
5
-# TODO: Remove these, vscode experiments are based on existing examples and are punting on making eslint happy just yet.
6
-**/integrations/vscode-extension/*
7
-**/integrations/vscode-simple/*

+ 15
- 0
.eslintrc View File

@@ -0,0 +1,15 @@
1
+{
2
+  "root": true,
3
+  "parser": "@typescript-eslint/parser",
4
+  "plugins": ["@typescript-eslint"],
5
+  "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
6
+  "overrides": [
7
+    {
8
+      // enable the rule specifically for TypeScript files
9
+      "files": ["*.ts", "*.tsx"],
10
+      "rules": {
11
+        "@typescript-eslint/explicit-module-boundary-types": [0]
12
+      }
13
+    }
14
+  ]
15
+}

+ 0
- 15
.eslintrc.js View File

@@ -1,15 +0,0 @@
1
-module.exports = {
2
-  root: true,
3
-  parser: '@typescript-eslint/parser',
4
-  plugins: ['@typescript-eslint'],
5
-  extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
6
-  overrides: [
7
-    {
8
-      // enable the rule specifically for TypeScript files
9
-      files: ['*.ts', '*.tsx'],
10
-      rules: {
11
-        '@typescript-eslint/explicit-module-boundary-types': [0],
12
-      },
13
-    },
14
-  ],
15
-}

+ 6
- 0
.prettierrc View File

@@ -0,0 +1,6 @@
1
+{
2
+  "trailingComma": "es5",
3
+  "singleQuote": true,
4
+  "semi": false,
5
+  "printWidth": 100
6
+}

+ 4
- 7
package.json View File

@@ -11,6 +11,7 @@
11 11
   "workspaces": [
12 12
     "electron",
13 13
     "vscode/editor",
14
+    "vscode/extension",
14 15
     "packages/tldraw",
15 16
     "example",
16 17
     "www"
@@ -20,7 +21,8 @@
20 21
     "test:watch": "jest --watchAll",
21 22
     "lerna": "lerna",
22 23
     "start:electron": "lerna run start:electron --stream --parallel",
23
-    "start:vscode": "lerna run start:vscode --stream --parallel",
24
+    "start:vscode": "yarn build:packages && lerna run start:vscode --stream --parallel & code vscode/extension; ",
25
+    "build:vscode": "cd vscode/extension && yarn package",
24 26
     "start": "lerna run start --stream --parallel",
25 27
     "start:www": "yarn build:packages && lerna run start --parallel & cd www && yarn dev",
26 28
     "build": "yarn build:packages && cd www && yarn build",
@@ -39,6 +41,7 @@
39 41
     "@types/node": "^15.0.1",
40 42
     "@types/react": "^17.0.33",
41 43
     "@types/react-dom": "^17.0.10",
44
+    "@types/vscode": "^1.59.0",
42 45
     "@typescript-eslint/eslint-plugin": "^4.19.0",
43 46
     "@typescript-eslint/parser": "^4.19.0",
44 47
     "eslint": "^7.32.0",
@@ -54,12 +57,6 @@
54 57
     "typedoc": "^0.22.3",
55 58
     "typescript": "^4.4.2"
56 59
   },
57
-  "prettier": {
58
-    "trailingComma": "es5",
59
-    "singleQuote": true,
60
-    "semi": false,
61
-    "printWidth": 100
62
-  },
63 60
   "husky": {
64 61
     "hooks": {
65 62
       "pre-commit": "lint-staged",

+ 1
- 2
packages/tldraw/package.json View File

@@ -23,7 +23,6 @@
23 23
   "types": "./dist/types/index.d.ts",
24 24
   "scripts": {
25 25
     "start:electron": "yarn start",
26
-    "start:vscode": "yarn start",
27 26
     "start": "node scripts/dev & yarn types:dev",
28 27
     "build": "node scripts/build && yarn types:build && node scripts/copy-readme",
29 28
     "types:dev": "tsc -w",
@@ -60,4 +59,4 @@
60 59
     "tsconfig-replace-paths": "^0.0.5"
61 60
   },
62 61
   "gitHead": "083b36e167b6911927a6b58cbbb830b11b33f00a"
63
-}
62
+}

+ 2
- 2
packages/tldraw/src/TLDraw.tsx View File

@@ -293,7 +293,7 @@ export function TLDraw({
293 293
   return (
294 294
     <TLDrawContext.Provider value={context}>
295 295
       <IdProvider>
296
-        <InnerTldraw
296
+        <InnerTLDraw
297 297
           key={sId || 'tldraw'}
298 298
           id={sId}
299 299
           currentPageId={currentPageId}
@@ -324,7 +324,7 @@ interface InnerTLDrawProps {
324 324
   readOnly: boolean
325 325
 }
326 326
 
327
-const InnerTldraw = React.memo(function InnerTldraw({
327
+const InnerTLDraw = React.memo(function InnerTLDraw({
328 328
   id,
329 329
   currentPageId,
330 330
   autofocus,

+ 48
- 8
vscode/README.md View File

@@ -1,15 +1,55 @@
1 1
 # @tldraw/vscode
2 2
 
3
-This folder contains the source for the tldraw VSCode extension.
3
+This folder contains the source for the tldraw VS Code extension.
4 4
 
5
-## 1. Setup editor project
5
+## Developing
6 6
 
7
-- Open `vscode/editor`
8
-- Install dependencies (`yarn`)
9
-- Start the development server (`yarn start`)
7
+## 1. Install dependencies
8
+
9
+- Run `yarn` from the root folder
10
+
11
+## 2. Build @tldraw/tldraw
12
+
13
+- Run `yarn build:packages` from the root folder.
14
+
15
+## 3. Start the editor
16
+
17
+In the root folder:
18
+
19
+- Run `yarn start:vscode`.
20
+
21
+This will start the development server for the `vscode/editor` project and open the `vscode/extension` folder in a new window.
10 22
 
11
-## 2. Start the Extension
23
+In the `vscode/extension` window, open the terminal and run:
12 24
 
13
-- Open `vscode/extension` in a new VSCode window
14 25
 - Install dependencies (`yarn`)
15
-- Run the extension (F5)
26
+- Start the VS Code debugger (Menu > Run > Start Debugging)
27
+
28
+Open a `.tldr` file or create a new `.tldr` file from the command palette.
29
+
30
+## Publishing
31
+
32
+To publish, chat with the team on the [Discord channel](https://discord.gg/s4FXZ6fppJ).
33
+
34
+- Install `vsce` globally
35
+- Run `vsce login tldraw-org` and sign in
36
+
37
+In the `vscode/extension` folder:
38
+
39
+- Run `yarn vscode:publish`
40
+
41
+#### References
42
+
43
+- [VS Code Marketplace Manager](https://marketplace.visualstudio.com/manage/)
44
+- [Web Extensions Guide](https://code.visualstudio.com/api/extension-guides/web-extensions)
45
+  - [Test Your Web Extension](https://code.visualstudio.com/api/extension-guides/web-extensions#test-your-web-extension)
46
+  - [Web Extension Testing](https://code.visualstudio.com/api/extension-guides/web-extensions#web-extension-tests)
47
+  - An example custom editor that does work as a Web Extension
48
+    - https://marketplace.visualstudio.com/items?itemName=hediet.vscode-drawio
49
+    - https://github.com/hediet/vscode-drawio
50
+- [VS Code Extension API/Landing Page](https://code.visualstudio.com/api)
51
+- [Getting Started](https://code.visualstudio.com/api/get-started/your-first-extension)
52
+- [Custom Editor API](https://code.visualstudio.com/api/extension-guides/custom-editors)
53
+- [github.com/microsoft/vscode-extension-samples](https://github.com/microsoft/vscode-extension-samples)
54
+- [Extensions Guide -> Webviews](https://code.visualstudio.com/api/extension-guides/webview)
55
+- [Publishing Extensions](https://code.visualstudio.com/api/working-with-extensions/publishing-extension)

+ 7
- 4
vscode/editor/README.md View File

@@ -1,6 +1,9 @@
1
-# @tldraw/tldraw-example
1
+<div style="text-align: center; transform: scale(.5);">
2
+  <img src="card-repo.png"/>
3
+</div>
2 4
 
3
-An example for @tldraw/tldraw with a very fast dev server.
5
+# @tldraw/vscode-editor
4 6
 
5
-**Note:** You probably do not need to start the server here: it is started as
6
-part of `yarn start` in the root directory.
7
+The app for the TLDraw VS Code Extension.
8
+
9
+See the README at `vscode` for more about this project.

BIN
vscode/editor/card-repo.png View File


+ 1
- 2
vscode/editor/scripts/dev.mjs View File

@@ -17,11 +17,10 @@ async function main() {
17 17
         incremental: true,
18 18
         target: 'es6',
19 19
         define: {
20
-          'process.env.NODE_ENV': '"development"',
20
+          'process.env.NODE_ENV': '"production"',
21 21
         },
22 22
         watch: {
23 23
           onRebuild(err) {
24
-            serve.update()
25 24
             err ? error('❌ Failed') : log('✅ Updated')
26 25
           },
27 26
         },

+ 20
- 8
vscode/editor/src/app.tsx View File

@@ -1,32 +1,44 @@
1 1
 import * as React from 'react'
2
-import { TLDraw, TLDrawState, TLDrawSnapshot, TLDrawFile } from '@tldraw/tldraw'
2
+import { TLDraw, TLDrawState, TLDrawFile, TLDrawDocument } from '@tldraw/tldraw'
3 3
 import { vscode } from './utils/vscode'
4
-import { eventsRegex } from './utils/eventsRegex'
5 4
 import { defaultDocument } from './utils/defaultDocument'
6 5
 import { UI_EVENT } from './types'
7 6
 import './styles.css'
7
+import { sanitizeDocument } from 'utils/sanitizeDocument'
8 8
 
9 9
 // Will be placed in global scope by extension
10 10
 declare let currentFile: TLDrawFile
11 11
 
12 12
 export default function App(): JSX.Element {
13 13
   const rTLDrawState = React.useRef<TLDrawState>()
14
+  const rInitialDocument = React.useRef<TLDrawDocument>(
15
+    currentFile ? currentFile.document : defaultDocument
16
+  )
14 17
 
15 18
   // When the editor mounts, save the state instance in a ref.
16
-  const handleMount = React.useCallback((tldr: TLDrawState) => {
17
-    rTLDrawState.current = tldr
19
+  const handleMount = React.useCallback((state: TLDrawState) => {
20
+    rTLDrawState.current = state
18 21
   }, [])
19 22
 
20 23
   // When the editor's document changes, post the stringified document to the vscode extension.
21
-  const handlePersist = React.useCallback((tldr: TLDrawState) => {
22
-    vscode.postMessage({ type: UI_EVENT.TLDRAW_UPDATED, text: JSON.stringify(tldr.document) })
24
+  const handlePersist = React.useCallback((state: TLDrawState) => {
25
+    const initialDocument = rInitialDocument.current
26
+
27
+    vscode.postMessage({
28
+      type: UI_EVENT.TLDRAW_UPDATED,
29
+      text: JSON.stringify({
30
+        ...currentFile,
31
+        document: sanitizeDocument(initialDocument, state.document),
32
+        assets: {},
33
+      }),
34
+    })
23 35
   }, [])
24 36
 
25 37
   return (
26 38
     <div className="tldraw">
27 39
       <TLDraw
28
-        id={currentFile.document.id}
29
-        document={currentFile.document ?? defaultDocument}
40
+        id={rInitialDocument.current.id}
41
+        document={rInitialDocument.current}
30 42
         onMount={handleMount}
31 43
         onPersist={handlePersist}
32 44
         autofocus

+ 1
- 1
vscode/editor/src/types.ts View File

@@ -3,5 +3,5 @@ export enum UI_EVENT {
3 3
 }
4 4
 
5 5
 export enum EXTENSION_EVENT {
6
-  LOCAL_FILE_UPDATED = 'LOCAL_FILE_UPDATED',
6
+  FILE_UPDATED = 'FILE_UPDATED',
7 7
 }

+ 3
- 1
vscode/editor/src/utils/defaultDocument.ts View File

@@ -1,7 +1,9 @@
1
-import type { TLDrawDocument } from '@tldraw/tldraw'
1
+import { TLDrawDocument, TLDrawState } from '@tldraw/tldraw'
2 2
 
3 3
 export const defaultDocument: TLDrawDocument = {
4 4
   id: 'doc',
5
+  name: 'New Document',
6
+  version: TLDrawState.version,
5 7
   pages: {
6 8
     page: {
7 9
       id: 'page',

+ 0
- 4
vscode/editor/src/utils/eventsRegex.ts View File

@@ -1,4 +0,0 @@
1
-// A regex to detect event types that we should send to the extension. We only want to send
2
-// events that change the document and that would be committed to the undo/redo stack; not
3
-// all the smaller patches or transient changes from sessions.
4
-export const eventsRegex = /command|undo|redo/

+ 17
- 0
vscode/editor/src/utils/sanitizeDocument.ts View File

@@ -0,0 +1,17 @@
1
+import type { TLDrawDocument } from '@tldraw/tldraw'
2
+
3
+export function sanitizeDocument(prev: TLDrawDocument, next: TLDrawDocument): TLDrawDocument {
4
+  return next
5
+
6
+  // // Don't save changes to page state?
7
+
8
+  // const final = { ...next, pageStates: { ...next.pageStates } }
9
+
10
+  // Object.values(prev.pageStates).forEach((pageState) => {
11
+  //   if (next.pages[pageState.id] !== undefined) {
12
+  //     final.pageStates[pageState.id] = pageState
13
+  //   }
14
+  // })
15
+
16
+  // return final
17
+}

+ 1
- 1
vscode/extension/.gitignore View File

@@ -1,6 +1,6 @@
1 1
 dist
2
+editor
2 3
 node_modules
3 4
 .vscode-test-web/
4 5
 *.vsix
5
-editor-build
6 6
 .DS_Store

+ 2
- 4
vscode/extension/.vscode/launch.json View File

@@ -16,8 +16,7 @@
16 16
 			],
17 17
 			"outFiles": [
18 18
 				"${workspaceFolder}/dist/web/**/*.js"
19
-			],
20
-			"preLaunchTask": "npm: watch-web"
19
+			]
21 20
 		},
22 21
 		{
23 22
 			"name": "Extension Tests in VS Code",
@@ -31,8 +30,7 @@
31 30
 			],
32 31
 			"outFiles": [
33 32
 				"${workspaceFolder}/dist/web/**/*.js"
34
-			],
35
-			"preLaunchTask": "npm: watch-web"
33
+			]
36 34
 		}
37 35
 	]
38 36
 }

+ 0
- 10
vscode/extension/.vscode/tasks.json View File

@@ -14,16 +14,6 @@
14 14
 				"$ts-webpack",
15 15
 				"$tslint-webpack"
16 16
 			]
17
-		},
18
-		{
19
-			"type": "npm",
20
-			"script": "watch-web",
21
-			"group": "build",
22
-			"isBackground": true,
23
-			"problemMatcher": [
24
-				"$ts-webpack-watch",
25
-				"$tslint-webpack-watch"
26
-			]
27 17
 		}
28 18
 	]
29 19
 }

+ 3
- 0
vscode/extension/CHANGELOG.md View File

@@ -0,0 +1,3 @@
1
+## 0.1.0
2
+
3
+- Launched!

+ 0
- 110
vscode/extension/CONTRIBUTING.md View File

@@ -1,110 +0,0 @@
1
-### VS Code Extension
2
-
3
-This folder contains code implementing a VS Code extension for working with tldraw within VS Code. Files are saved locally and thus play well with version control. Target use case is developer documentation.
4
-
5
-### Todos
6
-
7
-- Get live reloading working while extension developing (debug launched)
8
-  - Watching and rebuilding is working, it's just hot-updating the running editor instances that's failing
9
-  - It currently at least updates every time you open a new editor, currently it's the websocket
10
-    needed for the live reloading logic that is failing to connect.
11
-- Backlog
12
-  - Make sure extension works in Codespaces (when one of us gets into the beta)
13
-  - [Supporting Remote Development and GitHub Codespaces](https://code.visualstudio.com/api/advanced-topics/remote-extensions)
14
-
15
-
16
-## Test Cases
17
-Here's a list of functionality and behavior we'd like working for an initial beta.
18
-
19
- - Saving
20
-  - Save (Command+S or menu) should work
21
-  - Save As (menu or shortcut)
22
- - Undo/Redo
23
-  - Should reflect correctly in VS Code menus (can/can't do it based on stack)
24
- - Create new file using either of these methods
25
-   - Use VS Code's "New File", name the file with a .tldr extension 
26
-   - Use the Tldraw extensions registered command to create a blank .tldr file
27
- - Opening an
28
- - The editor should communicate that a file isn't valid when loading it
29
- - Detect and prevent multiple instances of the editor (For now)
30
-
31
-Things we're cutting
32
- - Distinguishing app state from user state (selection, zoom, pan, etc)
33
-
34
-## Running The Extension
35
-
36
-- Setup/Run the editor (a create react app that houses the tldraw component)
37
- - `cd integrations/vscode/editor`
38
- - `yarn`
39
- - `yarn start`
40
-- To setup/run the extension 
41
- - In a new terminal
42
-   - Install dependencies 
43
-     - `yarn`
44
-   - Open just the extension folder in VS Code (necessary to use it's launch.json)
45
-     - `cd integrations/vscode/extension`
46
-     - `code .`
47
-   - Run the extension using F5 (the launch.json setups watching too)
48
-    - This will open a new VS Code window where the extension is installed in memory
49
-    - Open a folder containing some .tldr files. Ex. tldraw/integrations/extension/examples
50
-    - Select a .tldr file to test
51
-    - You'll have to toggle between the extension/editor/debug VS Code instances to change things and see the results 
52
-    - NOTE: Hot reloading doesn't work right now for the editor's create-react-app workflow. I have yet to figure out how to set the websocket host, which currently assumes it's housed on the same host as the page it's loaded in (which for the extension is some weird custom protocol)
53
-     - If you close and reopen a .tldr file, it will load the latest change though
54
-
55
-## Publishing/Packaging Extensions
56
-**This stuff needs to be fully automated!!! We're not quite there yet.**
57
-
58
- - Make sure you have the vsce command line tool installed
59
-  - `npm install -g vsce`
60
- - Build the editor static site
61
-  - `cd integrations/vscode/editor`
62
-  - `yarn build`
63
-  - This will build a static version of the create react app and put it into `integrations/vscode/editor`.
64
- - Bump the package.json version
65
-   - Just do this manually in the file
66
- - Change the code in `integrations/vscode/extension/src/get-html.ts` so it uses the production path. It should look like this:
67
-   
68
-          //return getDevModeHTML(context, webview, documentContent);
69
-          return getProductionModeHTML(context, webview, documentContent);
70
-
71
- - Run script that copies over the latest static file path hashes
72
-   - **TODO**: Find this script. It seems to have gone missing and I can't find it in history
73
-    - The manual version is to look at the latest editor-build/index.html and copy/reference it into get-html.ts
74
- - Compile the extension in production mode
75
-   - `npm run package-web`
76
- - Package up the extension as an extension installer .vsix
77
-   - `vsce package`
78
-   - A file with a name like: `wardlt-0.8.0.vsix` will now be put in the extension root
79
-     - TODO: Make this get build to a proper temp directory like dist
80
- - Before publishing test using the .vsix based installation workflow available in VS Code Desktop
81
- - Use the Web UI to publish the latest extension by uploading the .vsix file
82
-   - https://marketplace.visualstudio.com/manage/publishers/Wardlt
83
-   - Click on the elipse button and choose Update, then select the .vsix we just generated
84
-   - It should take a few minutes to go through some automated validation the VS Code Marketplace does
85
- - Now test it quickly 
86
-   - Desktop
87
-   - github.dev
88
-    - Go here and then press '.' https://github.com/tldraw/tldraw/tree/vscode-extension-v1/integrations/vscode/extension/examples
89
-     - Try one of the .tldr files
90
-   - Codespaces
91
-     - Go here: https://github.com/conveyhq/codespaces-test
92
-     - Select Code -> main or go straight there via link: https://seflless-conveyhq-codespaces-test-x76jf9xq7.github.dev/
93
-     - I have a test code space here with a .tldr file already included
94
- - Read more about this topic here: [Publishing Extensions](https://code.visualstudio.com/api/working-with-extensions/publishing-extension)
95
-
96
-#### Good References
97
-
98
-- [VS Code Marketplace Manager](https://marketplace.visualstudio.com/manage/)
99
-- [Web Extensions Guide](https://code.visualstudio.com/api/extension-guides/web-extensions)
100
-  - [Test Your Web Extension](https://code.visualstudio.com/api/extension-guides/web-extensions#test-your-web-extension)
101
-  - [Web Extension Testing](https://code.visualstudio.com/api/extension-guides/web-extensions#web-extension-tests)
102
-  - An example custom editor that does work as a Web Extension
103
-    - https://marketplace.visualstudio.com/items?itemName=hediet.vscode-drawio
104
-    - https://github.com/hediet/vscode-drawio
105
-- [VS Code Extension API/Landing Page](https://code.visualstudio.com/api)
106
-- [Getting Started](https://code.visualstudio.com/api/get-started/your-first-extension)
107
-- [Custom Editor API](https://code.visualstudio.com/api/extension-guides/custom-editors)
108
-- [github.com/microsoft/vscode-extension-samples](https://github.com/microsoft/vscode-extension-samples)
109
-- [Extensions Guide -> Webviews](https://code.visualstudio.com/api/extension-guides/webview)
110
-- [Publishing Extensions](https://code.visualstudio.com/api/working-with-extensions/publishing-extension)

+ 21
- 0
vscode/extension/LICENSE.md View File

@@ -0,0 +1,21 @@
1
+MIT License
2
+
3
+Copyright (c) 2021 Stephen Ruiz Ltd
4
+
5
+Permission is hereby granted, free of charge, to any person obtaining a copy
6
+of this software and associated documentation files (the "Software"), to deal
7
+in the Software without restriction, including without limitation the rights
8
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+copies of the Software, and to permit persons to whom the Software is
10
+furnished to do so, subject to the following conditions:
11
+
12
+The above copyright notice and this permission notice shall be included in all
13
+copies or substantial portions of the Software.
14
+
15
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+SOFTWARE.

+ 29
- 8
vscode/extension/README.md View File

@@ -1,13 +1,34 @@
1
-# Wardlt
2
-This is an awesome sketch/diagramming extension for making doodles and diagrams of system. It allows you to naturally create informal but legible diagrams, designed to be version controlled along side your code.
1
+## Introduction
2
+
3
+TLDraw extends VS Code with support for [TLDraw](https://tldraw.com) files.
4
+
5
+[TLDraw](https://tldraw.com) is a free drawing and diagramming tool with a hand-drawn style and convenient features such as smart arrows, snapping, and sticky notes. With the TLDraw extension for VS Code, your TLDraw files can be version controlled alongside your code.
6
+
7
+> **Tip:** The files you create or edit here can also be opened in the TLDraw [web app](https://tldraw.com).
8
+
9
+## Installation
10
+
11
+You can install TLDraw from the Visual Studio Code Marketplace or by searching within VS Code.
3 12
 
4 13
 ## Features
5 14
 
6
- 1. Hand drawn style
7
- 2. Built in shapes like rectangles and ovals
8
- 3. Add text elements
9
- 4. Has smart arrows that support smart connecting between shapes/text for easy to make flow charts.
10
- 5. Supports dashed strokes on all shapes.
15
+1. View, edit and save TLDraw files (`.tldr`)
11 16
 
12 17
 ## Usage
13
-Create a new file by either creating a blank .tldr file or by using the provided command: "Tldraw: Create a new .tldr file".
18
+
19
+- To view an existing TLDraw file, open a file with the `.tldr` extension in VS Code.
20
+- To create a new TLDraw file, use the provided command: "TLDraw: New TLDraw File".
21
+
22
+## Release Notes
23
+
24
+For full release notes, see the [changelog](https://github.com/tldraw/tldraw).
25
+
26
+## Community
27
+
28
+### Support
29
+
30
+Need help? Please [open an issue](https://github.com/tldraw/tldraw/issues/new) for support.
31
+
32
+### Discussion
33
+
34
+Want to connect with other devs? Visit the [Discord channel](https://discord.gg/s4FXZ6fppJ).

+ 1015
- 1012
vscode/extension/examples/2.tldr
File diff suppressed because it is too large
View File


+ 4
- 5
vscode/extension/examples/3.tldr View File

@@ -3,6 +3,7 @@
3 3
   "fileHandle": {},
4 4
   "document": {
5 5
     "id": "doc",
6
+    "name": "New Document",
6 7
     "version": 13,
7 8
     "pages": {
8 9
       "page": {
@@ -17,8 +18,8 @@
17 18
             "parentId": "page",
18 19
             "childIndex": 1,
19 20
             "point": [
20
-              258.7,
21
-              246.85
21
+              268.18,
22
+              247.52
22 23
             ],
23 24
             "rotation": 0,
24 25
             "style": {
@@ -1095,9 +1096,7 @@
1095 1096
             -220.86
1096 1097
           ],
1097 1098
           "zoom": 2.462934947049924
1098
-        },
1099
-        "editingId": null,
1100
-        "hoveredId": "60a83a6a-6477-45ff-3cd9-5c705c210c3a"
1099
+        }
1101 1100
       }
1102 1101
     }
1103 1102
   },

BIN
vscode/extension/examples/smiley-image.png View File


+ 0
- 0
vscode/extension/examples/test.drawio View File


BIN
vscode/extension/icon.png View File


+ 41
- 27
vscode/extension/package.json View File

@@ -1,15 +1,33 @@
1 1
 {
2
-	"name": "wardlt",
3
-	"displayName": "Wardlt Editor",
4
-	"description": "The wardlt editor for VS Code",
5
-	"version": "0.10.0",
6
-	"publisher": "Wardlt",
7
-	"repository": "https://github.com/microsoft/vscode-extension-samples/helloworld-web-sample",
2
+	"name": "tldraw-vscode",
3
+	"displayName": "TLDraw",
4
+	"description": "The TLDraw Extension for VS Code.",
5
+	"version": "0.1.15",
6
+	"license": "MIT",
7
+	"publisher": "tldraw-org",
8
+	"repository": {
9
+		"type": "git",
10
+		"url": "https://github.com/tldraw/tldraw"
11
+	},
8 12
 	"engines": {
9 13
 		"vscode": "^1.59.0"
10 14
 	},
15
+	"keywords": [
16
+		"diagram",
17
+		"draw",
18
+		"drawing",
19
+		"sketch",
20
+		"design",
21
+		"documentation",
22
+		"tldraw"
23
+	],
24
+	"icon": "icon.png",
25
+	"galleryBanner": {
26
+		"color": "#1d1d1d",
27
+		"theme": "dark"
28
+	},
11 29
 	"categories": [
12
-		"Other"
30
+		"Visualization"
13 31
 	],
14 32
 	"activationEvents": [
15 33
 		"onCustomEditor:tldraw.tldr",
@@ -25,7 +43,7 @@
25 43
 		"customEditors": [
26 44
 			{
27 45
 				"viewType": "tldraw.tldr",
28
-				"displayName": "Tldr Editor",
46
+				"displayName": "TLDraw",
29 47
 				"selector": [
30 48
 					{
31 49
 						"filenamePattern": "*.tldr"
@@ -36,35 +54,31 @@
36 54
 		"commands": [
37 55
 			{
38 56
 				"command": "tldraw.tldr.new",
39
-				"title": "Create a new .tldr file",
40
-				"category": "Tldraw"
57
+				"title": "New TLDraw File",
58
+				"category": "TLDraw"
41 59
 			}
42 60
 		]
43 61
 	},
44 62
 	"scripts": {
45
-		"test": "vscode-test-web --browserType=chromium --extensionDevelopmentPath=. --extensionTestsPath=dist/web/test/suite/index.js",
63
+		"start:vscode": "node scripts/dev & yarn types:dev",
64
+		"types:dev": "tsc -w",
46 65
 		"web": "vscode-test-web --browserType=chromium --extensionDevelopmentPath=.",
47
-		"pretest": "npm run compile-web",
48
-		"vscode:prepublish": "npm run package-web",
49
-		"compile-web": "webpack",
50
-		"watch-web": "webpack --watch",
51
-		"package-web": "webpack --mode production --devtool hidden-source-map",
66
+		"package": "cd ../editor && yarn build && cd ../extension && node scripts/build && node scripts/package",
67
+		"vscode:publish": "yarn version && yarn package && vsce publish",
52 68
 		"lint": "eslint src --ext ts"
53 69
 	},
70
+	"dependencies": {},
71
+	"peerDependencies": {},
54 72
 	"devDependencies": {
55
-		"@types/vscode": "^1.59.0",
56
-		"@types/mocha": "^9.0.0",
57
-		"eslint": "^7.32.0",
58 73
 		"@typescript-eslint/eslint-plugin": "^4.31.1",
59 74
 		"@typescript-eslint/parser": "^4.31.1",
60
-		"mocha": "^9.1.1",
61
-		"typescript": "^4.4.3",
62 75
 		"@vscode/test-web": "^0.0.12",
63
-		"ts-loader": "^9.2.5",
64
-		"webpack": "^5.52.1",
65
-		"webpack-cli": "^4.8.0",
66
-		"@types/webpack-env": "^1.16.2",
67 76
 		"assert": "^2.0.0",
68
-		"process": "^0.11.10"
77
+		"eslint": "^7.32.0",
78
+		"mocha": "^9.1.1",
79
+		"process": "^0.11.10",
80
+		"ts-loader": "^9.2.5",
81
+		"typescript": "^4.4.3",
82
+		"vsce": "^2.2.0"
69 83
 	}
70
-}
84
+}

+ 53
- 0
vscode/extension/scripts/build.js View File

@@ -0,0 +1,53 @@
1
+/* eslint-disable */
2
+const fs = require('fs')
3
+const esbuild = require('esbuild')
4
+const { gzip } = require('zlib')
5
+const pkg = require('../package.json')
6
+
7
+async function main() {
8
+  if (fs.existsSync('./dist')) {
9
+    fs.rmSync('./dist', { recursive: true }, (e) => {
10
+      if (e) {
11
+        throw e
12
+      }
13
+    })
14
+  }
15
+
16
+  try {
17
+    const esmResult = esbuild.buildSync({
18
+      entryPoints: ['./src/extension.ts'],
19
+      outdir: 'dist/web',
20
+      minify: true,
21
+      bundle: true,
22
+      format: 'cjs',
23
+      target: 'es6',
24
+      define: {
25
+        'process.env.NODE_ENV': '"production"',
26
+      },
27
+      tsconfig: './tsconfig.json',
28
+      external: Object.keys(pkg.dependencies).concat(Object.keys(pkg.peerDependencies)).concat(["vscode"]),
29
+      metafile: true,
30
+      
31
+    })
32
+
33
+    let esmSize = 0
34
+    Object.values(esmResult.metafile.outputs).forEach((output) => {
35
+      esmSize += output.bytes
36
+    })
37
+
38
+    fs.readFile('./dist/web/index.js', (_err, data) => {
39
+      gzip(data, (_err, result) => {
40
+        console.log(
41
+          `✔ ${pkg.name}: Built pkg. ${(esmSize / 1000).toFixed(2)}kb (${(
42
+            result.length / 1000
43
+          ).toFixed(2)}kb minified)`
44
+        )
45
+      })
46
+    })
47
+  } catch (e) {
48
+    console.log(`× ${pkg.name}: Build failed due to an error.`)
49
+    console.log(e)
50
+  }
51
+}
52
+
53
+main()

+ 54
- 0
vscode/extension/scripts/dev.js View File

@@ -0,0 +1,54 @@
1
+/* eslint-disable */
2
+const fs = require('fs')
3
+const esbuild = require('esbuild')
4
+const { gzip } = require('zlib')
5
+const pkg = require('../package.json')
6
+
7
+async function main() {
8
+  if (fs.existsSync('./dist')) {
9
+    fs.rmSync('./dist', { recursive: true }, (e) => {
10
+      if (e) {
11
+        throw e
12
+      }
13
+    })
14
+  }
15
+
16
+  try {
17
+    const esmResult = esbuild.buildSync({
18
+      entryPoints: ['./src/extension.ts'],
19
+      outdir: 'dist/web',
20
+      minify: true,
21
+      bundle: true,
22
+      format: 'cjs',
23
+      target: 'es6',
24
+      define: {
25
+        'process.env.NODE_ENV': '"development"',
26
+      },
27
+      tsconfig: './tsconfig.json',
28
+      external: Object.keys(pkg.dependencies)
29
+        .concat(Object.keys(pkg.peerDependencies))
30
+        .concat(['vscode']),
31
+      metafile: true,
32
+    })
33
+
34
+    let esmSize = 0
35
+    Object.values(esmResult.metafile.outputs).forEach((output) => {
36
+      esmSize += output.bytes
37
+    })
38
+
39
+    fs.readFile('./dist/web/index.js', (_err, data) => {
40
+      gzip(data, (_err, result) => {
41
+        console.log(
42
+          `✔ ${pkg.name}: Built pkg. ${(esmSize / 1000).toFixed(2)}kb (${(
43
+            result.length / 1000
44
+          ).toFixed(2)}kb minified)`
45
+        )
46
+      })
47
+    })
48
+  } catch (e) {
49
+    console.log(`× ${pkg.name}: Build failed due to an error.`)
50
+    console.log(e)
51
+  }
52
+}
53
+
54
+main()

+ 37
- 0
vscode/extension/scripts/package.js View File

@@ -0,0 +1,37 @@
1
+/* eslint-disable */
2
+//const version = require('../../../lerna.json').version
3
+const pkg = require('../package.json')
4
+const { exec } = require('child_process')
5
+const fs = require('fs')
6
+const dir = './temp'
7
+
8
+async function main() {
9
+  if (fs.existsSync(dir)) {
10
+    fs.rmSync(dir, { recursive: true }, (e) => {
11
+      if (e) {
12
+        throw e
13
+      }
14
+    })
15
+  }
16
+
17
+  fs.mkdirSync(dir)
18
+
19
+  try {
20
+    exec(
21
+      `cp -r ../editor/dist editor; vsce package; mv ${pkg.name}-${pkg.version}.vsix ${dir}`,
22
+      (error, stdout, stderr) => {
23
+        if (error) {
24
+          throw new Error(error.message)
25
+        }
26
+        if (stderr && stderr.search('warning') !== 0) {
27
+          throw new Error(stderr)
28
+        }
29
+      }
30
+    )
31
+  } catch (e) {
32
+    console.log(`× ${pkg.name}: Build failed due to an error.`)
33
+    console.log(e)
34
+  }
35
+}
36
+
37
+main()

vscode/extension/src/web/tldraw-editor.ts → vscode/extension/src/TLDrawEditorProvider.ts View File

@@ -1,25 +1,27 @@
1 1
 import * as vscode from 'vscode'
2
-import { getHtmlForWebview } from './get-html'
2
+import { TLDrawFile } from '@tldraw/tldraw'
3
+import { getHtmlForWebview } from './getHtmlForWebview'
3 4
 import { EXTENSION_EVENT, UI_EVENT } from './types'
5
+import { sanitizeDocument } from './utils'
4 6
 
5 7
 /**
6
- * The Tldraw extension's editor uses CustomTextEditorProvider, which means
8
+ * The TLDraw extension's editor uses CustomTextEditorProvider, which means
7 9
  * it's underlying model from VS Code's perspective is a text file. We likely
8 10
  * will switch to CustomEditorProvider which gives us more control but will require
9 11
  * more book keeping on our part.
10 12
  */
11
-export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
13
+export class TLDrawEditorProvider implements vscode.CustomTextEditorProvider {
12 14
   private document?: vscode.TextDocument
13 15
 
14 16
   // When the tldraw.tldr.new command is triggered, we need to provide a file
15
-  // name when generating a new .tldr file. newTldrawFileId's current value is
17
+  // name when generating a new .tldr file. newTLDrawFileId's current value is
16 18
   // added to the end of the file to make it unique, and then incremented.
17 19
   //
18 20
   // While there is probably a more thoughtful way of creating suggested file names,
19 21
   // this name is only the temporary name for the new file. The file is still only in memory
20 22
   // and hasn't been saved to an actual underlying file. If we suggest a name that turns
21 23
   // out to already exist, VS Code will prevent it from being used in it's save dialogs.
22
-  private static newTldrawFileId = 1
24
+  private static newTLDrawFileId = 1
23 25
 
24 26
   // This is called one time by the main extension entry point. See 'extension.ts'.
25 27
   // We register commands here and register our custom editor's provider telling VS Code
@@ -28,33 +30,20 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
28 30
     // This makes a new command show up in the Command Palette that will
29 31
     // create a new empty .tldr. The file will actually start out
30 32
     // as an empty text file, which is fine as the editor treats
31
-    // blank text files as an empty Tldraw file. Once any change is made
33
+    // blank text files as an empty TLDraw file. Once any change is made
32 34
     // and the file saved it will be in a proper JSON format.
33
-    //
34
-    // The command shows up as: "Tldraw: Create a new .tldr file".
35
-    vscode.commands.registerCommand('tldraw.tldr.new', () => {
36
-      // This was included in the example CustomTextEditorProvider. It
37
-      // doesn't seem like we should need a workspace to be within to edit
38
-      // .tldr files, but I want to punt on digging into this.
39
-      // TODO: Test/decide if it is necessary to need a workspace.
40
-      // I can't think of why we'd want a concept of a global scope
41
-      // for editing .tldr files.
42
-      const workspaceFolders = vscode.workspace.workspaceFolders
43
-      if (!workspaceFolders) {
44
-        vscode.window.showErrorMessage(
45
-          'Creating new Tldraw Editor files currently requires opening a workspace'
46
-        )
47
-        return
48
-      }
49 35
 
36
+    // The command shows up as: "TLDraw: Create a new .tldr file".
37
+    vscode.commands.registerCommand('tldraw.tldr.new', () => {
50 38
       // Create a placeholder name for the new file. A new file isn't actually
51 39
       // created on disk yet, so this is just an in memory temporary name.
52
-      const uri = vscode.Uri.joinPath(
53
-        workspaceFolders[0].uri,
54
-        `drawing ${TldrawEditorProvider.newTldrawFileId++}.tldr`
55
-      ).with({
56
-        scheme: 'untitled',
57
-      })
40
+      const id = TLDrawEditorProvider.newTLDrawFileId++
41
+      const name = id > 1 ? `New Document ${id}.tldr` : `New Document.tldr`
42
+
43
+      // Create a placeholder file path for the folder. Use the workspace folder
44
+      // if one exists, otherwise make up an empty one.
45
+      const workspaceFolders = vscode.workspace.workspaceFolders
46
+      const path = workspaceFolders ? workspaceFolders[0].uri : vscode.Uri.parse('')
58 47
 
59 48
       // This triggers VS Code to open our custom editor to edit the file.
60 49
       // Note: Multiple editors can register to support certain files, so
@@ -62,15 +51,19 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
62 51
       // we are explicitly saying to launch our editor so we're streamlined. It
63 52
       // may awkwardly ask if they want to use our editor or a text editor when
64 53
       // first using our extension.
65
-      vscode.commands.executeCommand('vscode.openWith', uri, TldrawEditorProvider.viewType)
54
+      vscode.commands.executeCommand(
55
+        'vscode.openWith',
56
+        vscode.Uri.joinPath(path, name).with({ scheme: 'untitled' }),
57
+        TLDrawEditorProvider.viewType
58
+      )
66 59
     })
67 60
 
68 61
     // This registers our editor provider, indicating to VS Code that we can
69 62
     // handle files with the .tldr extension.
70
-    const provider = new TldrawEditorProvider(context)
63
+    const provider = new TLDrawEditorProvider(context)
71 64
 
72 65
     const providerRegistration = vscode.window.registerCustomEditorProvider(
73
-      TldrawEditorProvider.viewType,
66
+      TLDrawEditorProvider.viewType,
74 67
       provider,
75 68
       {
76 69
         webviewOptions: {
@@ -85,7 +78,7 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
85 78
 
86 79
         // I'm not sure about the exact semantics about this one. I'm going to leave it in though as
87 80
         // it sounds right for our needs. I think this ensures we get a unique instance of our provider
88
-        // per Tldraw editor tab, vs it being shared. It would be really cool if we could support
81
+        // per TLDraw editor tab, vs it being shared. It would be really cool if we could support
89 82
         // multiple tabs sharing the same document state, but separate editor state (like zoom/pan/selection),
90 83
         // but this will likely be a lot of work.
91 84
         //
@@ -147,9 +140,9 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
147 140
     // being if the file changed on disk, say from git pull that pulls down a change
148 141
     // to a .tldr file you have open in a tab.
149 142
 
150
-    const changeDocumentSubscription = vscode.workspace.onDidSaveTextDocument((e) => {
143
+    const changeDocumentSubscription = vscode.workspace.onDidSaveTextDocument(() => {
151 144
       webviewPanel.webview.postMessage({
152
-        type: EXTENSION_EVENT.LOCAL_FILE_UPDATED,
145
+        type: EXTENSION_EVENT.FILE_UPDATED,
153 146
         text: document.getText(),
154 147
       })
155 148
     })
@@ -165,8 +158,14 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
165 158
     webviewPanel.webview.onDidReceiveMessage((e) => {
166 159
       switch (e.type) {
167 160
         case UI_EVENT.TLDRAW_UPDATED: {
168
-          // Synchronize the TextDocument  with the tldraw components document state
169
-          this.synchronizeTextDocument(document, JSON.parse(e.text))
161
+          // Synchronize the TextDocument with the tldraw components document state
162
+
163
+          const prevFile = JSON.parse(document.getText()) as TLDrawFile
164
+          const nextFile = JSON.parse(e.text) as TLDrawFile
165
+
166
+          nextFile.document = sanitizeDocument(prevFile.document, nextFile.document)
167
+
168
+          this.synchronizeTextDocument(document, nextFile)
170 169
           break
171 170
         }
172 171
       }
@@ -178,7 +177,7 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
178 177
     // the extension isn't actually an enclosing web page.
179 178
 
180 179
     webviewPanel.webview.postMessage({
181
-      type: EXTENSION_EVENT.INITIAL_DOCUMENT,
180
+      type: EXTENSION_EVENT.OPENED_FILE,
182 181
       text: document.getText(),
183 182
     })
184 183
   }
@@ -189,7 +188,7 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
189 188
    * VS Code will handle detecting if the in memory content and the on disk
190 189
    * content are different, and then mark/unmark the tab as saved/unsaved
191 190
    */
192
-  private synchronizeTextDocument(document: vscode.TextDocument, json: any) {
191
+  private synchronizeTextDocument(document: vscode.TextDocument, nextFile: TLDrawFile) {
193 192
     // Just replace the entire document every time for this example extension.
194 193
     // A more complete extension should compute minimal edits instead.
195 194
     // TODO: Make sure to keep an eye on performance problems, as this may be the
@@ -201,7 +200,7 @@ export class TldrawEditorProvider implements vscode.CustomTextEditorProvider {
201 200
     edit.replace(
202 201
       document.uri,
203 202
       new vscode.Range(0, 0, document.lineCount, 0),
204
-      JSON.stringify(json, null, 2)
203
+      JSON.stringify(nextFile, null, 2)
205 204
     )
206 205
 
207 206
     return vscode.workspace.applyEdit(edit)

vscode/extension/src/web/extension.ts → vscode/extension/src/extension.ts View File

@@ -1,9 +1,9 @@
1 1
 import * as vscode from 'vscode'
2
-import { TldrawEditorProvider } from './tldraw-editor'
2
+import { TLDrawEditorProvider } from './TLDrawEditorProvider'
3 3
 
4 4
 // This is the extension entry point. This is called once on the first
5 5
 // time a .tldr extension is opened/created.
6 6
 export function activate(context: vscode.ExtensionContext) {
7 7
   // Register our custom editor providers
8
-  context.subscriptions.push(TldrawEditorProvider.register(context))
8
+  context.subscriptions.push(TLDrawEditorProvider.register(context))
9 9
 }

vscode/extension/src/web/get-html.ts → vscode/extension/src/getHtmlForWebview.ts View File

@@ -23,8 +23,12 @@ export function getHtmlForWebview(
23 23
     documentContent = 'null'
24 24
   }
25 25
 
26
-  return getDevModeHTML(context, webview, documentContent)
27
-  // return getProductionModeHTML(context, webview, documentContent);
26
+  if(process.env.NODE_ENV === 'production'){
27
+    return getProductionModeHTML(context, webview, documentContent);
28
+  } else {
29
+    return getDevModeHTML(context, webview, documentContent)
30
+  }
31
+  
28 32
 }
29 33
 
30 34
 /**
@@ -85,13 +89,15 @@ function getProductionModeHTML(
85 89
   documentContent: string
86 90
 ): string {
87 91
   const cssUrl = webview.asWebviewUri(
88
-    vscode.Uri.joinPath(context.extensionUri, 'editor-build/static/css', 'index.css')
92
+    vscode.Uri.joinPath(context.extensionUri, 'editor/', 'index.css')
89 93
   )
90 94
 
91 95
   const jsUrl = webview.asWebviewUri(
92
-    vscode.Uri.joinPath(context.extensionUri, 'editor-build/', 'index.js')
96
+    vscode.Uri.joinPath(context.extensionUri, 'editor/', 'index.js')
93 97
   )
94 98
 
99
+  console.log("production mode");
100
+
95 101
   return `
96 102
   <!DOCTYPE html>
97 103
   <html lang="en">

+ 8
- 0
vscode/extension/src/types.ts View File

@@ -0,0 +1,8 @@
1
+export enum UI_EVENT {
2
+  TLDRAW_UPDATED = 'TLDRAW_UPDATED',
3
+}
4
+
5
+export enum EXTENSION_EVENT {
6
+  OPENED_FILE = 'OPENED_FILE',
7
+  FILE_UPDATED = 'FILE_UPDATED',
8
+}

+ 21
- 0
vscode/extension/src/utils.ts View File

@@ -0,0 +1,21 @@
1
+import type { TLDrawDocument } from '@tldraw/tldraw'
2
+
3
+export function getNonce() {
4
+  let text = ''
5
+  const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
6
+  for (let i = 0; i < 32; i++) {
7
+    text += possible.charAt(Math.floor(Math.random() * possible.length))
8
+  }
9
+  return text
10
+}
11
+
12
+export function sanitizeDocument(prev: TLDrawDocument, next: TLDrawDocument): TLDrawDocument {
13
+  Object.values(prev.pageStates).forEach((pageState) => {
14
+    // Ensure that the previous page state is preserved, if possible
15
+    if (next.pages[pageState.id] !== undefined) {
16
+      next.pageStates[pageState.id] = pageState
17
+    }
18
+  })
19
+
20
+  return next
21
+}

+ 0
- 29
vscode/extension/src/web/test/suite/index.ts View File

@@ -1,29 +0,0 @@
1
-// imports mocha for the browser, defining the `mocha` global.
2
-require('mocha/mocha')
3
-
4
-export function run(): Promise<void> {
5
-  return new Promise((c, e) => {
6
-    mocha.setup({
7
-      ui: 'tdd',
8
-      reporter: undefined,
9
-    })
10
-
11
-    // bundles all files in the current directory matching `*.test`
12
-    const importAll = (r: __WebpackModuleApi.RequireContext) => r.keys().forEach(r)
13
-    importAll(require.context('.', true, /\.test$/))
14
-
15
-    try {
16
-      // Run the mocha test
17
-      mocha.run((failures) => {
18
-        if (failures > 0) {
19
-          e(new Error(`${failures} tests failed.`))
20
-        } else {
21
-          c()
22
-        }
23
-      })
24
-    } catch (err) {
25
-      console.error(err)
26
-      e(err)
27
-    }
28
-  })
29
-}

+ 0
- 12
vscode/extension/src/web/types.ts View File

@@ -1,12 +0,0 @@
1
-export enum UI_EVENT {
2
-  TLDRAW_UPDATED = 'TLDRAW_UPDATED',
3
-}
4
-
5
-export enum EXTENSION_EVENT {
6
-  INITIAL_DOCUMENT = 'INITIAL_DOCUMENT',
7
-  LOCAL_FILE_UPDATED = 'LOCAL_FILE_UPDATED',
8
-}
9
-
10
-export type UIMessage = MessageEvent<{ type: UI_EVENT; text: string }>
11
-
12
-export type ExtensionMessage = MessageEvent<{ type: EXTENSION_EVENT; text: string }>

+ 0
- 9
vscode/extension/src/web/util.ts View File

@@ -1,9 +0,0 @@
1
-export function getNonce() {
2
-  let text = ''
3
-  const possible =
4
-    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
5
-  for (let i = 0; i < 32; i++) {
6
-    text += possible.charAt(Math.floor(Math.random() * possible.length))
7
-  }
8
-  return text
9
-}

+ 0
- 67
vscode/extension/webpack.config.js View File

@@ -1,67 +0,0 @@
1
-/*---------------------------------------------------------------------------------------------
2
- *  Copyright (c) Microsoft Corporation. All rights reserved.
3
- *  Licensed under the MIT License. See License.txt in the project root for license information.
4
- *--------------------------------------------------------------------------------------------*/
5
-
6
-//@ts-check
7
-'use strict';
8
-
9
-//@ts-check
10
-/** @typedef {import('webpack').Configuration} WebpackConfig **/
11
-
12
-const path = require('path');
13
-const webpack = require('webpack');
14
-
15
-const webExtensionConfig = /** @type WebpackConfig */ {
16
-	mode: 'none', // this leaves the source code as close as possible to the original (when packaging we set this to 'production')
17
-	target: 'webworker', // extensions run in a webworker context
18
-	entry: {
19
-		extension: './src/web/extension.ts', // source of the web extension main file
20
-		'test/suite/index': './src/web/test/suite/index.ts', // source of the web extension test runner
21
-	},
22
-	output: {
23
-		filename: '[name].js',
24
-		path: path.join(__dirname, './dist/web'),
25
-		libraryTarget: 'commonjs',
26
-	},
27
-	resolve: {
28
-		mainFields: ['browser', 'module', 'main'], // look for `browser` entry point in imported node modules
29
-		extensions: ['.ts', '.js'], // support ts-files and js-files
30
-		alias: {
31
-			// provides alternate implementation for node module and source files
32
-		},
33
-		fallback: {
34
-			// Webpack 5 no longer polyfills Node.js core modules automatically.
35
-			// see https://webpack.js.org/configuration/resolve/#resolvefallback
36
-			// for the list of Node.js core module polyfills.
37
-			assert: require.resolve('assert'),
38
-		},
39
-	},
40
-	module: {
41
-		rules: [
42
-			{
43
-				test: /\.ts$/,
44
-				exclude: /node_modules/,
45
-				use: [
46
-					{
47
-						loader: 'ts-loader',
48
-					},
49
-				],
50
-			},
51
-		],
52
-	},
53
-	plugins: [
54
-		new webpack.ProvidePlugin({
55
-			process: 'process/browser', // provide a shim for the global `process` variable
56
-		}),
57
-	],
58
-	externals: {
59
-		vscode: 'commonjs vscode', // ignored because it doesn't exist
60
-	},
61
-	performance: {
62
-		hints: false,
63
-	},
64
-	devtool: 'nosources-source-map', // create a source map that points to the original source file
65
-};
66
-
67
-module.exports = [webExtensionConfig];

+ 1042
- 82
yarn.lock
File diff suppressed because it is too large
View File


Loading…
Cancel
Save