-
Notifications
You must be signed in to change notification settings - Fork 8
/
open-scd.ts
369 lines (332 loc) · 10.4 KB
/
open-scd.ts
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
import { css, html, LitElement, nothing, TemplateResult } from 'lit';
import { customElement, property, query, state } from 'lit/decorators.js';
import { html as staticHtml, unsafeStatic } from 'lit/static-html.js';
import { configureLocalization, localized, msg, str } from '@lit/localize';
import { spread } from '@open-wc/lit-helpers';
import '@material/mwc-button';
import '@material/mwc-dialog';
import '@material/mwc-drawer';
import '@material/mwc-icon';
import '@material/mwc-icon-button';
import '@material/mwc-list';
import '@material/mwc-tab-bar';
import '@material/mwc-top-app-bar-fixed';
import type { ActionDetail } from '@material/mwc-list';
import type { Dialog } from '@material/mwc-dialog';
import type { Drawer } from '@material/mwc-drawer';
import { allLocales, sourceLocale, targetLocales } from './locales.js';
import { isComplex, isInsert, isRemove, isUpdate } from './foundation.js';
import { Editing, LogEntry } from './mixins/Editing.js';
import { Plugging, Plugin, pluginTag } from './mixins/Plugging.js';
export { Plugging } from './mixins/Plugging.js';
export { Editing } from './mixins/Editing.js';
type Control = {
icon: string;
getName: () => string;
isDisabled: () => boolean;
action?: () => unknown;
};
type RenderedPlugin = Control & { tagName: string };
type LocaleTag = typeof allLocales[number];
type PropertyType = string | boolean | number | object;
const { getLocale, setLocale } = configureLocalization({
sourceLocale,
targetLocales,
loadLocale: locale =>
import(new URL(`locales/${locale}.js`, import.meta.url).href),
});
function describe({ undo, redo }: LogEntry) {
let result = msg('Something unexpected happened!');
if (isComplex(redo)) result = msg(str`≥ ${redo.length} nodes changed`);
if (isInsert(redo))
if (isInsert(undo))
result = msg(str`${redo.node.nodeName} moved to ${redo.parent.nodeName}`);
else
result = msg(
str`${redo.node.nodeName} inserted into ${redo.parent.nodeName}`
);
if (isRemove(redo)) result = msg(str`${redo.node.nodeName} removed`);
if (isUpdate(redo)) result = msg(str`${redo.element.tagName} updated`);
return result;
}
function renderActionItem(
control: Control,
slot = 'actionItems'
): TemplateResult {
return html`<mwc-icon-button
slot="${slot}"
icon="${control.icon}"
label="${control.getName()}"
?disabled=${control.isDisabled()}
@click=${control.action}
></mwc-icon-button>`;
}
function renderMenuItem(control: Control): TemplateResult {
return html`
<mwc-list-item graphic="icon" .disabled=${control.isDisabled()}
><mwc-icon slot="graphic">${control.icon}</mwc-icon>
<span>${control.getName()}</span>
</mwc-list-item>
`;
}
/**
*
* @description Outer Shell for OpenSCD.
*
* @cssprop --oscd-theme-primary Primary color for OpenSCD
* @cssprop --oscd-theme-app-bar-primary Primary color for OpenSCD appbar
*
* @tag open-scd
*/
@customElement('open-scd')
@localized()
export class OpenSCD extends Plugging(Editing(LitElement)) {
@query('#log')
logUI!: Dialog;
@query('#menu')
menuUI!: Drawer;
@property({ type: String, reflect: true })
get locale() {
return getLocale() as LocaleTag;
}
set locale(tag: LocaleTag) {
try {
setLocale(tag);
} catch {
// don't change locale if tag is invalid
}
}
@state()
private editorIndex = 0;
@state()
get editor() {
return this.editors[this.editorIndex]?.tagName ?? '';
}
private controls: Record<
'undo' | 'redo' | 'log' | 'menu',
Required<Control>
> = {
undo: {
icon: 'undo',
getName: () => msg('Undo'),
action: () => this.undo(),
isDisabled: () => !this.canUndo,
},
redo: {
icon: 'redo',
getName: () => msg('Redo'),
action: () => this.redo(),
isDisabled: () => !this.canRedo,
},
log: {
icon: 'history',
getName: () => msg('Editing history'),
action: () => (this.logUI.open ? this.logUI.close() : this.logUI.show()),
isDisabled: () => false,
},
menu: {
icon: 'menu',
getName: () => msg('Menu'),
action: async () => {
this.menuUI.open = !this.menuUI.open;
await this.menuUI.updateComplete;
if (this.menuUI.open) this.menuUI.querySelector('mwc-list')!.focus();
},
isDisabled: () => false,
},
};
#actions = [this.controls.undo, this.controls.redo, this.controls.log];
@state()
get menu() {
return (<Required<Control>[]>this.plugins.menu
?.map((plugin): RenderedPlugin | undefined =>
plugin.active
? {
icon: plugin.icon,
getName: () =>
plugin.translations?.[
this.locale as typeof targetLocales[number]
] || plugin.name,
isDisabled: () => (plugin.requireDoc && !this.docName) ?? false,
tagName: pluginTag(plugin.src),
action: () =>
this.shadowRoot!.querySelector<
HTMLElement & { run: () => Promise<void> }
>(pluginTag(plugin.src))!.run?.(),
}
: undefined
)
.filter(p => p !== undefined)).concat(this.#actions);
}
@state()
get editors() {
return <RenderedPlugin[]>this.plugins.editor
?.map((plugin): RenderedPlugin | undefined =>
plugin.active
? {
icon: plugin.icon,
getName: () =>
plugin.translations?.[
this.locale as typeof targetLocales[number]
] || plugin.name,
isDisabled: () => (plugin.requireDoc && !this.docName) ?? false,
tagName: pluginTag(plugin.src),
}
: undefined
)
.filter(p => p !== undefined);
}
private hotkeys: Partial<Record<string, () => void>> = {
m: this.controls.menu.action,
z: this.controls.undo.action,
y: this.controls.redo.action,
Z: this.controls.redo.action,
l: this.controls.log.action,
};
private handleKeyPress(e: KeyboardEvent): void {
if (!e.ctrlKey) return;
if (!Object.prototype.hasOwnProperty.call(this.hotkeys, e.key)) return;
this.hotkeys[e.key]!();
e.preventDefault();
}
constructor() {
super();
this.handleKeyPress = this.handleKeyPress.bind(this);
document.addEventListener('keydown', this.handleKeyPress);
}
private renderLogEntry(entry: LogEntry) {
return html` <abbr title="${describe(entry)}">
<mwc-list-item
graphic="icon"
?activated=${this.history[this.last] === entry}
>
<span>${describe(entry)}</span>
<mwc-icon slot="graphic">history</mwc-icon>
</mwc-list-item></abbr
>`;
}
private renderHistory(): TemplateResult[] | TemplateResult {
if (this.history.length > 0)
return this.history.slice().reverse().map(this.renderLogEntry, this);
return html`<mwc-list-item disabled graphic="icon">
<span>${msg('Your editing history will be displayed here.')}</span>
<mwc-icon slot="graphic">info</mwc-icon>
</mwc-list-item>`;
}
protected pluginProperties(_plugin: Plugin): { [key: string]: PropertyType } {
return {
'.editCount': this.editCount,
'.doc': this.doc,
'.locale': this.locale,
'.docName': this.docName,
'.docs': this.docs,
};
}
render() {
return html`<mwc-drawer
class="mdc-theme--surface"
hasheader
type="modal"
id="menu"
>
<span slot="title">${msg('Menu')}</span>
${this.docName
? html`<span slot="subtitle">${this.docName}</span>`
: ''}
<mwc-list
wrapFocus
@action=${(e: CustomEvent<ActionDetail>) =>
this.menu[e.detail.index]!.action()}
>
<li divider padded role="separator"></li>
${this.menu.map(renderMenuItem)}
</mwc-list>
<mwc-top-app-bar-fixed slot="appContent">
${renderActionItem(this.controls.menu, 'navigationIcon')}
<div slot="title" id="title">${this.docName}</div>
${this.#actions.map(op => renderActionItem(op))}
<mwc-tab-bar
activeIndex=${this.editors.filter(p => !p.isDisabled()).length
? 0
: -1}
@MDCTabBar:activated=${({
detail: { index },
}: {
detail: { index: number };
}) => {
this.editorIndex = index;
}}
>
${this.editors.map(editor =>
editor.isDisabled()
? nothing
: html`<mwc-tab
label="${editor.getName()}"
icon="${editor.icon}"
></mwc-tab>`
)}
</mwc-tab-bar>
${this.editor
? staticHtml`<${unsafeStatic(this.editor)} ${spread(
this.pluginProperties(this.loadedPlugins.get(this.editor)!)
)}></${unsafeStatic(this.editor)}>`
: nothing}
</mwc-top-app-bar-fixed>
</mwc-drawer>
<mwc-dialog id="log" heading="${this.controls.log.getName()}">
<mwc-list wrapFocus>${this.renderHistory()}</mwc-list>
<mwc-button
icon="undo"
label="${msg('Undo')}"
?disabled=${!this.canUndo}
@click=${this.undo}
slot="secondaryAction"
></mwc-button>
<mwc-button
icon="redo"
label="${msg('Redo')}"
?disabled=${!this.canRedo}
@click=${this.redo}
slot="secondaryAction"
></mwc-button>
<mwc-button slot="primaryAction" dialogaction="close"
>${msg('Close')}</mwc-button
>
</mwc-dialog>
<aside>
${(this.plugins.menu || []).map(
plugin =>
staticHtml`<${unsafeStatic(pluginTag(plugin.src))} ${spread(
this.pluginProperties(plugin)
)}></${unsafeStatic(pluginTag(plugin.src))}>`
)}
</aside>`;
}
static styles = css`
aside {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 0;
overflow: hidden;
margin: 0;
padding: 0;
}
abbr {
text-decoration: none;
}
mwc-top-app-bar-fixed {
--mdc-theme-primary: var(
--oscd-theme-app-bar-primary,
var(--oscd-theme-primary)
);
--mdc-theme-text-disabled-on-light: rgba(255, 255, 255, 0.38);
} /* hack to fix disabled icon buttons rendering black */
`;
}
declare global {
interface HTMLElementTagNameMap {
'open-scd': OpenSCD;
}
}