@colixsystems/widget-sdk 0.323.0 → 0.326.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/README.md +8 -4
- package/dist/contract.cjs +7 -2
- package/dist/contract.js +7 -2
- package/dist/host.d.ts +10 -0
- package/dist/host.js +3 -0
- package/dist/index.d.ts +17 -0
- package/dist/linter.cjs +50 -5
- package/dist/linter.js +50 -5
- package/dist/markdown-editor-bridge.js +6 -0
- package/dist/markdown-editor-bundle.js +1 -1
- package/dist/markdown-editor-core.js +14 -1
- package/dist/markdown-editor-field.js +8 -3
- package/dist/markdown-editor-html.js +1 -1
- package/dist/markdown-editor-webview.js +2 -0
- package/dist/markdown-input-view.js +13 -1
- package/dist/property-schema.js +3 -0
- package/dist/widget-font-families.cjs +47 -0
- package/dist/widget-font-families.js +40 -0
- package/package.json +1 -1
- package/src/contract.js +7 -2
package/README.md
CHANGED
|
@@ -91,7 +91,11 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
|
|
|
91
91
|
|
|
92
92
|
## Status
|
|
93
93
|
|
|
94
|
-
`v0.
|
|
94
|
+
`v0.326.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
|
|
95
|
+
|
|
96
|
+
### What's new in 0.324.0 (contract 1.264.0)
|
|
97
|
+
|
|
98
|
+
**A widget can insert text at the caret of a `<MarkdownInput>`.** Pass `editorRef={ref}` (from `useRef(null)`) and the field fills it with `{ insertText(text) }`: an emoji picker or a snippet button calls `ref.current.insertText("🎉")` and the text lands where the user's caret was, on web and in the WebView on iOS and Android alike. Before the user has placed a caret, the text goes at the end. It returns `false` while the editor is still loading, so a widget can append to its value instead. `editable={false}` locks the field and its toolbar, for example while a post is saving, so nothing typed then is lost. Additive.
|
|
95
99
|
|
|
96
100
|
### What's new in 0.323.0 (contract 1.263.0)
|
|
97
101
|
|
|
@@ -2608,7 +2612,7 @@ Additive — one new hook, one new optional context-slice member; no existing ex
|
|
|
2608
2612
|
|
|
2609
2613
|
**Two linter rules make the styling contract checkable, and `lintStyleWiring` joins the linter export (sc-6455).** Every visual value a widget writes reaches the app's owner through one of exactly two channels — a **theme token** (`useTheme()`), which is the app-wide default and follows a look change, or a **`styleSchema` field** read off `props.style`, which the Studio offers per instance in the widget editor *and* app-wide under **Design → Widget appearance**. A literal reaches neither: it outranks the theme permanently and no control on either surface can move it, so the owner finds a corner of their app they cannot restyle. Until now that rule was documentation only.
|
|
2610
2614
|
|
|
2611
|
-
- **`no-hardcoded-design`** flags a colour literal (`#rgb` / `#rrggbb` / `#rrggbbaa`, `rgb()`, `rgba()`, `hsl()`, `hsla()`), a `fontFamily` string literal, a numeric `fontSize`, or (since 0.165.0) a literal non-zero corner radius (`borderRadius: 12`, any per-corner spelling). A `fontSize` resolved off a theme token or a style field (`style.valueSize ?? 18`) is *not* flagged — a literal `default` beside a declared field is the contract working — and neither is a computed radius (`size / 2`) or `0`. Raw `padding` / `margin` numbers are deliberately out of scope: measured layout legitimately carries them, so a spacing rule would be noise.
|
|
2615
|
+
- **`no-hardcoded-design`** flags a colour literal (`#rgb` / `#rrggbb` / `#rrggbbaa`, `rgb()`, `rgba()`, `hsl()`, `hsla()`), a `fontFamily` string literal or (since 0.326.0) a family named as the fallback of a font read (`style.titleFont || "Lora"`), a numeric `fontSize`, or (since 0.165.0) a literal non-zero corner radius (`borderRadius: 12`, any per-corner spelling). A `fontSize` resolved off a theme token or a style field (`style.valueSize ?? 18`) is *not* flagged — a literal `default` beside a declared field is the contract working — and neither is a computed radius (`size / 2`) or `0`. Raw `padding` / `margin` numbers are deliberately out of scope: measured layout legitimately carries them, so a spacing rule would be noise.
|
|
2612
2616
|
- **`style-field-unread`** flags a `styleSchema` field whose name appears nowhere in the widget's source — a dead control the author moves to no effect. It runs over the WHOLE bundle, not per file, so a split-impl widget that reads a field in `widget.web.jsx` and not in `widget.native.jsx` is correctly counted as wired.
|
|
2613
2617
|
|
|
2614
2618
|
A value that genuinely cannot be a token — a categorical series palette, a video letterbox, a scannable QR plate — is licensed with a preceding comment. **The reason is mandatory**; a bare marker licenses nothing. A marker on its own line covers the whole statement below it (bracket-balanced, so one marker covers a multi-line palette); a trailing marker covers only its own line.
|
|
@@ -3597,7 +3601,7 @@ import { defineWidget, validateManifest, useDatastoreQuery, Text, View } from "@
|
|
|
3597
3601
|
- `ConfirmDialog` — the standard confirmation prompt, a preset of `Modal` and `Button`. `<ConfirmDialog visible={asking} tone="destructive" title="Delete this order?" message="This cannot be undone." confirmLabel="Delete" onCancel={() => setAsking(false)} onConfirm={removeOrder} />` asks before a delete or any other action that cannot be undone. Cancel, the close button, the backdrop, Escape and the Android back button fire `onCancel`; a promise returned from `onConfirm` keeps it busy (buttons disabled, a second press ignored) until it settles. Props: `visible`, `title`, `message`, `confirmLabel`, `cancelLabel`, `tone` (`default` | `destructive`), `busy`, `onConfirm`, `onCancel`, `closeAccessibilityLabel`, `testID`. Use it instead of building a confirmation from `Modal` yourself.
|
|
3598
3602
|
- `Modal` — the standard dialog, built on `Overlay`. `<Modal visible={open} onRequestClose={() => setOpen(false)} title="Edit order" footer={<Button title="Save" onPress={save} />}>…</Modal>` draws a title, a close button, a body that scrolls when it is long and a footer action row laid out below it. Its background, corner radius, padding, scrim, shadow and title colour come from the theme's `modal` scope (Design > Components > Dialogs), so every dialog in an app matches. Props: `visible`, `onRequestClose`, `dismissible`, `title`, `footer`, `presentation` (`dialog` | `sheet`), `size` (`sm` | `md` | `lg` | `full`), `dismissOnBackdropPress`, `role`, `initialFocusRef`, `closeAccessibilityLabel`, `accessibilityLabel`, `testID`. Use it for every dialog instead of hand-building a header and an action row inside `Overlay`.
|
|
3599
3603
|
- `RichText` — the formatted-content renderer. `<RichText value={post.body} />` parses the markdown subset (`**bold**`, `*italic*` / `_italic_`, `` `code` ``, `#`/`##`/`###` headings, `-`/`*` bullets, `1.` ordered items, one-line `` images) and renders it with SDK primitives, so formatted content reads the same in the web Player and the exported Expo app. `value` is markdown, NOT HTML — widgets have no `dangerouslySetInnerHTML` on either host, so tags in a content string render as literal tag soup; stored text that still holds legacy HTML is stripped to plain text rather than shown as markup. Props: `value`, `renderImage` (`({ src, alt, size }) => node` — supply it when images are filestore ids, because resolving one needs the scopes your own widget holds; without it only absolute `http(s)` URLs render), `style`, `testID`. Colour, type scale and leading come from the workspace theme — never re-style them.
|
|
3600
|
-
- `MarkdownInput` — the authoring half of `<RichText>`. `<MarkdownInput value={draft} onChange={setDraft} />` is a rich-text field where the author edits the formatted result directly (headings, emphasis, code, links, lists and real tables), with a toolbar, a Table button and a Link button — the way to let an app USER write formatted text, instead of a bare `TextInput` plus hand-rolled buttons that can only splice literal tags into the value. The value stays markdown. Props: `value`, `onChange(next)`, `placeholder`, `pages` (offered by name in the Link form), `minHeight` (150) and `maxHeight` (280) — it grows between them, then scrolls — `accessibilityLabel`, `style`, `testID
|
|
3604
|
+
- `MarkdownInput` — the authoring half of `<RichText>`. `<MarkdownInput value={draft} onChange={setDraft} />` is a rich-text field where the author edits the formatted result directly (headings, emphasis, code, links, lists and real tables), with a toolbar, a Table button and a Link button — the way to let an app USER write formatted text, instead of a bare `TextInput` plus hand-rolled buttons that can only splice literal tags into the value. The value stays markdown. Props: `value`, `onChange(next)`, `placeholder`, `pages` (offered by name in the Link form), `minHeight` (150) and `maxHeight` (280) — it grows between them, then scrolls — `accessibilityLabel`, `style`, `testID`, `editorRef` (filled with `{ insertText(text) }` to insert at the caret) and `editable` (`false` locks it, e.g. while saving). `showPreview`, `previewLabel` and `renderImage` are accepted and ignored.
|
|
3601
3605
|
- `parseMarkdown`, `markdownToPlainText`, `parseMarkdownImage`, `formatMarkdownImage`, `stripHtmlToMarkdown`, `MARKDOWN_IMAGE_SIZES` — the same grammar as pure helpers, for content you inspect rather than render: the block list, a marker-free projection (list previews, search, a11y labels), the one-line image form read and written, a legacy-HTML row normalised to markdown on read, and the closed size list (`small` | `medium` | `large` | `full`).
|
|
3602
3606
|
- `isSafeMarkdownImageSrc`, `isHttpImageSrc`, `normaliseMarkdownImageSize`, `readMarkdownAlt` — the image half of that grammar, for a widget rendering images itself via `renderImage`. `isSafeMarkdownImageSrc` is the same allowlist the parser applies (an `http(s)` URL or a filestore id; a `javascript:` scheme is refused), so the widget and the parser cannot disagree about which src is renderable.
|
|
3603
3607
|
- `List`, `ListRow`, `ListHeader`, `EmptyState` — the themed list building blocks. `<ListRow title subtitle leading trailing onPress selected divider>` draws one record row from the theme's `list` scope (padding, height, gap, radius, background, divider); `<List>` spaces its rows and hands overrides down; `<ListHeader>` labels a table's columns on the rows' own inset; `<EmptyState icon title message>` is the "nothing here" panel. Use them by default for record rows and a table's header; build your own row when it needs what `ListRow` cannot do (a swipe-to-delete row, a row that expands in place).
|
|
@@ -4071,7 +4075,7 @@ const wiring = lintStyleWiring(manifest, { "widget.jsx": source });
|
|
|
4071
4075
|
const editability = lintEditability(manifest, { "widget.jsx": source });
|
|
4072
4076
|
```
|
|
4073
4077
|
|
|
4074
|
-
Two rules keep a widget's look reachable from the Studio. `no-hardcoded-design` flags a colour literal, a `fontFamily` string, or a numeric `fontSize` — values that outrank the theme permanently and that no control can move. `style-field-unread` flags a `styleSchema` field the source never reads, which renders a control that does nothing. Both are warnings for a human author and blocking for the AI widget agent. License a genuinely un-tokenizable value with a preceding `// appstudio-design-ok: <reason>` (the reason is required); see *What's new in 0.110.0*.
|
|
4078
|
+
Two rules keep a widget's look reachable from the Studio. `no-hardcoded-design` flags a colour literal, a `fontFamily` string, or a numeric `fontSize` — values that outrank the theme permanently and that no control can move. `style-field-unread` flags a `styleSchema` field the source never reads, which renders a control that does nothing. Both are warnings for a human author and blocking for the AI widget agent. License a genuinely un-tokenizable value with a preceding `// appstudio-design-ok: <reason>` (the reason is required); see *What's new in 0.110.0*. A font family is never licensed (since 0.326.0): one written in the source never loads on either host, so use the workspace's fonts or a `{ type: "font" }` style field read with the theme font as its fallback.
|
|
4075
4079
|
|
|
4076
4080
|
Three more rules keep a widget EDITABLE once it ships, via the bundle-level `lintEditability(manifest, files)`. `style-group-missing` flags a `styleSchema` field with no `ui.group` — or one under a catch-all name — so a long Style section reads as labelled per-element fieldsets. `style-elements-uncovered` flags a multi-element widget whose Style section still only restyles the widget as a whole. `text-literal-unexposed` flags copy pinned in a `<Text>` — wording no control can change and no locale can translate. All three are warnings here and blocking for the AI widget agent; see *What's new in 0.140.0*.
|
|
4077
4081
|
|
package/dist/contract.cjs
CHANGED
|
@@ -3746,7 +3746,7 @@ const PRIMITIVES = [
|
|
|
3746
3746
|
{
|
|
3747
3747
|
name: "MarkdownInput",
|
|
3748
3748
|
description:
|
|
3749
|
-
"Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID
|
|
3749
|
+
"Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID`, `editorRef` (a ref filled with `{ insertText(text) }`, which inserts plain text at the caret, e.g. from an emoji picker, or at the end before the user has placed one, and returns false while the editor loads), and `editable` (default true; `false` locks the field and its toolbar, e.g. while saving). `showPreview`, `previewLabel` and `renderImage` are still accepted and ignored. Images show inside the field when their source is an http(s) URL and as a labelled placeholder when it is a filestore id. Links in the field are inert, so a tap while editing cannot navigate away from the draft.",
|
|
3750
3750
|
rnComponent: null,
|
|
3751
3751
|
docsUrl: null,
|
|
3752
3752
|
},
|
|
@@ -7027,7 +7027,12 @@ const CONTRACT = deepFreeze({
|
|
|
7027
7027
|
// update writes a paid status is the `payment-status-written` warning.
|
|
7028
7028
|
// 1.263.0: stricter lint — in a widget reading groupIds or useGroups(), a
|
|
7029
7029
|
// propertySchema text field holding group ids is `group-ids-as-text`.
|
|
7030
|
-
|
|
7030
|
+
// 1.264.0: additive (sc-17317) — `<MarkdownInput editorRef>` is filled
|
|
7031
|
+
// with `{ insertText(text) }`, inserting plain text at the caret, and
|
|
7032
|
+
// `editable={false}` locks the field and its toolbar.
|
|
7033
|
+
// 1.265.0: `font` is a field type, and a font named in the source is
|
|
7034
|
+
// `no-hardcoded-design` with no licence (sc-17364).
|
|
7035
|
+
version: "1.265.0",
|
|
7031
7036
|
sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
|
|
7032
7037
|
hooks: HOOKS,
|
|
7033
7038
|
primitives: PRIMITIVES,
|
package/dist/contract.js
CHANGED
|
@@ -3741,7 +3741,7 @@ const PRIMITIVES = [
|
|
|
3741
3741
|
{
|
|
3742
3742
|
name: "MarkdownInput",
|
|
3743
3743
|
description:
|
|
3744
|
-
"Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID
|
|
3744
|
+
"Formatted-content editor. `<MarkdownInput value={draft} onChange={setDraft} />`. The default way to let an app USER write formatted text: a rich-text field where the user edits the FORMATTED RESULT directly — headings, bold, italic, code, links, bulleted and numbered lists and real tables are shown as they will read, with no markdown markers in view — plus a toolbar (bold, italic, code, H2, H3, bullets, numbered list), a Table button that inserts a real table, with buttons to add or remove rows and columns or delete the table while the caret is in one, and a Link button that opens a form for the link text plus its target. Typing `## `, `- `, `1. `, `**bold**` or `*italic*` formats as you type. Use it rather than a bare `TextInput` plus formatting buttons of your own, and do NOT add a `<RichText>` preview under it: the field already shows the result; an editor you do build (one that only bolds, a checklist editor) still stores markdown markers and previews with `<RichText>` — buttons that splice `<strong>`/`<br>`/`<table>` tags into the string leave the author reading tag soup. The stored value is markdown text in the `<RichText>` grammar; loading a value never rewrites it, and an edit writes each construct in its canonical spelling. On iOS and Android the field runs in a WebView bundled into the SDK (no network). Props: `value`, `onChange(next)`, `placeholder`, `pages` (optional `[{ id, name }]` — supply it and the Link form offers those pages to link to by name; without it the form offers only an external address, because a widget cannot know the app's pages on its own), `minHeight` (default 150) and `maxHeight` (default 280) — the field grows with its content between them, then scrolls — `accessibilityLabel`, `style`, `testID`, `editorRef` (a ref filled with `{ insertText(text) }`, which inserts plain text at the caret, e.g. from an emoji picker, or at the end before the user has placed one, and returns false while the editor loads), and `editable` (default true; `false` locks the field and its toolbar, e.g. while saving). `showPreview`, `previewLabel` and `renderImage` are still accepted and ignored. Images show inside the field when their source is an http(s) URL and as a labelled placeholder when it is a filestore id. Links in the field are inert, so a tap while editing cannot navigate away from the draft.",
|
|
3745
3745
|
rnComponent: null,
|
|
3746
3746
|
docsUrl: null,
|
|
3747
3747
|
},
|
|
@@ -7022,7 +7022,12 @@ const CONTRACT = deepFreeze({
|
|
|
7022
7022
|
// update writes a paid status is the `payment-status-written` warning.
|
|
7023
7023
|
// 1.263.0: stricter lint — in a widget reading groupIds or useGroups(), a
|
|
7024
7024
|
// propertySchema text field holding group ids is `group-ids-as-text`.
|
|
7025
|
-
|
|
7025
|
+
// 1.264.0: additive (sc-17317) — `<MarkdownInput editorRef>` is filled
|
|
7026
|
+
// with `{ insertText(text) }`, inserting plain text at the caret, and
|
|
7027
|
+
// `editable={false}` locks the field and its toolbar.
|
|
7028
|
+
// 1.265.0: `font` is a field type, and a font named in the source is
|
|
7029
|
+
// `no-hardcoded-design` with no licence (sc-17364).
|
|
7030
|
+
version: "1.265.0",
|
|
7026
7031
|
sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
|
|
7027
7032
|
hooks: HOOKS,
|
|
7028
7033
|
primitives: PRIMITIVES,
|
package/dist/host.d.ts
CHANGED
|
@@ -136,6 +136,16 @@ export function applyThemeComponentStyle<T = Record<string, unknown>>(
|
|
|
136
136
|
styleSchema?: Record<string, unknown> | null,
|
|
137
137
|
): T;
|
|
138
138
|
|
|
139
|
+
/**
|
|
140
|
+
* sc-17349: every family a manifest `font` field resolves to (the instance
|
|
141
|
+
* value, else the field default, at any depth), for each host to load.
|
|
142
|
+
*/
|
|
143
|
+
export function widgetFontFamilies(input?: {
|
|
144
|
+
propertySchema?: Record<string, unknown> | null;
|
|
145
|
+
styleSchema?: Record<string, unknown> | null;
|
|
146
|
+
props?: Record<string, unknown> | null;
|
|
147
|
+
}): string[];
|
|
148
|
+
|
|
139
149
|
/** One text role's validated fields (REQ-THEME-ROLE). */
|
|
140
150
|
export type TypographyRole = Record<string, string | number>;
|
|
141
151
|
|
package/dist/host.js
CHANGED
|
@@ -159,6 +159,9 @@ export {
|
|
|
159
159
|
resolveLoginTextVisibility,
|
|
160
160
|
} from "./theme-background.js";
|
|
161
161
|
|
|
162
|
+
// sc-17349: the families a widget's `font` fields name, which each host must load.
|
|
163
|
+
export { widgetFontFamilies } from "./widget-font-families.js";
|
|
164
|
+
|
|
162
165
|
// REQ-THEME-APPEARANCE (sc-12335): an app's light and dark palettes. Each host
|
|
163
166
|
// resolves the mode it shows and the theme it renders through these, so a dark
|
|
164
167
|
// palette and the choice of palette mean the same thing on web and native.
|
package/dist/index.d.ts
CHANGED
|
@@ -22,6 +22,8 @@ export type WidgetPropertyType =
|
|
|
22
22
|
| "number"
|
|
23
23
|
| "boolean"
|
|
24
24
|
| "color"
|
|
25
|
+
// A font family picker; both hosts load the family it names.
|
|
26
|
+
| "font"
|
|
25
27
|
| "icon"
|
|
26
28
|
| "image"
|
|
27
29
|
| "select"
|
|
@@ -6216,8 +6218,23 @@ export const MarkdownInput: (props: {
|
|
|
6216
6218
|
accessibilityLabel?: string;
|
|
6217
6219
|
style?: any;
|
|
6218
6220
|
testID?: string;
|
|
6221
|
+
/**
|
|
6222
|
+
* Filled with `{ insertText(text) }`, which inserts plain text at the caret
|
|
6223
|
+
* (e.g. from an emoji picker), or at the end before the user has placed one.
|
|
6224
|
+
* Returns false while the editor is loading; on iOS and Android true means
|
|
6225
|
+
* the text was sent to the editor page.
|
|
6226
|
+
*/
|
|
6227
|
+
editorRef?:
|
|
6228
|
+
| { current: MarkdownInputHandle | null }
|
|
6229
|
+
| ((handle: MarkdownInputHandle | null) => void);
|
|
6230
|
+
/** False locks the field and its toolbar, e.g. while saving. Defaults to true. */
|
|
6231
|
+
editable?: boolean;
|
|
6219
6232
|
}) => any;
|
|
6220
6233
|
|
|
6234
|
+
export interface MarkdownInputHandle {
|
|
6235
|
+
insertText(text: string): boolean;
|
|
6236
|
+
}
|
|
6237
|
+
|
|
6221
6238
|
// ------------------------------------------------------- theme derivation
|
|
6222
6239
|
// sc-3696: the colour maths both hosts resolve `useTheme()` with. Exported so
|
|
6223
6240
|
// the Player (frontend/src/services/widgetTheme.js) and the exported app's
|
package/dist/linter.cjs
CHANGED
|
@@ -3073,7 +3073,17 @@ function narrowManifestForFile(manifest, filename) {
|
|
|
3073
3073
|
const _DESIGN_HEX_RE =
|
|
3074
3074
|
/#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})(?![0-9a-fA-F])/;
|
|
3075
3075
|
const _DESIGN_FUNC_COLOR_RE = /\b(?:rgba?|hsla?)\s*\(/;
|
|
3076
|
-
|
|
3076
|
+
// The quoted value after `fontFamily:`, or (sc-17364) after `||` / `??` on a
|
|
3077
|
+
// font read such as `style.titleFont`, `style["titleFont"]?.trim()`, across
|
|
3078
|
+
// lines. fontWeight / fontSize never match.
|
|
3079
|
+
const _DESIGN_FONT_LITERAL_RE =
|
|
3080
|
+
/(?:\bfontFamily\s*:|[Ff]ont(?:Family)?(?:\?\.\w+\(\)|["'\])])*\s*(?:\|\||\?\?))\s*(["'`])([^"'`\n]*)/g;
|
|
3081
|
+
// Faces every host already has; naming one loads nothing.
|
|
3082
|
+
const _DESIGN_FONT_GENERIC = new Set([
|
|
3083
|
+
"serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "math",
|
|
3084
|
+
"emoji", "fangsong", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded",
|
|
3085
|
+
"-apple-system", "inherit", "initial", "unset", "revert", "revert-layer",
|
|
3086
|
+
]);
|
|
3077
3087
|
const _DESIGN_FONT_SIZE_RE = /\bfontSize\s*:\s*-?\d/;
|
|
3078
3088
|
const _DESIGN_RADIUS_RE =
|
|
3079
3089
|
/\bborder(?:Top|Bottom|Start|End)?(?:Left|Right|Start|End)?Radius\s*:\s*(?:0*[1-9]\d*(?:\.\d+)?|0\.\d*[1-9]\d*)\s*(?=[,}]|$)/;
|
|
@@ -3123,20 +3133,55 @@ function _designExemptLines(source) {
|
|
|
3123
3133
|
return exempt;
|
|
3124
3134
|
}
|
|
3125
3135
|
|
|
3136
|
+
const _DESIGN_FONT_LABEL =
|
|
3137
|
+
"a font-family name in the source never loads: the web Player and the " +
|
|
3138
|
+
"exported app load only the workspace's fonts and the families a " +
|
|
3139
|
+
"`type: \"font\"` field names, so this text renders a fallback face and " +
|
|
3140
|
+
"no theme change reaches it. Use theme.typography.fontFamily or " +
|
|
3141
|
+
"theme.typography.headingFontFamily. To override the workspace font, " +
|
|
3142
|
+
"declare a styleSchema field { type: \"font\" } and read " +
|
|
3143
|
+
"props.style.<field> || theme.typography.headingFontFamily; its default " +
|
|
3144
|
+
"may name the family. appstudio-design-ok does not license a font.";
|
|
3145
|
+
|
|
3146
|
+
/** Lines (1-based) where the source names a font family to load. */
|
|
3147
|
+
function _namedFontLines(code) {
|
|
3148
|
+
const lines = new Set();
|
|
3149
|
+
for (const m of code.matchAll(_DESIGN_FONT_LITERAL_RE)) {
|
|
3150
|
+
const value = m[2].trim();
|
|
3151
|
+
if (value.startsWith("${")) continue;
|
|
3152
|
+
const first = value.split(",")[0].trim().replace(/^["']|["']$/g, "").toLowerCase();
|
|
3153
|
+
if (!/[a-z]/.test(first) || _DESIGN_FONT_GENERIC.has(first)) continue;
|
|
3154
|
+
const at = m.index + m[0].length - m[2].length;
|
|
3155
|
+
lines.add(code.slice(0, at).split("\n").length);
|
|
3156
|
+
}
|
|
3157
|
+
return lines;
|
|
3158
|
+
}
|
|
3159
|
+
|
|
3126
3160
|
function _hardcodedDesignRules(source) {
|
|
3127
3161
|
// Comments blanked, string CONTENT kept — a colour literal IS a string.
|
|
3128
|
-
const
|
|
3162
|
+
const stripped = _stripNonCode(source, { keepStrings: true }).replace(/\r\n/g, "\n");
|
|
3163
|
+
const code = stripped.split("\n");
|
|
3129
3164
|
const sourceLines = source.split(/\r?\n/);
|
|
3130
3165
|
const exempt = _designExemptLines(source);
|
|
3166
|
+
const fontLines = _namedFontLines(stripped);
|
|
3131
3167
|
const findings = [];
|
|
3132
3168
|
for (let i = 0; i < code.length; i += 1) {
|
|
3133
|
-
if (exempt.has(i + 1)) continue;
|
|
3134
3169
|
const line = code[i];
|
|
3170
|
+
// sc-17364: a font named in the source never loads on either host, so
|
|
3171
|
+
// no marker can license it.
|
|
3172
|
+
if (fontLines.has(i + 1)) {
|
|
3173
|
+
findings.push({
|
|
3174
|
+
rule: "no-hardcoded-design",
|
|
3175
|
+
severity: "warning",
|
|
3176
|
+
label: _DESIGN_FONT_LABEL,
|
|
3177
|
+
line: i + 1,
|
|
3178
|
+
snippet: (sourceLines[i] || "").trim().slice(0, 200),
|
|
3179
|
+
});
|
|
3180
|
+
}
|
|
3181
|
+
if (exempt.has(i + 1)) continue;
|
|
3135
3182
|
let what = null;
|
|
3136
3183
|
if (_DESIGN_HEX_RE.test(line) || _DESIGN_FUNC_COLOR_RE.test(line)) {
|
|
3137
3184
|
what = "a colour literal";
|
|
3138
|
-
} else if (_DESIGN_FONT_FAMILY_RE.test(line)) {
|
|
3139
|
-
what = "a font-family name";
|
|
3140
3185
|
} else if (
|
|
3141
3186
|
_DESIGN_FONT_SIZE_RE.test(line) &&
|
|
3142
3187
|
!_DESIGN_TOKEN_REF_RE.test(line)
|
package/dist/linter.js
CHANGED
|
@@ -3068,7 +3068,17 @@ export function narrowManifestForFile(manifest, filename) {
|
|
|
3068
3068
|
const _DESIGN_HEX_RE =
|
|
3069
3069
|
/#(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{3,4})(?![0-9a-fA-F])/;
|
|
3070
3070
|
const _DESIGN_FUNC_COLOR_RE = /\b(?:rgba?|hsla?)\s*\(/;
|
|
3071
|
-
|
|
3071
|
+
// The quoted value after `fontFamily:`, or (sc-17364) after `||` / `??` on a
|
|
3072
|
+
// font read such as `style.titleFont`, `style["titleFont"]?.trim()`, across
|
|
3073
|
+
// lines. fontWeight / fontSize never match.
|
|
3074
|
+
const _DESIGN_FONT_LITERAL_RE =
|
|
3075
|
+
/(?:\bfontFamily\s*:|[Ff]ont(?:Family)?(?:\?\.\w+\(\)|["'\])])*\s*(?:\|\||\?\?))\s*(["'`])([^"'`\n]*)/g;
|
|
3076
|
+
// Faces every host already has; naming one loads nothing.
|
|
3077
|
+
const _DESIGN_FONT_GENERIC = new Set([
|
|
3078
|
+
"serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "math",
|
|
3079
|
+
"emoji", "fangsong", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded",
|
|
3080
|
+
"-apple-system", "inherit", "initial", "unset", "revert", "revert-layer",
|
|
3081
|
+
]);
|
|
3072
3082
|
const _DESIGN_FONT_SIZE_RE = /\bfontSize\s*:\s*-?\d/;
|
|
3073
3083
|
const _DESIGN_RADIUS_RE =
|
|
3074
3084
|
/\bborder(?:Top|Bottom|Start|End)?(?:Left|Right|Start|End)?Radius\s*:\s*(?:0*[1-9]\d*(?:\.\d+)?|0\.\d*[1-9]\d*)\s*(?=[,}]|$)/;
|
|
@@ -3118,20 +3128,55 @@ function _designExemptLines(source) {
|
|
|
3118
3128
|
return exempt;
|
|
3119
3129
|
}
|
|
3120
3130
|
|
|
3131
|
+
const _DESIGN_FONT_LABEL =
|
|
3132
|
+
"a font-family name in the source never loads: the web Player and the " +
|
|
3133
|
+
"exported app load only the workspace's fonts and the families a " +
|
|
3134
|
+
"`type: \"font\"` field names, so this text renders a fallback face and " +
|
|
3135
|
+
"no theme change reaches it. Use theme.typography.fontFamily or " +
|
|
3136
|
+
"theme.typography.headingFontFamily. To override the workspace font, " +
|
|
3137
|
+
"declare a styleSchema field { type: \"font\" } and read " +
|
|
3138
|
+
"props.style.<field> || theme.typography.headingFontFamily; its default " +
|
|
3139
|
+
"may name the family. appstudio-design-ok does not license a font.";
|
|
3140
|
+
|
|
3141
|
+
/** Lines (1-based) where the source names a font family to load. */
|
|
3142
|
+
function _namedFontLines(code) {
|
|
3143
|
+
const lines = new Set();
|
|
3144
|
+
for (const m of code.matchAll(_DESIGN_FONT_LITERAL_RE)) {
|
|
3145
|
+
const value = m[2].trim();
|
|
3146
|
+
if (value.startsWith("${")) continue;
|
|
3147
|
+
const first = value.split(",")[0].trim().replace(/^["']|["']$/g, "").toLowerCase();
|
|
3148
|
+
if (!/[a-z]/.test(first) || _DESIGN_FONT_GENERIC.has(first)) continue;
|
|
3149
|
+
const at = m.index + m[0].length - m[2].length;
|
|
3150
|
+
lines.add(code.slice(0, at).split("\n").length);
|
|
3151
|
+
}
|
|
3152
|
+
return lines;
|
|
3153
|
+
}
|
|
3154
|
+
|
|
3121
3155
|
function _hardcodedDesignRules(source) {
|
|
3122
3156
|
// Comments blanked, string CONTENT kept — a colour literal IS a string.
|
|
3123
|
-
const
|
|
3157
|
+
const stripped = _stripNonCode(source, { keepStrings: true }).replace(/\r\n/g, "\n");
|
|
3158
|
+
const code = stripped.split("\n");
|
|
3124
3159
|
const sourceLines = source.split(/\r?\n/);
|
|
3125
3160
|
const exempt = _designExemptLines(source);
|
|
3161
|
+
const fontLines = _namedFontLines(stripped);
|
|
3126
3162
|
const findings = [];
|
|
3127
3163
|
for (let i = 0; i < code.length; i += 1) {
|
|
3128
|
-
if (exempt.has(i + 1)) continue;
|
|
3129
3164
|
const line = code[i];
|
|
3165
|
+
// sc-17364: a font named in the source never loads on either host, so
|
|
3166
|
+
// no marker can license it.
|
|
3167
|
+
if (fontLines.has(i + 1)) {
|
|
3168
|
+
findings.push({
|
|
3169
|
+
rule: "no-hardcoded-design",
|
|
3170
|
+
severity: "warning",
|
|
3171
|
+
label: _DESIGN_FONT_LABEL,
|
|
3172
|
+
line: i + 1,
|
|
3173
|
+
snippet: (sourceLines[i] || "").trim().slice(0, 200),
|
|
3174
|
+
});
|
|
3175
|
+
}
|
|
3176
|
+
if (exempt.has(i + 1)) continue;
|
|
3130
3177
|
let what = null;
|
|
3131
3178
|
if (_DESIGN_HEX_RE.test(line) || _DESIGN_FUNC_COLOR_RE.test(line)) {
|
|
3132
3179
|
what = "a colour literal";
|
|
3133
|
-
} else if (_DESIGN_FONT_FAMILY_RE.test(line)) {
|
|
3134
|
-
what = "a font-family name";
|
|
3135
3180
|
} else if (
|
|
3136
3181
|
_DESIGN_FONT_SIZE_RE.test(line) &&
|
|
3137
3182
|
!_DESIGN_TOKEN_REF_RE.test(line)
|
|
@@ -40,6 +40,7 @@ export function makeMarkdownEditorField({ View, WebView }) {
|
|
|
40
40
|
tokens,
|
|
41
41
|
minHeight,
|
|
42
42
|
maxHeight,
|
|
43
|
+
editable = true,
|
|
43
44
|
testID,
|
|
44
45
|
},
|
|
45
46
|
ref,
|
|
@@ -63,6 +64,10 @@ export function makeMarkdownEditorField({ View, WebView }) {
|
|
|
63
64
|
send({ type: "set", markdown: value });
|
|
64
65
|
}, [value, send]);
|
|
65
66
|
|
|
67
|
+
React.useEffect(() => {
|
|
68
|
+
send({ type: "editable", editable });
|
|
69
|
+
}, [editable, send]);
|
|
70
|
+
|
|
66
71
|
// A theme switch repaints the page, as it does the web field.
|
|
67
72
|
React.useEffect(() => {
|
|
68
73
|
send({ type: "style", tokens, minHeight });
|
|
@@ -99,6 +104,7 @@ export function makeMarkdownEditorField({ View, WebView }) {
|
|
|
99
104
|
label: accessibilityLabel,
|
|
100
105
|
tokens,
|
|
101
106
|
minHeight,
|
|
107
|
+
editable,
|
|
102
108
|
});
|
|
103
109
|
} else if (
|
|
104
110
|
message.type === "change" &&
|
|
@@ -155,4 +155,4 @@ img.ProseMirror-separator {
|
|
|
155
155
|
`);if(i.length<2)return;let s=i[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(s)||!s.includes("|"))return;let l=n1(o);if(l===o)return;let a=n.blockTokens(l)[0];if(a?.type!=="table"||!a.raw)return;let c=a.raw.split(`
|
|
156
156
|
`).length,u=t.split(`
|
|
157
157
|
`).slice(0,c).join(`
|
|
158
|
-
`);return{...a,raw:u}}},addCommands(){return{insertTable:({rows:t=3,cols:e=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:o,editor:i})=>{let s=e1(i.schema,t,e,n);if(o){let l=r.selection.from+1;r.replaceSelectionWith(s).scrollIntoView().setSelection(v.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:t,dispatch:e})=>Af(t,e),addColumnAfter:()=>({state:t,dispatch:e})=>Tf(t,e),deleteColumn:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return Nf(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},addRowBefore:()=>({state:t,dispatch:e})=>Rf(t,e),addRowAfter:()=>({state:t,dispatch:e})=>Df(t,e),deleteRow:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return If(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},deleteTable:()=>({state:t,dispatch:e})=>zf(t,e),mergeCells:()=>({state:t,dispatch:e})=>bl(t,e),splitCell:()=>({state:t,dispatch:e})=>kl(t,e),toggleHeaderColumn:()=>({state:t,dispatch:e})=>wn("column")(t,e),toggleHeaderRow:()=>({state:t,dispatch:e})=>wn("row")(t,e),toggleHeaderCell:()=>({state:t,dispatch:e})=>Lf(t,e),mergeOrSplit:()=>({state:t,dispatch:e})=>bl(t,e)?!0:kl(t,e),setCellAttribute:(t,e)=>({state:n,dispatch:r})=>Pf(t,e)(n,r),goToNextCell:()=>({state:t,dispatch:e})=>wl(1)(t,e),goToPreviousCell:()=>({state:t,dispatch:e})=>wl(-1)(t,e),fixTables:()=>({state:t,dispatch:e})=>(e&&yl(t),!0),setCellSelection:t=>({tr:e,dispatch:n})=>{if(n){let r=j.create(e.doc,t.anchorCell,t.headCell);e.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:Jo,"Mod-Backspace":Jo,Delete:Jo,"Mod-Delete":Jo}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[Bf({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],Hf({allowTableNodeSelection:this.options.allowTableNodeSelection}),c1()]},addNodeView(){let t=this.options.View;return t?({node:e,view:n,HTMLAttributes:r})=>{let o=B(this.options.HTMLAttributes,r);return new t(e,this.options.cellMinWidth,n,o)}:null},extendNodeSchema(t){let e={name:t.name,options:t.options,storage:t.storage};return{tableRole:L(M(t,"tableRole",e))}}}),_S=W.create({name:"tableKit",addExtensions(){let t=[];return this.options.table!==!1&&t.push(Ml.configure(this.options.table)),this.options.tableCell!==!1&&t.push(xl.configure(this.options.tableCell)),this.options.tableHeader!==!1&&t.push(Cl.configure(this.options.tableHeader)),this.options.tableRow!==!1&&t.push(vl.configure(this.options.tableRow)),t}});function Xf(t={}){return new R({view(e){return new El(e,t)}})}var El=class{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(o=>{let i=s=>{this[o](s)};return e.dom.addEventListener(o,i),{name:o,handler:i}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){if(this.cursorPos!=null&&n.doc!=e.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,o=this.editorView.dom,i=o.getBoundingClientRect(),s=i.width/o.offsetWidth,l=i.height/o.offsetHeight;if(n){let d=e.nodeBefore,f=e.nodeAfter;if(d||f){let h=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(h){let p=h.getBoundingClientRect(),m=d?p.bottom:p.top;d&&f&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*s;r={left:d.left-f,right:d.left+f,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),f=d.width/a.offsetWidth,h=d.height/a.offsetHeight;c=d.left-a.scrollLeft*f,u=d.top-a.scrollTop*h}this.element.style.left=(r.left-c)/s+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/s+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}computeTarget(e){let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),o=r&&r.type.spec.disableDropCursor,i=typeof o=="function"?o(this.editorView,n,e):o;if(!n||i)return null;let s=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=wr(this.editorView.state.doc,s,this.editorView.dragging.slice);l!=null&&(s=l)}return s}dragover(e){if(!this.editorView.editable)return;this.lastDragEvent=e;let n=this.computeTarget(e);n!=null&&(this.setCursor(n),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}};var ue=class t extends E{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return t.valid(r)?new t(r):E.near(r)}content(){return C.empty}eq(e){return e instanceof t&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new t(e.resolve(n.pos))}getBookmark(){return new Al(this.anchor)}static valid(e){let n=e.parent;if(n.inlineContent||!u1(e)||!d1(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let o=n.contentMatchAt(e.index()).defaultType;return o&&o.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&t.valid(e))return e;let o=e.pos,i=null;for(let s=e.depth;;s--){let l=e.node(s);if(n>0?e.indexAfter(s)<l.childCount:e.index(s)>0){i=l.child(n>0?e.indexAfter(s):e.index(s)-1);break}else if(s==0)return null;o+=n;let a=e.doc.resolve(o);if(t.valid(a))return a}for(;;){let s=n>0?i.firstChild:i.lastChild;if(!s){if(i.isAtom&&!i.isText&&!A.isSelectable(i)){e=e.doc.resolve(o+i.nodeSize*n),r=!1;continue e}break}i=s,o+=n;let l=e.doc.resolve(o);if(t.valid(l))return l}return null}}};ue.prototype.visible=!1;ue.findFrom=ue.findGapCursorFrom;E.jsonID("gapcursor",ue);var Al=class t{constructor(e){this.pos=e}map(e){return new t(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return ue.valid(n)?new ue(n):E.near(n)}};function Yf(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function u1(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n-1);;o=o.lastChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function d1(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n);;o=o.firstChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function Qf(){return new R({props:{decorations:m1,createSelectionBetween(t,e,n){return e.pos==n.pos&&ue.valid(n)?new ue(n):null},handleClick:h1,handleKeyDown:f1,handleDOMEvents:{beforeinput:p1}}})}var f1=_n({ArrowLeft:Go("horiz",-1),ArrowRight:Go("horiz",1),ArrowUp:Go("vert",-1),ArrowDown:Go("vert",1)});function Go(t,e){let n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,o,i){let s=r.selection,l=e>0?s.$to:s.$from,a=s.empty;if(s instanceof v){if(!i.endOfTextblock(n)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=ue.findGapCursorFrom(l,e,a);return c?(o&&o(r.tr.setSelection(new ue(c))),!0):!1}}function h1(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!ue.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&A.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new ue(r))),!0)}function p1(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof ue))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let o=b.empty;for(let s=r.length-1;s>=0;s--)o=b.from(r[s].createAndFill(null,o));let i=t.state.tr.replace(n.pos,n.pos,new C(o,0,0));return i.setSelection(v.near(i.doc.resolve(n.pos+1))),t.dispatch(i),!1}function m1(t){if(!(t.selection instanceof ue))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",$.create(t.doc,[Z.widget(t.selection.head,e,{key:"gapcursor"})])}var dx=W.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{let e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){let n=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(n)}return e.nodeSize},this.storage.words=t=>{let e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new R({key:new P("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;let o=this.options.limit,i=this.options.autoTrim;if(o==null||o===0||i===!1){t=!0;return}let s=this.storage.characters({node:r.doc});if(s>o){let l=s-o,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);let u=r.tr.deleteRange(a,c);return t=!0,u}t=!0},filterTransaction:(e,n)=>{let r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;let o=this.storage.characters({node:n.doc}),i=this.storage.characters({node:e.doc});if(i<=r||o>r&&i>r&&i<=o)return!0;if(o>r&&i>r&&i>o||!e.getMeta("paste"))return!1;let s=e.selection.$head.pos,l=s-(i-r),a=s;return e.deleteRange(l,a),!(this.storage.characters({node:e.doc})>r)}})]}}),fx=W.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Xf(this.options)]}}),hx=W.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new R({key:new P("focus"),props:{decorations:({doc:t,selection:e})=>{let{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,i=[];if(!n||!r)return $.create(t,[]);let s=0;this.options.mode==="deepest"&&t.descendants((a,c)=>{if(!a.isText){if(!(o>=c&&o<=c+a.nodeSize-1))return!1;s+=1}});let l=0;return t.descendants((a,c)=>{if(a.isText||!(o>=c&&o<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&s-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";i.push(Z.node(c,c+a.nodeSize,{class:this.options.className}))}),$.create(t,i)}}})]}}),th=W.create({name:"gapCursor",addProseMirrorPlugins(){return[Qf()]},extendNodeSchema(t){var e;let n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=L(M(t,"allowGapCursor",n)))!==null&&e!==void 0?e:null}}}),nh="placeholder",Zf=new P("tiptap__placeholder");function rh(t){let{editor:e,placeholder:n,dataAttribute:r,pos:o,node:i,isEmptyDoc:s,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=t,u=[a];return s&&u.push(c),Z.node(o,o+i.nodeSize,{class:u.join(" "),[r]:typeof n=="function"?n({editor:e,node:i,pos:o,hasAnchor:l}):n})}function oh(t,e){return typeof t=="function"?t(e):t}function ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:i,to:s}){let{anchor:l}=o,a=[],c=t.isEmpty;return r.nodesBetween(i,s,(u,d)=>{let f=l>=d&&l<=d+u.nodeSize,h=!u.isLeaf&&hn(u);return u.type.isTextblock&&(f||!e.showOnlyCurrent)&&h&&a.push(rh({editor:t,isEmptyDoc:c,dataAttribute:n,hasAnchor:f,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:u,pos:d,hasAnchor:f})},node:u,pos:d})),e.includeChildren}),a}function sh({editor:t,options:e,dataAttribute:n,doc:r,selection:o}){if(!(t.isEditable||!e.showOnlyWhenEditable))return null;let{anchor:i}=o,s=[],l=t.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){let a=r.resolve(i),c=a.depth>0?a.node(1):a.nodeAfter,u=a.depth>0?a.before(1):i;if(c&&c.type.isTextblock&&hn(c)){let d=i>=u&&i<=u+c.nodeSize;s.push(rh({editor:t,isEmptyDoc:l,dataAttribute:n,hasAnchor:d,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:c,pos:u,hasAnchor:d})},node:c,pos:u}))}}else s.push(...ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return $.create(r,s)}function ir(t,e){let n=t.resolve(e);if(n.depth===0){var r;let i=(r=n.nodeAfter)!==null&&r!==void 0?r:n.nodeBefore;if(!i)return{from:e,to:e};let s=n.nodeAfter?e:e-i.nodeSize;return{from:s,to:s+i.nodeSize}}let o=n.before(1);return{from:o,to:o+n.node(1).nodeSize}}function sr(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function g1(t,e,n){let r=[];return t.forEach((o,i)=>{let s=i,l=s+o.nodeSize,a=s+1,c=l+1;a<n&&c>e&&r.push({from:s,to:l})}),r}function y1(t){if(t.length===0)return[];let e=[...t].sort((r,o)=>r.from-o.from),n=[{...e[0]}];for(let r=1;r<e.length;r+=1){let o=n[n.length-1],i=e[r];i.from<=o.to?o.to=Math.max(o.to,i.to):n.push({...i})}return n}function b1(t,e){let n=g1(t,e.from,e.to);return n.push(sr(t,ir(t,e.from))),e.to>e.from?n.push(sr(t,ir(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(sr(t,ir(t,Math.min(e.from+1,t.content.size)))),n}function k1(t,e,n){let r=[];if(t.docChanged){let o=fn(t);for(let i of o)r.push(...b1(n.doc,i.newRange))}return t.selectionSet&&(r.push(sr(n.doc,ir(n.doc,t.mapping.map(e.selection.anchor)))),r.push(sr(n.doc,ir(n.doc,n.selection.anchor)))),y1(r)}function w1(t,e,n){let r=Math.max(0,Math.min(t,n.content.size));return{from:r,to:Math.max(r,Math.min(e,n.content.size))}}function S1({decorations:t,ranges:e,editor:n,options:r,dataAttribute:o,doc:i,selection:s}){let l=t;for(let a of e){let{from:c,to:u}=w1(a.from,a.to,i),d=l.find(c,u).filter(h=>h.from>=c&&h.to<=u);d.length&&(l=l.remove(d));let f=ih({editor:n,options:r,dataAttribute:o,doc:i,selection:s,from:c,to:u});f.length&&(l=l.add(i,f))}return l}function x1({editor:t,options:e,dataAttribute:n}){return{init(r,o){let i=sh({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return i??$.empty},apply(r,o,i,s){return!r.docChanged&&!r.selectionSet?o:S1({decorations:o.map(r.mapping,r.doc),ranges:k1(r,i,s),editor:t,options:e,dataAttribute:n,doc:s.doc,selection:s.selection})}}}function C1(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function v1({editor:t,options:e}){let n=e.dataAttribute?`data-${C1(e.dataAttribute)}`:`data-${nh}`,r=e.showOnlyCurrent&&!e.includeChildren;return new R({key:Zf,...r?{}:{state:x1({editor:t,options:e,dataAttribute:n})},props:{decorations:r?({doc:o,selection:i})=>sh({editor:t,options:e,dataAttribute:n,doc:o,selection:i}):o=>{var i;return e.showOnlyWhenEditable&&!t.isEditable?$.empty:(i=Zf.getState(o))!==null&&i!==void 0?i:$.empty}}})}var lh=W.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:nh,placeholder:"Write something \u2026",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[v1({editor:this.editor,options:this.options})]}});function Tl(t,e){return!t.selection.empty&&!Zu(t.selection)&&e.isEditable}function M1(t,e){return Tl(t,e)&&!e.isFocused&&!e.view.dragging}function E1(){var t;(t=window.getSelection())===null||t===void 0||t.removeAllRanges()}function A1(t){t.focus()}var px=W.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){let{editor:t,options:e}=this;return[new R({key:new P("selection"),props:{decorations(n){return M1(n,t)?$.create(n.doc,[Z.inline(n.selection.from,n.selection.to,{class:e.className})]):null},handleDOMEvents:{blur(n){return Tl(n.state,t)&&E1(),!1},focus(n){return Tl(n.state,t)&&requestAnimationFrame(()=>{!t.isDestroyed&&n.hasFocus()&&A1(n)}),!1}}}})]}});function eh({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var ah=W.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;let e=new P(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)===null||t===void 0?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,o])=>o).filter(o=>(this.options.notAfter||[]).concat(n).includes(o.name));return[new R({key:e,appendTransaction:(o,i,s)=>{let{doc:l,tr:a,schema:c}=s,u=e.getState(s),d=l.content.size,f=c.nodes[n];if(!o.some(h=>h.getMeta("skipTrailingNode"))&&u)return a.insert(d,f.create())},state:{init:(o,i)=>{let s=i.tr.doc.lastChild;return!eh({node:s,types:r})},apply:(o,i)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return i;let s=o.doc.lastChild;return!eh({node:s,types:r})}}})]}}),ch=W.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>hs(t,e),redo:()=>({state:t,dispatch:e})=>ps(t,e)}},addProseMirrorPlugins(){return[uu(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-\u044F":()=>this.editor.commands.undo(),"Shift-Mod-\u044F":()=>this.editor.commands.redo()}}});import{markdownToDoc as uh,docToMarkdown as T1}from"./markdown-doc.js";import{isHttpImageSrc as N1}from"./markdown.js";var dh=/^\s*(javascript|data|vbscript):/i,O1=ff.extend({renderHTML({node:t,HTMLAttributes:e}){return N1(t.attrs.src)?["img",e]:["div",{class:"md-image-placeholder"},t.attrs.alt||"Image"]}}),R1=Ml.extend({addAttributes(){return{...this.parent?.(),align:{default:[],rendered:!1}}}}),Nl={content:"paragraph"};function D1(t){return[kd,wd,Sd,Md.extend({excludes:"italic code"}),Ed.extend({excludes:"bold code"}),Ad,Td.configure({levels:[1,2,3]}),Ps,Hs,$s.extend(Nl),Fs,uf.configure({openOnClick:!1,autolink:!1,isAllowedUri:e=>!dh.test(String(e)),HTMLAttributes:{target:null,rel:"noopener noreferrer nofollow"}}),df,O1.configure({inline:!1,allowBase64:!1}),R1.configure({resizable:!1}),vl,Cl.extend(Nl),xl.extend(Nl),th,ah,ch,lh.configure({placeholder:t||""})]}var fh={bold:t=>t.toggleBold(),italic:t=>t.toggleItalic(),code:t=>t.toggleCode(),heading2:t=>t.toggleHeading({level:2}),heading3:t=>t.toggleHeading({level:3}),bullet:t=>t.toggleBulletList(),ordered:t=>t.toggleOrderedList(),table:t=>t.insertTable({rows:3,cols:3,withHeaderRow:!0}),addRow:t=>t.addRowAfter(),addColumn:t=>t.addColumnAfter(),removeRow:t=>t.deleteRow(),removeColumn:t=>t.deleteColumn(),removeTable:t=>t.deleteTable(),undo:t=>t.undo(),redo:t=>t.redo(),link:(t,{label:e,target:n}={},r)=>{let o=String(n||"").trim();if(!o||dh.test(o))return t;let i=String(e||"").trim(),{from:s,to:l,empty:a}=r.state.selection;return!a&&(!i||i===r.state.doc.textBetween(s,l," ").trim())?t.setLink({href:o}):t.insertContent({type:"text",text:i||o,marks:[{type:"link",attrs:{href:o}}]})}},Dx=Object.freeze(Object.keys(fh));function Ix({element:t,markdown:e,placeholder:n,label:r,onChange:o,onFocusChange:i,onState:s}){let l=typeof e=="string"?e:"",a=new md({element:t,extensions:D1(n),content:uh(l,{stripLegacyHtml:!1}),editorProps:{attributes:{role:"textbox","aria-multiline":"true",...r?{"aria-label":r}:null}}});if(a.on("update",({transaction:c})=>{if(!c.docChanged)return;let u=T1(a.getJSON());u!==l&&(l=u,typeof o=="function"&&o(l))}),typeof s=="function"){let c=!1;a.on("transaction",()=>{let u=a.isActive("table");u!==c&&s({inTable:c=u})})}return typeof i=="function"&&(a.on("focus",()=>i(!0)),a.on("blur",()=>i(!1))),{setMarkdown(c){let u=typeof c=="string"?c:"";u!==l&&(l=u,a.commands.setContent(uh(u,{stripLegacyHtml:!1}),{emitUpdate:!1}))},command(c,u){let d=fh[c];return d?d(a.chain().focus(),u,a).run():!1},selectedText(){let{from:c,to:u}=a.state.selection;return a.state.doc.textBetween(c,u," ")},focus(){a.commands.focus()},destroy(){a.destroy()},editor:a}}export{Dx as MARKDOWN_EDITOR_COMMANDS,Ix as createMarkdownEditor};
|
|
158
|
+
`);return{...a,raw:u}}},addCommands(){return{insertTable:({rows:t=3,cols:e=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:o,editor:i})=>{let s=e1(i.schema,t,e,n);if(o){let l=r.selection.from+1;r.replaceSelectionWith(s).scrollIntoView().setSelection(v.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:t,dispatch:e})=>Af(t,e),addColumnAfter:()=>({state:t,dispatch:e})=>Tf(t,e),deleteColumn:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return Nf(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},addRowBefore:()=>({state:t,dispatch:e})=>Rf(t,e),addRowAfter:()=>({state:t,dispatch:e})=>Df(t,e),deleteRow:()=>({state:t,dispatch:e})=>{let n=dn(t.selection.$from,r=>r.type.name==="table");return If(t,e&&(r=>{n&&Wf(r,n.pos),e(r)}))},deleteTable:()=>({state:t,dispatch:e})=>zf(t,e),mergeCells:()=>({state:t,dispatch:e})=>bl(t,e),splitCell:()=>({state:t,dispatch:e})=>kl(t,e),toggleHeaderColumn:()=>({state:t,dispatch:e})=>wn("column")(t,e),toggleHeaderRow:()=>({state:t,dispatch:e})=>wn("row")(t,e),toggleHeaderCell:()=>({state:t,dispatch:e})=>Lf(t,e),mergeOrSplit:()=>({state:t,dispatch:e})=>bl(t,e)?!0:kl(t,e),setCellAttribute:(t,e)=>({state:n,dispatch:r})=>Pf(t,e)(n,r),goToNextCell:()=>({state:t,dispatch:e})=>wl(1)(t,e),goToPreviousCell:()=>({state:t,dispatch:e})=>wl(-1)(t,e),fixTables:()=>({state:t,dispatch:e})=>(e&&yl(t),!0),setCellSelection:t=>({tr:e,dispatch:n})=>{if(n){let r=j.create(e.doc,t.anchorCell,t.headCell);e.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:Jo,"Mod-Backspace":Jo,Delete:Jo,"Mod-Delete":Jo}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[Bf({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:null,lastColumnResizable:this.options.lastColumnResizable})]:[],Hf({allowTableNodeSelection:this.options.allowTableNodeSelection}),c1()]},addNodeView(){let t=this.options.View;return t?({node:e,view:n,HTMLAttributes:r})=>{let o=B(this.options.HTMLAttributes,r);return new t(e,this.options.cellMinWidth,n,o)}:null},extendNodeSchema(t){let e={name:t.name,options:t.options,storage:t.storage};return{tableRole:L(M(t,"tableRole",e))}}}),_S=W.create({name:"tableKit",addExtensions(){let t=[];return this.options.table!==!1&&t.push(Ml.configure(this.options.table)),this.options.tableCell!==!1&&t.push(xl.configure(this.options.tableCell)),this.options.tableHeader!==!1&&t.push(Cl.configure(this.options.tableHeader)),this.options.tableRow!==!1&&t.push(vl.configure(this.options.tableRow)),t}});function Xf(t={}){return new R({view(e){return new El(e,t)}})}var El=class{constructor(e,n){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(o=>{let i=s=>{this[o](s)};return e.dom.addEventListener(o,i),{name:o,handler:i}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:e,handler:n})=>this.editorView.dom.removeEventListener(e,n))}update(e,n){if(this.cursorPos!=null&&n.doc!=e.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),n=!e.parent.inlineContent,r,o=this.editorView.dom,i=o.getBoundingClientRect(),s=i.width/o.offsetWidth,l=i.height/o.offsetHeight;if(n){let d=e.nodeBefore,f=e.nodeAfter;if(d||f){let h=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(h){let p=h.getBoundingClientRect(),m=d?p.bottom:p.top;d&&f&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*s;r={left:d.left-f,right:d.left+f,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),f=d.width/a.offsetWidth,h=d.height/a.offsetHeight;c=d.left-a.scrollLeft*f,u=d.top-a.scrollTop*h}this.element.style.left=(r.left-c)/s+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/s+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}computeTarget(e){let n=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),o=r&&r.type.spec.disableDropCursor,i=typeof o=="function"?o(this.editorView,n,e):o;if(!n||i)return null;let s=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=wr(this.editorView.state.doc,s,this.editorView.dragging.slice);l!=null&&(s=l)}return s}dragover(e){if(!this.editorView.editable)return;this.lastDragEvent=e;let n=this.computeTarget(e);n!=null&&(this.setCursor(n),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}};var ue=class t extends E{constructor(e){super(e,e)}map(e,n){let r=e.resolve(n.map(this.head));return t.valid(r)?new t(r):E.near(r)}content(){return C.empty}eq(e){return e instanceof t&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new t(e.resolve(n.pos))}getBookmark(){return new Al(this.anchor)}static valid(e){let n=e.parent;if(n.inlineContent||!u1(e)||!d1(e))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let o=n.contentMatchAt(e.index()).defaultType;return o&&o.isTextblock}static findGapCursorFrom(e,n,r=!1){e:for(;;){if(!r&&t.valid(e))return e;let o=e.pos,i=null;for(let s=e.depth;;s--){let l=e.node(s);if(n>0?e.indexAfter(s)<l.childCount:e.index(s)>0){i=l.child(n>0?e.indexAfter(s):e.index(s)-1);break}else if(s==0)return null;o+=n;let a=e.doc.resolve(o);if(t.valid(a))return a}for(;;){let s=n>0?i.firstChild:i.lastChild;if(!s){if(i.isAtom&&!i.isText&&!A.isSelectable(i)){e=e.doc.resolve(o+i.nodeSize*n),r=!1;continue e}break}i=s,o+=n;let l=e.doc.resolve(o);if(t.valid(l))return l}return null}}};ue.prototype.visible=!1;ue.findFrom=ue.findGapCursorFrom;E.jsonID("gapcursor",ue);var Al=class t{constructor(e){this.pos=e}map(e){return new t(e.map(this.pos))}resolve(e){let n=e.resolve(this.pos);return ue.valid(n)?new ue(n):E.near(n)}};function Yf(t){return t.isAtom||t.spec.isolating||t.spec.createGapCursor}function u1(t){for(let e=t.depth;e>=0;e--){let n=t.index(e),r=t.node(e);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n-1);;o=o.lastChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function d1(t){for(let e=t.depth;e>=0;e--){let n=t.indexAfter(e),r=t.node(e);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let o=r.child(n);;o=o.firstChild){if(o.childCount==0&&!o.inlineContent||Yf(o.type))return!0;if(o.inlineContent)return!1}}return!0}function Qf(){return new R({props:{decorations:m1,createSelectionBetween(t,e,n){return e.pos==n.pos&&ue.valid(n)?new ue(n):null},handleClick:h1,handleKeyDown:f1,handleDOMEvents:{beforeinput:p1}}})}var f1=_n({ArrowLeft:Go("horiz",-1),ArrowRight:Go("horiz",1),ArrowUp:Go("vert",-1),ArrowDown:Go("vert",1)});function Go(t,e){let n=t=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,o,i){let s=r.selection,l=e>0?s.$to:s.$from,a=s.empty;if(s instanceof v){if(!i.endOfTextblock(n)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=ue.findGapCursorFrom(l,e,a);return c?(o&&o(r.tr.setSelection(new ue(c))),!0):!1}}function h1(t,e,n){if(!t||!t.editable)return!1;let r=t.state.doc.resolve(e);if(!ue.valid(r))return!1;let o=t.posAtCoords({left:n.clientX,top:n.clientY});return o&&o.inside>-1&&A.isSelectable(t.state.doc.nodeAt(o.inside))?!1:(t.dispatch(t.state.tr.setSelection(new ue(r))),!0)}function p1(t,e){if(e.inputType!="insertCompositionText"||!(t.state.selection instanceof ue))return!1;let{$from:n}=t.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(t.state.schema.nodes.text);if(!r)return!1;let o=b.empty;for(let s=r.length-1;s>=0;s--)o=b.from(r[s].createAndFill(null,o));let i=t.state.tr.replace(n.pos,n.pos,new C(o,0,0));return i.setSelection(v.near(i.doc.resolve(n.pos+1))),t.dispatch(i),!1}function m1(t){if(!(t.selection instanceof ue))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",$.create(t.doc,[Z.widget(t.selection.head,e,{key:"gapcursor"})])}var dx=W.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:t=>t.length,wordCounter:t=>t.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=t=>{let e=t?.node||this.editor.state.doc;if((t?.mode||this.options.mode)==="textSize"){let n=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(n)}return e.nodeSize},this.storage.words=t=>{let e=t?.node||this.editor.state.doc,n=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(n)}},addProseMirrorPlugins(){let t=!1;return[new R({key:new P("characterCount"),appendTransaction:(e,n,r)=>{if(t)return;let o=this.options.limit,i=this.options.autoTrim;if(o==null||o===0||i===!1){t=!0;return}let s=this.storage.characters({node:r.doc});if(s>o){let l=s-o,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${o} characters. Content was automatically trimmed.`);let u=r.tr.deleteRange(a,c);return t=!0,u}t=!0},filterTransaction:(e,n)=>{let r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;let o=this.storage.characters({node:n.doc}),i=this.storage.characters({node:e.doc});if(i<=r||o>r&&i>r&&i<=o)return!0;if(o>r&&i>r&&i>o||!e.getMeta("paste"))return!1;let s=e.selection.$head.pos,l=s-(i-r),a=s;return e.deleteRange(l,a),!(this.storage.characters({node:e.doc})>r)}})]}}),fx=W.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Xf(this.options)]}}),hx=W.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new R({key:new P("focus"),props:{decorations:({doc:t,selection:e})=>{let{isEditable:n,isFocused:r}=this.editor,{anchor:o}=e,i=[];if(!n||!r)return $.create(t,[]);let s=0;this.options.mode==="deepest"&&t.descendants((a,c)=>{if(!a.isText){if(!(o>=c&&o<=c+a.nodeSize-1))return!1;s+=1}});let l=0;return t.descendants((a,c)=>{if(a.isText||!(o>=c&&o<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&s-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";i.push(Z.node(c,c+a.nodeSize,{class:this.options.className}))}),$.create(t,i)}}})]}}),th=W.create({name:"gapCursor",addProseMirrorPlugins(){return[Qf()]},extendNodeSchema(t){var e;let n={name:t.name,options:t.options,storage:t.storage};return{allowGapCursor:(e=L(M(t,"allowGapCursor",n)))!==null&&e!==void 0?e:null}}}),nh="placeholder",Zf=new P("tiptap__placeholder");function rh(t){let{editor:e,placeholder:n,dataAttribute:r,pos:o,node:i,isEmptyDoc:s,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=t,u=[a];return s&&u.push(c),Z.node(o,o+i.nodeSize,{class:u.join(" "),[r]:typeof n=="function"?n({editor:e,node:i,pos:o,hasAnchor:l}):n})}function oh(t,e){return typeof t=="function"?t(e):t}function ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:i,to:s}){let{anchor:l}=o,a=[],c=t.isEmpty;return r.nodesBetween(i,s,(u,d)=>{let f=l>=d&&l<=d+u.nodeSize,h=!u.isLeaf&&hn(u);return u.type.isTextblock&&(f||!e.showOnlyCurrent)&&h&&a.push(rh({editor:t,isEmptyDoc:c,dataAttribute:n,hasAnchor:f,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:u,pos:d,hasAnchor:f})},node:u,pos:d})),e.includeChildren}),a}function sh({editor:t,options:e,dataAttribute:n,doc:r,selection:o}){if(!(t.isEditable||!e.showOnlyWhenEditable))return null;let{anchor:i}=o,s=[],l=t.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){let a=r.resolve(i),c=a.depth>0?a.node(1):a.nodeAfter,u=a.depth>0?a.before(1):i;if(c&&c.type.isTextblock&&hn(c)){let d=i>=u&&i<=u+c.nodeSize;s.push(rh({editor:t,isEmptyDoc:l,dataAttribute:n,hasAnchor:d,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:oh(e.emptyNodeClass,{editor:t,node:c,pos:u,hasAnchor:d})},node:c,pos:u}))}}else s.push(...ih({editor:t,options:e,dataAttribute:n,doc:r,selection:o,from:0,to:r.content.size}));return $.create(r,s)}function ir(t,e){let n=t.resolve(e);if(n.depth===0){var r;let i=(r=n.nodeAfter)!==null&&r!==void 0?r:n.nodeBefore;if(!i)return{from:e,to:e};let s=n.nodeAfter?e:e-i.nodeSize;return{from:s,to:s+i.nodeSize}}let o=n.before(1);return{from:o,to:o+n.node(1).nodeSize}}function sr(t,e){return{from:Math.max(0,e.from-1),to:Math.min(t.content.size,e.to-1)}}function g1(t,e,n){let r=[];return t.forEach((o,i)=>{let s=i,l=s+o.nodeSize,a=s+1,c=l+1;a<n&&c>e&&r.push({from:s,to:l})}),r}function y1(t){if(t.length===0)return[];let e=[...t].sort((r,o)=>r.from-o.from),n=[{...e[0]}];for(let r=1;r<e.length;r+=1){let o=n[n.length-1],i=e[r];i.from<=o.to?o.to=Math.max(o.to,i.to):n.push({...i})}return n}function b1(t,e){let n=g1(t,e.from,e.to);return n.push(sr(t,ir(t,e.from))),e.to>e.from?n.push(sr(t,ir(t,Math.min(e.to,t.content.size+1)-1))):e.from<t.content.size+1&&n.push(sr(t,ir(t,Math.min(e.from+1,t.content.size)))),n}function k1(t,e,n){let r=[];if(t.docChanged){let o=fn(t);for(let i of o)r.push(...b1(n.doc,i.newRange))}return t.selectionSet&&(r.push(sr(n.doc,ir(n.doc,t.mapping.map(e.selection.anchor)))),r.push(sr(n.doc,ir(n.doc,n.selection.anchor)))),y1(r)}function w1(t,e,n){let r=Math.max(0,Math.min(t,n.content.size));return{from:r,to:Math.max(r,Math.min(e,n.content.size))}}function S1({decorations:t,ranges:e,editor:n,options:r,dataAttribute:o,doc:i,selection:s}){let l=t;for(let a of e){let{from:c,to:u}=w1(a.from,a.to,i),d=l.find(c,u).filter(h=>h.from>=c&&h.to<=u);d.length&&(l=l.remove(d));let f=ih({editor:n,options:r,dataAttribute:o,doc:i,selection:s,from:c,to:u});f.length&&(l=l.add(i,f))}return l}function x1({editor:t,options:e,dataAttribute:n}){return{init(r,o){let i=sh({editor:t,options:e,dataAttribute:n,doc:o.doc,selection:o.selection});return i??$.empty},apply(r,o,i,s){return!r.docChanged&&!r.selectionSet?o:S1({decorations:o.map(r.mapping,r.doc),ranges:k1(r,i,s),editor:t,options:e,dataAttribute:n,doc:s.doc,selection:s.selection})}}}function C1(t){return t.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function v1({editor:t,options:e}){let n=e.dataAttribute?`data-${C1(e.dataAttribute)}`:`data-${nh}`,r=e.showOnlyCurrent&&!e.includeChildren;return new R({key:Zf,...r?{}:{state:x1({editor:t,options:e,dataAttribute:n})},props:{decorations:r?({doc:o,selection:i})=>sh({editor:t,options:e,dataAttribute:n,doc:o,selection:i}):o=>{var i;return e.showOnlyWhenEditable&&!t.isEditable?$.empty:(i=Zf.getState(o))!==null&&i!==void 0?i:$.empty}}})}var lh=W.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:nh,placeholder:"Write something \u2026",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[v1({editor:this.editor,options:this.options})]}});function Tl(t,e){return!t.selection.empty&&!Zu(t.selection)&&e.isEditable}function M1(t,e){return Tl(t,e)&&!e.isFocused&&!e.view.dragging}function E1(){var t;(t=window.getSelection())===null||t===void 0||t.removeAllRanges()}function A1(t){t.focus()}var px=W.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){let{editor:t,options:e}=this;return[new R({key:new P("selection"),props:{decorations(n){return M1(n,t)?$.create(n.doc,[Z.inline(n.selection.from,n.selection.to,{class:e.className})]):null},handleDOMEvents:{blur(n){return Tl(n.state,t)&&E1(),!1},focus(n){return Tl(n.state,t)&&requestAnimationFrame(()=>{!t.isDestroyed&&n.hasFocus()&&A1(n)}),!1}}}})]}});function eh({types:t,node:e}){return e&&Array.isArray(t)&&t.includes(e.type)||e?.type===t}var ah=W.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var t;let e=new P(this.name),n=this.options.node||((t=this.editor.schema.topNodeType.contentMatch.defaultType)===null||t===void 0?void 0:t.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,o])=>o).filter(o=>(this.options.notAfter||[]).concat(n).includes(o.name));return[new R({key:e,appendTransaction:(o,i,s)=>{let{doc:l,tr:a,schema:c}=s,u=e.getState(s),d=l.content.size,f=c.nodes[n];if(!o.some(h=>h.getMeta("skipTrailingNode"))&&u)return a.insert(d,f.create())},state:{init:(o,i)=>{let s=i.tr.doc.lastChild;return!eh({node:s,types:r})},apply:(o,i)=>{if(!o.docChanged||o.getMeta("__uniqueIDTransaction"))return i;let s=o.doc.lastChild;return!eh({node:s,types:r})}}})]}}),ch=W.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:t,dispatch:e})=>hs(t,e),redo:()=>({state:t,dispatch:e})=>ps(t,e)}},addProseMirrorPlugins(){return[uu(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-\u044F":()=>this.editor.commands.undo(),"Shift-Mod-\u044F":()=>this.editor.commands.redo()}}});import{markdownToDoc as uh,docToMarkdown as T1}from"./markdown-doc.js";import{isHttpImageSrc as N1}from"./markdown.js";var dh=/^\s*(javascript|data|vbscript):/i,O1=ff.extend({renderHTML({node:t,HTMLAttributes:e}){return N1(t.attrs.src)?["img",e]:["div",{class:"md-image-placeholder"},t.attrs.alt||"Image"]}}),R1=Ml.extend({addAttributes(){return{...this.parent?.(),align:{default:[],rendered:!1}}}}),Nl={content:"paragraph"};function D1(t){return[kd,wd,Sd,Md.extend({excludes:"italic code"}),Ed.extend({excludes:"bold code"}),Ad,Td.configure({levels:[1,2,3]}),Ps,Hs,$s.extend(Nl),Fs,uf.configure({openOnClick:!1,autolink:!1,isAllowedUri:e=>!dh.test(String(e)),HTMLAttributes:{target:null,rel:"noopener noreferrer nofollow"}}),df,O1.configure({inline:!1,allowBase64:!1}),R1.configure({resizable:!1}),vl,Cl.extend(Nl),xl.extend(Nl),th,ah,ch,lh.configure({placeholder:t||""})]}var fh={bold:t=>t.toggleBold(),italic:t=>t.toggleItalic(),code:t=>t.toggleCode(),heading2:t=>t.toggleHeading({level:2}),heading3:t=>t.toggleHeading({level:3}),bullet:t=>t.toggleBulletList(),ordered:t=>t.toggleOrderedList(),table:t=>t.insertTable({rows:3,cols:3,withHeaderRow:!0}),addRow:t=>t.addRowAfter(),addColumn:t=>t.addColumnAfter(),removeRow:t=>t.deleteRow(),removeColumn:t=>t.deleteColumn(),removeTable:t=>t.deleteTable(),insertText:(t,{text:e}={})=>typeof e=="string"&&e?t.insertContent({type:"text",text:e}):t,undo:t=>t.undo(),redo:t=>t.redo(),link:(t,{label:e,target:n}={},r)=>{let o=String(n||"").trim();if(!o||dh.test(o))return t;let i=String(e||"").trim(),{from:s,to:l,empty:a}=r.state.selection;return!a&&(!i||i===r.state.doc.textBetween(s,l," ").trim())?t.setLink({href:o}):t.insertContent({type:"text",text:i||o,marks:[{type:"link",attrs:{href:o}}]})}},Dx=Object.freeze(Object.keys(fh));function Ix({element:t,markdown:e,placeholder:n,label:r,onChange:o,onFocusChange:i,onState:s}){let l=typeof e=="string"?e:"",a=new md({element:t,extensions:D1(n),content:uh(l,{stripLegacyHtml:!1}),editorProps:{attributes:{role:"textbox","aria-multiline":"true",...r?{"aria-label":r}:null}}});if(a.on("update",({transaction:u})=>{if(!u.docChanged)return;let d=T1(a.getJSON());d!==l&&(l=d,typeof o=="function"&&o(l))}),typeof s=="function"){let u=!1;a.on("transaction",()=>{let d=a.isActive("table");d!==u&&s({inTable:u=d})})}let c=!1;return a.on("transaction",({transaction:u})=>{u.selectionSet&&(c=!0)}),typeof i=="function"&&(a.on("focus",()=>i(!0)),a.on("blur",()=>i(!1))),{setMarkdown(u){let d=typeof u=="string"?u:"";d!==l&&(l=d,a.commands.setContent(uh(d,{stripLegacyHtml:!1}),{emitUpdate:!1}))},command(u,d){let f=fh[u];if(!f)return!1;let h=u==="insertText"&&!c?"end":null;return f(a.chain().focus(h),d,a).run()},selectedText(){let{from:u,to:d}=a.state.selection;return a.state.doc.textBetween(u,d," ")},focus(){a.commands.focus()},setEditable(u){a.setEditable(u!==!1)},destroy(){a.destroy()},editor:a}}export{Dx as MARKDOWN_EDITOR_COMMANDS,Ix as createMarkdownEditor};
|
|
@@ -89,6 +89,9 @@ const COMMANDS = {
|
|
|
89
89
|
removeRow: (chain) => chain.deleteRow(),
|
|
90
90
|
removeColumn: (chain) => chain.deleteColumn(),
|
|
91
91
|
removeTable: (chain) => chain.deleteTable(),
|
|
92
|
+
// A text node, never a parsed string, so inserted text cannot become markup.
|
|
93
|
+
insertText: (chain, { text } = {}) =>
|
|
94
|
+
typeof text === "string" && text ? chain.insertContent({ type: "text", text }) : chain,
|
|
92
95
|
undo: (chain) => chain.undo(),
|
|
93
96
|
redo: (chain) => chain.redo(),
|
|
94
97
|
link: (chain, { label, target } = {}, editor) => {
|
|
@@ -151,6 +154,12 @@ export function createMarkdownEditor({
|
|
|
151
154
|
if (next !== inTable) onState({ inTable: (inTable = next) });
|
|
152
155
|
});
|
|
153
156
|
}
|
|
157
|
+
// Until the author places a caret, an insert appends rather than prepends.
|
|
158
|
+
// Loading a value never sets a selection; a click or select-all does.
|
|
159
|
+
let caretPlaced = false;
|
|
160
|
+
editor.on("transaction", ({ transaction }) => {
|
|
161
|
+
if (transaction.selectionSet) caretPlaced = true;
|
|
162
|
+
});
|
|
154
163
|
if (typeof onFocusChange === "function") {
|
|
155
164
|
editor.on("focus", () => onFocusChange(true));
|
|
156
165
|
editor.on("blur", () => onFocusChange(false));
|
|
@@ -167,7 +176,8 @@ export function createMarkdownEditor({
|
|
|
167
176
|
command(name, args) {
|
|
168
177
|
const build = COMMANDS[name];
|
|
169
178
|
if (!build) return false;
|
|
170
|
-
|
|
179
|
+
const at = name === "insertText" && !caretPlaced ? "end" : null;
|
|
180
|
+
return build(editor.chain().focus(at), args, editor).run();
|
|
171
181
|
},
|
|
172
182
|
selectedText() {
|
|
173
183
|
const { from, to } = editor.state.selection;
|
|
@@ -176,6 +186,9 @@ export function createMarkdownEditor({
|
|
|
176
186
|
focus() {
|
|
177
187
|
editor.commands.focus();
|
|
178
188
|
},
|
|
189
|
+
setEditable(editable) {
|
|
190
|
+
editor.setEditable(editable !== false);
|
|
191
|
+
},
|
|
179
192
|
destroy() {
|
|
180
193
|
editor.destroy();
|
|
181
194
|
},
|
|
@@ -22,13 +22,13 @@ function touchFontSize(size) {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
export const MarkdownEditorField = React.forwardRef(function MarkdownEditorField(
|
|
25
|
-
{ value, onChangeText, onStateChange, placeholder, accessibilityLabel, tokens, minHeight, maxHeight, testID },
|
|
25
|
+
{ value, onChangeText, onStateChange, placeholder, accessibilityLabel, tokens, minHeight, maxHeight, editable = true, testID },
|
|
26
26
|
ref,
|
|
27
27
|
) {
|
|
28
28
|
const host = React.useRef(null);
|
|
29
29
|
const editor = React.useRef(null);
|
|
30
|
-
const latest = React.useRef({ value, onChangeText, onStateChange });
|
|
31
|
-
latest.current = { value, onChangeText, onStateChange };
|
|
30
|
+
const latest = React.useRef({ value, onChangeText, onStateChange, editable });
|
|
31
|
+
latest.current = { value, onChangeText, onStateChange, editable };
|
|
32
32
|
const [failed, setFailed] = React.useState(false);
|
|
33
33
|
const scope = `md-editor-${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
|
|
34
34
|
|
|
@@ -53,6 +53,7 @@ export const MarkdownEditorField = React.forwardRef(function MarkdownEditorField
|
|
|
53
53
|
});
|
|
54
54
|
// The parent may have replaced the value while the editor loaded.
|
|
55
55
|
editor.current.setMarkdown(latest.current.value);
|
|
56
|
+
editor.current.setEditable(latest.current.editable);
|
|
56
57
|
})
|
|
57
58
|
.catch(() => {
|
|
58
59
|
if (!cancelled) setFailed(true);
|
|
@@ -70,6 +71,10 @@ export const MarkdownEditorField = React.forwardRef(function MarkdownEditorField
|
|
|
70
71
|
if (editor.current) editor.current.setMarkdown(value);
|
|
71
72
|
}, [value]);
|
|
72
73
|
|
|
74
|
+
React.useEffect(() => {
|
|
75
|
+
if (editor.current) editor.current.setEditable(editable);
|
|
76
|
+
}, [editable]);
|
|
77
|
+
|
|
73
78
|
React.useImperativeHandle(
|
|
74
79
|
ref,
|
|
75
80
|
() => ({
|