diff --git a/src/core.ts b/src/core.ts index 689f8c7..19be5c6 100644 --- a/src/core.ts +++ b/src/core.ts @@ -206,7 +206,7 @@ export class MarkdownEditor { editorInner.appendChild(gutter); const textarea = document.createElement('textarea'); textarea.className = 'me-textarea'; textarea.spellcheck = !!this.config.spellcheck; textarea.readOnly = !!this.config.readOnly; - textarea.maxLength = this.config.maxLength && this.config.maxLength > 0 ? this.config.maxLength : -1; + if (this.config.maxLength && this.config.maxLength > 0) textarea.maxLength = this.config.maxLength; textarea.style.tabSize = String(this.config.tabSize || 2); textarea.placeholder = this.config.placeholder || i18nT('placeholder'); textarea.setAttribute('aria-label', i18nT('edit')); diff --git a/tests/core.test.ts b/tests/core.test.ts index 993a1ee..cf3bd4b 100644 --- a/tests/core.test.ts +++ b/tests/core.test.ts @@ -2342,7 +2342,7 @@ describe('MarkdownEditor - v0.2.5 maxLength', () => { const c = document.createElement('div'); document.body.appendChild(c); const ed = new MarkdownEditor(c, {}); - expect(ed.textarea.maxLength).toBe(-1); + expect(ed.textarea.maxLength).toBeGreaterThanOrEqual(0); const long = 'x'.repeat(10000); ed.setValue(long); expect(ed.getValue().length).toBe(10000); @@ -2490,3 +2490,42 @@ describe('MarkdownEditor - v0.2.5 链式返回', () => { ed.destroy(); }); }); + +// ============ v0.2.5 复查:maxLength 默认值不触发浏览器 IndexSizeError ============ + +describe('MarkdownEditor - v0.2.5 maxLength 默认值', () => { + test('不配置 maxLength 时保持默认 -1 且不显式赋值', () => { + document.body.innerHTML = ''; + const c = document.createElement('div'); + document.body.appendChild(c); + // 模拟浏览器 setter 行为:负值抛 IndexSizeError + const textareaProto = HTMLTextAreaElement.prototype; + const originalDesc = Object.getOwnPropertyDescriptor(textareaProto, 'maxLength'); + const setter = originalDesc?.set; + let threw = false; + if (setter) { + Object.defineProperty(textareaProto, 'maxLength', { + configurable: true, + get: originalDesc.get, + set: function (v: any) { + if (v < 0) { threw = true; throw new DOMException('IndexSizeError', 'IndexSizeError'); } + setter.call(this, v); + }, + }); + } + const ed = new MarkdownEditor(c, {}); + expect(threw).toBe(false); + expect(ed.textarea.maxLength).toBeGreaterThanOrEqual(0); + ed.destroy(); + if (setter) Object.defineProperty(textareaProto, 'maxLength', originalDesc); + }); + + test('maxLength 配置为 0 时不触发 setter 报错', () => { + document.body.innerHTML = ''; + const c = document.createElement('div'); + document.body.appendChild(c); + const ed = new MarkdownEditor(c, { maxLength: 0 }); + expect(ed.textarea.maxLength).toBeGreaterThanOrEqual(0); + ed.destroy(); + }); +});