@open-spreadsheet/core 0.2.0 → 0.4.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.
- package/app/assets.ts +1479 -0
- package/app/book.ts +115 -24
- package/app/charts.test.ts +62 -1
- package/app/charts.ts +268 -46
- package/app/i18n-more.ts +230 -2
- package/app/i18n.ts +154 -2
- package/app/icons.ts +5 -0
- package/app/markdown.test.ts +25 -0
- package/app/markdown.ts +150 -0
- package/app/note-editor.ts +252 -0
- package/app/style.css +154 -0
- package/app/types.ts +3 -1
- package/assets.js +232 -0
- package/dist/charts.js +384 -0
- package/mcp.js +97 -5
- package/ops.js +6 -1
- package/package.json +6 -3
- package/server.js +81 -2
- package/skills/apply-notes/SKILL.md +3 -1
- package/skills/sheet-authoring/SKILL.md +11 -1
- package/templates/AGENTS.md +1 -0
package/app/i18n.ts
CHANGED
|
@@ -216,6 +216,82 @@ export const en = {
|
|
|
216
216
|
protectedOn: (r: string) => `Protected: ${r}. Its cells cannot be changed until unprotected.`,
|
|
217
217
|
protectedOff: 'Protection removed.',
|
|
218
218
|
protectedRefused: 'This range is protected. Unprotect it first (right-click → Unprotect range).',
|
|
219
|
+
assets: 'Assets',
|
|
220
|
+
assetsHint: "Chart images and pictures for this workbook. Make a chart from the sheet's toolbar.",
|
|
221
|
+
assetsThisBook: 'This workbook',
|
|
222
|
+
assetsShared: 'Shared',
|
|
223
|
+
newChartImage: 'Chart image',
|
|
224
|
+
newNote: 'New note',
|
|
225
|
+
uploadImage: 'Upload image',
|
|
226
|
+
noAssets: 'Nothing here yet.',
|
|
227
|
+
saveIn: 'Save in',
|
|
228
|
+
noteContextHint: 'Markdown. Agents read these notes before working on the workbook: what the numbers mean, where they come from, what to keep.',
|
|
229
|
+
deleteAssetTitle: (n: string) => `Delete “${n}”?`,
|
|
230
|
+
deleteAssetBody: 'It moves to the assets .trash folder.',
|
|
231
|
+
chartSaved: (n: string) => `Saved “${n}” to Assets`,
|
|
232
|
+
chartsMoved: (k: number) => `Moved ${k} chart${k === 1 ? '' : 's'} to Assets`,
|
|
233
|
+
chartsOnGrid: (k: number) => `${k} chart${k === 1 ? '' : 's'} on the grid`,
|
|
234
|
+
moveChartsToAssets: 'Move to Assets',
|
|
235
|
+
close: 'Close',
|
|
236
|
+
viewSheet: 'Sheet',
|
|
237
|
+
viewAssets: 'Assets',
|
|
238
|
+
viewNotes: 'Notes',
|
|
239
|
+
notesTitle: 'Notes for this workbook',
|
|
240
|
+
noImagesYet: 'No images yet. In the sheet, select the data and use the chart button in the toolbar.',
|
|
241
|
+
noNotesYet: 'No notes yet',
|
|
242
|
+
newChart: 'New chart',
|
|
243
|
+
editChart: 'Edit chart',
|
|
244
|
+
chartType: 'Type',
|
|
245
|
+
sheetLabel: 'Sheet',
|
|
246
|
+
rangeLabel: 'Range',
|
|
247
|
+
noAssetsYet: 'No assets yet',
|
|
248
|
+
notePlaceholder: 'Write, or type # for a heading, - for a list…',
|
|
249
|
+
markdownSource: 'Markdown source',
|
|
250
|
+
chartBarH: 'Bar (horizontal)',
|
|
251
|
+
chartStacked: 'Stacked column',
|
|
252
|
+
chartArea: 'Area',
|
|
253
|
+
chartDoughnut: 'Doughnut',
|
|
254
|
+
chartScatter: 'Scatter',
|
|
255
|
+
chartCombo: 'Combo',
|
|
256
|
+
notesRecent: 'Recent',
|
|
257
|
+
notesFavorites: 'Favorites',
|
|
258
|
+
notesAll: 'All',
|
|
259
|
+
searchNotes: 'Search notes',
|
|
260
|
+
favorite: 'Add to favorites',
|
|
261
|
+
unfavorite: 'Remove from favorites',
|
|
262
|
+
noFavorites: 'No favorites yet',
|
|
263
|
+
noMatches: 'No matches',
|
|
264
|
+
justNow: 'Just now',
|
|
265
|
+
minutesAgo: (n: number) => `${n} min ago`,
|
|
266
|
+
hoursAgo: (n: number) => `${n} h ago`,
|
|
267
|
+
home: 'Home',
|
|
268
|
+
searchAssets: 'Search assets',
|
|
269
|
+
chartStyles: 'Chart styles',
|
|
270
|
+
newStyle: 'New style',
|
|
271
|
+
styleLabel: 'Style',
|
|
272
|
+
defaultBadge: 'Default',
|
|
273
|
+
makeDefault: 'Use for new charts',
|
|
274
|
+
builtIn: 'Built-in',
|
|
275
|
+
duplicateEdit: 'Duplicate to edit',
|
|
276
|
+
styleColors: 'Series colours',
|
|
277
|
+
styleColorsMore: 'Other colours',
|
|
278
|
+
styleBackground: 'Background',
|
|
279
|
+
styleText: 'Title',
|
|
280
|
+
styleMuted: 'Labels',
|
|
281
|
+
styleGrid: 'Grid',
|
|
282
|
+
styleFont: 'Font',
|
|
283
|
+
styleCorners: 'Bar corners',
|
|
284
|
+
styleGridLines: 'Grid lines',
|
|
285
|
+
fontSans: 'Sans serif',
|
|
286
|
+
fontSerif: 'Serif',
|
|
287
|
+
fontMono: 'Monospace',
|
|
288
|
+
fontRounded: 'Rounded',
|
|
289
|
+
addColor: 'Add colour',
|
|
290
|
+
removeColor: 'Remove last colour',
|
|
291
|
+
noFavoriteAssets: 'No favourites yet',
|
|
292
|
+
followDefault: (n: string) => `Follow the default (${n})`,
|
|
293
|
+
builtinStyle: (id: string) => (({ default: 'Standard', ocean: 'Ocean', warm: 'Warm', pastel: 'Pastel', mono: 'Mono', night: 'Night' }) as Record<string, string>)[id] ?? id,
|
|
294
|
+
insertAsset: 'Insert asset',
|
|
219
295
|
fontSize: 'Font size',
|
|
220
296
|
fontSizeOther: 'Other size…',
|
|
221
297
|
customSort: 'Custom sort…',
|
|
@@ -251,7 +327,7 @@ export const en = {
|
|
|
251
327
|
splitDone: (n: number) => `Split ${n} cell${n === 1 ? '' : 's'}`,
|
|
252
328
|
pasteTranspose: 'Paste transposed',
|
|
253
329
|
insertChart: 'Insert chart',
|
|
254
|
-
chartBar: '
|
|
330
|
+
chartBar: 'Column',
|
|
255
331
|
chartLine: 'Line chart',
|
|
256
332
|
chartPie: 'Pie chart',
|
|
257
333
|
chartTitle: 'Chart title…',
|
|
@@ -484,6 +560,82 @@ const zh: Dict = {
|
|
|
484
560
|
protectedOn: (r: string) => `已保護 ${r}:取消保護前不能修改。`,
|
|
485
561
|
protectedOff: '已取消保護。',
|
|
486
562
|
protectedRefused: '這個範圍受保護。請先取消保護(右鍵 → 取消保護)。',
|
|
563
|
+
assets: 'Assets',
|
|
564
|
+
assetsHint: '這本活頁簿的圖表圖片與上傳的圖片;圖表從「表格」的工具列建立。',
|
|
565
|
+
assetsThisBook: '這本活頁簿',
|
|
566
|
+
assetsShared: '共用',
|
|
567
|
+
newChartImage: '圖表圖片',
|
|
568
|
+
close: '關閉',
|
|
569
|
+
newNote: '新增筆記',
|
|
570
|
+
uploadImage: '上傳圖片',
|
|
571
|
+
noAssets: '還沒有內容。',
|
|
572
|
+
saveIn: '存放在',
|
|
573
|
+
noteContextHint: 'Markdown 格式。Agent 處理這本活頁簿前會先讀這些筆記:數字的意思、來源、要遵守的規則。',
|
|
574
|
+
deleteAssetTitle: (n: string) => `刪除「${n}」?`,
|
|
575
|
+
deleteAssetBody: '會移到 assets 的 .trash 資料夾。',
|
|
576
|
+
chartSaved: (n: string) => `已存到素材:${n}`,
|
|
577
|
+
chartsMoved: (k: number) => `已把 ${k} 個圖表移到素材`,
|
|
578
|
+
chartsOnGrid: (k: number) => `格子上有 ${k} 個圖表`,
|
|
579
|
+
moveChartsToAssets: '移到素材',
|
|
580
|
+
viewSheet: '表格',
|
|
581
|
+
viewAssets: '素材',
|
|
582
|
+
viewNotes: '筆記',
|
|
583
|
+
notesTitle: '這本活頁簿的筆記',
|
|
584
|
+
noImagesYet: '還沒有圖片。在「表格」選好資料,按工具列的圖表按鈕。',
|
|
585
|
+
noNotesYet: '還沒有筆記',
|
|
586
|
+
newChart: '新增圖表',
|
|
587
|
+
editChart: '編輯圖表',
|
|
588
|
+
chartType: '類型',
|
|
589
|
+
sheetLabel: '工作表',
|
|
590
|
+
rangeLabel: '範圍',
|
|
591
|
+
noAssetsYet: '還沒有素材',
|
|
592
|
+
notePlaceholder: '開始寫,輸入 # 變標題、- 變清單…',
|
|
593
|
+
markdownSource: 'Markdown 原始碼',
|
|
594
|
+
chartBarH: '橫條圖',
|
|
595
|
+
chartStacked: '堆疊直條圖',
|
|
596
|
+
chartArea: '區域圖',
|
|
597
|
+
chartDoughnut: '環圈圖',
|
|
598
|
+
chartScatter: '散佈圖',
|
|
599
|
+
chartCombo: '組合圖',
|
|
600
|
+
notesRecent: '最近',
|
|
601
|
+
notesFavorites: '最愛',
|
|
602
|
+
notesAll: '全部',
|
|
603
|
+
searchNotes: '搜尋筆記',
|
|
604
|
+
favorite: '加入最愛',
|
|
605
|
+
unfavorite: '移除最愛',
|
|
606
|
+
noFavorites: '還沒有最愛的筆記',
|
|
607
|
+
noMatches: '找不到符合的項目',
|
|
608
|
+
justNow: '剛剛',
|
|
609
|
+
minutesAgo: (n: number) => `${n} 分鐘前`,
|
|
610
|
+
hoursAgo: (n: number) => `${n} 小時前`,
|
|
611
|
+
home: '首頁',
|
|
612
|
+
searchAssets: '搜尋素材',
|
|
613
|
+
chartStyles: '圖表風格',
|
|
614
|
+
newStyle: '新增風格',
|
|
615
|
+
styleLabel: '風格',
|
|
616
|
+
defaultBadge: '預設',
|
|
617
|
+
makeDefault: '設為預設',
|
|
618
|
+
builtIn: '內建',
|
|
619
|
+
duplicateEdit: '複製來編輯',
|
|
620
|
+
styleColors: '數列色彩',
|
|
621
|
+
styleColorsMore: '其他色彩',
|
|
622
|
+
styleBackground: '背景',
|
|
623
|
+
styleText: '標題',
|
|
624
|
+
styleMuted: '標籤',
|
|
625
|
+
styleGrid: '格線',
|
|
626
|
+
styleFont: '字型',
|
|
627
|
+
styleCorners: '長條圓角',
|
|
628
|
+
styleGridLines: '顯示格線',
|
|
629
|
+
fontSans: '黑體',
|
|
630
|
+
fontSerif: '明體',
|
|
631
|
+
fontMono: '等寬',
|
|
632
|
+
fontRounded: '圓體',
|
|
633
|
+
addColor: '新增顏色',
|
|
634
|
+
removeColor: '移除最後一個顏色',
|
|
635
|
+
noFavoriteAssets: '還沒有最愛的素材',
|
|
636
|
+
followDefault: (n: string) => `跟隨預設(${n})`,
|
|
637
|
+
builtinStyle: (id: string) => (({ default: '標準', ocean: '海洋', warm: '暖陽', pastel: '柔和', mono: '黑白', night: '夜間' }) as Record<string, string>)[id] ?? id,
|
|
638
|
+
insertAsset: '插入素材',
|
|
487
639
|
fontSize: '字型大小',
|
|
488
640
|
fontSizeOther: '其他大小…',
|
|
489
641
|
customSort: '自訂排序…',
|
|
@@ -519,7 +671,7 @@ const zh: Dict = {
|
|
|
519
671
|
splitDone: (n) => `已拆開 ${n} 格`,
|
|
520
672
|
pasteTranspose: '轉置貼上',
|
|
521
673
|
insertChart: '插入圖表',
|
|
522
|
-
chartBar: '
|
|
674
|
+
chartBar: '直條圖',
|
|
523
675
|
chartLine: '折線圖',
|
|
524
676
|
chartPie: '圓餅圖',
|
|
525
677
|
chartTitle: '圖表標題…',
|
package/app/icons.ts
CHANGED
|
@@ -10,6 +10,11 @@ const P: Record<string, string> = {
|
|
|
10
10
|
chevronDown: '<path d="m6 9 6 6 6-6"/>',
|
|
11
11
|
arrowLeft: '<path d="M19 12H5M12 19l-7-7 7-7"/>',
|
|
12
12
|
arrowRight: '<path d="M5 12h14M12 5l7 7-7 7"/>',
|
|
13
|
+
code: '<path d="m8 8-4 4 4 4M16 8l4 4-4 4"/>',
|
|
14
|
+
image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="1.6"/><path d="m21 16-5-5-9 9"/>',
|
|
15
|
+
home: '<path d="M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6h-6v6H4a1 1 0 0 1-1-1z"/>',
|
|
16
|
+
star: '<path d="m12 3 2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z"/>',
|
|
17
|
+
starFill: '<path d="m12 3 2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1-4.4-4.3 6.1-.9z" fill="currentColor"/>',
|
|
13
18
|
more: '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
|
|
14
19
|
sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>',
|
|
15
20
|
moon: '<path d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"/>',
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { inline, mdToHtml } from './markdown.ts';
|
|
3
|
+
|
|
4
|
+
describe('note Markdown', () => {
|
|
5
|
+
it('renders the blocks people write in notes', () => {
|
|
6
|
+
expect(mdToHtml('# 業績\n\n第一行\n第二行\n\n- 甲\n- 乙\n\n1. 一\n2. 二\n\n> 引言\n\n---\n\n```\nx < 1\n```')).toBe(
|
|
7
|
+
'<h1>業績</h1><p>第一行<br>第二行</p><ul><li>甲</li><li>乙</li></ul><ol><li>一</li><li>二</li></ol><blockquote><p>引言</p></blockquote><hr><pre><code>x < 1</code></pre>',
|
|
8
|
+
);
|
|
9
|
+
});
|
|
10
|
+
|
|
11
|
+
it('renders inline marks, keeps code literal, and never runs HTML or unsafe links', () => {
|
|
12
|
+
expect(inline('**粗** 與 *斜* 與 `**不是粗體**`')).toBe('<strong>粗</strong> 與 <em>斜</em> 與 <code>**不是粗體**</code>');
|
|
13
|
+
expect(inline('<img src=x onerror=alert(1)>')).toBe('<img src=x onerror=alert(1)>');
|
|
14
|
+
expect(inline('[ok](https://example.com) [bad](javascript:alert(1))')).toBe('<a href="https://example.com" target="_blank" rel="noopener noreferrer">ok</a> bad)');
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it('shows an image only where the note resolves it, and nothing in it is read as Markdown', () => {
|
|
18
|
+
const at = (src: string) => (src.endsWith('.svg') ? `/f?n=${src}` : null);
|
|
19
|
+
expect(inline('', at)).toBe('<img class="md-img" src="/f?n=a.svg" alt="業績 *圖*" data-src="a.svg">');
|
|
20
|
+
expect(inline('', at)).toBe('x');
|
|
21
|
+
expect(inline('')).toBe('x');
|
|
22
|
+
expect(inline('[link](https://a.b) ', at)).toContain('<a href="https://a.b"');
|
|
23
|
+
expect(inline('', at)).not.toContain('" onerror');
|
|
24
|
+
});
|
|
25
|
+
});
|
package/app/markdown.ts
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Markdown for notes, both ways: a small renderer (the subset people write in
|
|
2
|
+
// notes — headings, paragraphs, lists, quotes, code, rules, bold, italic, code,
|
|
3
|
+
// links, images) and a serializer back from the edited DOM. Text is always
|
|
4
|
+
// escaped and links are http(s) or mailto only: a note may come from an agent.
|
|
5
|
+
// An image shows only when the caller resolves its source (to an asset beside
|
|
6
|
+
// the note); anything else stays as its alt text.
|
|
7
|
+
|
|
8
|
+
/** Where an image's Markdown source points, as a URL to show; null to leave it out. */
|
|
9
|
+
export type ImageResolver = (src: string) => string | null;
|
|
10
|
+
|
|
11
|
+
const esc = (s: string) => s.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
|
|
12
|
+
|
|
13
|
+
const safeHref = (url: string) => (/^(https?:|mailto:)/i.test(url.trim()) ? url.trim() : '');
|
|
14
|
+
|
|
15
|
+
/** Inline Markdown in one line of text: `code`, **bold**, *italic*, [text](url), . */
|
|
16
|
+
export function inline(text: string, image?: ImageResolver): string {
|
|
17
|
+
const parts: string[] = [];
|
|
18
|
+
// Code spans first, so nothing inside them is read as Markdown.
|
|
19
|
+
const re = /`([^`\n]+)`/g;
|
|
20
|
+
let last = 0;
|
|
21
|
+
for (let m = re.exec(text); m; m = re.exec(text)) {
|
|
22
|
+
parts.push(rest(text.slice(last, m.index)), `<code>${esc(m[1]!)}</code>`);
|
|
23
|
+
last = m.index + m[0].length;
|
|
24
|
+
}
|
|
25
|
+
parts.push(rest(text.slice(last)));
|
|
26
|
+
return parts.join('');
|
|
27
|
+
|
|
28
|
+
function rest(t: string): string {
|
|
29
|
+
// Images first, held out as tokens so nothing in their alt text or source is read as Markdown.
|
|
30
|
+
const held: string[] = [];
|
|
31
|
+
return esc(t)
|
|
32
|
+
.replace(/!\[([^\]\n]*)\]\(([^)\s]+)\)/g, (_, alt: string, src: string) => {
|
|
33
|
+
const raw = src.replaceAll('&', '&');
|
|
34
|
+
const url = image?.(raw);
|
|
35
|
+
held.push(url ? `<img class="md-img" src="${esc(url)}" alt="${alt}" data-src="${esc(raw)}">` : alt);
|
|
36
|
+
return `\u0000${held.length - 1}\u0000`;
|
|
37
|
+
})
|
|
38
|
+
.replace(/\[([^\]\n]+)\]\(([^)\s]+)\)/g, (_, label: string, url: string) => {
|
|
39
|
+
const href = safeHref(url.replaceAll('&', '&'));
|
|
40
|
+
return href ? `<a href="${esc(href)}" target="_blank" rel="noopener noreferrer">${label}</a>` : label;
|
|
41
|
+
})
|
|
42
|
+
.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>')
|
|
43
|
+
.replace(/(^|[^*])\*([^*\n]+)\*(?!\*)/g, '$1<em>$2</em>')
|
|
44
|
+
.replace(/\u0000(\d+)\u0000/g, (_, k: string) => held[Number(k)] ?? '');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const inlineWith = (t: string, image?: ImageResolver) => inline(t, image);
|
|
49
|
+
|
|
50
|
+
/** A note's Markdown as HTML blocks for the editor. */
|
|
51
|
+
export function mdToHtml(md: string, image?: ImageResolver): string {
|
|
52
|
+
const inline = (t: string) => inlineWith(t, image);
|
|
53
|
+
const lines = md.replaceAll('\r\n', '\n').split('\n');
|
|
54
|
+
const out: string[] = [];
|
|
55
|
+
let i = 0;
|
|
56
|
+
while (i < lines.length) {
|
|
57
|
+
const line = lines[i]!;
|
|
58
|
+
if (/^```/.test(line)) {
|
|
59
|
+
const body: string[] = [];
|
|
60
|
+
i++;
|
|
61
|
+
while (i < lines.length && !/^```/.test(lines[i]!)) body.push(lines[i++]!);
|
|
62
|
+
i++;
|
|
63
|
+
out.push(`<pre><code>${esc(body.join('\n'))}</code></pre>`);
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const h = /^(#{1,3})\s+(.*)$/.exec(line);
|
|
67
|
+
if (h) {
|
|
68
|
+
out.push(`<h${h[1]!.length}>${inline(h[2]!)}</h${h[1]!.length}>`);
|
|
69
|
+
i++;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (/^\s*(-{3,}|\*{3,})\s*$/.test(line)) {
|
|
73
|
+
out.push('<hr>');
|
|
74
|
+
i++;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (/^\s*[-*]\s+/.test(line) || /^\s*\d+[.)]\s+/.test(line)) {
|
|
78
|
+
const ordered = /^\s*\d+[.)]\s+/.test(line);
|
|
79
|
+
const items: string[] = [];
|
|
80
|
+
while (i < lines.length && (ordered ? /^\s*\d+[.)]\s+/ : /^\s*[-*]\s+/).test(lines[i]!)) {
|
|
81
|
+
items.push(`<li>${inline(lines[i]!.replace(ordered ? /^\s*\d+[.)]\s+/ : /^\s*[-*]\s+/, ''))}</li>`);
|
|
82
|
+
i++;
|
|
83
|
+
}
|
|
84
|
+
out.push(ordered ? `<ol>${items.join('')}</ol>` : `<ul>${items.join('')}</ul>`);
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
if (/^>\s?/.test(line)) {
|
|
88
|
+
const body: string[] = [];
|
|
89
|
+
while (i < lines.length && /^>\s?/.test(lines[i]!)) body.push(inline(lines[i++]!.replace(/^>\s?/, '')));
|
|
90
|
+
out.push(`<blockquote><p>${body.join('<br>')}</p></blockquote>`);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (!line.trim()) {
|
|
94
|
+
i++;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const para: string[] = [];
|
|
98
|
+
while (i < lines.length && lines[i]!.trim() && !/^(#{1,3}\s|```|>|\s*[-*]\s+|\s*\d+[.)]\s+|\s*(-{3,}|\*{3,})\s*$)/.test(lines[i]!)) para.push(inline(lines[i++]!));
|
|
99
|
+
out.push(`<p>${para.join('<br>')}</p>`);
|
|
100
|
+
}
|
|
101
|
+
return out.join('') || '<p><br></p>';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Inline content of an element back to Markdown. */
|
|
105
|
+
function inlineMd(node: Node): string {
|
|
106
|
+
let s = '';
|
|
107
|
+
for (const child of node.childNodes) {
|
|
108
|
+
if (child.nodeType === Node.TEXT_NODE) {
|
|
109
|
+
s += (child.textContent ?? '').replaceAll(' ', ' ');
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (!(child instanceof HTMLElement)) continue;
|
|
113
|
+
const tag = child.tagName;
|
|
114
|
+
const inner = inlineMd(child);
|
|
115
|
+
if (tag === 'BR') s += '\n';
|
|
116
|
+
else if (tag === 'STRONG' || tag === 'B') s += inner.trim() ? `**${inner}**` : inner;
|
|
117
|
+
else if (tag === 'EM' || tag === 'I') s += inner.trim() ? `*${inner}*` : inner;
|
|
118
|
+
else if (tag === 'CODE') s += `\`${child.textContent ?? ''}\``;
|
|
119
|
+
else if (tag === 'IMG') s += child.dataset.src ? `` : '';
|
|
120
|
+
else if (tag === 'A') s += safeHref(child.getAttribute('href') ?? '') ? `[${inner}](${child.getAttribute('href')})` : inner;
|
|
121
|
+
else s += inner;
|
|
122
|
+
}
|
|
123
|
+
return s;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The edited document back to Markdown, one block per paragraph. */
|
|
127
|
+
export function htmlToMd(root: HTMLElement): string {
|
|
128
|
+
const blocks: string[] = [];
|
|
129
|
+
const text = (el: Element) => inlineMd(el).replace(/\n+$/, '');
|
|
130
|
+
for (const child of root.childNodes) {
|
|
131
|
+
if (child.nodeType === Node.TEXT_NODE) {
|
|
132
|
+
if ((child.textContent ?? '').trim()) blocks.push(child.textContent!.trim());
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (!(child instanceof HTMLElement)) continue;
|
|
136
|
+
const tag = child.tagName;
|
|
137
|
+
if (/^H[1-6]$/.test(tag)) blocks.push(`${'#'.repeat(Math.min(3, Number(tag[1])))} ${text(child).replaceAll('\n', ' ')}`);
|
|
138
|
+
else if (tag === 'UL' || tag === 'OL') {
|
|
139
|
+
const items = [...child.children].filter((li) => li.tagName === 'LI');
|
|
140
|
+
blocks.push(items.map((li, k) => `${tag === 'OL' ? `${k + 1}.` : '-'} ${text(li).replaceAll('\n', ' ')}`).join('\n'));
|
|
141
|
+
} else if (tag === 'BLOCKQUOTE') blocks.push(text(child).split('\n').map((l) => `> ${l}`).join('\n'));
|
|
142
|
+
else if (tag === 'PRE') blocks.push(`\`\`\`\n${(child.textContent ?? '').replace(/\n$/, '')}\n\`\`\``);
|
|
143
|
+
else if (tag === 'HR') blocks.push('---');
|
|
144
|
+
else {
|
|
145
|
+
const t = text(child);
|
|
146
|
+
if (t.trim()) blocks.push(t.trim());
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return `${blocks.join('\n\n')}\n`;
|
|
150
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// A note edited as it reads, Medium-style: Markdown typed at the start of a
|
|
2
|
+
// line becomes the block (#, ##, ###, -, 1., >, ```, ---), and **bold**,
|
|
3
|
+
// *italic* and `code` turn into marks as they close. What is saved is Markdown.
|
|
4
|
+
import { htmlToMd, type ImageResolver, mdToHtml } from './markdown.ts';
|
|
5
|
+
import { el } from './ui.ts';
|
|
6
|
+
|
|
7
|
+
export interface NoteEditor {
|
|
8
|
+
el: HTMLElement;
|
|
9
|
+
setMarkdown(md: string): void;
|
|
10
|
+
getMarkdown(): string;
|
|
11
|
+
focus(): void;
|
|
12
|
+
/** Puts a line of Markdown (an image) after the block the caret was last in. */
|
|
13
|
+
insertBlock(md: string): void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function caretAtEnd(node: Node) {
|
|
17
|
+
const range = document.createRange();
|
|
18
|
+
range.selectNodeContents(node);
|
|
19
|
+
range.collapse(false);
|
|
20
|
+
const sel = getSelection();
|
|
21
|
+
sel?.removeAllRanges();
|
|
22
|
+
sel?.addRange(range);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createNoteEditor(opts: { onChange: () => void; placeholder: string; image?: () => ImageResolver }): NoteEditor {
|
|
26
|
+
const doc = el('div', 'note-doc');
|
|
27
|
+
doc.contentEditable = 'true';
|
|
28
|
+
doc.spellcheck = false;
|
|
29
|
+
doc.dataset.placeholder = opts.placeholder;
|
|
30
|
+
|
|
31
|
+
/** The top-level block the caret is in. */
|
|
32
|
+
const blockAt = (): HTMLElement | null => {
|
|
33
|
+
let n = getSelection()?.anchorNode ?? null;
|
|
34
|
+
while (n && n.parentNode !== doc) n = n.parentNode;
|
|
35
|
+
return n instanceof HTMLElement ? n : null;
|
|
36
|
+
};
|
|
37
|
+
const replaceBlock = (old: HTMLElement, tag: string, keep: Node[]): HTMLElement => {
|
|
38
|
+
const next = el(tag as 'p');
|
|
39
|
+
next.append(...keep);
|
|
40
|
+
if (!next.textContent) next.append(el('br'));
|
|
41
|
+
old.replaceWith(next);
|
|
42
|
+
return next;
|
|
43
|
+
};
|
|
44
|
+
const emptyEnd = () => {
|
|
45
|
+
const sel = getSelection();
|
|
46
|
+
const block = blockAt();
|
|
47
|
+
if (!sel || !block || !sel.isCollapsed) return false;
|
|
48
|
+
const r = document.createRange();
|
|
49
|
+
r.selectNodeContents(block);
|
|
50
|
+
r.setStart(sel.anchorNode!, sel.anchorOffset);
|
|
51
|
+
return !r.toString();
|
|
52
|
+
};
|
|
53
|
+
/** The block the caret was last in, so a toolbar click can insert after it. */
|
|
54
|
+
let lastBlock: HTMLElement | null = null;
|
|
55
|
+
const remember = () => {
|
|
56
|
+
const b = blockAt();
|
|
57
|
+
if (b) lastBlock = b;
|
|
58
|
+
};
|
|
59
|
+
doc.addEventListener('keyup', remember);
|
|
60
|
+
doc.addEventListener('mouseup', remember);
|
|
61
|
+
const isEmpty = (n: HTMLElement) => !(n.textContent ?? '').replace(//g, '').trim();
|
|
62
|
+
|
|
63
|
+
/** Block shortcuts: a marker and a space at the start of a paragraph. */
|
|
64
|
+
function blockRules(): boolean {
|
|
65
|
+
const block = blockAt();
|
|
66
|
+
if (!block || !/^(P|DIV)$/.test(block.tagName)) return false;
|
|
67
|
+
const text = (block.textContent ?? '').replaceAll(' ', ' ');
|
|
68
|
+
const m = /^(#{1,3}|[-*]|\d+[.)]|>) (.*)$/s.exec(text);
|
|
69
|
+
if (!m) return false;
|
|
70
|
+
const marker = m[1]!;
|
|
71
|
+
// Drop the marker from the block's first text, keep the rest (and any marks) as they are.
|
|
72
|
+
const first = block.firstChild;
|
|
73
|
+
if (first?.nodeType === Node.TEXT_NODE) first.textContent = (first.textContent ?? '').replace(/^\S+[ ]/, '');
|
|
74
|
+
const keep = [...block.childNodes].filter((n) => !(n instanceof HTMLBRElement) || block.childNodes.length > 1);
|
|
75
|
+
let target: HTMLElement;
|
|
76
|
+
if (marker.startsWith('#')) target = replaceBlock(block, `h${marker.length}`, keep);
|
|
77
|
+
else if (marker === '>') {
|
|
78
|
+
const q = el('blockquote');
|
|
79
|
+
const p = el('p');
|
|
80
|
+
p.append(...keep);
|
|
81
|
+
if (!p.textContent) p.append(el('br'));
|
|
82
|
+
q.append(p);
|
|
83
|
+
block.replaceWith(q);
|
|
84
|
+
target = p;
|
|
85
|
+
} else {
|
|
86
|
+
const list = el(/\d/.test(marker) ? 'ol' : 'ul');
|
|
87
|
+
const li = el('li');
|
|
88
|
+
li.append(...keep);
|
|
89
|
+
if (!li.textContent) li.append(el('br'));
|
|
90
|
+
list.append(li);
|
|
91
|
+
block.replaceWith(list);
|
|
92
|
+
target = li;
|
|
93
|
+
}
|
|
94
|
+
caretAtEnd(target);
|
|
95
|
+
return true;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Inline marks: **bold**, *italic*, `code` turn into elements as they close. */
|
|
99
|
+
function inlineRules() {
|
|
100
|
+
const sel = getSelection();
|
|
101
|
+
const node = sel?.anchorNode;
|
|
102
|
+
if (!sel || !node || node.nodeType !== Node.TEXT_NODE || !sel.isCollapsed) return;
|
|
103
|
+
if ((node.parentElement?.closest('code, pre') ?? null) !== null) return;
|
|
104
|
+
const before = (node.textContent ?? '').slice(0, sel.anchorOffset);
|
|
105
|
+
const rules: [RegExp, string][] = [
|
|
106
|
+
[/\*\*([^*]+)\*\*$/, 'strong'],
|
|
107
|
+
[/`([^`]+)`$/, 'code'],
|
|
108
|
+
[/(?:^|[^*])\*([^*\s][^*]*)\*$/, 'em'],
|
|
109
|
+
];
|
|
110
|
+
for (const [re, tag] of rules) {
|
|
111
|
+
const m = re.exec(before);
|
|
112
|
+
if (!m) continue;
|
|
113
|
+
const inner = m[1]!;
|
|
114
|
+
const start = before.length - (tag === 'em' ? inner.length + 2 : m[0].length);
|
|
115
|
+
const text = node as Text;
|
|
116
|
+
const after = text.splitText(start);
|
|
117
|
+
after.textContent = (after.textContent ?? '').slice(m[0].length - (tag === 'em' && m[0].length > inner.length + 2 ? 1 : 0));
|
|
118
|
+
const mark = el(tag as 'strong', '', inner);
|
|
119
|
+
const tail = document.createTextNode('');
|
|
120
|
+
after.before(mark, tail);
|
|
121
|
+
const r = document.createRange();
|
|
122
|
+
r.setStart(tail, 1);
|
|
123
|
+
r.collapse(true);
|
|
124
|
+
sel.removeAllRanges();
|
|
125
|
+
sel.addRange(r);
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
doc.addEventListener('input', () => {
|
|
131
|
+
if (!blockRules()) inlineRules();
|
|
132
|
+
opts.onChange();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
doc.addEventListener('keydown', (e) => {
|
|
136
|
+
const block = blockAt();
|
|
137
|
+
if (e.key === 'Enter' && !e.shiftKey && block) {
|
|
138
|
+
const text = (block.textContent ?? '').trim();
|
|
139
|
+
if (/^(P|DIV)$/.test(block.tagName) && (text === '---' || text === '***')) {
|
|
140
|
+
e.preventDefault();
|
|
141
|
+
const hr = el('hr');
|
|
142
|
+
const p = el('p');
|
|
143
|
+
p.append(el('br'));
|
|
144
|
+
block.replaceWith(hr);
|
|
145
|
+
hr.after(p);
|
|
146
|
+
caretAtEnd(p);
|
|
147
|
+
opts.onChange();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (/^(P|DIV)$/.test(block.tagName) && text === '```') {
|
|
151
|
+
e.preventDefault();
|
|
152
|
+
const pre = el('pre');
|
|
153
|
+
const code = el('code');
|
|
154
|
+
code.append(document.createTextNode('\n'));
|
|
155
|
+
pre.append(code);
|
|
156
|
+
block.replaceWith(pre);
|
|
157
|
+
caretAtEnd(code);
|
|
158
|
+
opts.onChange();
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (block.tagName === 'PRE') {
|
|
162
|
+
e.preventDefault();
|
|
163
|
+
document.execCommand('insertText', false, '\n');
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
// A heading or quote ends on Enter: the next line is a paragraph.
|
|
167
|
+
if (/^H[1-3]$|^BLOCKQUOTE$/.test(block.tagName) && emptyEnd()) {
|
|
168
|
+
e.preventDefault();
|
|
169
|
+
const p = el('p');
|
|
170
|
+
p.append(el('br'));
|
|
171
|
+
block.after(p);
|
|
172
|
+
caretAtEnd(p);
|
|
173
|
+
opts.onChange();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
// Enter on an empty list item leaves the list.
|
|
177
|
+
const li = (getSelection()?.anchorNode as Node | null)?.parentElement?.closest('li') ?? (getSelection()?.anchorNode instanceof HTMLLIElement ? (getSelection()!.anchorNode as HTMLLIElement) : null);
|
|
178
|
+
if (li && isEmpty(li) && (block.tagName === 'UL' || block.tagName === 'OL')) {
|
|
179
|
+
e.preventDefault();
|
|
180
|
+
const p = el('p');
|
|
181
|
+
p.append(el('br'));
|
|
182
|
+
li.remove();
|
|
183
|
+
block.after(p);
|
|
184
|
+
if (!block.querySelector('li')) block.remove();
|
|
185
|
+
caretAtEnd(p);
|
|
186
|
+
opts.onChange();
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
// Backspace at the start of a heading or quote turns it back into a paragraph.
|
|
190
|
+
if (e.key === 'Backspace' && block && /^H[1-3]$|^BLOCKQUOTE$/.test(block.tagName)) {
|
|
191
|
+
const sel = getSelection();
|
|
192
|
+
if (sel?.isCollapsed) {
|
|
193
|
+
const r = document.createRange();
|
|
194
|
+
r.selectNodeContents(block);
|
|
195
|
+
r.setEnd(sel.anchorNode!, sel.anchorOffset);
|
|
196
|
+
if (!r.toString()) {
|
|
197
|
+
e.preventDefault();
|
|
198
|
+
const inner = block.tagName === 'BLOCKQUOTE' ? (block.firstElementChild ?? block) : block;
|
|
199
|
+
const p = replaceBlock(block, 'p', [...inner.childNodes]);
|
|
200
|
+
const start = document.createRange();
|
|
201
|
+
start.setStart(p, 0);
|
|
202
|
+
start.collapse(true);
|
|
203
|
+
sel.removeAllRanges();
|
|
204
|
+
sel.addRange(start);
|
|
205
|
+
opts.onChange();
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
// Plain text only: no styles from a web page, and a pasted Markdown note reads as Markdown.
|
|
212
|
+
doc.addEventListener('paste', (e) => {
|
|
213
|
+
e.preventDefault();
|
|
214
|
+
const text = e.clipboardData?.getData('text/plain') ?? '';
|
|
215
|
+
if (!text) return;
|
|
216
|
+
if (/\n/.test(text) && /^(#{1,3}\s|[-*]\s|\d+[.)]\s|>\s|```)/m.test(text)) {
|
|
217
|
+
document.execCommand('insertHTML', false, mdToHtml(text, opts.image?.()));
|
|
218
|
+
} else document.execCommand('insertText', false, text);
|
|
219
|
+
});
|
|
220
|
+
doc.addEventListener('focus', () => document.execCommand('defaultParagraphSeparator', false, 'p'));
|
|
221
|
+
|
|
222
|
+
return {
|
|
223
|
+
el: doc,
|
|
224
|
+
setMarkdown(md) {
|
|
225
|
+
doc.innerHTML = mdToHtml(md, opts.image?.());
|
|
226
|
+
lastBlock = null;
|
|
227
|
+
},
|
|
228
|
+
insertBlock(md) {
|
|
229
|
+
const holder = el('div');
|
|
230
|
+
holder.innerHTML = mdToHtml(md, opts.image?.());
|
|
231
|
+
const block = holder.firstElementChild as HTMLElement | null;
|
|
232
|
+
if (!block) return;
|
|
233
|
+
const after = lastBlock && lastBlock.parentNode === doc ? lastBlock : null;
|
|
234
|
+
// An empty paragraph is replaced rather than left above the picture.
|
|
235
|
+
if (after && isEmpty(after) && !after.querySelector('img')) after.replaceWith(block);
|
|
236
|
+
else if (after) after.after(block);
|
|
237
|
+
else doc.append(block);
|
|
238
|
+
const next = el('p');
|
|
239
|
+
next.append(el('br'));
|
|
240
|
+
if (!block.nextElementSibling) block.after(next);
|
|
241
|
+
doc.focus();
|
|
242
|
+
caretAtEnd(block.nextElementSibling ?? block);
|
|
243
|
+
lastBlock = block;
|
|
244
|
+
opts.onChange();
|
|
245
|
+
},
|
|
246
|
+
getMarkdown: () => htmlToMd(doc).replaceAll('', ''),
|
|
247
|
+
focus() {
|
|
248
|
+
doc.focus();
|
|
249
|
+
caretAtEnd(doc.lastElementChild ?? doc);
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|