-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplitflap-card.js
More file actions
873 lines (803 loc) · 33 KB
/
splitflap-card.js
File metadata and controls
873 lines (803 loc) · 33 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
/**
* Split-Flap Card for Home Assistant
* A split-flap display card inspired by FlipOff (github.com/magnum6actual/flipoff)
*
* Installation:
* 1. Copy this file to /config/www/splitflap-card.js
* 2. Add as a resource in HA:
* Settings → Dashboards → ⋮ → Resources → Add
* URL: /local/splitflap-card.js Type: JavaScript Module
* 3. Create an input_text helper:
* Settings → Devices & Services → Helpers → Create → Text
* Name: "Splitflap Message" (entity: input_text.splitflap_message)
* Max length: 132 (6 rows × 22 cols)
* 4. Add the card to a dashboard (use YAML or visual editor)
*
* Minimal YAML:
* type: custom:splitflap-card
* entity: input_text.splitflap_message
*
* Full YAML options:
* type: custom:splitflap-card
* entity: input_text.splitflap_message
* title: "" # optional heading above the board
* rows: 6 # default 6
* columns: 22 # default 22
* font_size: auto # "auto" scales to card, or px value e.g. "24px"
* font_family: "Courier New" # any installed or Google Font name
* font_weight: "bold" # "light" (300), "normal" (400), "bold" (700), "extra-bold" (800)
* animation: true # set false for e-ink displays (instant update, no scramble)
* scramble_duration: 600 # ms per tile scramble animation
* stagger_delay: 25 # ms stagger between tiles
* color_mode: "default" # "default" (dark tiles) or "random" (each tile keeps a random colour)
* bar_style: "rainbow" # "rainbow" (multicolour), "solid" (accent colour), "off" (hidden)
* background_color: "#1a1a1a" # board background colour
* sound: false # enable click sound (default off)
* sound_type: "mechanical" # "mechanical" (click+flutter+thud) or "soft" (gentle clack)
* sound_delay: 0 # ms offset to adjust sound timing vs animation (can be negative)
* sound_every: 3 # play a sound every N tiles (1 = every tile, 3 = every 3rd)
* accent_color: "#e8572a" # bar colour (used by solid bar style)
* scramble_colors: # colours shown during scramble (and used by random color_mode)
* - "#e8572a"
* - "#f5a623"
* - "#4a90d9"
* - "#7ed321"
* - "#bd10e0"
* word_wrap: true # wrap words across rows (vs truncate)
* line_separator: "|" # character to force a new line in message
*/
const VALID_CHARS = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&()-+=[]:;\x27",.<>?/\u00b0';
const DEFAULT_SCRAMBLE_COLORS = ['#e8572a', '#f5a623', '#4a90d9', '#7ed321', '#bd10e0'];
const DEFAULT_ACCENT = '#e8572a';
const FONT_WEIGHT_MAP = {
'light': 300,
'normal': 400,
'bold': 700,
'extra-bold': 800,
};
// Google Fonts that work well for split-flap displays
const FONT_PRESETS = [
'Courier New',
'Consolas',
'Roboto Mono',
'JetBrains Mono',
'Fira Mono',
'Source Code Pro',
'IBM Plex Mono',
'Space Mono',
'Ubuntu Mono',
'PT Mono',
];
// Google Fonts that need loading (not system fonts)
const GOOGLE_FONTS = new Set([
'Roboto Mono', 'JetBrains Mono', 'Fira Mono', 'Source Code Pro',
'IBM Plex Mono', 'Space Mono', 'Ubuntu Mono', 'PT Mono',
]);
class SplitflapCard extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._config = {};
this._hass = null;
this._currentGrid = null;
this._tiles = [];
this._rendered = false;
this._lastValue = null;
this._audioCtx = null;
this._loadedFonts = new Set();
}
/* ── HA plumbing ─────────────────────────────────── */
static getConfigElement() {
return document.createElement('splitflap-card-editor');
}
static getStubConfig() {
return {
entity: '',
rows: 6,
columns: 22,
font_family: 'Courier New',
font_weight: 'bold',
animation: true,
scramble_duration: 600,
stagger_delay: 25,
color_mode: 'default',
bar_style: 'rainbow',
background_color: '#1a1a1a',
sound: false,
sound_type: 'mechanical',
sound_delay: 0,
sound_every: 3,
word_wrap: true,
line_separator: '|',
accent_color: DEFAULT_ACCENT,
};
}
setConfig(config) {
if (!config.entity) {
throw new Error('Please define an entity (e.g. input_text.splitflap_message)');
}
this._config = {
rows: 6,
columns: 22,
font_family: 'Courier New',
font_weight: 'bold',
animation: true,
scramble_duration: 600,
stagger_delay: 25,
color_mode: 'default',
bar_style: 'rainbow',
background_color: '#1a1a1a',
sound: false,
sound_type: 'mechanical',
sound_delay: 0,
sound_every: 3,
word_wrap: true,
line_separator: '|',
accent_color: DEFAULT_ACCENT,
scramble_colors: DEFAULT_SCRAMBLE_COLORS,
font_size: 'auto',
title: '',
...config,
};
this._rendered = false;
this._render();
}
set hass(hass) {
this._hass = hass;
if (!this._rendered) this._render();
// Pass hass to editor if it exists
const editor = this.shadowRoot.querySelector('splitflap-card-editor');
if (editor) editor.hass = hass;
const entityId = this._config.entity;
const stateObj = hass.states[entityId];
if (!stateObj) return;
const value = (stateObj.state || '').toUpperCase();
if (value !== this._lastValue) {
this._lastValue = value;
this._setMessage(value);
}
}
getCardSize() {
return this._config.rows + 1;
}
/* ── Google Fonts loader ─────────────────────────── */
_loadGoogleFont(fontFamily) {
if (this._loadedFonts.has(fontFamily)) return;
if (!GOOGLE_FONTS.has(fontFamily)) {
// Check if it looks like a Google Font (not a system font)
const systemFonts = ['Courier New', 'Consolas', 'Arial', 'Helvetica', 'monospace',
'serif', 'sans-serif', 'SF Pro Display', 'Segoe UI', 'system-ui'];
if (systemFonts.some(sf => fontFamily.toLowerCase() === sf.toLowerCase())) return;
}
// Inject Google Font link into document head (not shadow DOM — fonts must be global)
const encoded = fontFamily.replace(/\s+/g, '+');
const linkId = `splitflap-font-${encoded}`;
if (!document.getElementById(linkId)) {
const link = document.createElement('link');
link.id = linkId;
link.rel = 'stylesheet';
link.href = `https://fonts.googleapis.com/css2?family=${encoded}:wght@300;400;700;800&display=swap`;
document.head.appendChild(link);
}
this._loadedFonts.add(fontFamily);
}
/* ── Rendering ───────────────────────────────────── */
_render() {
const c = this._config;
const rows = c.rows;
const cols = c.columns;
const accent = c.accent_color;
const bgColor = c.background_color || '#1a1a1a';
const fontFamily = c.font_family || 'Courier New';
const fontWeightNum = FONT_WEIGHT_MAP[c.font_weight] || FONT_WEIGHT_MAP['bold'];
const barStyle = c.bar_style || 'rainbow';
// Bar CSS
let barTopCSS = '', barBottomCSS = '';
if (barStyle === 'rainbow') {
barTopCSS = `height: 4px; background: linear-gradient(90deg, ${accent} 0%, ${accent} 30%, #f5a623 50%, #4a90d9 70%, #7ed321 100%); border-radius: 2px; margin: 8px 10px;`;
barBottomCSS = `height: 4px; background: linear-gradient(90deg, #7ed321 0%, #4a90d9 30%, #f5a623 60%, ${accent} 100%); border-radius: 2px; margin: 4px 10px 10px;`;
} else if (barStyle === 'solid') {
barTopCSS = `height: 4px; background: ${accent}; border-radius: 2px; margin: 8px 10px;`;
barBottomCSS = `height: 4px; background: ${accent}; border-radius: 2px; margin: 4px 10px 10px;`;
}
// barStyle === 'off' → empty strings, bars won't render
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
--accent: ${accent};
--rows: ${rows};
--cols: ${cols};
}
* { box-sizing: border-box; margin: 0; padding: 0; }
${bgColor === 'transparent' ? 'ha-card { background: transparent !important; box-shadow: none !important; }' : ''}
.vb-wrap {
background: ${bgColor};
border-radius: 12px;
overflow: hidden;
padding: 0;
container-type: inline-size;
}
.vb-title {
color: #aaa;
font-family: 'Segoe UI', system-ui, sans-serif;
font-size: 13px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 12px 16px 0;
}
.vb-bar-top { ${barTopCSS} }
.vb-bar-bottom { ${barBottomCSS} }
.vb-board {
display: grid;
grid-template-columns: repeat(var(--cols), 1fr);
grid-template-rows: repeat(var(--rows), 1fr);
gap: 3px;
padding: 6px 10px;
aspect-ratio: calc(var(--cols) * 1.0) / calc(var(--rows) * 1.45);
}
.tile {
position: relative;
background: #2c2c2c;
border-radius: 3px;
display: flex;
align-items: center;
justify-content: center;
aspect-ratio: 1 / 1.45;
overflow: hidden;
transition: background-color 0.08s;
}
.tile::after {
content: '';
position: absolute;
left: 0; right: 0;
top: 49%; height: 1px;
background: rgba(0,0,0,0.35);
pointer-events: none;
z-index: 2;
}
.tile-char {
font-family: '${fontFamily}', 'Courier New', monospace;
font-weight: ${fontWeightNum};
color: #f0f0f0;
line-height: 1;
user-select: none;
z-index: 1;
text-align: center;
font-size: ${c.font_size === 'auto' ? 'min(3.2cqi, 2.8vh)' : c.font_size};
}
@keyframes scrambleIn {
0% { transform: rotateX(90deg); opacity: 0; }
40% { transform: rotateX(-10deg); opacity: 1; }
70% { transform: rotateX(5deg); }
100% { transform: rotateX(0deg); opacity: 1; }
}
.tile.flipping .tile-char {
animation: scrambleIn 0.25s ease-out forwards;
}
</style>
<ha-card>
<div class="vb-wrap">
${c.title ? `<div class="vb-title">${c.title}</div>` : ''}
${barStyle !== 'off' ? '<div class="vb-bar-top"></div>' : ''}
<div class="vb-board" id="board"></div>
${barStyle !== 'off' ? '<div class="vb-bar-bottom"></div>' : ''}
</div>
</ha-card>
`;
// Load Google Font if needed
this._loadGoogleFont(fontFamily);
// Build tile grid
const board = this.shadowRoot.getElementById('board');
this._tiles = [];
this._currentGrid = [];
for (let r = 0; r < rows; r++) {
this._currentGrid[r] = [];
for (let c2 = 0; c2 < cols; c2++) {
const tile = document.createElement('div');
tile.className = 'tile';
const charEl = document.createElement('span');
charEl.className = 'tile-char';
charEl.textContent = ' ';
tile.appendChild(charEl);
board.appendChild(tile);
this._tiles.push({ el: tile, charEl, row: r, col: c2 });
this._currentGrid[r][c2] = ' ';
}
}
this._rendered = true;
if (this._lastValue !== null) {
this._setMessage(this._lastValue);
}
}
/* ── Message layout ──────────────────────────────── */
_messageToGrid(text) {
const rows = this._config.rows;
const cols = this._config.columns;
const sep = this._config.line_separator;
const wrap = this._config.word_wrap;
let lines = text.split(sep);
const wrappedLines = [];
for (const line of lines) {
if (!wrap) {
wrappedLines.push(line.substring(0, cols));
} else {
const words = line.trim().split(/\s+/);
let current = '';
for (const word of words) {
if (word.length > cols) {
if (current) { wrappedLines.push(current); current = ''; }
for (let i = 0; i < word.length; i += cols) {
wrappedLines.push(word.substring(i, i + cols));
}
} else if (current.length === 0) {
current = word;
} else if (current.length + 1 + word.length <= cols) {
current += ' ' + word;
} else {
wrappedLines.push(current);
current = word;
}
}
if (current) wrappedLines.push(current);
if (line.trim() === '') wrappedLines.push('');
}
}
const usedRows = Math.min(wrappedLines.length, rows);
const startRow = Math.floor((rows - usedRows) / 2);
const grid = [];
for (let r = 0; r < rows; r++) {
grid[r] = [];
const lineIdx = r - startRow;
const lineText = (lineIdx >= 0 && lineIdx < wrappedLines.length)
? wrappedLines[lineIdx] : '';
const pad = Math.floor((cols - lineText.length) / 2);
for (let c2 = 0; c2 < cols; c2++) {
const charIdx = c2 - pad;
const ch = (charIdx >= 0 && charIdx < lineText.length) ? lineText[charIdx] : ' ';
grid[r][c2] = VALID_CHARS.includes(ch) ? ch : ' ';
}
}
return grid;
}
/* ── Animation engine ────────────────────────────── */
_setMessage(text) {
if (!this._rendered || !this._tiles.length) return;
const newGrid = this._messageToGrid(text);
this._animateTransition(newGrid);
}
_animateTransition(newGrid) {
const duration = this._config.scramble_duration;
const stagger = this._config.stagger_delay;
const colors = this._config.scramble_colors || DEFAULT_SCRAMBLE_COLORS;
const rows = this._config.rows;
const cols = this._config.columns;
const animate = this._config.animation !== false;
const colorMode = this._config.color_mode || 'default';
const changes = [];
for (let r = 0; r < rows; r++) {
for (let c2 = 0; c2 < cols; c2++) {
if (this._currentGrid[r][c2] !== newGrid[r][c2]) {
changes.push({ r, c2, target: newGrid[r][c2] });
}
}
}
if (changes.length === 0) return;
if (animate) {
if (this._config.sound && changes.length > 0) {
this._scheduleFlipSounds(changes.length, stagger, duration);
}
changes.forEach((ch, idx) => {
const tileIdx = ch.r * cols + ch.c2;
const tile = this._tiles[tileIdx];
const delay = idx * stagger;
const scrambleSteps = Math.floor(duration / 60);
setTimeout(() => {
this._scrambleTile(tile, ch.target, scrambleSteps, colors, colorMode);
}, delay);
});
} else {
// E-ink / no-animation mode
changes.forEach((ch) => {
const tileIdx = ch.r * cols + ch.c2;
const tile = this._tiles[tileIdx];
tile.charEl.textContent = ch.target;
if (colorMode === 'random' && ch.target !== ' ') {
tile.el.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
} else {
tile.el.style.backgroundColor = '';
}
});
}
for (let r = 0; r < rows; r++) {
for (let c2 = 0; c2 < cols; c2++) {
this._currentGrid[r][c2] = newGrid[r][c2];
}
}
}
_scrambleTile(tile, targetChar, steps, colors, colorMode) {
let step = 0;
const interval = setInterval(() => {
if (step >= steps) {
clearInterval(interval);
tile.charEl.textContent = targetChar;
// Random colour mode: non-space tiles keep a colour
if (colorMode === 'random' && targetChar !== ' ') {
tile.el.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
} else {
tile.el.style.backgroundColor = '';
}
tile.el.classList.add('flipping');
setTimeout(() => tile.el.classList.remove('flipping'), 260);
return;
}
const randChar = VALID_CHARS[Math.floor(Math.random() * VALID_CHARS.length)];
const randColor = colors[Math.floor(Math.random() * colors.length)];
tile.charEl.textContent = randChar;
tile.el.style.backgroundColor = randColor;
step++;
}, 60);
}
/* ── Sound engine (Web Audio API synthesis) ──────── */
_getAudioCtx() {
if (!this._audioCtx) {
this._audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
if (this._audioCtx.state === 'suspended') {
this._audioCtx.resume();
}
return this._audioCtx;
}
_noiseBuffer(duration) {
const ctx = this._getAudioCtx();
const len = ctx.sampleRate * duration;
const buf = ctx.createBuffer(1, len, ctx.sampleRate);
const data = buf.getChannelData(0);
for (let i = 0; i < len; i++) data[i] = Math.random() * 2 - 1;
return buf;
}
_scheduleFlipSounds(tileCount, staggerMs, durationMs) {
try {
const ctx = this._getAudioCtx();
const now = ctx.currentTime;
const staggerSec = staggerMs / 1000;
const delaySec = (this._config.sound_delay || 0) / 1000;
const every = Math.max(1, Math.round(this._config.sound_every || 3));
const sharedNoise = this._noiseBuffer(0.08);
const type = this._config.sound_type || 'mechanical';
for (let i = 0; i < tileCount; i += every) {
const flipTime = now + (i * staggerSec) + delaySec;
const jitter = (Math.random() - 0.5) * 0.01;
const t = Math.max(now, flipTime + jitter);
if (type === 'mechanical') {
this._scheduleMechanical(ctx, sharedNoise, t);
} else {
this._scheduleSoft(ctx, sharedNoise, t);
}
}
} catch (_) { /* audio not available */ }
}
_scheduleMechanical(ctx, noiseBuf, t) {
const clickSrc = ctx.createBufferSource();
clickSrc.buffer = noiseBuf;
const clickGain = ctx.createGain();
clickGain.gain.setValueAtTime(0.3, t);
clickGain.gain.exponentialRampToValueAtTime(0.001, t + 0.012);
const clickFilter = ctx.createBiquadFilter();
clickFilter.type = 'bandpass';
clickFilter.frequency.value = 3000 + Math.random() * 1000;
clickFilter.Q.value = 1.5;
clickSrc.connect(clickFilter).connect(clickGain).connect(ctx.destination);
clickSrc.start(t); clickSrc.stop(t + 0.015);
const flutterSrc = ctx.createBufferSource();
flutterSrc.buffer = noiseBuf;
const flutterGain = ctx.createGain();
flutterGain.gain.setValueAtTime(0.0001, t + 0.008);
flutterGain.gain.linearRampToValueAtTime(0.10, t + 0.018);
flutterGain.gain.exponentialRampToValueAtTime(0.001, t + 0.055);
const flutterFilter = ctx.createBiquadFilter();
flutterFilter.type = 'bandpass';
flutterFilter.frequency.value = 1800 + Math.random() * 600;
flutterFilter.Q.value = 0.8;
flutterSrc.connect(flutterFilter).connect(flutterGain).connect(ctx.destination);
flutterSrc.start(t + 0.008); flutterSrc.stop(t + 0.06);
const thudOsc = ctx.createOscillator();
thudOsc.type = 'sine';
thudOsc.frequency.setValueAtTime(130 + Math.random() * 40, t + 0.045);
thudOsc.frequency.exponentialRampToValueAtTime(55, t + 0.09);
const thudGain = ctx.createGain();
thudGain.gain.setValueAtTime(0.15, t + 0.045);
thudGain.gain.exponentialRampToValueAtTime(0.001, t + 0.095);
thudOsc.connect(thudGain).connect(ctx.destination);
thudOsc.start(t + 0.045); thudOsc.stop(t + 0.1);
const landSrc = ctx.createBufferSource();
landSrc.buffer = noiseBuf;
const landGain = ctx.createGain();
landGain.gain.setValueAtTime(0.15, t + 0.048);
landGain.gain.exponentialRampToValueAtTime(0.001, t + 0.06);
const landFilter = ctx.createBiquadFilter();
landFilter.type = 'highpass';
landFilter.frequency.value = 2200 + Math.random() * 600;
landSrc.connect(landFilter).connect(landGain).connect(ctx.destination);
landSrc.start(t + 0.048); landSrc.stop(t + 0.065);
}
_scheduleSoft(ctx, noiseBuf, t) {
const src = ctx.createBufferSource();
src.buffer = noiseBuf;
const gain = ctx.createGain();
gain.gain.setValueAtTime(0.12, t);
gain.gain.exponentialRampToValueAtTime(0.001, t + 0.035);
const filter = ctx.createBiquadFilter();
filter.type = 'bandpass';
filter.frequency.value = 1600 + Math.random() * 500;
filter.Q.value = 0.6;
src.connect(filter).connect(gain).connect(ctx.destination);
src.start(t); src.stop(t + 0.04);
const osc = ctx.createOscillator();
osc.type = 'sine';
osc.frequency.setValueAtTime(90 + Math.random() * 30, t + 0.02);
osc.frequency.exponentialRampToValueAtTime(35, t + 0.06);
const g2 = ctx.createGain();
g2.gain.setValueAtTime(0.08, t + 0.02);
g2.gain.exponentialRampToValueAtTime(0.001, t + 0.06);
osc.connect(g2).connect(ctx.destination);
osc.start(t + 0.02); osc.stop(t + 0.07);
}
}
/* ── Visual Config Editor ──────────────────────────── */
class SplitflapCardEditor extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this._config = {};
this._hass = null;
}
set hass(hass) {
this._hass = hass;
// Populate entity datalist with all available entities
const datalist = this.shadowRoot && this.shadowRoot.getElementById('entity-list');
if (datalist && hass) {
datalist.innerHTML = Object.keys(hass.states)
.sort()
.map(id => `<option value="${id}">${hass.states[id].attributes.friendly_name ? hass.states[id].attributes.friendly_name + ' (' + id + ')' : id}</option>`)
.join('');
}
}
setConfig(config) {
this._config = { ...config };
this._render();
}
_render() {
const c = this._config;
const fontOptions = [
'Courier New', 'Consolas', 'Roboto Mono', 'JetBrains Mono',
'Fira Mono', 'Source Code Pro', 'IBM Plex Mono', 'Space Mono',
'Ubuntu Mono', 'PT Mono',
].map(f => `<option value="${f}" ${(c.font_family || 'Courier New') === f ? 'selected' : ''}>${f}</option>`).join('');
this.shadowRoot.innerHTML = `
<style>
:host { display: block; padding: 16px; }
.row { margin-bottom: 12px; }
.section {
font-size: 11px; font-weight: 600; text-transform: uppercase;
letter-spacing: 0.08em; color: var(--secondary-text-color);
margin: 16px 0 8px; padding-top: 8px;
border-top: 1px solid var(--divider-color, #333);
}
.section:first-child { border-top: none; margin-top: 0; padding-top: 0; }
label { display: block; font-weight: 500; margin-bottom: 4px; font-size: 13px; color: var(--primary-text-color); }
input, select {
width: 100%; padding: 8px; border-radius: 6px;
border: 1px solid var(--divider-color, #ccc);
background: var(--card-background-color, #fff);
color: var(--primary-text-color); font-size: 14px;
}
.cols-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.hint { font-size: 11px; color: var(--secondary-text-color); margin-top: 2px; }
.custom-font-row { margin-top: 4px; }
.custom-font-row input { font-size: 13px; }
</style>
<div class="section">General</div>
<div class="row">
<label>Entity</label>
<input id="entity" list="entity-list" value="${c.entity || ''}" placeholder="Start typing to search entities..." />
<datalist id="entity-list"></datalist>
<div class="hint">Works with input_text, template sensors, or any entity with a text state</div>
</div>
<div class="row">
<label>Title (optional)</label>
<input id="title" value="${c.title || ''}" placeholder="" />
</div>
<div class="cols-2">
<div class="row">
<label>Rows</label>
<input id="rows" type="number" value="${c.rows || 6}" min="1" max="20" />
</div>
<div class="row">
<label>Columns</label>
<input id="columns" type="number" value="${c.columns || 22}" min="4" max="44" />
</div>
</div>
<div class="row">
<label>Line separator character</label>
<input id="line_separator" value="${c.line_separator || '|'}" maxlength="1" />
<div class="hint">Use this character in your message to force a new line</div>
</div>
<div class="section">Appearance</div>
<div class="cols-2">
<div class="row">
<label>Font</label>
<select id="font_family">${fontOptions}<option value="custom" ${!['Courier New','Consolas','Roboto Mono','JetBrains Mono','Fira Mono','Source Code Pro','IBM Plex Mono','Space Mono','Ubuntu Mono','PT Mono'].includes(c.font_family || 'Courier New') ? 'selected' : ''}>Custom...</option></select>
</div>
<div class="row">
<label>Font weight</label>
<select id="font_weight">
<option value="light" ${c.font_weight === 'light' ? 'selected' : ''}>Light</option>
<option value="normal" ${c.font_weight === 'normal' ? 'selected' : ''}>Normal</option>
<option value="bold" ${(!c.font_weight || c.font_weight === 'bold') ? 'selected' : ''}>Bold</option>
<option value="extra-bold" ${c.font_weight === 'extra-bold' ? 'selected' : ''}>Extra Bold</option>
</select>
</div>
</div>
<div class="row custom-font-row" id="custom-font-row" style="display:${!['Courier New','Consolas','Roboto Mono','JetBrains Mono','Fira Mono','Source Code Pro','IBM Plex Mono','Space Mono','Ubuntu Mono','PT Mono'].includes(c.font_family || 'Courier New') ? 'block' : 'none'}">
<label>Custom font name</label>
<input id="custom_font" value="${!['Courier New','Consolas','Roboto Mono','JetBrains Mono','Fira Mono','Source Code Pro','IBM Plex Mono','Space Mono','Ubuntu Mono','PT Mono'].includes(c.font_family || 'Courier New') ? (c.font_family || '') : ''}" placeholder="e.g. SF Pro Display, Oswald" />
<div class="hint">System font or Google Font name</div>
</div>
<div class="cols-2">
<div class="row">
<label>Accent colour</label>
<input id="accent_color" type="color" value="${c.accent_color || DEFAULT_ACCENT}" />
</div>
<div class="row">
<label>Background colour</label>
<input id="background_color" type="color" value="${(!c.background_color || c.background_color === 'transparent') ? '#1a1a1a' : c.background_color}" ${c.background_color === 'transparent' ? 'disabled' : ''} />
<label style="display:flex;align-items:center;gap:6px;margin-top:4px;font-weight:400;font-size:12px;">
<input id="bg_transparent" type="checkbox" ${c.background_color === 'transparent' ? 'checked' : ''} style="width:auto;" />
Transparent
</label>
</div>
</div>
<div class="cols-2">
<div class="row">
<label>Bars</label>
<select id="bar_style">
<option value="rainbow" ${(!c.bar_style || c.bar_style === 'rainbow') ? 'selected' : ''}>Rainbow</option>
<option value="solid" ${c.bar_style === 'solid' ? 'selected' : ''}>Solid (accent colour)</option>
<option value="off" ${c.bar_style === 'off' ? 'selected' : ''}>Off</option>
</select>
</div>
<div class="row">
<label>Tile colours</label>
<select id="color_mode">
<option value="default" ${(!c.color_mode || c.color_mode === 'default') ? 'selected' : ''}>Default (dark)</option>
<option value="random" ${c.color_mode === 'random' ? 'selected' : ''}>Random per character</option>
</select>
</div>
</div>
<div class="section">Animation</div>
<div class="row">
<label>Animation</label>
<select id="animation">
<option value="true" ${c.animation !== false ? 'selected' : ''}>On (scramble + flip)</option>
<option value="false" ${c.animation === false ? 'selected' : ''}>Off (instant update — e-ink)</option>
</select>
</div>
<div class="cols-2">
<div class="row">
<label>Scramble duration (ms)</label>
<input id="scramble_duration" type="number" value="${c.scramble_duration || 600}" min="100" max="3000" step="50" />
<div class="hint">How long each tile scrambles</div>
</div>
<div class="row">
<label>Stagger delay (ms)</label>
<input id="stagger_delay" type="number" value="${c.stagger_delay || 25}" min="0" max="200" step="5" />
<div class="hint">Delay between each tile starting</div>
</div>
</div>
<div class="section">Sound</div>
<div class="cols-2">
<div class="row">
<label>Sound</label>
<select id="sound">
<option value="false" ${!c.sound || c.sound === 'false' ? 'selected' : ''}>Off</option>
<option value="true" ${c.sound === true || c.sound === 'true' ? 'selected' : ''}>On</option>
</select>
<div class="hint">Tap card once on tablet to enable audio</div>
</div>
<div class="row">
<label>Sound type</label>
<select id="sound_type">
<option value="mechanical" ${(c.sound_type || 'mechanical') === 'mechanical' ? 'selected' : ''}>Mechanical</option>
<option value="soft" ${c.sound_type === 'soft' ? 'selected' : ''}>Soft</option>
</select>
</div>
</div>
<div class="cols-2">
<div class="row">
<label>Sound delay (ms)</label>
<input id="sound_delay" type="number" value="${c.sound_delay || 0}" min="-500" max="1000" step="25" />
<div class="hint">Shift sound vs animation. Positive = later, negative = earlier</div>
</div>
<div class="row">
<label>Sound every N tiles</label>
<input id="sound_every" type="number" value="${c.sound_every || 3}" min="1" max="20" step="1" />
<div class="hint">1 = every tile clicks, 3 = every 3rd</div>
</div>
</div>
`;
// Font family dropdown → show/hide custom font field
const fontSelect = this.shadowRoot.getElementById('font_family');
const customFontRow = this.shadowRoot.getElementById('custom-font-row');
fontSelect.addEventListener('change', () => {
if (fontSelect.value === 'custom') {
customFontRow.style.display = 'block';
} else {
customFontRow.style.display = 'none';
this._config = { ...this._config, font_family: fontSelect.value };
this.dispatchEvent(new CustomEvent('config-changed', {
detail: { config: this._config },
}));
}
});
// Custom font name input
const customFontInput = this.shadowRoot.getElementById('custom_font');
customFontInput.addEventListener('change', () => {
if (customFontInput.value.trim()) {
this._config = { ...this._config, font_family: customFontInput.value.trim() };
this.dispatchEvent(new CustomEvent('config-changed', {
detail: { config: this._config },
}));
}
});
// Transparent background checkbox
const bgTransparent = this.shadowRoot.getElementById('bg_transparent');
const bgColorInput = this.shadowRoot.getElementById('background_color');
bgTransparent.addEventListener('change', () => {
if (bgTransparent.checked) {
bgColorInput.disabled = true;
this._config = { ...this._config, background_color: 'transparent' };
} else {
bgColorInput.disabled = false;
this._config = { ...this._config, background_color: bgColorInput.value };
}
this.dispatchEvent(new CustomEvent('config-changed', {
detail: { config: this._config },
}));
});
// Wire up all other change events
['entity', 'title', 'rows', 'columns', 'line_separator', 'accent_color', 'background_color',
'font_weight', 'bar_style', 'color_mode',
'animation', 'scramble_duration', 'stagger_delay',
'sound', 'sound_type', 'sound_delay', 'sound_every'].forEach(key => {
const el = this.shadowRoot.getElementById(key);
if (!el) return;
el.addEventListener('change', () => {
let val;
if (key === 'sound' || key === 'animation') {
val = el.value === 'true';
} else if (el.type === 'number') {
val = parseFloat(el.value);
} else {
val = el.value;
}
this._config = { ...this._config, [key]: val };
this.dispatchEvent(new CustomEvent('config-changed', {
detail: { config: this._config },
}));
});
});
}
}
/* ── Register ──────────────────────────────────────── */
customElements.define('splitflap-card', SplitflapCard);
customElements.define('splitflap-card-editor', SplitflapCardEditor);
window.customCards = window.customCards || [];
window.customCards.push({
type: 'splitflap-card',
name: 'Split-Flap Display',
description: 'Split-flap display card with flip animations',
preview: true,
documentationURL: 'https://github.com/RazManSource/splitflap-card',
});