@kubohiroya/turbowarp-plus-editor-code-views 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +38 -0
  3. package/README.md +37 -2
  4. package/dist/asset-edit-session.d.ts +24 -0
  5. package/dist/asset-edit-session.js +58 -0
  6. package/dist/block-argument-text.d.ts +39 -0
  7. package/dist/block-argument-text.js +170 -0
  8. package/dist/block-drag.d.ts +17 -0
  9. package/dist/block-drag.js +184 -0
  10. package/dist/code-extensions.d.ts +38 -0
  11. package/dist/code-extensions.js +418 -0
  12. package/dist/code-pane.d.ts +63 -0
  13. package/dist/code-pane.js +363 -0
  14. package/dist/custom-extension-fields.d.ts +45 -0
  15. package/dist/custom-extension-fields.js +144 -0
  16. package/dist/detached-block-palette-view.d.ts +10 -0
  17. package/dist/detached-block-palette-view.js +62 -0
  18. package/dist/detached-block-palette.d.ts +41 -0
  19. package/dist/detached-block-palette.js +197 -0
  20. package/dist/dockview-unsaved.d.ts +45 -0
  21. package/dist/dockview-unsaved.js +123 -0
  22. package/dist/history.d.ts +57 -0
  23. package/dist/history.js +85 -0
  24. package/dist/index.d.ts +28 -0
  25. package/dist/index.js +729 -0
  26. package/dist/native-extension-field.d.ts +26 -0
  27. package/dist/native-extension-field.js +204 -0
  28. package/dist/native-field-svg.d.ts +20 -0
  29. package/dist/native-field-svg.js +156 -0
  30. package/dist/palette-category-reorder.d.ts +4 -0
  31. package/dist/palette-category-reorder.js +167 -0
  32. package/dist/palette-category-search.d.ts +26 -0
  33. package/dist/palette-category-search.js +74 -0
  34. package/dist/palette-dropdown-resize.d.ts +19 -0
  35. package/dist/palette-dropdown-resize.js +135 -0
  36. package/dist/parent-field-layout.d.ts +2 -0
  37. package/dist/parent-field-layout.js +90 -0
  38. package/dist/parent-field-mirror.d.ts +3 -0
  39. package/dist/parent-field-mirror.js +290 -0
  40. package/dist/parent-field-resources.d.ts +9 -0
  41. package/dist/parent-field-resources.js +199 -0
  42. package/dist/preview-chrome.d.ts +9 -0
  43. package/dist/preview-chrome.js +78 -0
  44. package/dist/procedure-editor.d.ts +9 -0
  45. package/dist/procedure-editor.js +122 -0
  46. package/dist/procedure-edits.d.ts +16 -0
  47. package/dist/procedure-edits.js +47 -0
  48. package/dist/programmatic-extension-field.d.ts +20 -0
  49. package/dist/programmatic-extension-field.js +69 -0
  50. package/dist/protocol.d.ts +15 -0
  51. package/dist/protocol.js +36 -0
  52. package/dist/script-layout-dialog.d.ts +10 -0
  53. package/dist/script-layout-dialog.js +93 -0
  54. package/dist/script-layout-view.d.ts +68 -0
  55. package/dist/script-layout-view.js +164 -0
  56. package/dist/script-layout-workspace.d.ts +45 -0
  57. package/dist/script-layout-workspace.js +55 -0
  58. package/dist/script-layout.d.ts +17 -0
  59. package/dist/script-layout.js +25 -0
  60. package/dist/script-view-menu.d.ts +46 -0
  61. package/dist/script-view-menu.js +161 -0
  62. package/dist/sprite-code-windows.d.ts +31 -0
  63. package/dist/sprite-code-windows.js +180 -0
  64. package/dist/stage-code-prewarm.d.ts +52 -0
  65. package/dist/stage-code-prewarm.js +216 -0
  66. package/dist/target-combobox.d.ts +10 -0
  67. package/dist/target-combobox.js +92 -0
  68. package/dist/variable-references.d.ts +1 -0
  69. package/dist/variable-references.js +87 -0
  70. package/dist/workspace.d.ts +103 -0
  71. package/dist/workspace.js +1102 -0
  72. package/package.json +100 -4
  73. package/src/asset-edit-session.ts +72 -0
  74. package/src/block-argument-text.ts +172 -0
  75. package/src/block-drag.ts +190 -0
  76. package/src/code-extensions.ts +394 -0
  77. package/src/code-pane.ts +353 -0
  78. package/src/custom-extension-fields.ts +154 -0
  79. package/src/detached-block-palette-view.tsx +97 -0
  80. package/src/detached-block-palette.ts +218 -0
  81. package/src/dockview-unsaved.ts +134 -0
  82. package/src/history.ts +114 -0
  83. package/src/index.ts +680 -0
  84. package/src/native-extension-field.ts +201 -0
  85. package/src/native-field-svg.ts +140 -0
  86. package/src/palette-category-reorder.ts +155 -0
  87. package/src/palette-category-search.ts +82 -0
  88. package/src/palette-dropdown-resize.ts +132 -0
  89. package/src/parent-field-layout.ts +88 -0
  90. package/src/parent-field-mirror.ts +260 -0
  91. package/src/parent-field-resources.ts +179 -0
  92. package/src/preview-chrome.ts +82 -0
  93. package/src/procedure-editor.ts +123 -0
  94. package/src/procedure-edits.ts +46 -0
  95. package/src/programmatic-extension-field.ts +76 -0
  96. package/src/protocol.ts +47 -0
  97. package/src/script-layout-dialog.ts +104 -0
  98. package/src/script-layout-view.ts +198 -0
  99. package/src/script-layout-workspace.ts +95 -0
  100. package/src/script-layout.ts +40 -0
  101. package/src/script-view-menu.ts +213 -0
  102. package/src/sprite-code-windows.tsx +182 -0
  103. package/src/stage-code-prewarm.ts +242 -0
  104. package/src/styles.css +595 -0
  105. package/src/target-combobox.tsx +106 -0
  106. package/src/variable-references.ts +85 -0
  107. package/src/workspace.ts +1124 -0
  108. package/tsconfig.json +23 -0
@@ -0,0 +1,197 @@
1
+ import React from 'react';
2
+ import ReactDOM from 'react-dom';
3
+ import Palette from "./detached-block-palette-view.js";
4
+ const sources = new WeakMap();
5
+ const opened = new WeakMap();
6
+ const dragType = 'application/x-tw-plus-palette-block';
7
+ export function openDetachedBlockPalette(workspace, { locale, categoryIcons, decorate }) {
8
+ const source = sources.get(workspace);
9
+ const owner = source?.surface.ownerDocument.defaultView;
10
+ if (!owner)
11
+ return;
12
+ const existing = opened.get(source);
13
+ if (existing && !existing.popup.closed) {
14
+ existing.popup.focus();
15
+ return;
16
+ }
17
+ const popup = owner.open('about:blank', '', 'popup,width=720,height=440');
18
+ if (!popup)
19
+ return;
20
+ const doc = popup.document;
21
+ doc.title = /^ja(?:-|$)/i.test(locale) ? 'ブロックパレット' : 'Block palette';
22
+ const undecorate = decorate(doc);
23
+ const mount = doc.createElement('div');
24
+ doc.body.append(mount);
25
+ const events = new AbortController();
26
+ let drag;
27
+ const close = () => {
28
+ if (events.signal.aborted)
29
+ return;
30
+ events.abort();
31
+ drag = undefined;
32
+ opened.delete(source);
33
+ ReactDOM.unmountComponentAtNode(mount);
34
+ source.setDetached(false);
35
+ undecorate();
36
+ if (!popup.closed)
37
+ popup.close();
38
+ };
39
+ opened.set(source, { popup, close });
40
+ popup.addEventListener('pagehide', close, { signal: events.signal });
41
+ owner.addEventListener('pagehide', close, { signal: events.signal });
42
+ source.surface.addEventListener('dragover', event => {
43
+ if (!drag || !event.dataTransfer?.types.includes(dragType))
44
+ return;
45
+ event.preventDefault();
46
+ event.dataTransfer.dropEffect = 'copy';
47
+ }, { signal: events.signal });
48
+ source.surface.addEventListener('drop', event => {
49
+ if (!drag || !event.dataTransfer?.getData(dragType))
50
+ return;
51
+ event.preventDefault();
52
+ drag.insert({ x: event.clientX, y: event.clientY });
53
+ drag = undefined;
54
+ }, { signal: events.signal });
55
+ try {
56
+ source.setDetached(true);
57
+ ReactDOM.render(React.createElement(Palette, {
58
+ source, locale, categoryIcons, close,
59
+ startDrag(item, data) {
60
+ drag = item;
61
+ data.effectAllowed = 'copy';
62
+ data.setData(dragType, 'block');
63
+ },
64
+ endDrag() { drag = undefined; }
65
+ }), mount);
66
+ }
67
+ catch (error) {
68
+ close();
69
+ throw error;
70
+ }
71
+ }
72
+ function registerDetachedBlockPalette(workspace, source) {
73
+ sources.set(workspace, source);
74
+ return () => {
75
+ opened.get(source)?.close();
76
+ sources.delete(workspace);
77
+ };
78
+ }
79
+ export function connectDetachedBlockPalette({ blocks, workspace, flyout, menu, categories, show, setDetached }) {
80
+ const surface = workspace.getParentSvg();
81
+ const ns = 'http://www.w3.org/2000/svg';
82
+ const win = surface.ownerDocument.defaultView;
83
+ const placement = (point) => {
84
+ const bounds = surface.getBoundingClientRect();
85
+ const matrix = workspace.getCanvas().getScreenCTM();
86
+ if (!matrix || !bounds.width || !bounds.height)
87
+ return;
88
+ const position = surface.createSVGPoint();
89
+ position.x = point?.x ?? bounds.left + bounds.width / 2;
90
+ position.y = point?.y ?? bounds.top + bounds.height / 2;
91
+ return position.matrixTransform(matrix.inverse());
92
+ };
93
+ return registerDetachedBlockPalette(workspace, {
94
+ surface, categories, setDetached,
95
+ read(id) {
96
+ show(id);
97
+ const items = [];
98
+ for (const button of flyout.buttons_) {
99
+ if (button.getIsCategoryLabel())
100
+ continue;
101
+ const callback = button.callback_;
102
+ items.push({ label: blocks.utils.replaceMessageReferences(button.getText()), ...(callback && { insert() {
103
+ if (!placement())
104
+ return;
105
+ surface.ownerDocument.defaultView.focus();
106
+ callback(button);
107
+ } }) });
108
+ }
109
+ for (const block of flyout.workspace_.getTopBlocks(true)) {
110
+ const original = block.getSvgRoot();
111
+ const { x, y, width, height } = original.getBBox();
112
+ if (!width || !height)
113
+ continue;
114
+ const preview = original.ownerDocument.createElementNS(ns, 'svg');
115
+ preview.setAttribute('viewBox', [x, y, width, height].join(' '));
116
+ preview.setAttribute('width', String(width));
117
+ preview.setAttribute('height', String(height));
118
+ const graphic = original.cloneNode(true);
119
+ graphic.removeAttribute('transform');
120
+ preview.append(graphic);
121
+ const xml = blocks.Xml.blockToDom(block, true);
122
+ const label = block.toString();
123
+ items.push({ label, preview, disabled: Boolean(block.disabled), insert(point) {
124
+ const position = placement(point);
125
+ if (!position)
126
+ return;
127
+ const previous = blocks.Events.getGroup();
128
+ blocks.Events.setGroup(true);
129
+ try {
130
+ const inserted = blocks.Xml.domToBlock(xml.cloneNode(true), workspace);
131
+ inserted.moveBy(position.x, position.y);
132
+ }
133
+ finally {
134
+ blocks.Events.setGroup(previous);
135
+ }
136
+ } });
137
+ }
138
+ return items;
139
+ },
140
+ subscribe(refresh) {
141
+ const observer = new win.MutationObserver(refresh);
142
+ observer.observe(menu, { childList: true, subtree: true, characterData: true });
143
+ const onChange = event => {
144
+ if (event.type?.startsWith('var_'))
145
+ refresh();
146
+ };
147
+ workspace.addChangeListener(onChange);
148
+ return () => {
149
+ observer.disconnect();
150
+ workspace.removeChangeListener(onChange);
151
+ };
152
+ }
153
+ });
154
+ }
155
+ export function installGestureOwnerDocument(blocks) {
156
+ const prototype = blocks.Gesture.prototype;
157
+ const bind = prototype.bindMouseEvents;
158
+ prototype.bindMouseEvents = function (event) {
159
+ const inputDocument = event.target?.ownerDocument;
160
+ bind.call(this, event);
161
+ if (!inputDocument || inputDocument === document)
162
+ return;
163
+ // Move the registered handlers so Blockly's gesture cleanup still owns them.
164
+ for (const binding of [...this.onMoveWrapper_, ...this.onUpWrapper_]) {
165
+ const [node, type, handler] = binding;
166
+ node.removeEventListener(type, handler, false);
167
+ inputDocument.addEventListener(type, handler, { passive: false });
168
+ binding[0] = inputDocument;
169
+ }
170
+ };
171
+ const dragger = blocks.BlockDragger.prototype;
172
+ const start = dragger.startBlockDrag;
173
+ const dispose = dragger.dispose;
174
+ const inlineDrags = new WeakSet();
175
+ dragger.startBlockDrag = function (...args) {
176
+ const block = this.draggingBlock_;
177
+ if (block.useDragSurface_ && block.getSvgRoot().ownerDocument !== document) {
178
+ // The optimized drag surface looks up its injection container in the opener.
179
+ block.useDragSurface_ = false;
180
+ inlineDrags.add(this);
181
+ }
182
+ return start.apply(this, args);
183
+ };
184
+ dragger.dispose = function () {
185
+ if (inlineDrags.delete(this))
186
+ this.draggingBlock_.useDragSurface_ = true;
187
+ return dispose.call(this);
188
+ };
189
+ }
190
+ export function moveBlockWidgets(blocks, target) {
191
+ const widgets = [blocks.WidgetDiv.DIV, blocks.DropDownDiv.DIV, blocks.Tooltip.DIV]
192
+ .filter(widget => widget && widget.ownerDocument !== target);
193
+ if (!widgets.length)
194
+ return;
195
+ blocks.hideChaff();
196
+ target.body.append(...widgets);
197
+ }
@@ -0,0 +1,45 @@
1
+ type Reference = {
2
+ providerId: string;
3
+ documentId: string;
4
+ };
5
+ type Asset = {
6
+ assetId: string;
7
+ name: string;
8
+ dataFormat: string;
9
+ rotationCenterX?: number;
10
+ rotationCenterY?: number;
11
+ bitmapResolution?: number;
12
+ format?: string;
13
+ rate?: number;
14
+ sampleCount?: number;
15
+ };
16
+ type Target = {
17
+ id: string;
18
+ isOriginal: boolean;
19
+ extensionStorage?: unknown;
20
+ toJSON(): {
21
+ costume: unknown;
22
+ costumes: Asset[];
23
+ sounds: Asset[];
24
+ };
25
+ };
26
+ type TabSubject = {
27
+ target?: Target;
28
+ document?: Reference;
29
+ };
30
+ type Project = {
31
+ runtime: {
32
+ targets: Target[];
33
+ on(event: 'PROJECT_LOADED', listener: () => void): void;
34
+ removeListener(event: 'PROJECT_LOADED', listener: () => void): void;
35
+ };
36
+ on(event: string, listener: () => void): void;
37
+ removeListener(event: string, listener: () => void): void;
38
+ };
39
+ export declare const documentEditEvent = "tw-plus-document-edit-state";
40
+ export declare function mountDockviewUnsaved(vm: Project, root: HTMLElement, locale: string): {
41
+ tab(element: HTMLElement, subject: () => TabSubject): () => void;
42
+ document(element: HTMLElement, reference: Reference): () => void;
43
+ dispose(): void;
44
+ };
45
+ export {};
@@ -0,0 +1,123 @@
1
+ export const documentEditEvent = 'tw-plus-document-edit-state';
2
+ const documentKey = ({ providerId, documentId }) => JSON.stringify([providerId, documentId]);
3
+ function targetSnapshot(target) {
4
+ // Use the VM's target model without invoking project serialization or copying asset bytes.
5
+ const { costume: _current, costumes, sounds, ...properties } = target.toJSON();
6
+ const assets = costumes.map(({ assetId, name, dataFormat, rotationCenterX, rotationCenterY, bitmapResolution }) => [assetId, name, dataFormat, rotationCenterX, rotationCenterY, bitmapResolution]);
7
+ const audio = sounds.map(({ assetId, name, dataFormat, format, rate, sampleCount }) => [assetId, name, dataFormat, format, rate, sampleCount]);
8
+ return JSON.stringify([properties, assets, audio, target.extensionStorage]);
9
+ }
10
+ export function mountDockviewUnsaved(vm, root, locale) {
11
+ const document = root.ownerDocument;
12
+ const window = document.defaultView;
13
+ const store = window.ReduxStore;
14
+ if (!store)
15
+ return;
16
+ const label = locale.startsWith('ja') ? '未保存の変更' : 'Unsaved changes';
17
+ const tabs = new Set();
18
+ const applied = new Set();
19
+ const drafts = new Set();
20
+ function snapshot() {
21
+ return new Map(vm.runtime.targets.filter(target => target.isOriginal).map(target => [target.id, targetSnapshot(target)]));
22
+ }
23
+ let baseline = snapshot();
24
+ let current = baseline;
25
+ let frame;
26
+ let dirty = store.getState().scratchGui.projectChanged;
27
+ const refreshTabs = () => tabs.forEach(refresh => refresh());
28
+ const update = () => {
29
+ frame = undefined;
30
+ current = snapshot();
31
+ refreshTabs();
32
+ };
33
+ const schedule = () => {
34
+ frame ??= window.requestAnimationFrame(update);
35
+ };
36
+ const resetBaseline = () => {
37
+ if (frame !== undefined)
38
+ window.cancelAnimationFrame(frame);
39
+ frame = undefined;
40
+ baseline = current = snapshot();
41
+ applied.clear();
42
+ refreshTabs();
43
+ };
44
+ const loaded = () => {
45
+ drafts.clear();
46
+ resetBaseline();
47
+ };
48
+ const unsubscribe = store.subscribe(() => {
49
+ const next = store.getState().scratchGui.projectChanged;
50
+ if (dirty === next)
51
+ return;
52
+ dirty = next;
53
+ if (dirty)
54
+ schedule();
55
+ else
56
+ resetBaseline();
57
+ });
58
+ vm.on('PROJECT_CHANGED', schedule);
59
+ vm.runtime.on('PROJECT_LOADED', loaded);
60
+ // Some hosts create the workbench before installing their default project.
61
+ const initialTargets = () => {
62
+ if (!dirty && !baseline.size && vm.runtime.targets.length)
63
+ resetBaseline();
64
+ };
65
+ vm.on('targetsUpdate', initialTargets);
66
+ return {
67
+ tab(element, subject) {
68
+ const title = element.querySelector('.dv-default-tab-content');
69
+ const marker = document.createElement('span');
70
+ marker.dataset.twPlusUnsavedMarker = '';
71
+ marker.dataset.twPlusUnsavedTab = '';
72
+ marker.setAttribute('aria-hidden', 'true');
73
+ marker.title = label;
74
+ marker.hidden = true;
75
+ title?.after(marker);
76
+ const refresh = () => {
77
+ const { target, document: reference } = subject();
78
+ const key = reference && documentKey(reference);
79
+ const changed = target && dirty && baseline.get(target.id) !== current.get(target.id) ||
80
+ key && (drafts.has(key) || applied.has(key));
81
+ marker.hidden = !changed;
82
+ const tab = element.closest('[role="tab"]');
83
+ if (changed)
84
+ tab?.setAttribute('aria-description', label);
85
+ else
86
+ tab?.removeAttribute('aria-description');
87
+ };
88
+ tabs.add(refresh);
89
+ refresh();
90
+ // Dockview sets up the renderer before inserting it into its tab element.
91
+ queueMicrotask(() => { if (tabs.has(refresh))
92
+ refresh(); });
93
+ return () => { tabs.delete(refresh); };
94
+ },
95
+ document(element, reference) {
96
+ const key = documentKey(reference);
97
+ const changed = (event) => {
98
+ if (event.detail.draft)
99
+ drafts.add(key);
100
+ else
101
+ drafts.delete(key);
102
+ if (event.detail.applied)
103
+ applied.add(key);
104
+ refreshTabs();
105
+ };
106
+ element.addEventListener(documentEditEvent, changed);
107
+ return () => {
108
+ element.removeEventListener(documentEditEvent, changed);
109
+ if (drafts.delete(key))
110
+ refreshTabs();
111
+ };
112
+ },
113
+ dispose() {
114
+ if (frame !== undefined)
115
+ window.cancelAnimationFrame(frame);
116
+ unsubscribe();
117
+ vm.removeListener('PROJECT_CHANGED', schedule);
118
+ vm.runtime.removeListener('PROJECT_LOADED', loaded);
119
+ vm.removeListener('targetsUpdate', initialTargets);
120
+ tabs.clear();
121
+ }
122
+ };
123
+ }
@@ -0,0 +1,57 @@
1
+ interface CommentData {
2
+ id: string;
3
+ blockId: string | null;
4
+ text: string;
5
+ x: number;
6
+ y: number;
7
+ width: number;
8
+ height: number;
9
+ minimized: boolean;
10
+ }
11
+ export interface CodeTarget {
12
+ isStage: boolean;
13
+ blocks: {
14
+ _blocks: Record<string, unknown>;
15
+ _scripts: string[];
16
+ getScripts(): string[];
17
+ resetCache(): void;
18
+ emitProjectChanged(): void;
19
+ toXML(comments: Record<string, CommentData>): string;
20
+ };
21
+ comments: Record<string, CommentData & {
22
+ toXML(): string;
23
+ }>;
24
+ variables: Record<string, {
25
+ name?: string;
26
+ type?: string;
27
+ toXML(local?: boolean): string;
28
+ }>;
29
+ createComment(id: string, blockId: string | null, text: string, x: number, y: number, width: number, height: number, minimized: boolean): void;
30
+ }
31
+ export declare const capture: (target: CodeTarget) => {
32
+ blocks: Record<string, unknown>;
33
+ scripts: string[];
34
+ comments: Record<string, CommentData & {
35
+ toXML(): string;
36
+ }>;
37
+ };
38
+ export declare function restore(target: CodeTarget, snapshot: ReturnType<typeof capture>): void;
39
+ type BroadcastStage = Pick<CodeTarget, 'variables'> & {
40
+ createVariable(id: string, name: string, type: 'broadcast_msg', isCloud: false): void;
41
+ };
42
+ export declare function createHistory(target: CodeTarget, stage: BroadcastStage): {
43
+ readonly state: {
44
+ revision: number;
45
+ canUndo: boolean;
46
+ canRedo: boolean;
47
+ };
48
+ commit(): boolean;
49
+ renameSpriteReferences(oldName: string, newName: string): void;
50
+ step(redo: boolean): boolean;
51
+ };
52
+ export declare function workspaceXML(vm: {
53
+ runtime: {
54
+ getTargetForStage(): CodeTarget;
55
+ };
56
+ }, target: CodeTarget): string;
57
+ export {};
@@ -0,0 +1,85 @@
1
+ const historyLimit = 100;
2
+ export const capture = (target) => structuredClone({
3
+ blocks: target.blocks._blocks,
4
+ scripts: target.blocks.getScripts(),
5
+ comments: target.comments
6
+ });
7
+ export function restore(target, snapshot) {
8
+ const { blocks, scripts, comments } = structuredClone(snapshot);
9
+ // Keep the live Blocks container, which also belongs to any clones of the sprite.
10
+ target.blocks._blocks = Object.assign(Object.create(null), blocks);
11
+ target.blocks._scripts = scripts;
12
+ // Recreate VM Comment instances so projections and SB3 retain attached and workspace comments.
13
+ target.comments = Object.create(null);
14
+ for (const { id, blockId, text, x, y, width, height, minimized } of Object.values(comments)) {
15
+ target.createComment(id, blockId, text, x, y, width, height, minimized);
16
+ }
17
+ target.blocks.resetCache();
18
+ target.blocks.emitProjectChanged();
19
+ }
20
+ export function createHistory(target, stage) {
21
+ const captureRevision = () => {
22
+ const snapshot = capture(target);
23
+ const messages = new Map();
24
+ for (const block of Object.values(snapshot.blocks)) {
25
+ const id = block.fields?.BROADCAST_OPTION?.id;
26
+ const message = id && stage.variables[id];
27
+ if (message?.type === 'broadcast_msg' && typeof message.name === 'string')
28
+ messages.set(id, message.name);
29
+ }
30
+ return { ...snapshot, messages: [...messages] };
31
+ };
32
+ const past = [];
33
+ const future = [];
34
+ let present = captureRevision();
35
+ let revision = 0;
36
+ return {
37
+ get state() { return { revision, canUndo: past.length > 0, canRedo: future.length > 0 }; },
38
+ commit() {
39
+ const next = captureRevision();
40
+ if (JSON.stringify(next) === JSON.stringify(present))
41
+ return false;
42
+ past.push(present);
43
+ if (past.length > historyLimit)
44
+ past.shift();
45
+ present = next;
46
+ future.length = 0;
47
+ revision++;
48
+ return true;
49
+ },
50
+ renameSpriteReferences(oldName, newName) {
51
+ // Use the pinned VM's field rules for snapshots without touching the live block cache.
52
+ const blocks = Object.create(target.blocks);
53
+ blocks.resetCache = () => { };
54
+ for (const snapshot of [...past, present, ...future]) {
55
+ blocks._blocks = snapshot.blocks;
56
+ blocks.updateAssetName(oldName, newName, 'sprite');
57
+ }
58
+ },
59
+ step(redo) {
60
+ const next = (redo ? future : past).pop();
61
+ if (!next)
62
+ return false;
63
+ (redo ? past : future).push(present);
64
+ present = next;
65
+ // The VM prunes unused broadcast IDs on workspace refresh.
66
+ // Restore messages that were still registered in this revision.
67
+ for (const [id, name] of present.messages) {
68
+ if (!Object.hasOwn(stage.variables, id))
69
+ stage.createVariable(id, name, 'broadcast_msg', false);
70
+ }
71
+ restore(target, present);
72
+ revision++;
73
+ return true;
74
+ }
75
+ };
76
+ }
77
+ export function workspaceXML(vm, target) {
78
+ const stage = vm.runtime.getTargetForStage();
79
+ const globals = Object.values(stage.variables).map(variable => variable.toXML());
80
+ const locals = target.isStage ? [] : Object.values(target.variables).map(variable => variable.toXML(true));
81
+ const comments = Object.values(target.comments).filter(comment => comment.blockId === null)
82
+ .map(comment => comment.toXML());
83
+ return `<xml xmlns="http://www.w3.org/1999/xhtml"><variables>${globals.join('')}${locals.join('')}</variables>` +
84
+ `${comments.join('')}${target.blocks.toXML(target.comments)}</xml>`;
85
+ }
@@ -0,0 +1,28 @@
1
+ export { attachDockedCodeExtensions } from './code-extensions.ts';
2
+ export type { NativeFieldEditSession } from './native-extension-field.ts';
3
+ export type { FieldActionPanel, ProgrammaticExtensionField } from './programmatic-extension-field.ts';
4
+ export { encodeEdit } from './protocol.ts';
5
+ export declare function refreshExternalBlockViews(vm: any, targets: any): void;
6
+ export declare function createCodeSession({ vm, workspace, ScratchBlocks, document, locale, canUse, onError, receiveBackpackDrop }: {
7
+ vm: any;
8
+ workspace: any;
9
+ ScratchBlocks: any;
10
+ document: any;
11
+ locale: any;
12
+ canUse: any;
13
+ onError: any;
14
+ receiveBackpackDrop: any;
15
+ }): {
16
+ attach: ({ target, mount, port, close, duplicate, layoutMenu }: {
17
+ target: any;
18
+ mount: any;
19
+ port: any;
20
+ close: any;
21
+ duplicate: any;
22
+ layoutMenu: any;
23
+ }) => () => void;
24
+ flush: () => Promise<void>;
25
+ setCanDuplicate(available: any): void;
26
+ dispose(): void;
27
+ };
28
+ export { attachStageCodePrewarm } from './stage-code-prewarm.ts';