-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathcomponent-browser.cp.js
More file actions
1935 lines (1800 loc) · 60.2 KB
/
component-browser.cp.js
File metadata and controls
1935 lines (1800 loc) · 60.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { pt, Color, rect } from 'lively.graphics';
import { TilingLayout, morph, config, easings, MorphicDB, Icon, Morph, Label, ShadowObject, ViewModel, add, part, component } from 'lively.morphic';
import { Project } from 'lively.project';
import { isModuleLoaded, module } from 'lively.modules';
import { InputLineDefault } from 'lively.components/inputs.cp.js';
import { MullerColumnView, ColumnListDark, ColumnListDefault } from 'lively.components/muller-columns.cp.js';
import { TreeData, LabeledCheckbox, LabeledCheckboxLight } from 'lively.components';
import { arr, promise, num, date, string, fun } from 'lively.lang';
import { resource } from 'lively.resources';
import { renderMorphToDataURI } from 'lively.morphic/rendering/morph-to-image.js';
import { localInterface } from 'lively-system-interface';
import { once, noUpdate } from 'lively.bindings/index.js';
import { adoptObject } from 'lively.lang/object.js';
import { DropDownList, DarkDropDownList } from 'lively.components/list.cp.js';
import { withAllViewModelsDo } from 'lively.morphic/components/policy.js';
import { ButtonDarkDefault, SystemButton } from 'lively.components/buttons.cp.js';
import { Text } from 'lively.morphic/text/morph.js';
import { COLORS } from '../js/browser/index.js';
import { Spinner, DarkPopupWindow } from './shared.cp.js';
import { InteractiveComponentDescriptor } from '../components/editor.js';
import { PopupWindow, SystemList } from '../styling/shared.cp.js';
import { joinPath } from 'lively.lang/string.js';
import { runCommand } from 'lively.shell/client-command.js';
import ShellClientResource from 'lively.shell/client-resource.js';
import { StatusMessageError, StatusMessageConfirm } from 'lively.halos/components/messages.cp.js';
import { unsubscribe, subscribe } from 'lively.notifications/index.js';
class MasterComponentTreeData extends TreeData {
/**
* Create a tree data object listing master component files.
* @param { object } props
* @property { ComponentBrowserModel } props.browser - Reference to the component browser view model.
*/
constructor (props) {
super(props);
this.ensurePopularComponentsCollection();
}
isCollapsed ({ isCollapsed }) { return isCollapsed; }
async collapse (node, bool) {
if (node === this.root) {
bool = false; // never collapse root
node.subNodes = await this.listAllComponentCollections();
}
if (!bool && node.type === 'package loader') {
// clear the selection
this.columnView.reset();
this.interactivelyImportProject();
return;
}
node.isCollapsed = bool;
node.isDirty = true;
if (!bool) {
const loadedFiles = await this.getLoadedComponentFileUrls();
if (node.type === 'package') {
node.subNodes = await this.listComponentFilesInPackage(node.url, loadedFiles);
}
if (node.children) {
node.children.forEach(child => {
child.isDeclaration = true;
child.isCollapsed = true;
child.parent = node;
});
node.subNodes = node.children;
}
if (node.type === 'directory') {
node.subNodes = await this.listComponentFilesInDir(node.url, loadedFiles);
}
if (node.type === 'cp.js') {
node.subNodes = await this.listModuleScope(node.url);
}
}
}
getChildren (parent) {
let { subNodes } = parent;
let result = subNodes || [];
result && result.forEach(n => this.parentMap.set(n, parent));
return result;
}
isLeaf ({ type, isDeclaration, children }) {
if (isDeclaration) return !children;
return !['package', 'directory', 'cp.js'].includes(type);
}
display (node) {
const { type, pkg, isCollapsed, componentObject, lastModified, size, name, url } = node;
const isSelected = this.columnView.isSelected(node);
if (type === 'package') {
return this.displayPackage(pkg, isSelected);
} else if (type === 'package loader') {
return this.renderPackageLoader();
} else if (componentObject) {
return this.displayComponent(componentObject, isSelected);
} else {
let col1Size = 19;
let datePrinted = lastModified
? date.format(lastModified, 'yyyy-mm-dd HH:MM:ss')
: ' '.repeat(col1Size);
let sizePrinted = size ? num.humanReadableByteSize(size) : '';
let displayedName;
switch (type) {
case 'cp.js':
if (!node.isLoaded && isSelected) node.isLoaded = true;
displayedName = this.displayComponentFile(name, isSelected, node.isLoaded, url);
break;
case 'directory':
displayedName = this.displayDirectory(name, !isCollapsed);
break;
}
return [
...displayedName,
`\t${sizePrinted} ${datePrinted}`, {
paddingTop: '3px',
opacity: 0.5,
fontSize: '70%',
textStyleClasses: ['annotation']
}
];
}
}
renderPackageLoader () {
return [...Icon.textAttribute('ti-square-rounded-arrow-right', { fontColor: Color.darkGray }), ' Import project...', {
fontColor: Color.darkGray,
fontWeight: 'bold',
fontStyle: 'italic',
nativeCursor: 'pointer'
}];
}
/**
* @returns { Morph } - The visual representation of the muller columns view presenting this data.
*/
get columnView () { return this.root.browser.models.componentFilesView; }
/**
* @returns { LivelySystemInterface } - Returns the local interface to be used to resolve the modules (client only)
*/
get systemInterface () { return localInterface; }
/**
* Returns the text attributes needed to display an entry of the list covering the
* components contained in the currently openend component file.
* @param { Object } componentDecl - The code entity representing the declaration of the component.
*/
displayComponent (componentObj, isSelected) {
if (isSelected && !this.root.browser._pauseUpdates) {
this.root.browser.selectComponent(componentObj, true);
}
return [...Icon.textAttribute('cube'), ' ' + string.truncate(componentObj.componentName || '[PARSE_ERROR]', 18, '…'), null];
}
/**
* Returns the text attributes needed to display a package that contains a collection
* of component files.
*/
displayPackage (pkg, isSelected) {
if (isSelected && !this.root.browser._pauseUpdates) {
this.root.browser.reset(false);
}
const isOpenedProject = pkg.url === $world.openedProject?.package.url;
return [
...Icon.textAttribute('cubes'),
' ' + string.truncate(pkg.name, 26, '…'), {
fontWeight: isOpenedProject ? 'bold' : 'normal',
fontStyle: pkg.kind === 'git' && !isOpenedProject ? 'italic' : 'normal'
},
`\t${pkg.kind}`, {
paddingTop: '3px',
opacity: 0.5,
fontSize: '70%',
textStyleClasses: ['annotation']
}
];
}
/**
* Returns the text attributes needed to display a directory that contains a collection
* of component files.
* @param { String } dir - The name of the directory.
* @param { Boolean } isOpen - Wether or not the directory is currently opened.
*/
displayDirectory (dir, isOpen) {
if (isOpen && !this.root.browser._pauseUpdates) {
this.root.browser.reset(false);
}
return [
...Icon.textAttribute(isOpen ? 'folder-open' : 'folder', {
fontWeight: '400'
}),
' ' + dir, null
];
}
/**
* Returns the text attributes needed to display an entry that represents a component file.
*/
displayComponentFile (modUrl, isSelected, isLoaded, url) {
if (isSelected && !this.root.browser._pauseUpdates) {
const mod = module(url);
const pkg = mod.package();
const isOpenedProject = pkg && pkg.url === $world.openedProject?.package.url;
modUrl = arr.last(modUrl.split('--'));
this.getComponentsInModule(url).then(components => {
this.root.browser.showComponentsInFile(modUrl, components, isOpenedProject);
});
}
return [
...Icon.textAttribute('shapes', {
fontColor: isSelected ? Color.white : COLORS.cp,
opacity: isLoaded ? 1 : 0.5
}),
' ' + string.truncate(modUrl.replace('.cp.js', ''), 24, '…'), null
];
}
async getComponentsInModule (moduleName) {
return await this.root.browser.getComponentsInModule(moduleName);
}
async listModuleScope (moduleName) {
const exportedComponents = await this.getComponentsInModule(moduleName);
return exportedComponents.map(componentObject => {
return {
isCollapsed: true,
isDeclaration: true,
componentObject
};
});
}
async interactivelyImportProject () {
const availableProjects = await Project.listAvailableProjects();
const notLoaded = availableProjects
.filter(proj => !isModuleLoaded(joinPath(proj.url, proj.main || 'index.js')))
.map(proj => ({
isListItem: true,
value: proj,
tooltip: `${proj.name} by ${proj.projectRepoOwner} at version ${proj.version}`,
label: [
proj.name, {},
proj.version, {
paddingLeft: '5px',
fontSize: '70%',
textStyleClasses: ['truncated-text', 'annotation']
}
]
}));
const win = this.root.browser.view.getWindow();
const { selected: [projectToLoad] } = await $world.filterableListPrompt('Select project to import', notLoaded, {
requester: win,
multiSelect: false
});
if (projectToLoad) {
await $world.withLoadingIndicatorDo(async () => {
await Project.loadProject(projectToLoad.name, true);
this.root.subNodes = await this.listAllComponentCollections();
this.columnView.refresh();
}, win, 'Importing project...');
}
}
/**
* Returns all the custom project inside the lively.next projects folder
* that may contain custom component definitions.
* @todo Implement this feature.
*/
async getCustomLocalProjects () {
return (await Project.listAvailableProjects()).filter(({ main = 'index.js', url }) => {
return isModuleLoaded(joinPath(url, main));
});
}
/**
* Initializes a local folder comprising a set of "popular" component files such as
* buttons, input fields or lists.
*/
async ensurePopularComponentsCollection () {
const res = resource('local://VeryPopularComponents');
['buttons', 'list', 'inputs'].map(async name => {
res.join(name + '.cp.js').write('redirect -> ' + await System.decanonicalize(`lively.components/${name}.cp.js`));
});
['value-widgets', 'styling/color-picker'].map(async name => {
res.join(name + '.cp.js').write('redirect -> ' + await System.decanonicalize(`lively.ide/${name}.cp.js`));
});
}
async getComponentCollections () {
return [
...await Promise.all(['lively.ide', 'lively.components'].map(pkgName => this.systemInterface.getPackage(pkgName))),
...await this.getCustomLocalProjects(),
{ name: 'Popular', url: 'local://VeryPopularComponents' }
];
}
async listAllComponentCollections () {
let coll = await this.getComponentCollections();
coll = arr.sortBy(coll.map(pkg => {
let kind = 'git';
if (pkg.url?.startsWith('local')) kind = 'local';
if (pkg.name.startsWith('lively')) kind = 'core';
pkg.kind = kind;
return {
url: pkg.url + (pkg.url.endsWith('/') ? '' : '/'),
isCollapsed: true,
type: 'package',
name: pkg.name,
tooltip: pkg.name,
pkg
};
}), ({ pkg }) => ({ core: 2, local: 1, git: 3 }[pkg.kind]));
if (!this.root.browser.selectionMode) {
coll.push({
type: 'package loader',
isCollapsed: true,
tooltip: 'Import additional project'
});
}
return coll;
}
async listComponentFilesInPackage (pkg, loadedFiles) {
return await this.listComponentFilesInDir(pkg, loadedFiles);
}
async getLoadedComponentFileUrls () {
const selectedPkg = this.root.subNodes.find(pkg => !pkg.isCollapsed);
if (!selectedPkg) return {};
const files = await resource(selectedPkg.url).dirList('infinity', {
exclude: (res) => {
if (res.url.match(/\.git|\.gitignore|.github|assets|build/)) return true;
return !(res.url.endsWith('.cp.js') || res.isDirectory() || !module(res.url).isLoaded());
}
});
if (selectedPkg.name !== 'Popular') {
// ensure the package is present in the system
// so that we do not get any orphaned modules...
await this.systemInterface.getPackage(selectedPkg.url);
}
const loadedModules = {};
files.forEach(file => {
loadedModules[file.url] = file;
});
return loadedModules;
}
async listComponentFilesInDir (folderLocation, loadedFiles) {
if (!loadedFiles) loadedFiles = await this.getLoadedComponentFileUrls();
const resources = (await resource(folderLocation).dirList(1, {
exclude: (res) => {
if (res.name() === 'assets' || res.name() === 'tests' || res.name() === 'node_modules') return true;
return !((res.url.endsWith('.cp.js') || res.isDirectory()) && !res.name().startsWith('.'));
}
}));
// ensure that the package is loaded at this point
// ensure that we only list folders who will in turn have anything to show
const files = arr.compact(await Promise.all(resources.map(async res => {
let type;
if (res.isDirectory()) {
type = 'directory';
if ((await this.listComponentFilesInDir(res.url, loadedFiles)).length === 0) return;
} else {
type = 'cp.js';
if ((await res.read()).match(/['"]skip listing['"];/)) return;
if (res.url.endsWith('.cp.js') && (await this.getComponentsInModule(res.url)).length === 0) return;
}
return {
isDirty: true, // ensure proper rendering
isCollapsed: true,
name: res.name(),
size: res.size,
lastModified: res.lastModified,
url: res.url,
type
};
})));
return files.map(file => {
file.isLoaded = !!loadedFiles[file.url];
return file;
});
}
}
export class ExportedComponent extends Morph {
static get properties () {
return {
project: {},
componentBrowser: {
derived: true,
get () {
return this.ownerChain().find(m => m.isComponentBrowser);
}
},
dragTriggerDistance: {
get () { return 30; }
},
fetchUrl: {
after: ['submorphs'],
set (url) {
this.setProperty('fetchUrl', url);
this.updateLabel();
}
},
isSelected: {},
isInOpenedProject: {
derived: true,
readOnly: true,
get () {
return $world.openedProject?.package.url === this.package.url;
}
},
package: {
get () {
return module(this.component[Symbol.for('lively-module-meta')].moduleId).package();
}
},
preview: {
derived: true,
set (url) {
this.getSubmorphNamed('preview holder').imageUrl = url;
this.fitPreview();
}
},
component: {
set (cp) {
this.setProperty('component', cp);
this.generatePreview();
}
}
};
}
generatePreview () {
try {
const preview = part(this.component, { defaultViewModel: null, name: this.component.componentName });
const container = this.get('preview container');
const maxExtent = pt(100, 70);
const padding = -10;
preview.scale = 1;
// This is needed since the centering via css layouts gets currently quite
// confused when transforms are applied (scale, rotation)
const previewBoundsWrapper = morph({ fill: Color.transparent, reactsToPointer: false, extent: preview.bounds().extent(), submorphs: [preview] });
preview.topLeft = pt(0, 0);
previewBoundsWrapper.scale = Math.min(
maxExtent.x / (previewBoundsWrapper.bounds().width - padding),
maxExtent.y / (previewBoundsWrapper.bounds().height - padding));
container.submorphs = [previewBoundsWrapper];
preview.withAllSubmorphsDo(m => m.reactsToPointer = false);
} catch (err) {
this.displayError(err);
}
this.get('component name').textString = string.decamelize(this.component.componentName);
}
displayError (err) {
this.get('preview container').submorphs = [
part(ComponentError, { submorphs: [{ name: 'error message', textString: err.message }] }) // eslint-disable-line no-use-before-define
];
}
async initExportIndicatorIfNeeded () {
if (this.fetchUrl.startsWith('part://$world/')) {
const exportIndicator = this.addMorph(
this.getSubmorphNamed('export indicator') ||
await resource('part://SystemDialogs/export indicator').read()
);
exportIndicator.name = 'export indicator';
exportIndicator.fetchUrl = this.fetchUrl;
exportIndicator.isLayoutable = false;
return exportIndicator;
}
}
async fitPreview () {
const img = this.getSubmorphNamed('preview holder');
if (!this.world()) img.opacity = 0;
await this.master.whenApplied();
const naturalExtent = await img.determineNaturalExtent();
// scale the preview down to fit into width and height;
const maxWidth = 130;
const maxHeight = 130;
const scaleFactor = Math.min(maxWidth / naturalExtent.x, maxHeight / naturalExtent.y);
img.extent = naturalExtent.scaleBy(scaleFactor);
img.opacity = 1;
const exportIndicator = this.getSubmorphNamed('export indicator') || await this.initExportIndicatorIfNeeded();
if (!exportIndicator) {
return;
}
// ensure the layout has applied itself already...
exportIndicator.topRight = this.innerBounds().insetBy(2).topRight();
}
updateLabel () {
const nameLabel = this.getSubmorphNamed('component name');
nameLabel.value = resource(this.fetchUrl).url.replace(/part:\/\/[^\/]*\//, '');
this.tooltip = this.fetchUrl;
}
onMouseDown (evt) {
super.onMouseDown(evt);
// this is pretty bad style
if (this.project) {
this.project.selectComponent(this);
// notify the column view to update accordingly if active...
}
}
onDrag (evt) {
if (!this.component) return;
const [{ scale }] = this.getSubmorphNamed('preview container').submorphs;
const instance = part(this.component, { scale });
if (!this.componentBrowser.importAlive) {
// disable the behavior
withAllViewModelsDo(instance, m => m.viewModel.detach());
}
// on drop scale to 1
instance.openInHand();
const grabShadow = new ShadowObject({ fast: false, color: Color.rgba(0, 0, 0, 0.6), blur: 40 });
instance.animate({
scale: 1,
center: instance.center,
dropShadow: grabShadow,
duration: 300
});
once(instance, 'onBeingDroppedOn', async (hand) => {
if (this.componentBrowser.globalBounds().containsPoint(hand.position)) {
instance.openInWorld(hand.position);
await instance.animate({ center: this.globalBounds().center(), opacity: 0, duration: 300 });
instance.remove();
}
});
}
select (active) {
this.isSelected = active;
this.master.setState(active ? 'selected' : null);
}
}
export class ProjectEntry extends Morph {
static get properties () {
return {
exportedComponents: {
derived: true,
get () {
return this.getSubmorphNamed('component previews').submorphs.map(m => m.component);
}
},
selectedComponent: {
derived: true,
get () {
const selectedPreview = this.getSubmorphNamed('component previews').submorphs.find(m => m.isSelected);
return selectedPreview && selectedPreview.component;
}
},
previewMaster: {
isComponent: true,
initialize () {
this.previewMaster = ComponentPreview; // eslint-disable-line no-use-before-define
}
},
selectedPreviewMaster: {
isComponent: true,
initialize () {
this.selectedPreviewMaster = ComponentPreviewSelected; // eslint-disable-line no-use-before-define
}
},
worldName: {
derived: true,
set (name) {
this.getSubmorphNamed('project title').value = [name, {}, ' ', {}].concat(name === 'This Project' ? [] : Icon.textAttribute('external-link-square-alt', { paddingTop: '3px' }));
},
// this.worldName
get () {
return this.getSubmorphNamed('project title').value[0];
}
}
};
}
onMouseUp (evt) {
super.onMouseUp(evt);
if (this._navigationDisabled) return;
const projectTitle = this.getSubmorphNamed('project title');
if (projectTitle.textBounds().containsPoint(evt.positionIn(projectTitle))) { this.openComponentWorld(); }
}
async openComponentWorld () {
const selectedComponent = this.selectedComponent || this.exportedComponents[0];
const { moduleId: moduleName, exportedName: name } = selectedComponent[Symbol.for('lively-module-meta')];
await $world.execCommand('open browser', { moduleName, codeEntity: [{ name }] });
}
renderComponents (components) {
const previewContainer = this.getSubmorphNamed('component previews');
previewContainer.submorphs = components.map(cp => {
let preview = previewContainer.submorphs.find(p => p.component === cp);
if (!preview) {
preview = part(this.previewMaster, {
master: {
states: {
selected: this.selectedPreviewMaster
}
}
});
preview.project = this;
preview.component = cp;
}
return preview;
});
return this;
}
selectComponent (component) {
this.owner.getSubmorphsByStyleClassName('ExportedComponent').forEach(m => m.select(false));
component.select(true);
}
disableNavigation () {
this._navigationDisabled = true;
this.getSubmorphNamed('project title').nativeCursor = 'auto';
this.getSubmorphNamed('project title').value = [this.worldName, {}];
}
}
export class NameSection extends ProjectEntry {
static get properties () {
return {
char: {
derived: true,
set (name) {
this.getSubmorphNamed('project title').value = [name, null];
},
get () {
return this.getSubmorphNamed('project title').value[0];
}
}
};
}
}
export class ExportIndicator extends Morph {
static get properties () {
return {
fetchUrl: {
set (url) {
this.setProperty('fetchUrl', url.replace('part://$world/', ''));
this.exported = this.isExported(this.fetchUrl);
}
},
exported: {
after: ['submorphs'],
set (isExported) {
this.setProperty('exported', isExported);
this.updateStyle();
}
},
ui: {
get () {
return {
publicIndicator: this.getSubmorphNamed('public indicator'),
privateIndicator: this.getSubmorphNamed('private indicator')
};
}
}
};
}
updateStyle () {
const { publicIndicator, privateIndicator } = this.ui;
publicIndicator.isLayoutable = publicIndicator.visible = this.exported;
privateIndicator.isLayoutable = privateIndicator.visible = !this.exported;
}
onMouseDown (evt) {
super.onMouseDown(evt);
this.toggleExport();
}
isExported (url) {
return !$world.hiddenComponents.includes(url);
}
toggleExport () {
this.exported = !this.exported;
if (this.exported) {
this.exportComponent();
} else {
this.hideComponent();
}
}
exportComponent () {
$world.hiddenComponents = arr.without($world.hiddenComponents, this.fetchUrl);
}
hideComponent () {
$world.hiddenComponents = [this.fetchUrl, ...$world.hiddenComponents];
}
}
const SearchComponentsNotice = component({
extent: pt(663.7, 592.1),
layout: new TilingLayout({
axis: 'column',
axisAlign: 'center',
orderByIndex: true
}),
fill: Color.rgba(255, 255, 255, 0),
submorphs: [
{
type: Text,
name: 'component box',
extent: pt(164, 231),
dropShadow: new ShadowObject({ color: Color.rgba(0, 0, 0, 0.16), blur: 15, fast: false }),
fontColor: Color.rgba(0, 0, 0, 0.25),
fontSize: 164,
fontWeight: 700,
position: pt(-5, 26),
textAndAttributes: ['', {
fontFamily: 'Tabler Icons',
fontWeight: '900'
}]
}, {
type: 'text',
name: 'notice',
textAlign: 'center',
fixedWidth: true,
fontColor: Color.rgba(0, 0, 0, 0.25),
dropShadow: new ShadowObject({ color: Color.rgba(0, 0, 0, 0.16), blur: 15, fast: false }),
fontSize: 34,
fontWeight: 700,
lineWrapping: 'by-words',
textAndAttributes: ['Begin searching to display components...', null],
extent: pt(354.6, 191)
}]
});
const SearchComponentsNoticeDark = component(SearchComponentsNotice, {
submorphs: [{
name: 'component box',
fontColor: Color.rgba(255, 255, 255, 0.25)
}, {
name: 'notice',
fontColor: Color.rgba(255, 255, 255, 0.25)
}]
});
export class ComponentBrowserModel extends ViewModel {
static get properties () {
return {
isComponentBrowser: {
get () { return true; }
},
sectionMaster: {
initialize () {
this.sectionMaster = ProjectSection; // eslint-disable-line no-use-before-define
}
},
SearchComponentsNotice: {
initialize () { this.SearchComponentsNotice = SearchComponentsNotice; }
},
isPrompt: { get () { return true; } },
isEpiMorph: {
get () { return true; }
},
isHaloItem: { get () { return true; } },
importAlive: {
defaultValue: false
},
selectionMode: {
defaultValue: false
},
groupBy: {
type: 'Enum',
values: ['name', 'module'],
defaultValue: 'module'
},
db: {
serialize: false,
readOnly: true,
get () { return MorphicDB.default; }
},
expose: {
get () {
return ['activate', 'isComponentBrowser', 'reset', 'isEpiMorph', 'close',
'isPrompt', 'isHaloItem', 'onWindowClose', 'menuItems', 'importAlive'];
}
}
};
}
menuItems () {
const checked = Icon.textAttribute('check-square', { paddingRight: '3px' });
const unchecked = Icon.textAttribute('square', { paddingRight: '3px' });
return [
['Import project...', () => {
this.ui.componentFilesView.treeData.interactivelyImportProject();
}],
[[...this.importAlive ? checked : unchecked, ' Enable behavior'], () => this.importAlive = !this.importAlive],
['Group Components by ', [
[[...this.groupBy === 'module' ? checked : unchecked, ' Modules'], () => { this.groupBy = 'module'; }],
[[...this.groupBy === 'name' ? checked : unchecked, ' Names'], () => { this.groupBy = 'name'; }]
]]
];
}
get bindings () {
return [
{
signal: 'onWindowClose',
handler: 'close'
},
{
target: 'import button',
signal: 'fire',
handler: 'importSelectedComponent'
},
{
target: 'selection button',
signal: 'fire',
handler: 'chooseComponent'
},
{ target: 'edit button', signal: 'fire', handler: 'editSelectedComponent' },
{
target: 'search input',
signal: 'inputChanged',
handler: 'filterAllComponents'
},
{
signal: 'onKeyDown',
handler: 'close',
updater: ($reject, evt) => {
if (evt.key === 'Escape') $reject();
}
},
{ signal: 'onMouseDown', handler: 'focus' },
{
target: /component files view|master component list/,
signal: 'onMouseUp',
handler: 'ensureButtonControls'
},
{
target: /component files view|master component list/,
signal: 'onMouseUp',
handler: 'ensureComponentEntitySelected'
},
{
target: 'behavior toggle',
signal: 'checked',
handler: 'toggleBehaviorImport'
}, {
model: 'sorting selector',
signal: 'selection',
handler: 'changeComponentGrouping'
},
{
target: 'search clear button',
signal: 'onMouseDown',
handler: 'resetSearchInput'
}
];
}
focus () { this.view.bringToFront(); }
ensureButtonControls () {
const selectedComponent = this.getSelectedComponent();
this.models.importButton.deactivated = !selectedComponent;
this.models.editButton.deactivated = !selectedComponent || !selectedComponent.isInOpenedProject;
if (this.models.editButton.deactivated) this.ui.editButton.tooltip = 'You can not edit this component, since it is outside of your current project.';
else {
this.ui.editButton.tooltip = 'Click to start editing this component.\nNote that changes to this component will\npropagate throughout your project.';
this.models.selectionButton.deactivated = !selectedComponent;
}
}
viewDidLoad () {
if (!this.view.isComponent) {
this.view.withMetaDo({ metaInteraction: true }, () => {
this.ui.componentFilesView.setTreeData(new MasterComponentTreeData({ browser: this }));
});
}
const openedProject = $world.openedProject;
if (!(openedProject?.owner === 'LivelyKernel' && openedProject?.name === 'partsbin') && !$world._partsbinUpdated) {
const li = $world.showLoadingIndicatorFor(null, 'Updating `partsbin`');
// This relies on the assumption, that the default directory the shell command gets dropped in is `lively.server`.
// `install.sh` ensures that the partsbin repository exists.
// As users should fork the partsbin to contribute, no special precaution is taken here when stashing.
const cmd = runCommand('cd ../local_projects/LivelyKernel--partsbin && git stash && git checkout main && git pull origin main', { l2lClient: ShellClientResource.defaultL2lClient });
cmd.whenDone().then(() => {
if (cmd.exitCode !== 0) {
$world.setStatusMessage('`partsbin` could not be updated.', StatusMessageError);
return;
}
$world.setStatusMessage('`partsbin` updated!', StatusMessageConfirm);
$world._partsbinUpdated = true;
li.remove();
});
}
}
async refresh () {
const selectedModule = this.getSelectedModule();
const { componentFilesView, searchInput } = this.ui;
if (!selectedModule && searchInput.input) {
await componentFilesView.setTreeData(new MasterComponentTreeData({ browser: this }));
this.filterAllComponents();
return;
}
if (selectedModule) {
delete selectedModule.subNodes;
componentFilesView.treeData.collapse(selectedModule, false);
componentFilesView.treeData.display(selectedModule);
}
}
onRefresh (change) {
super.onRefresh(change);
this.ui.behaviorToggle.checked = this.importAlive;
this.handleColumnViewVisibility();
this.ui.editButton.visible = !this.isPopupModel && !this.selectionMode && config.ide.studio.componentEditViaComponentBrowser;
this.ui.behaviorToggle.visible = !this.selectionMode;
this.ui.importButton.visible = !this.selectionMode;
this.ui.selectionButton.visible = this.selectionMode;
noUpdate(() => this.ui.sortingSelector.selection = this.groupBy);
}
handleColumnViewVisibility () {
const { componentFilesView, searchInput } = this.ui;
componentFilesView.visible = false;
if (this.groupBy === 'name') {
// do nothing really
} else if (!searchInput.input) componentFilesView.visible = true;
}
get systemInterface () { return localInterface; }
reset (resetScroll = true) {
this.ui.masterComponentList.submorphs = [];
if (resetScroll) this.ui.componentFilesView.scroll = pt(0, 0);
}
async activate (pos = false) {
this._refreshOnLoaded = subscribe('lively.modules/moduleloaded', () => this.refresh(), System);
this._refreshOnChanged = subscribe('lively.modules/modulechanged', () => this.refresh(), System);
this.ui.editButton.visible = !this.isPopupModel && config.ide.studio.componentEditViaComponentBrowser;
this._promise = promise.deferred();
this.ui.searchInput.focus();
this.ensureButtonControls();
return this._promise.promise;
}
onWindowClose () { this.close(); }
close () {
unsubscribe('lively.modules/moduleloaded', this._refreshOnLoaded, System);
unsubscribe('lively.modules/modulechanged', this._refreshOnChanged, System);
if (this._promise) this._promise.resolve(null);
}
async importSelectedComponent () {
const selectedComponent = this.getSelectedComponent();
const importedComponent = part(selectedComponent.component);
if (!this.importAlive) {
// disable the behavior
withAllViewModelsDo(importedComponent, m => m.viewModel.detach());
}
importedComponent.openInWorld();
importedComponent.world().showHaloFor(importedComponent);
}
chooseComponent () {
this._promise.resolve(this.getSelectedComponent().component);
this.close();
}
async editSelectedComponent () {
const selectedComponent = this.getSelectedComponent();
const editableComponent = await selectedComponent.component.edit();
if (editableComponent) {
editableComponent.applyLayoutIfNeeded();
editableComponent.openInWorld();
}
}
toggleBusyState (active) {