@plexui/ui 0.61.0 → 0.62.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/dist/es/components/Accordion/Accordion.js +21 -2
- package/dist/es/components/Accordion/Accordion.js.map +1 -1
- package/dist/es/components/Button/NavigationButton.js +1 -1
- package/dist/es/components/Button/NavigationButton.js.map +1 -1
- package/dist/es/components/Dialog/Dialog.js +51 -3
- package/dist/es/components/Dialog/Dialog.js.map +1 -1
- package/dist/es/components/Dialog/sheetDrag.js +45 -12
- package/dist/es/components/Dialog/sheetDrag.js.map +1 -1
- package/dist/es/components/Field/Field.js +3 -1
- package/dist/es/components/Field/Field.js.map +1 -1
- package/dist/es/components/Markdown/Markdown.js +7 -2
- package/dist/es/components/Markdown/Markdown.js.map +1 -1
- package/dist/es/components/Markdown/directives.js +52 -10
- package/dist/es/components/Markdown/directives.js.map +1 -1
- package/dist/es/components/Menu/Menu.js +22 -1
- package/dist/es/components/Menu/Menu.js.map +1 -1
- package/dist/es/components/PlexUIProvider/PlexUIProvider.js +40 -6
- package/dist/es/components/PlexUIProvider/PlexUIProvider.js.map +1 -1
- package/dist/es/components/PlexUIProvider/androidRipple.js +98 -0
- package/dist/es/components/PlexUIProvider/androidRipple.js.map +1 -0
- package/dist/es/components/PlexUIProvider/index.js.map +1 -1
- package/dist/es/components/Select/Select.js +217 -39
- package/dist/es/components/Select/Select.js.map +1 -1
- package/dist/es/components/Toolbar/Toolbar.js +230 -5
- package/dist/es/components/Toolbar/Toolbar.js.map +1 -1
- package/dist/es/components/Toolbar/index.js.map +1 -1
- package/dist/es/lib/accordionMotion.js +144 -0
- package/dist/es/lib/accordionMotion.js.map +1 -0
- package/dist/es/lib/fieldRow.js +73 -1
- package/dist/es/lib/fieldRow.js.map +1 -1
- package/dist/es/lib/presentMotion.js +151 -0
- package/dist/es/lib/presentMotion.js.map +1 -0
- package/dist/es/styles/android.css +1 -0
- package/dist/types/components/Accordion/Accordion.d.ts +1 -1
- package/dist/types/components/Button/NavigationButton.d.ts +8 -1
- package/dist/types/components/Field/Field.d.ts +3 -0
- package/dist/types/components/Markdown/directives.d.ts +11 -1
- package/dist/types/components/PlexUIProvider/PlexUIProvider.d.ts +10 -3
- package/dist/types/components/PlexUIProvider/androidRipple.d.ts +9 -0
- package/dist/types/components/PlexUIProvider/index.d.ts +1 -1
- package/dist/types/components/Select/Select.d.ts +24 -0
- package/dist/types/components/Toolbar/Toolbar.d.ts +16 -1
- package/dist/types/components/Toolbar/index.d.ts +1 -1
- package/dist/types/lib/accordionMotion.d.ts +20 -0
- package/dist/types/lib/fieldRow.d.ts +14 -0
- package/dist/types/lib/presentMotion.d.ts +46 -0
- package/package.json +2 -2
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { isPhoneLayout } from "../../lib/phoneLayout.js";
|
|
2
|
+
import { SHEET_EXIT_MS, SHEET_RELEASE_SPRING, springEasing } from "../../lib/presentMotion.js";
|
|
2
3
|
// A bottom sheet follows the finger. A drag from its top 44px moves it 1:1, never up. Past 30% of its
|
|
3
|
-
// height, or at 0.5px/ms, it closes; otherwise it returns.
|
|
4
|
+
// height, or at 0.5px/ms, it closes; otherwise it returns. Either way it goes on at the finger's speed, on a spring
|
|
5
|
+
// that starts at it, as a sheet let go of does on iOS. Buttons in that strip keep their press.
|
|
4
6
|
// As on iOS, a pull down that starts anywhere else moves the sheet too once the content under the finger is at
|
|
5
7
|
// its top: the first move decides, down and mostly vertical with every scroller under the finger at its top
|
|
6
8
|
// takes the sheet; up, sideways, a move another handler took, a field, a control that pans by itself or a
|
|
@@ -21,6 +23,11 @@ const EXITING = "[data-exiting], [data-exiting-active]";
|
|
|
21
23
|
// A sheet at its full height says so: a sheet under it then steps back, as one presented from a sheet does on iOS.
|
|
22
24
|
// A shorter sheet leaves the one under it in place, as a medium detent does.
|
|
23
25
|
const FULL = "data-sheet-full";
|
|
26
|
+
// A sheet that grew out of its button would shrink back into it; one let go of leaves down instead (Dialog sets it).
|
|
27
|
+
const PRESENTED_FROM = "data-presented-from";
|
|
28
|
+
const EXIT_DURATION = "--dialog-exit-duration";
|
|
29
|
+
const EXIT_EASING = "--dialog-exit-easing";
|
|
30
|
+
const reducedMotion = (view) => Boolean(view.matchMedia?.("(prefers-reduced-motion: reduce)").matches);
|
|
24
31
|
const watchFullHeight = (panel, view) => {
|
|
25
32
|
if (!view.ResizeObserver)
|
|
26
33
|
return () => { };
|
|
@@ -68,20 +75,27 @@ export const attachSheetDrag = (panel, close) => {
|
|
|
68
75
|
stopSettling();
|
|
69
76
|
clearInline();
|
|
70
77
|
panel.style.removeProperty(DRAG_TRANSFORM);
|
|
78
|
+
panel.style.removeProperty(EXIT_DURATION);
|
|
79
|
+
panel.style.removeProperty(EXIT_EASING);
|
|
71
80
|
};
|
|
72
81
|
const onSettled = (event) => {
|
|
73
82
|
if (event.target === panel && event.propertyName === "transform")
|
|
74
83
|
clear();
|
|
75
84
|
};
|
|
76
|
-
|
|
85
|
+
// `from` is where the sheet is let go of, `velocity` the finger's speed down in px/ms: the sheet starts back at it.
|
|
86
|
+
const returnToRest = (from = 0, velocity = 0) => {
|
|
77
87
|
stopSettling();
|
|
78
|
-
if (view
|
|
88
|
+
if (reducedMotion(view)) {
|
|
79
89
|
clear();
|
|
80
90
|
return;
|
|
81
91
|
}
|
|
82
|
-
|
|
92
|
+
// Back up is the way to rest: a finger still going down starts it the other way.
|
|
93
|
+
const spring = springEasing(SHEET_RELEASE_SPRING, from > 0 ? (-velocity * 1000) / from : 0, true);
|
|
94
|
+
panel.style.transition = `transform ${spring.ms}ms ${spring.easing}`;
|
|
83
95
|
panel.style.transform = "";
|
|
84
96
|
panel.style.removeProperty(DRAG_TRANSFORM);
|
|
97
|
+
panel.style.removeProperty(EXIT_DURATION);
|
|
98
|
+
panel.style.removeProperty(EXIT_EASING);
|
|
85
99
|
const durationText = view.getComputedStyle(panel).transitionDuration;
|
|
86
100
|
const duration = Number.parseFloat(durationText) * (durationText.endsWith("ms") ? 1 : 1000);
|
|
87
101
|
if (duration === 0) {
|
|
@@ -170,29 +184,48 @@ export const attachSheetDrag = (panel, close) => {
|
|
|
170
184
|
if (fromContent && travelled > DECIDE && event.cancelable)
|
|
171
185
|
event.preventDefault();
|
|
172
186
|
fromContent = false;
|
|
173
|
-
// A finger that rested before lifting is no flick.
|
|
174
|
-
const
|
|
187
|
+
// A finger that rested before lifting is no flick, and gives the sheet no speed.
|
|
188
|
+
const moving = event.timeStamp - lastTime < REST;
|
|
189
|
+
const velocity = moving ? speed : 0;
|
|
190
|
+
const flick = speed > CLOSE_SPEED && moving;
|
|
175
191
|
startY = null;
|
|
176
192
|
if (travelled <= 0) {
|
|
177
193
|
clear();
|
|
178
194
|
return;
|
|
179
195
|
}
|
|
180
|
-
|
|
196
|
+
const height = panel.getBoundingClientRect().height;
|
|
197
|
+
if (travelled > height * CLOSE_SHARE || flick) {
|
|
181
198
|
// The normal/exit-start CSS states retain this exact release position.
|
|
182
199
|
// No inline transform or transition may mask the active CSS exit.
|
|
183
200
|
panel.style.setProperty(DRAG_TRANSFORM, `translateY(${travelled}px)`);
|
|
184
201
|
clearInline();
|
|
202
|
+
// The rest of the way down goes on at the finger's speed, within the time the dialog gives its exit
|
|
203
|
+
const presentedFrom = panel.hasAttribute(PRESENTED_FROM);
|
|
204
|
+
panel.removeAttribute(PRESENTED_FROM);
|
|
205
|
+
if (!reducedMotion(view)) {
|
|
206
|
+
const left = Math.max(1, height - travelled);
|
|
207
|
+
const spring = springEasing(SHEET_RELEASE_SPRING, (Math.max(0, velocity) * 1000) / left, true);
|
|
208
|
+
panel.style.setProperty(EXIT_DURATION, `${Math.min(spring.ms, SHEET_EXIT_MS)}ms`);
|
|
209
|
+
panel.style.setProperty(EXIT_EASING, spring.easing);
|
|
210
|
+
}
|
|
185
211
|
// An owner can veto close. Register before close, which can detach us.
|
|
186
212
|
settleTimer = view.setTimeout(() => {
|
|
187
213
|
settleTimer = undefined;
|
|
188
|
-
if (panel.isConnected
|
|
189
|
-
|
|
214
|
+
if (!panel.isConnected || panel.closest(EXITING))
|
|
215
|
+
return;
|
|
216
|
+
// An owner that kept the dialog open without saying so: it still goes back into its button later
|
|
217
|
+
if (presentedFrom)
|
|
218
|
+
panel.setAttribute(PRESENTED_FROM, "");
|
|
219
|
+
returnToRest(travelled, velocity);
|
|
190
220
|
}, SETTLE);
|
|
191
|
-
if (close(event) === false)
|
|
192
|
-
|
|
221
|
+
if (close(event) === false) {
|
|
222
|
+
if (presentedFrom)
|
|
223
|
+
panel.setAttribute(PRESENTED_FROM, "");
|
|
224
|
+
returnToRest(travelled, velocity);
|
|
225
|
+
}
|
|
193
226
|
return;
|
|
194
227
|
}
|
|
195
|
-
returnToRest();
|
|
228
|
+
returnToRest(travelled, velocity);
|
|
196
229
|
};
|
|
197
230
|
const onCancel = () => {
|
|
198
231
|
startY = null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sheetDrag.js","sourceRoot":"","sources":["../../../../src/components/Dialog/sheetDrag.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AAErD,sGAAsG;AACtG,mGAAmG;AACnG,+GAA+G;AAC/G,4GAA4G;AAC5G,0GAA0G;AAC1G,sFAAsF;AACtF,MAAM,IAAI,GAAG,EAAE,CAAA;AACf,MAAM,WAAW,GAAG,GAAG,CAAA;AACvB,MAAM,WAAW,GAAG,GAAG,CAAA;AACvB,MAAM,IAAI,GAAG,GAAG,CAAA;AAChB,MAAM,MAAM,GAAG,GAAG,CAAA;AAClB,MAAM,WAAW,GAAG,qDAAqD,CAAA;AACzE,MAAM,QAAQ,GAAG,4FAA4F,CAAA;AAC7G,6GAA6G;AAC7G,MAAM,MAAM,GAAG,CAAC,CAAA;AAChB,yFAAyF;AACzF,MAAM,IAAI,GAAG,GAAG,CAAA;AAChB,MAAM,cAAc,GAAG,+BAA+B,CAAA;AACtD,MAAM,OAAO,GAAG,uCAAuC,CAAA;AACv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AI,EAAE,CAAC,CAAA;IAChE,KAAK,CAAC,gBAAgB,CAAC,WAAW,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAA;IAC/D,KAAK,CAAC,gBAAgB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAA;IACzC,KAAK,CAAC,gBAAgB,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAA;IAE/C,OAAO,GAAG,EAAE;QACV,WAAW,EAAE,CAAA;QACb,aAAa,EAAE,UAAU,EAAE,CAAA;QAC3B,KAAK,CAAC,mBAAmB,CAAC,YAAY,EAAE,OAAO,CAAC,CAAA;QAChD,KAAK,CAAC,mBAAmB,CAAC,WAAW,EAAE,MAAM,CAAC,CAAA;QAC9C,KAAK,CAAC,mBAAmB,CAAC,UAAU,EAAE,KAAK,CAAC,CAAA;QAC5C,KAAK,CAAC,mBAAmB,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAA;QAClD,MAAM,GAAG,IAAI,CAAA;QACb,OAAO,GAAG,IAAI,CAAA;QACd,KAAK,EAAE,CAAA;IACT,CAAC,CAAA;AACH,CAAC,CAAA","sourcesContent":["import { isPhoneLayout } from \"../../lib/phoneLayout\"\n\n// A bottom sheet follows the finger. A drag from its top 44px moves it 1:1, never up. Past 30% of its\n// height, or at 0.5px/ms, it closes; otherwise it returns. Buttons in that strip keep their press.\n// As on iOS, a pull down that starts anywhere else moves the sheet too once the content under the finger is at\n// its top: the first move decides, down and mostly vertical with every scroller under the finger at its top\n// takes the sheet; up, sideways, a move another handler took, a field, a control that pans by itself or a\n// finger that rested first (a hold: Sortable, a context menu) stays with the content.\nconst GRIP = 44\nconst CLOSE_SHARE = 0.3\nconst CLOSE_SPEED = 0.5\nconst REST = 100\nconst SETTLE = 400\nconst INTERACTIVE = \"a, button, input, select, textarea, [role='button']\"\nconst EDITABLE = \"input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='slider']\"\n// The move that settles which way the finger goes, under the browser's own slop so it can still be cancelled\nconst DECIDE = 4\n// A finger that rests this long holds (a Sortable row, a context menu) rather than pulls\nconst HOLD = 200\nconst DRAG_TRANSFORM = \"--dialog-panel-drag-transform\"\nconst EXITING = \"[data-exiting], [data-exiting-active]\"\n// A sheet at its full height says so: a sheet under it then steps back, as one presented from a sheet does on iOS.\n// A shorter sheet leaves the one under it in place, as a medium detent does.\nconst FULL = \"data-sheet-full\"\n\nconst watchFullHeight = (panel: HTMLElement, view: Window & typeof globalThis) => {\n if (!view.ResizeObserver) return () => {}\n const update = () => {\n const max = Number.parseFloat(view.getComputedStyle(panel).maxHeight)\n const full = Number.isFinite(max) && panel.offsetHeight >= max - 1\n if (full !== panel.hasAttribute(FULL)) panel.toggleAttribute(FULL, full)\n }\n const observer = new view.ResizeObserver(update)\n // Its height with the border, as `offsetHeight` reads it\n observer.observe(panel, { box: \"border-box\" })\n update()\n return () => {\n observer.disconnect()\n panel.removeAttribute(FULL)\n }\n}\n\n/** `close` returns false when the owner keeps the dialog open: the sheet then returns at once. */\nexport const attachSheetDrag = (panel: HTMLElement, close: (event: TouchEvent) => boolean | void) => {\n const view = panel.ownerDocument.defaultView\n if (!view) return () => {}\n const unwatchFull = watchFullHeight(panel, view)\n let startY: number | null = null\n // A touch in the content that may become a pull, until its first move says which way it goes\n let pending: { x: number; y: number; time: number; target: Element } | null = null\n // The pull began in the content: its release must not press what lies under the finger\n let fromContent = false\n let lastY = 0\n let lastTime = 0\n let speed = 0\n let settleTimer: number | undefined\n\n const stopSettling = () => {\n if (settleTimer !== undefined) view.clearTimeout(settleTimer)\n settleTimer = undefined\n panel.removeEventListener(\"transitionend\", onSettled)\n }\n const clearInline = () => {\n panel.style.transition = \"\"\n panel.style.transform = \"\"\n }\n const clear = () => {\n stopSettling()\n clearInline()\n panel.style.removeProperty(DRAG_TRANSFORM)\n }\n const onSettled = (event: TransitionEvent) => {\n if (event.target === panel && event.propertyName === \"transform\") clear()\n }\n const returnToRest = () => {\n stopSettling()\n if (view.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches) {\n clear()\n return\n }\n panel.style.transition = \"transform var(--motion-enter) var(--cubic-enter)\"\n panel.style.transform = \"\"\n panel.style.removeProperty(DRAG_TRANSFORM)\n const durationText = view.getComputedStyle(panel).transitionDuration\n const duration = Number.parseFloat(durationText) * (durationText.endsWith(\"ms\") ? 1 : 1000)\n if (duration === 0) {\n clear()\n return\n }\n panel.addEventListener(\"transitionend\", onSettled)\n // A theme can lengthen the token or remove the transition altogether.\n // This cleanup must not cut a valid longer transition at the veto timeout.\n settleTimer = view.setTimeout(clear, Math.max(SETTLE, Number.isFinite(duration) ? duration : 0))\n }\n\n const begin = (clientY: number, time: number) => {\n stopSettling()\n startY = clientY\n lastY = clientY\n lastTime = time\n speed = 0\n }\n\n // Every element from the target up to the panel: one that can scroll up, or pans by itself, keeps the move.\n const contentTakes = (target: Element) => {\n for (let element: Element | null = target; element; element = element.parentElement) {\n if (element.scrollTop > 0) return true\n const touchAction = view.getComputedStyle(element).touchAction\n if (touchAction && touchAction !== \"auto\" && touchAction !== \"manipulation\" && !touchAction.includes(\"pan-y\")) return true\n if (element === panel) break\n }\n return false\n }\n\n const onStart = (event: TouchEvent) => {\n pending = null\n fromContent = false\n const phone = isPhoneLayout(panel)\n if (event.touches.length !== 1 || !phone || panel.closest(EXITING)) return\n const { clientX, clientY } = event.touches[0]\n const target = event.target instanceof view.Element ? event.target : null\n if (clientY - panel.getBoundingClientRect().top <= GRIP) {\n if (target?.closest(INTERACTIVE)) return\n begin(clientY, event.timeStamp)\n return\n }\n if (!target || target.closest(EDITABLE)) return\n pending = { x: clientX, y: clientY, time: event.timeStamp, target }\n }\n\n // The first move of a touch in the content: a pull down from the top takes the sheet from here on.\n const decide = (event: TouchEvent, touch: Touch) => {\n const start = pending!\n const dx = touch.clientX - start.x\n const dy = touch.clientY - start.y\n if (Math.max(Math.abs(dx), Math.abs(dy)) < DECIDE) return\n pending = null\n if (event.defaultPrevented || !event.cancelable || event.timeStamp - start.time > HOLD) return\n if (dy <= 0 || Math.abs(dx) > dy || contentTakes(start.target)) return\n fromContent = true\n begin(start.y, start.time)\n }\n\n const onMove = (event: TouchEvent) => {\n const touch = event.touches[0]\n if (startY === null && pending && touch) decide(event, touch)\n if (startY === null || !touch) return\n event.preventDefault()\n const { clientY } = touch\n speed = (clientY - lastY) / Math.max(1, event.timeStamp - lastTime)\n lastY = clientY\n lastTime = event.timeStamp\n panel.style.transition = \"none\"\n panel.style.transform = `translateY(${Math.max(0, clientY - startY)}px)`\n }\n\n const onEnd = (event: TouchEvent) => {\n pending = null\n if (startY === null) return\n const travelled = lastY - startY\n // A pull from the content ends where it lifted, not in a press of the row under it. A finger that barely\n // moved keeps its tap.\n if (fromContent && travelled > DECIDE && event.cancelable) event.preventDefault()\n fromContent = false\n // A finger that rested before lifting is no flick.\n const flick = speed > CLOSE_SPEED && event.timeStamp - lastTime < REST\n startY = null\n if (travelled <= 0) {\n clear()\n return\n }\n if (travelled > panel.getBoundingClientRect().height * CLOSE_SHARE || flick) {\n // The normal/exit-start CSS states retain this exact release position.\n // No inline transform or transition may mask the active CSS exit.\n panel.style.setProperty(DRAG_TRANSFORM, `translateY(${travelled}px)`)\n clearInline()\n // An owner can veto close. Register before close, which can detach us.\n settleTimer = view.setTimeout(() => {\n settleTimer = undefined\n if (panel.isConnected && !panel.closest(EXITING)) returnToRest()\n }, SETTLE)\n if (close(event) === false) returnToRest()\n return\n }\n returnToRest()\n }\n\n const onCancel = () => {\n startY = null\n pending = null\n fromContent = false\n clear()\n }\n\n // A retained panel can reopen before its exit completes. Its new entrance\n // must return to rest, not finish at the old gesture's release offset.\n const dialog = panel.closest(\"[data-plex-dialog]\")\n const stateObserver = dialog ? new view.MutationObserver((records) => {\n if (panel.style.getPropertyValue(DRAG_TRANSFORM) &&\n dialog.getAttribute(\"data-state\") === \"open\" &&\n records.some((record) => record.oldValue === \"closed\")) clear()\n }) : undefined\n stateObserver?.observe(dialog ?? panel, {\n attributes: true, attributeFilter: [\"data-state\"], attributeOldValue: true,\n })\n\n panel.addEventListener(\"touchstart\", onStart, { passive: true })\n panel.addEventListener(\"touchmove\", onMove, { passive: false })\n panel.addEventListener(\"touchend\", onEnd)\n panel.addEventListener(\"touchcancel\", onCancel)\n\n return () => {\n unwatchFull()\n stateObserver?.disconnect()\n panel.removeEventListener(\"touchstart\", onStart)\n panel.removeEventListener(\"touchmove\", onMove)\n panel.removeEventListener(\"touchend\", onEnd)\n panel.removeEventListener(\"touchcancel\", onCancel)\n startY = null\n pending = null\n clear()\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sheetDrag.js","sourceRoot":"","sources":["../../../../src/components/Dialog/sheetDrag.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AACrD,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AAE3F,sGAAsG;AACtG,oHAAoH;AACpH,+FAA+F;AAC/F,+GAA+G;AAC/G,4GAA4G;AAC5G,0GAA0G;AAC1G,sFAAsF;AACtF,MAAM,IAAI,GAAG,EAAE,CAAA;AACf,MAAM,WAAW,GAAG,GAAG,CAAA;AACvB,MAAM,WAAW,GAAG,GAAG,CAAA;AACvB,MAAM,IAAI,GAAG,GAAG,CAAA;AAChB,MAAM,MAAM,GAAG,GAAG,CAAA;AAClB,MAAM,WAAW,GAAG,qDAAqD,CAAA;AACzE,MAAM,QAAQ,GAAG,4FAA4F,CAAA;AAC7G,6GAA6G;AAC7G,MAAM,MAAM,GAAG,CAAC,CAAA;AAChB,yFAAyF;AACzF,MAAM,IAAI,GAAG,GAAG,CAAA;AAChB,MAAM,cAAc,GAAG,+BAA+B,CAAA;AACtD,MAAM,OAAO,GAAG,uCAAuC,CAAA;AACvD,mHAAmH;AACnH,6EAA6E;AAC7E,MAAM,IAAI,GAAG,iBAAiB,CAAA;AAC9B,qHAAqH;AACrH,MAAM,cAAc,GAAG,qBAAqB,CAAA;AAC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AAA;AACH,CAAC,CAAA","sourcesContent":["import { isPhoneLayout } from \"../../lib/phoneLayout\"\nimport { SHEET_EXIT_MS, SHEET_RELEASE_SPRING, springEasing } from \"../../lib/presentMotion\"\n\n// A bottom sheet follows the finger. A drag from its top 44px moves it 1:1, never up. Past 30% of its\n// height, or at 0.5px/ms, it closes; otherwise it returns. Either way it goes on at the finger's speed, on a spring\n// that starts at it, as a sheet let go of does on iOS. Buttons in that strip keep their press.\n// As on iOS, a pull down that starts anywhere else moves the sheet too once the content under the finger is at\n// its top: the first move decides, down and mostly vertical with every scroller under the finger at its top\n// takes the sheet; up, sideways, a move another handler took, a field, a control that pans by itself or a\n// finger that rested first (a hold: Sortable, a context menu) stays with the content.\nconst GRIP = 44\nconst CLOSE_SHARE = 0.3\nconst CLOSE_SPEED = 0.5\nconst REST = 100\nconst SETTLE = 400\nconst INTERACTIVE = \"a, button, input, select, textarea, [role='button']\"\nconst EDITABLE = \"input, textarea, select, [contenteditable]:not([contenteditable='false']), [role='slider']\"\n// The move that settles which way the finger goes, under the browser's own slop so it can still be cancelled\nconst DECIDE = 4\n// A finger that rests this long holds (a Sortable row, a context menu) rather than pulls\nconst HOLD = 200\nconst DRAG_TRANSFORM = \"--dialog-panel-drag-transform\"\nconst EXITING = \"[data-exiting], [data-exiting-active]\"\n// A sheet at its full height says so: a sheet under it then steps back, as one presented from a sheet does on iOS.\n// A shorter sheet leaves the one under it in place, as a medium detent does.\nconst FULL = \"data-sheet-full\"\n// A sheet that grew out of its button would shrink back into it; one let go of leaves down instead (Dialog sets it).\nconst PRESENTED_FROM = \"data-presented-from\"\nconst EXIT_DURATION = \"--dialog-exit-duration\"\nconst EXIT_EASING = \"--dialog-exit-easing\"\n\nconst reducedMotion = (view: Window) => Boolean(view.matchMedia?.(\"(prefers-reduced-motion: reduce)\").matches)\n\nconst watchFullHeight = (panel: HTMLElement, view: Window & typeof globalThis) => {\n if (!view.ResizeObserver) return () => {}\n const update = () => {\n const max = Number.parseFloat(view.getComputedStyle(panel).maxHeight)\n const full = Number.isFinite(max) && panel.offsetHeight >= max - 1\n if (full !== panel.hasAttribute(FULL)) panel.toggleAttribute(FULL, full)\n }\n const observer = new view.ResizeObserver(update)\n // Its height with the border, as `offsetHeight` reads it\n observer.observe(panel, { box: \"border-box\" })\n update()\n return () => {\n observer.disconnect()\n panel.removeAttribute(FULL)\n }\n}\n\n/** `close` returns false when the owner keeps the dialog open: the sheet then returns at once. */\nexport const attachSheetDrag = (panel: HTMLElement, close: (event: TouchEvent) => boolean | void) => {\n const view = panel.ownerDocument.defaultView\n if (!view) return () => {}\n const unwatchFull = watchFullHeight(panel, view)\n let startY: number | null = null\n // A touch in the content that may become a pull, until its first move says which way it goes\n let pending: { x: number; y: number; time: number; target: Element } | null = null\n // The pull began in the content: its release must not press what lies under the finger\n let fromContent = false\n let lastY = 0\n let lastTime = 0\n let speed = 0\n let settleTimer: number | undefined\n\n const stopSettling = () => {\n if (settleTimer !== undefined) view.clearTimeout(settleTimer)\n settleTimer = undefined\n panel.removeEventListener(\"transitionend\", onSettled)\n }\n const clearInline = () => {\n panel.style.transition = \"\"\n panel.style.transform = \"\"\n }\n const clear = () => {\n stopSettling()\n clearInline()\n panel.style.removeProperty(DRAG_TRANSFORM)\n panel.style.removeProperty(EXIT_DURATION)\n panel.style.removeProperty(EXIT_EASING)\n }\n const onSettled = (event: TransitionEvent) => {\n if (event.target === panel && event.propertyName === \"transform\") clear()\n }\n // `from` is where the sheet is let go of, `velocity` the finger's speed down in px/ms: the sheet starts back at it.\n const returnToRest = (from = 0, velocity = 0) => {\n stopSettling()\n if (reducedMotion(view)) {\n clear()\n return\n }\n // Back up is the way to rest: a finger still going down starts it the other way.\n const spring = springEasing(SHEET_RELEASE_SPRING, from > 0 ? (-velocity * 1000) / from : 0, true)\n panel.style.transition = `transform ${spring.ms}ms ${spring.easing}`\n panel.style.transform = \"\"\n panel.style.removeProperty(DRAG_TRANSFORM)\n panel.style.removeProperty(EXIT_DURATION)\n panel.style.removeProperty(EXIT_EASING)\n const durationText = view.getComputedStyle(panel).transitionDuration\n const duration = Number.parseFloat(durationText) * (durationText.endsWith(\"ms\") ? 1 : 1000)\n if (duration === 0) {\n clear()\n return\n }\n panel.addEventListener(\"transitionend\", onSettled)\n // A theme can lengthen the token or remove the transition altogether.\n // This cleanup must not cut a valid longer transition at the veto timeout.\n settleTimer = view.setTimeout(clear, Math.max(SETTLE, Number.isFinite(duration) ? duration : 0))\n }\n\n const begin = (clientY: number, time: number) => {\n stopSettling()\n startY = clientY\n lastY = clientY\n lastTime = time\n speed = 0\n }\n\n // Every element from the target up to the panel: one that can scroll up, or pans by itself, keeps the move.\n const contentTakes = (target: Element) => {\n for (let element: Element | null = target; element; element = element.parentElement) {\n if (element.scrollTop > 0) return true\n const touchAction = view.getComputedStyle(element).touchAction\n if (touchAction && touchAction !== \"auto\" && touchAction !== \"manipulation\" && !touchAction.includes(\"pan-y\")) return true\n if (element === panel) break\n }\n return false\n }\n\n const onStart = (event: TouchEvent) => {\n pending = null\n fromContent = false\n const phone = isPhoneLayout(panel)\n if (event.touches.length !== 1 || !phone || panel.closest(EXITING)) return\n const { clientX, clientY } = event.touches[0]\n const target = event.target instanceof view.Element ? event.target : null\n if (clientY - panel.getBoundingClientRect().top <= GRIP) {\n if (target?.closest(INTERACTIVE)) return\n begin(clientY, event.timeStamp)\n return\n }\n if (!target || target.closest(EDITABLE)) return\n pending = { x: clientX, y: clientY, time: event.timeStamp, target }\n }\n\n // The first move of a touch in the content: a pull down from the top takes the sheet from here on.\n const decide = (event: TouchEvent, touch: Touch) => {\n const start = pending!\n const dx = touch.clientX - start.x\n const dy = touch.clientY - start.y\n if (Math.max(Math.abs(dx), Math.abs(dy)) < DECIDE) return\n pending = null\n if (event.defaultPrevented || !event.cancelable || event.timeStamp - start.time > HOLD) return\n if (dy <= 0 || Math.abs(dx) > dy || contentTakes(start.target)) return\n fromContent = true\n begin(start.y, start.time)\n }\n\n const onMove = (event: TouchEvent) => {\n const touch = event.touches[0]\n if (startY === null && pending && touch) decide(event, touch)\n if (startY === null || !touch) return\n event.preventDefault()\n const { clientY } = touch\n speed = (clientY - lastY) / Math.max(1, event.timeStamp - lastTime)\n lastY = clientY\n lastTime = event.timeStamp\n panel.style.transition = \"none\"\n panel.style.transform = `translateY(${Math.max(0, clientY - startY)}px)`\n }\n\n const onEnd = (event: TouchEvent) => {\n pending = null\n if (startY === null) return\n const travelled = lastY - startY\n // A pull from the content ends where it lifted, not in a press of the row under it. A finger that barely\n // moved keeps its tap.\n if (fromContent && travelled > DECIDE && event.cancelable) event.preventDefault()\n fromContent = false\n // A finger that rested before lifting is no flick, and gives the sheet no speed.\n const moving = event.timeStamp - lastTime < REST\n const velocity = moving ? speed : 0\n const flick = speed > CLOSE_SPEED && moving\n startY = null\n if (travelled <= 0) {\n clear()\n return\n }\n const height = panel.getBoundingClientRect().height\n if (travelled > height * CLOSE_SHARE || flick) {\n // The normal/exit-start CSS states retain this exact release position.\n // No inline transform or transition may mask the active CSS exit.\n panel.style.setProperty(DRAG_TRANSFORM, `translateY(${travelled}px)`)\n clearInline()\n // The rest of the way down goes on at the finger's speed, within the time the dialog gives its exit\n const presentedFrom = panel.hasAttribute(PRESENTED_FROM)\n panel.removeAttribute(PRESENTED_FROM)\n if (!reducedMotion(view)) {\n const left = Math.max(1, height - travelled)\n const spring = springEasing(SHEET_RELEASE_SPRING, (Math.max(0, velocity) * 1000) / left, true)\n panel.style.setProperty(EXIT_DURATION, `${Math.min(spring.ms, SHEET_EXIT_MS)}ms`)\n panel.style.setProperty(EXIT_EASING, spring.easing)\n }\n // An owner can veto close. Register before close, which can detach us.\n settleTimer = view.setTimeout(() => {\n settleTimer = undefined\n if (!panel.isConnected || panel.closest(EXITING)) return\n // An owner that kept the dialog open without saying so: it still goes back into its button later\n if (presentedFrom) panel.setAttribute(PRESENTED_FROM, \"\")\n returnToRest(travelled, velocity)\n }, SETTLE)\n if (close(event) === false) {\n if (presentedFrom) panel.setAttribute(PRESENTED_FROM, \"\")\n returnToRest(travelled, velocity)\n }\n return\n }\n returnToRest(travelled, velocity)\n }\n\n const onCancel = () => {\n startY = null\n pending = null\n fromContent = false\n clear()\n }\n\n // A retained panel can reopen before its exit completes. Its new entrance\n // must return to rest, not finish at the old gesture's release offset.\n const dialog = panel.closest(\"[data-plex-dialog]\")\n const stateObserver = dialog ? new view.MutationObserver((records) => {\n if (panel.style.getPropertyValue(DRAG_TRANSFORM) &&\n dialog.getAttribute(\"data-state\") === \"open\" &&\n records.some((record) => record.oldValue === \"closed\")) clear()\n }) : undefined\n stateObserver?.observe(dialog ?? panel, {\n attributes: true, attributeFilter: [\"data-state\"], attributeOldValue: true,\n })\n\n panel.addEventListener(\"touchstart\", onStart, { passive: true })\n panel.addEventListener(\"touchmove\", onMove, { passive: false })\n panel.addEventListener(\"touchend\", onEnd)\n panel.addEventListener(\"touchcancel\", onCancel)\n\n return () => {\n unwatchFull()\n stateObserver?.disconnect()\n panel.removeEventListener(\"touchstart\", onStart)\n panel.removeEventListener(\"touchmove\", onMove)\n panel.removeEventListener(\"touchend\", onEnd)\n panel.removeEventListener(\"touchcancel\", onCancel)\n startY = null\n pending = null\n clear()\n }\n}\n"]}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
3
|
import clsx from "clsx";
|
|
4
4
|
import { cloneElement, isValidElement, useId, useRef } from "react";
|
|
5
|
-
import { FieldRowContext } from "../../lib/fieldRow.js";
|
|
5
|
+
import { FieldRowContext, useBlankPlaceholder } from "../../lib/fieldRow.js";
|
|
6
6
|
import { FieldError } from "../FieldError/index.js";
|
|
7
7
|
import s from "@plexui/styles/components/Field/Field.module.css";
|
|
8
8
|
// What a row's press can reach: a form control, a popup trigger, a choice
|
|
@@ -28,6 +28,8 @@ export function Field({ label, hideLabel = false, description, errorMessage, lab
|
|
|
28
28
|
const controlId = childProps?.id || fieldId;
|
|
29
29
|
const descriptionId = description ? `${fieldId}-description` : undefined;
|
|
30
30
|
const errorId = errorMessage ? `${fieldId}-error` : undefined;
|
|
31
|
+
// In the Plex Android look a text field under its shown label floats the label in its place while it is empty
|
|
32
|
+
useBlankPlaceholder(controlId, row && orientation === "vertical" && !hideLabel);
|
|
31
33
|
// Build aria-describedby from description + error IDs
|
|
32
34
|
const ariaDescribedBy = [descriptionId, errorId].filter(Boolean).join(" ") || undefined;
|
|
33
35
|
const invalid = !!errorMessage;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Field.js","sourceRoot":"","sources":["../../../../src/components/Field/Field.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAA;;AAEZ,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,OAAO,CAAA;AAEnE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAA;AAEpD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAE1C,OAAO,CAAC,MAAM,kDAAkD,CAAA;AAEhE,0EAA0E;AAC1E,MAAM,WAAW,GAAG,wKAAwK,CAAA;AAE5L;oCACoC;AACpC,SAAS,cAAc,CAAC,OAAoB;IAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAc,WAAW,CAAC,CAAC,CAAA;IAC5E,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,OAAO,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC7G,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAA;AAC7C,CAAC;AAWD,MAAM,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C,OAAO,aACvB,cAAK,SAAS,EAAE,CAAC,CAAC,OAAO,YAAG,gBAAgB,GAAO,EAClD,YAAY,IAAI,CACf,KAAC,UAAU,IAAC,EAAE,EAAE,OAAO,YAAG,YAAY,GAAc,CACrD,IACG,EACL,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,cAAK,SAAS,EAAE,CAAC,CAAC,MAAM,YAAG,MAAM,GAAO,CAAC,CAAC,CAAC,IAAI,IAC5D,GACmB,CAC5B,CAAA;AACH,CAAC","sourcesContent":["\"use client\"\n\nimport clsx from \"clsx\"\nimport { cloneElement, isValidElement, useId, useRef } from \"react\"\n\nimport { FieldRowContext } from \"../../lib/fieldRow\"\nimport type { ControlSize } from \"../../types\"\nimport { FieldError } from \"../FieldError\"\n\nimport s from \"@plexui/styles/components/Field/Field.module.css\"\n\n// What a row's press can reach: a form control, a popup trigger, a choice\nconst ROW_CONTROL = 'input:not([type=\"hidden\"]):not([aria-hidden=\"true\"]), textarea, select, button, [role=\"button\"], [role=\"switch\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"combobox\"]'\n\n/** The one control inside a wrapper that took the Field's id; a control nested in another (a clear button in a\n * trigger) counts as part of it. */\nfunction soleRowControl(wrapper: HTMLElement): HTMLElement | null {\n const found = Array.from(wrapper.querySelectorAll<HTMLElement>(ROW_CONTROL))\n const outer = found.filter((element) => !found.some((other) => other !== element && other.contains(element)))\n return outer.length === 1 ? outer[0] : null\n}\n\nexport type FieldChildProps = {\n id: string\n /** The label's id. Spread onto a control that the label's `for` cannot name, such as a Select trigger. */\n \"aria-labelledby\"?: string\n \"aria-describedby\"?: string\n \"aria-invalid\"?: boolean\n opticallyAlign?: \"start\" | \"end\"\n}\n\nconst CONTROL_SIZES: ReadonlySet<unknown> = new Set([\"3xs\", \"2xs\", \"xs\", \"sm\", \"md\", \"lg\", \"xl\", \"2xl\", \"3xl\"])\n\nexport type FieldProps = {\n /**\n * Label text for the field\n */\n label: React.ReactNode\n /**\n * Helper/description text displayed below the label.\n * Automatically linked via aria-describedby.\n */\n description?: React.ReactNode\n /**\n * Hides the label from view; it still names the control for assistive technology.\n * On a `row` the value or placeholder then starts at the row's edge, as an iOS cell that\n * shows only its placeholder or value (Notes, a title, a server's address), so the row is\n * vertical unless `orientation` says otherwise. Words that explain the field go in the\n * FieldGroup's `footer`.\n * @default false\n */\n hideLabel?: boolean\n /**\n * Error message displayed below the control.\n * When provided, the child control receives aria-invalid=\"true\".\n * Uses the existing FieldError component internally.\n */\n errorMessage?: React.ReactNode\n /**\n * Content placed at the end of the label row, such as a link that acts on\n * the field (\"Forgot password?\", \"Replace\").\n */\n labelAction?: React.ReactNode\n /**\n * On a `row`, a control at the end of the row after the row's own control. On a `fill`\n * row, such as a button that adds to a list, it stays on the list's first line, and on a\n * phone it stands beside the label with the list on a line of its own. On a row whose\n * control is a radio, such as an info button after a network or a VPN, the radio's mark\n * leads in the icon column and the action alone stands at the end.\n */\n action?: React.ReactNode\n /**\n * On a `row`, a symbol or an app's picture before the label, as an iOS cell's image: the label, its\n * description and the line above the row start after it. An `img` fills the column with the corners of an\n * app icon; an icon takes the symbol size.\n */\n icon?: React.ReactNode\n /**\n * Controls the font size of the label to visually match the child control's size.\n * Matches the ControlSize scale used by Input, Select, etc.\n * @default the child control's `size`, else \"md\"\n */\n size?: ControlSize\n /**\n * Display a required indicator (asterisk) after the label.\n * This is purely visual — it does not add the `required` HTML attribute.\n * @default false\n */\n required?: boolean\n /**\n * Layout direction of label and control.\n * - \"vertical\": label stacked above control (default)\n * - \"horizontal\": label beside control\n * @default \"horizontal\" on a `row` with a visible label, else \"vertical\"\n */\n orientation?: \"vertical\" | \"horizontal\"\n /**\n * One line of a FieldGroup: label at the start, control at the end, an error\n * under both. Other div props reach the root only on a row, so it can carry\n * a click or data attributes.\n * Clicking a non-interactive part of the row focuses its text editor or activates its choice control or popup trigger.\n * A control at the end of the row is a pill unless its own `pill` says otherwise.\n * @default false\n */\n row?: boolean\n /**\n * On a `row`, the control takes the rest of the line after the label, for a\n * list of tags and the like.\n * @default false\n */\n fill?: boolean\n /**\n * Allows overriding the auto-generated `id`. When provided, this becomes\n * the id set on the child control and the `htmlFor` on the label. A child's\n * own `id` wins over both: it stays, and the label's `htmlFor` follows it.\n */\n id?: string\n /**\n * Applies a negative margin on the child control using its gutter to\n * optically align the control's text with surrounding content.\n * Passed through to the child control via cloneElement / render prop.\n */\n opticallyAlign?: \"start\" | \"end\"\n /**\n * CSS class applied to the root wrapper\n */\n className?: string\n /**\n * The form control(s) to render.\n * - If a single ReactElement, Field clones it with { id, aria-describedby, aria-invalid },\n * keeping an `id` the child already has.\n * A child without its own `aria-label`, `aria-labelledby` or `label` also gets\n * `aria-labelledby` pointing at the label, which names controls the label's\n * `for` cannot reach, such as the Select and DatePicker triggers.\n * - If a function (render prop), it is called with { id, \"aria-labelledby\", \"aria-describedby\", \"aria-invalid\" }.\n */\n children: React.ReactElement | ((fieldProps: FieldChildProps) => React.ReactNode)\n} & Omit<React.ComponentProps<\"div\">, \"children\" | \"id\" | \"className\">\n\nexport function Field({\n label,\n hideLabel = false,\n description,\n errorMessage,\n labelAction,\n action,\n icon,\n size: sizeProp,\n required = false,\n orientation: orientationProp,\n row = false,\n fill = false,\n opticallyAlign,\n id: idProp,\n className,\n children,\n ...rest\n}: FieldProps) {\n const orientation = orientationProp ?? (row && !hideLabel ? \"horizontal\" : \"vertical\")\n const generatedId = useId()\n const forwardingRowClick = useRef(false)\n const fieldId = idProp || `field-${generatedId}`\n const labelId = `${fieldId}-label`\n const childProps = isValidElement<{ size?: unknown; id?: string }>(children) ? children.props : undefined\n const childSize = childProps?.size\n const size = sizeProp ?? (CONTROL_SIZES.has(childSize) ? (childSize as ControlSize) : \"md\")\n // The control's id, which the label's `htmlFor` has to match\n const controlId = childProps?.id || fieldId\n const descriptionId = description ? `${fieldId}-description` : undefined\n const errorId = errorMessage ? `${fieldId}-error` : undefined\n\n // Build aria-describedby from description + error IDs\n const ariaDescribedBy =\n [descriptionId, errorId].filter(Boolean).join(\" \") || undefined\n\n const invalid = !!errorMessage\n\n // Props to inject into the child control (`aria-labelledby` is added below:\n // to a render prop's props, and to a cloned child without a name of its own)\n const fieldChildProps: FieldChildProps = {\n id: controlId,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": invalid || undefined,\n ...(opticallyAlign && { opticallyAlign }),\n }\n\n // Resolve the children\n let resolvedChildren: React.ReactNode\n if (typeof children === \"function\") {\n resolvedChildren = children({ ...fieldChildProps, \"aria-labelledby\": labelId })\n } else if (isValidElement(children)) {\n const child = children as React.ReactElement<Record<string, unknown>>\n // Merge with the child's own associations instead of overwriting them\n const childDescribedBy = child.props[\"aria-describedby\"] as string | undefined\n const childNamed =\n child.props[\"aria-label\"] != null || child.props[\"aria-labelledby\"] != null || child.props.label != null\n resolvedChildren = cloneElement(child, {\n ...fieldChildProps,\n \"aria-describedby\":\n [childDescribedBy, ariaDescribedBy].filter(Boolean).join(\" \") || undefined,\n \"aria-invalid\": child.props[\"aria-invalid\"] ?? fieldChildProps[\"aria-invalid\"],\n ...(!childNamed && { \"aria-labelledby\": labelId }),\n })\n } else {\n resolvedChildren = children\n }\n\n const labelElement = (\n <label className={s.Label} id={labelId} htmlFor={controlId}>\n {label}\n {required && (\n <span className={s.RequiredIndicator} aria-hidden=\"true\">\n *\n </span>\n )}\n </label>\n )\n\n return (\n <FieldRowContext.Provider value={row && orientation === \"horizontal\"}>\n <div\n {...(row ? rest : undefined)}\n onClick={row ? (event) => {\n if (forwardingRowClick.current) return\n rest.onClick?.(event)\n if (event.defaultPrevented) return\n const target = event.target\n const root = event.currentTarget\n // The linked control remains the keyboard stop and owns its state.\n // Nested actions keep their own click, including a Select's clear button.\n if (!(target instanceof Element) || target.closest(\"[data-row]\") !== root ||\n target.closest('button, a, input, select, textarea, [role=\"button\"], [role=\"link\"], [contenteditable]:not([contenteditable=\"false\"])')) return\n const linkedControl = root.ownerDocument.getElementById(controlId)\n if (!linkedControl || linkedControl.closest(\"[data-row]\") !== root) return\n // Select's id belongs to its hidden form proxy inside the trigger.\n // Never search sibling popups, such as an InputGroup's unit action.\n const direct = linkedControl.matches('input[aria-hidden=\"true\"]')\n ? linkedControl.closest<HTMLElement>(':is(button, [role=\"button\"])[aria-haspopup]:not([aria-haspopup=\"false\"])') ?? linkedControl\n : linkedControl\n // A product's own wrapper may take the id (a row component around a Select): the row then reaches the one\n // control inside it, as an iOS cell does; with two controls, or none, the press stays on the row.\n const control = direct === linkedControl && !linkedControl.matches(ROW_CONTROL) ? soleRowControl(linkedControl) : direct\n // A control of a row nested in the wrapper belongs to that row\n if (!control || control.closest(\"[data-row]\") !== root) return\n if (control.matches(':disabled, [disabled], [data-disabled], [aria-disabled=\"true\"], [data-loading], [aria-busy=\"true\"]')) return\n const label = target.closest(\"label\")\n // Native labels already click their linked form control. A directly\n // linked span trigger, such as DatePicker's, needs forwarding instead.\n if (label && (label.htmlFor !== linkedControl.id || label.control === linkedControl)) return\n // The row is the hit area for its plain editor. Focus only: a synthetic\n // click would also run input actions or disturb native text selection.\n if (control.matches('textarea, input:not([type]), input[type=\"text\"], input[type=\"email\"], input[type=\"password\"], input[type=\"search\"], input[type=\"tel\"], input[type=\"url\"], input[type=\"number\"]') &&\n !control.matches('[hidden], [aria-hidden=\"true\"]')) {\n control.focus({ preventScroll: true })\n return\n }\n if (!control.matches('button[role=\"radio\"], button[role=\"checkbox\"], button[role=\"switch\"], input[type=\"radio\"], input[type=\"checkbox\"], :is(button, [role=\"button\"])[aria-haspopup]:not([aria-haspopup=\"false\"])')) return\n forwardingRowClick.current = true\n try {\n control.focus({ preventScroll: true })\n control.click()\n } finally {\n // Form controls can bubble their hidden input click after the render flush.\n queueMicrotask(() => { forwardingRowClick.current = false })\n }\n } : undefined}\n className={clsx(s.Field, className)}\n data-slot=\"field\"\n data-size={size}\n data-orientation={orientation}\n data-optically-align={opticallyAlign}\n data-row={row ? \"\" : undefined}\n data-fill={fill ? \"\" : undefined}\n data-label-hidden={hideLabel ? \"\" : undefined}\n >\n {row && icon ? <div className={s.Icon} aria-hidden=\"true\">{icon}</div> : null}\n <div className={s.LabelGroup}>\n {labelAction ? (\n <div className={s.LabelRow}>\n {labelElement}\n <div className={s.LabelAction}>{labelAction}</div>\n </div>\n ) : (\n labelElement\n )}\n {description && (\n <div className={s.Description} id={descriptionId}>\n {description}\n </div>\n )}\n </div>\n <div className={s.Content}>\n <div className={s.Control}>{resolvedChildren}</div>\n {errorMessage && (\n <FieldError id={errorId}>{errorMessage}</FieldError>\n )}\n </div>\n {row && action ? <div className={s.Action}>{action}</div> : null}\n </div>\n </FieldRowContext.Provider>\n )\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Field.js","sourceRoot":"","sources":["../../../../src/components/Field/Field.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAA;;AAEZ,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,YAAY,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,OAAO,CAAA;AAEnE,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAA;AAEzE,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAE1C,OAAO,CAAC,MAAM,kDAAkD,CAAA;AAEhE,0EAA0E;AAC1E,MAAM,WAAW,GAAG,wKAAwK,CAAA;AAE5L;oCACoC;AACpC,SAAS,cAAc,CAAC,OAAoB;IAC1C,MAAM,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAc,WAAW,CAAC,CAAC,CAAA;IAC5E,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,OAAO,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAA;IAC7G,OAAO,KAAK,CAAC,MAAM,KAAK,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,WAAW,YAAG,WAAW,GAAO,IAC9C,CACP,CAAC,CAAC,CAAC,CACF,YAAY,CACb,EACA,WAAW,IAAI,CACd,cAAK,SAAS,EAAE,CAAC,CAAC,WAAW,EAAE,EAAE,EAAE,aAAa,YAC7C,WAAW,GACR,CACP,IACG,EACN,eAAK,SAAS,EAAE,CAAC,CAAC,OAAO,aACvB,cAAK,SAAS,EAAE,CAAC,CAAC,OAAO,YAAG,gBAAgB,GAAO,EAClD,YAAY,IAAI,CACf,KAAC,UAAU,IAAC,EAAE,EAAE,OAAO,YAAG,YAAY,GAAc,CACrD,IACG,EACL,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,cAAK,SAAS,EAAE,CAAC,CAAC,MAAM,YAAG,MAAM,GAAO,CAAC,CAAC,CAAC,IAAI,IAC5D,GACmB,CAC5B,CAAA;AACH,CAAC","sourcesContent":["\"use client\"\n\nimport clsx from \"clsx\"\nimport { cloneElement, isValidElement, useId, useRef } from \"react\"\n\nimport { FieldRowContext, useBlankPlaceholder } from \"../../lib/fieldRow\"\nimport type { ControlSize } from \"../../types\"\nimport { FieldError } from \"../FieldError\"\n\nimport s from \"@plexui/styles/components/Field/Field.module.css\"\n\n// What a row's press can reach: a form control, a popup trigger, a choice\nconst ROW_CONTROL = 'input:not([type=\"hidden\"]):not([aria-hidden=\"true\"]), textarea, select, button, [role=\"button\"], [role=\"switch\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"combobox\"]'\n\n/** The one control inside a wrapper that took the Field's id; a control nested in another (a clear button in a\n * trigger) counts as part of it. */\nfunction soleRowControl(wrapper: HTMLElement): HTMLElement | null {\n const found = Array.from(wrapper.querySelectorAll<HTMLElement>(ROW_CONTROL))\n const outer = found.filter((element) => !found.some((other) => other !== element && other.contains(element)))\n return outer.length === 1 ? outer[0] : null\n}\n\nexport type FieldChildProps = {\n id: string\n /** The label's id. Spread onto a control that the label's `for` cannot name, such as a Select trigger. */\n \"aria-labelledby\"?: string\n \"aria-describedby\"?: string\n \"aria-invalid\"?: boolean\n opticallyAlign?: \"start\" | \"end\"\n}\n\nconst CONTROL_SIZES: ReadonlySet<unknown> = new Set([\"3xs\", \"2xs\", \"xs\", \"sm\", \"md\", \"lg\", \"xl\", \"2xl\", \"3xl\"])\n\nexport type FieldProps = {\n /**\n * Label text for the field\n */\n label: React.ReactNode\n /**\n * Helper/description text displayed below the label.\n * Automatically linked via aria-describedby.\n */\n description?: React.ReactNode\n /**\n * Hides the label from view; it still names the control for assistive technology.\n * On a `row` the value or placeholder then starts at the row's edge, as an iOS cell that\n * shows only its placeholder or value (Notes, a title, a server's address), so the row is\n * vertical unless `orientation` says otherwise. Words that explain the field go in the\n * FieldGroup's `footer`.\n * @default false\n */\n hideLabel?: boolean\n /**\n * Error message displayed below the control.\n * When provided, the child control receives aria-invalid=\"true\".\n * Uses the existing FieldError component internally.\n */\n errorMessage?: React.ReactNode\n /**\n * Content placed at the end of the label row, such as a link that acts on\n * the field (\"Forgot password?\", \"Replace\").\n */\n labelAction?: React.ReactNode\n /**\n * On a `row`, a control at the end of the row after the row's own control. On a `fill`\n * row, such as a button that adds to a list, it stays on the list's first line, and on a\n * phone it stands beside the label with the list on a line of its own. On a row whose\n * control is a radio, such as an info button after a network or a VPN, the radio's mark\n * leads in the icon column and the action alone stands at the end.\n */\n action?: React.ReactNode\n /**\n * On a `row`, a symbol or an app's picture before the label, as an iOS cell's image: the label, its\n * description and the line above the row start after it. An `img` fills the column with the corners of an\n * app icon; an icon takes the symbol size.\n */\n icon?: React.ReactNode\n /**\n * Controls the font size of the label to visually match the child control's size.\n * Matches the ControlSize scale used by Input, Select, etc.\n * @default the child control's `size`, else \"md\"\n */\n size?: ControlSize\n /**\n * Display a required indicator (asterisk) after the label.\n * This is purely visual — it does not add the `required` HTML attribute.\n * @default false\n */\n required?: boolean\n /**\n * Layout direction of label and control.\n * - \"vertical\": label stacked above control (default)\n * - \"horizontal\": label beside control\n * In the Plex Android look a vertical `row` whose control is an Input or a Textarea is a field\n * of an input card: the label stands in the empty field as its hint and floats over the value once the\n * field has the focus or a value, with a line under the field.\n * @default \"horizontal\" on a `row` with a visible label, else \"vertical\"\n */\n orientation?: \"vertical\" | \"horizontal\"\n /**\n * One line of a FieldGroup: label at the start, control at the end, an error\n * under both. Other div props reach the root only on a row, so it can carry\n * a click or data attributes.\n * Clicking a non-interactive part of the row focuses its text editor or activates its choice control or popup trigger.\n * A control at the end of the row is a pill unless its own `pill` says otherwise.\n * @default false\n */\n row?: boolean\n /**\n * On a `row`, the control takes the rest of the line after the label, for a\n * list of tags and the like.\n * @default false\n */\n fill?: boolean\n /**\n * Allows overriding the auto-generated `id`. When provided, this becomes\n * the id set on the child control and the `htmlFor` on the label. A child's\n * own `id` wins over both: it stays, and the label's `htmlFor` follows it.\n */\n id?: string\n /**\n * Applies a negative margin on the child control using its gutter to\n * optically align the control's text with surrounding content.\n * Passed through to the child control via cloneElement / render prop.\n */\n opticallyAlign?: \"start\" | \"end\"\n /**\n * CSS class applied to the root wrapper\n */\n className?: string\n /**\n * The form control(s) to render.\n * - If a single ReactElement, Field clones it with { id, aria-describedby, aria-invalid },\n * keeping an `id` the child already has.\n * A child without its own `aria-label`, `aria-labelledby` or `label` also gets\n * `aria-labelledby` pointing at the label, which names controls the label's\n * `for` cannot reach, such as the Select and DatePicker triggers.\n * - If a function (render prop), it is called with { id, \"aria-labelledby\", \"aria-describedby\", \"aria-invalid\" }.\n */\n children: React.ReactElement | ((fieldProps: FieldChildProps) => React.ReactNode)\n} & Omit<React.ComponentProps<\"div\">, \"children\" | \"id\" | \"className\">\n\nexport function Field({\n label,\n hideLabel = false,\n description,\n errorMessage,\n labelAction,\n action,\n icon,\n size: sizeProp,\n required = false,\n orientation: orientationProp,\n row = false,\n fill = false,\n opticallyAlign,\n id: idProp,\n className,\n children,\n ...rest\n}: FieldProps) {\n const orientation = orientationProp ?? (row && !hideLabel ? \"horizontal\" : \"vertical\")\n const generatedId = useId()\n const forwardingRowClick = useRef(false)\n const fieldId = idProp || `field-${generatedId}`\n const labelId = `${fieldId}-label`\n const childProps = isValidElement<{ size?: unknown; id?: string }>(children) ? children.props : undefined\n const childSize = childProps?.size\n const size = sizeProp ?? (CONTROL_SIZES.has(childSize) ? (childSize as ControlSize) : \"md\")\n // The control's id, which the label's `htmlFor` has to match\n const controlId = childProps?.id || fieldId\n const descriptionId = description ? `${fieldId}-description` : undefined\n const errorId = errorMessage ? `${fieldId}-error` : undefined\n\n // In the Plex Android look a text field under its shown label floats the label in its place while it is empty\n useBlankPlaceholder(controlId, row && orientation === \"vertical\" && !hideLabel)\n\n // Build aria-describedby from description + error IDs\n const ariaDescribedBy =\n [descriptionId, errorId].filter(Boolean).join(\" \") || undefined\n\n const invalid = !!errorMessage\n\n // Props to inject into the child control (`aria-labelledby` is added below:\n // to a render prop's props, and to a cloned child without a name of its own)\n const fieldChildProps: FieldChildProps = {\n id: controlId,\n \"aria-describedby\": ariaDescribedBy,\n \"aria-invalid\": invalid || undefined,\n ...(opticallyAlign && { opticallyAlign }),\n }\n\n // Resolve the children\n let resolvedChildren: React.ReactNode\n if (typeof children === \"function\") {\n resolvedChildren = children({ ...fieldChildProps, \"aria-labelledby\": labelId })\n } else if (isValidElement(children)) {\n const child = children as React.ReactElement<Record<string, unknown>>\n // Merge with the child's own associations instead of overwriting them\n const childDescribedBy = child.props[\"aria-describedby\"] as string | undefined\n const childNamed =\n child.props[\"aria-label\"] != null || child.props[\"aria-labelledby\"] != null || child.props.label != null\n resolvedChildren = cloneElement(child, {\n ...fieldChildProps,\n \"aria-describedby\":\n [childDescribedBy, ariaDescribedBy].filter(Boolean).join(\" \") || undefined,\n \"aria-invalid\": child.props[\"aria-invalid\"] ?? fieldChildProps[\"aria-invalid\"],\n ...(!childNamed && { \"aria-labelledby\": labelId }),\n })\n } else {\n resolvedChildren = children\n }\n\n const labelElement = (\n <label className={s.Label} id={labelId} htmlFor={controlId}>\n {label}\n {required && (\n <span className={s.RequiredIndicator} aria-hidden=\"true\">\n *\n </span>\n )}\n </label>\n )\n\n return (\n <FieldRowContext.Provider value={row && orientation === \"horizontal\"}>\n <div\n {...(row ? rest : undefined)}\n onClick={row ? (event) => {\n if (forwardingRowClick.current) return\n rest.onClick?.(event)\n if (event.defaultPrevented) return\n const target = event.target\n const root = event.currentTarget\n // The linked control remains the keyboard stop and owns its state.\n // Nested actions keep their own click, including a Select's clear button.\n if (!(target instanceof Element) || target.closest(\"[data-row]\") !== root ||\n target.closest('button, a, input, select, textarea, [role=\"button\"], [role=\"link\"], [contenteditable]:not([contenteditable=\"false\"])')) return\n const linkedControl = root.ownerDocument.getElementById(controlId)\n if (!linkedControl || linkedControl.closest(\"[data-row]\") !== root) return\n // Select's id belongs to its hidden form proxy inside the trigger.\n // Never search sibling popups, such as an InputGroup's unit action.\n const direct = linkedControl.matches('input[aria-hidden=\"true\"]')\n ? linkedControl.closest<HTMLElement>(':is(button, [role=\"button\"])[aria-haspopup]:not([aria-haspopup=\"false\"])') ?? linkedControl\n : linkedControl\n // A product's own wrapper may take the id (a row component around a Select): the row then reaches the one\n // control inside it, as an iOS cell does; with two controls, or none, the press stays on the row.\n const control = direct === linkedControl && !linkedControl.matches(ROW_CONTROL) ? soleRowControl(linkedControl) : direct\n // A control of a row nested in the wrapper belongs to that row\n if (!control || control.closest(\"[data-row]\") !== root) return\n if (control.matches(':disabled, [disabled], [data-disabled], [aria-disabled=\"true\"], [data-loading], [aria-busy=\"true\"]')) return\n const label = target.closest(\"label\")\n // Native labels already click their linked form control. A directly\n // linked span trigger, such as DatePicker's, needs forwarding instead.\n if (label && (label.htmlFor !== linkedControl.id || label.control === linkedControl)) return\n // The row is the hit area for its plain editor. Focus only: a synthetic\n // click would also run input actions or disturb native text selection.\n if (control.matches('textarea, input:not([type]), input[type=\"text\"], input[type=\"email\"], input[type=\"password\"], input[type=\"search\"], input[type=\"tel\"], input[type=\"url\"], input[type=\"number\"]') &&\n !control.matches('[hidden], [aria-hidden=\"true\"]')) {\n control.focus({ preventScroll: true })\n return\n }\n if (!control.matches('button[role=\"radio\"], button[role=\"checkbox\"], button[role=\"switch\"], input[type=\"radio\"], input[type=\"checkbox\"], :is(button, [role=\"button\"])[aria-haspopup]:not([aria-haspopup=\"false\"])')) return\n forwardingRowClick.current = true\n try {\n control.focus({ preventScroll: true })\n control.click()\n } finally {\n // Form controls can bubble their hidden input click after the render flush.\n queueMicrotask(() => { forwardingRowClick.current = false })\n }\n } : undefined}\n className={clsx(s.Field, className)}\n data-slot=\"field\"\n data-size={size}\n data-orientation={orientation}\n data-optically-align={opticallyAlign}\n data-row={row ? \"\" : undefined}\n data-fill={fill ? \"\" : undefined}\n data-label-hidden={hideLabel ? \"\" : undefined}\n >\n {row && icon ? <div className={s.Icon} aria-hidden=\"true\">{icon}</div> : null}\n <div className={s.LabelGroup}>\n {labelAction ? (\n <div className={s.LabelRow}>\n {labelElement}\n <div className={s.LabelAction}>{labelAction}</div>\n </div>\n ) : (\n labelElement\n )}\n {description && (\n <div className={s.Description} id={descriptionId}>\n {description}\n </div>\n )}\n </div>\n <div className={s.Content}>\n <div className={s.Control}>{resolvedChildren}</div>\n {errorMessage && (\n <FieldError id={errorId}>{errorMessage}</FieldError>\n )}\n </div>\n {row && action ? <div className={s.Action}>{action}</div> : null}\n </div>\n </FieldRowContext.Provider>\n )\n}\n"]}
|
|
@@ -35,10 +35,15 @@ export function Markdown({ children, directives, includeMath = false, breakNewLi
|
|
|
35
35
|
acc[directive.directiveName] = directive.render;
|
|
36
36
|
return acc;
|
|
37
37
|
}, baseComponents) ?? baseComponents;
|
|
38
|
+
// The directives this Markdown renders as elements: its own and the components' tags
|
|
39
|
+
const directiveNames = [
|
|
40
|
+
...(directives?.map((directive) => directive.directiveName) ?? []),
|
|
41
|
+
...Object.keys(propsComponents ?? {}),
|
|
42
|
+
].join("\n");
|
|
38
43
|
const mergedRemarkPlugins = useMemo(() => {
|
|
39
44
|
const baseRemarkPlugins = [
|
|
40
45
|
remarkDirective,
|
|
41
|
-
reactMarkdownRemarkDirective,
|
|
46
|
+
[reactMarkdownRemarkDirective, { names: directiveNames.split("\n") }],
|
|
42
47
|
...mathPlugins.remarkPlugins,
|
|
43
48
|
];
|
|
44
49
|
if (breakNewLines) {
|
|
@@ -52,7 +57,7 @@ export function Markdown({ children, directives, includeMath = false, breakNewLi
|
|
|
52
57
|
baseRemarkPlugins.push([remarkGfm, { singleTilde: false }]);
|
|
53
58
|
}
|
|
54
59
|
return [...baseRemarkPlugins, ...(remarkPlugins ?? [])];
|
|
55
|
-
}, [mathPlugins.remarkPlugins, remarkPlugins, breakNewLines]);
|
|
60
|
+
}, [mathPlugins.remarkPlugins, remarkPlugins, breakNewLines, directiveNames]);
|
|
56
61
|
return (_jsx(ReactMarkdown, { className: clsx(s.MarkdownContent, className), remarkPlugins: mergedRemarkPlugins, rehypePlugins: [...(rehypePlugins ?? []), ...mathPlugins.rehypePlugins], components: components, allowedElements: allowedElements, disallowedElements: disallowedElements, skipHtml: skipHtml, urlTransform: urlTransform, children: children }));
|
|
57
62
|
}
|
|
58
63
|
const Pre = ({ children, className }) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Markdown.js","sourceRoot":"","sources":["../../../../src/components/Markdown/Markdown.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAA;;AAEZ,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAgD,MAAM,OAAO,CAAA;AACvF,OAAO,aAAa,MAAM,gBAAgB,CAAA;AAC1C,OAAO,YAAY,MAAM,eAAe,CAAA;AACxC,OAAO,eAAe,MAAM,kBAAkB,CAAA;AAC9C,OAAO,SAAS,MAAM,YAAY,CAAA;AAElC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAA;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAC/C,OAAO,EAAE,4BAA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AQ,YAAG,IAAI,GAAsB,GACrD,CACjB,CAAA;AACH,CAAC,CAAA;AAED,MAAM,kCAAkC,GAAsC;IAC5E,GAAG,EAAE,oBAAoB;CACjB,CAAA;AAEV,MAAM,cAAc,GAAsB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,EAAE,EAAE;IACpE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAA;IACxD,OAAO,CACL,KAAC,oBAAoB,IAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,YAC3D,IAAI,GACgB,CACxB,CAAA;AACH,CAAC,CAAA;AAED,MAAM,iCAAiC,GAAsC;IAC3E,GAAG,EAAE,cAAc;CACX,CAAA","sourcesContent":["\"use client\"\n\nimport clsx from \"clsx\"\nimport { Children, useMemo, type ComponentProps, type FC, type ReactNode } from \"react\"\nimport ReactMarkdown from \"react-markdown\"\nimport remarkBreaks from \"remark-breaks\"\nimport remarkDirective from \"remark-directive\"\nimport remarkGfm from \"remark-gfm\"\n\nimport { CodeBlock, CodeBlockBase } from \"../CodeBlock/CodeBlock\"\nimport { CollapsibleCodeBlock } from \"../CodeBlock/CollapsibleCodeBlock\"\nimport { TextLink } from \"../TextLink/TextLink\"\nimport { reactMarkdownRemarkDirective, type MarkdownDirective } from \"./directives\"\nimport s from \"@plexui/styles/components/Markdown/Markdown.module.css\"\nimport { defaultUrlTransform } from \"./urlTransform\"\nimport { useMathPlugins } from \"./useMathPlugins\"\nimport { useParseMarkdownPre } from \"./useParseMarkdownPre\"\n\nconst supportsLookbehind = (() => {\n try {\n new RegExp(\"(?<=a)b\")\n return true\n } catch {\n return false\n }\n})()\n\nexport type MarkdownComponent = FC<{\n children?: ReactNode\n className?: string\n node: Record<string, unknown>\n}>\n\nexport type MarkdownProps = {\n children: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n directives?: MarkdownDirective<any>[]\n /** Determines if remark-math plugins should be loaded for rendering LaTeX */\n includeMath?: boolean\n /** Determines whether single newlines should insert <br> tags */\n breakNewLines?: boolean\n components?: Record<string, MarkdownComponent>\n remarkPlugins?: ComponentProps<typeof ReactMarkdown>[\"remarkPlugins\"]\n rehypePlugins?: ComponentProps<typeof ReactMarkdown>[\"rehypePlugins\"]\n allowedElements?: ComponentProps<typeof ReactMarkdown>[\"allowedElements\"]\n disallowedElements?: ComponentProps<typeof ReactMarkdown>[\"disallowedElements\"]\n urlTransform?: ComponentProps<typeof ReactMarkdown>[\"urlTransform\"]\n skipHtml?: boolean\n className?: string\n copyableCodeBlocks?: boolean\n /** Determines if code blocks should use the collapsible view with \"View Code\" button */\n collapsibleCodeBlocks?: boolean\n}\n\nexport function Markdown({\n children,\n directives,\n includeMath = false,\n breakNewLines = false,\n components: propsComponents,\n remarkPlugins,\n rehypePlugins,\n allowedElements,\n disallowedElements,\n skipHtml,\n urlTransform = defaultUrlTransform,\n className,\n copyableCodeBlocks = true,\n collapsibleCodeBlocks = true,\n}: MarkdownProps) {\n const mathPlugins = useMathPlugins(includeMath)\n const baseComponents = {\n ...COMMON_COMPONENTS,\n ...(collapsibleCodeBlocks ? COLLAPSIBLE_CODE_BLOCK_COMPONENTS : null),\n ...(copyableCodeBlocks ? null : NON_COPYABLE_CODE_BLOCK_COMPONENTS),\n ...propsComponents,\n }\n const components =\n directives?.reduce((acc, directive) => {\n acc[directive.directiveName] = directive.render\n return acc\n }, baseComponents) ?? baseComponents\n\n const mergedRemarkPlugins = useMemo(() => {\n const baseRemarkPlugins = [\n remarkDirective,\n reactMarkdownRemarkDirective,\n ...mathPlugins.remarkPlugins,\n ]\n\n if (breakNewLines) {\n baseRemarkPlugins.push(remarkBreaks)\n }\n\n // remark-gfm requires lookbehind support, which will throw in <= Safari 16.4\n // with no easily available polyfill.\n if (supportsLookbehind) {\n // Do not treat single tilde as strikethrough to allow for more\n // conversational use cases such as \"~$20-$30\"\n baseRemarkPlugins.push([remarkGfm, { singleTilde: false }])\n }\n\n return [...baseRemarkPlugins, ...(remarkPlugins ?? [])]\n }, [mathPlugins.remarkPlugins, remarkPlugins, breakNewLines])\n\n return (\n <ReactMarkdown\n className={clsx(s.MarkdownContent, className)}\n remarkPlugins={mergedRemarkPlugins}\n rehypePlugins={[...(rehypePlugins ?? []), ...mathPlugins.rehypePlugins]}\n components={components}\n allowedElements={allowedElements}\n disallowedElements={disallowedElements}\n skipHtml={skipHtml}\n urlTransform={urlTransform}\n >\n {children}\n </ReactMarkdown>\n )\n}\n\nconst Pre: MarkdownComponent = ({ children, className }) => {\n const { code, language } = useParseMarkdownPre(children)\n return (\n <CodeBlock language={language} className={className}>\n {code}\n </CodeBlock>\n )\n}\n\nconst InlineCode: MarkdownComponent = ({ children, className }) => (\n <code className={clsx(s.InlineCode, className)}>{children}</code>\n)\n\nconst Anchor: MarkdownComponent = ({ children, node: _node, ...props }) => (\n <TextLink as=\"a\" {...props}>\n {children}\n </TextLink>\n)\n\n// Sourced from common markdown implementations\nconst TableCell: MarkdownComponent = ({ node: _node, children, ...rest }) => {\n return (\n <td {...rest}>\n {Children.map(children, (child, i) =>\n // ReactMarkdown does not support <br> tags in tables without using\n // remark-html (which may not be safe), so we need to manually handle them\n child === \"<br>\" ? <br key={i} /> : child,\n )}\n </td>\n )\n}\n\nconst COMMON_COMPONENTS: Record<string, MarkdownComponent> = {\n code: InlineCode,\n pre: Pre,\n a: Anchor,\n td: TableCell,\n}\n\nconst NonCopyableCodeBlock: MarkdownComponent = ({ children, className }) => {\n const { code, language } = useParseMarkdownPre(children)\n return (\n <CodeBlockBase className={className}>\n <CodeBlockBase.Code language={language}>{code}</CodeBlockBase.Code>\n </CodeBlockBase>\n )\n}\n\nconst NON_COPYABLE_CODE_BLOCK_COMPONENTS: Record<string, MarkdownComponent> = {\n pre: NonCopyableCodeBlock,\n} as const\n\nconst CollapsiblePre: MarkdownComponent = ({ children, className }) => {\n const { code, language } = useParseMarkdownPre(children)\n return (\n <CollapsibleCodeBlock language={language} className={className}>\n {code}\n </CollapsibleCodeBlock>\n )\n}\n\nconst COLLAPSIBLE_CODE_BLOCK_COMPONENTS: Record<string, MarkdownComponent> = {\n pre: CollapsiblePre,\n} as const\n"]}
|
|
1
|
+
{"version":3,"file":"Markdown.js","sourceRoot":"","sources":["../../../../src/components/Markdown/Markdown.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAA;;AAEZ,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAgD,MAAM,OAAO,CAAA;AACvF,OAAO,aAAa,MAAM,gBAAgB,CAAA;AAC1C,OAAO,YAAY,MAAM,eAAe,CAAA;AACxC,OAAO,eAAe,MAAM,kBAAkB,CAAA;AAC9C,OAAO,SAAS,MAAM,YAAY,CAAA;AAElC,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAA;AACxE,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAA;AAC/C,OAAO,EAAE,4BAA4B,EAA0B,MAAM,cAAc,CAAA;AACnF,OAAO,CAAC,MAAM,wDAAwD,CAAA;AACtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAE3D,MAAM,kBAAkB,GAAG,CAAC,GAAG,EAAE;IAC/B,IAAI,CAAC;QACH,IAAI,MAAM,CAAC,SAAS,CAAC,CAAA;QACrB,OAAO,IAAI,CAAA;IACb,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAA;IACd,CAAC;AACH,CAAC,CAAC,EAAE,CAAA;AA6BJ,MAAM,UAAU,QAAQ,CAAC,EACvB,QAAQ,EACR,UAAU,EACV,WAAW,GAAG,KAAK,EACnB,aAAa,GAAG,KAAK,EACrB,UAAU,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E,IAAI,EAAE,QAAQ,EAAE,GAAG,mBAAmB,CAAC,QAAQ,CAAC,CAAA;IACxD,OAAO,CACL,KAAC,oBAAoB,IAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,YAC3D,IAAI,GACgB,CACxB,CAAA;AACH,CAAC,CAAA;AAED,MAAM,iCAAiC,GAAsC;IAC3E,GAAG,EAAE,cAAc;CACX,CAAA","sourcesContent":["\"use client\"\n\nimport clsx from \"clsx\"\nimport { Children, useMemo, type ComponentProps, type FC, type ReactNode } from \"react\"\nimport ReactMarkdown from \"react-markdown\"\nimport remarkBreaks from \"remark-breaks\"\nimport remarkDirective from \"remark-directive\"\nimport remarkGfm from \"remark-gfm\"\n\nimport { CodeBlock, CodeBlockBase } from \"../CodeBlock/CodeBlock\"\nimport { CollapsibleCodeBlock } from \"../CodeBlock/CollapsibleCodeBlock\"\nimport { TextLink } from \"../TextLink/TextLink\"\nimport { reactMarkdownRemarkDirective, type MarkdownDirective } from \"./directives\"\nimport s from \"@plexui/styles/components/Markdown/Markdown.module.css\"\nimport { defaultUrlTransform } from \"./urlTransform\"\nimport { useMathPlugins } from \"./useMathPlugins\"\nimport { useParseMarkdownPre } from \"./useParseMarkdownPre\"\n\nconst supportsLookbehind = (() => {\n try {\n new RegExp(\"(?<=a)b\")\n return true\n } catch {\n return false\n }\n})()\n\nexport type MarkdownComponent = FC<{\n children?: ReactNode\n className?: string\n node: Record<string, unknown>\n}>\n\nexport type MarkdownProps = {\n children: string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n directives?: MarkdownDirective<any>[]\n /** Determines if remark-math plugins should be loaded for rendering LaTeX */\n includeMath?: boolean\n /** Determines whether single newlines should insert <br> tags */\n breakNewLines?: boolean\n components?: Record<string, MarkdownComponent>\n remarkPlugins?: ComponentProps<typeof ReactMarkdown>[\"remarkPlugins\"]\n rehypePlugins?: ComponentProps<typeof ReactMarkdown>[\"rehypePlugins\"]\n allowedElements?: ComponentProps<typeof ReactMarkdown>[\"allowedElements\"]\n disallowedElements?: ComponentProps<typeof ReactMarkdown>[\"disallowedElements\"]\n urlTransform?: ComponentProps<typeof ReactMarkdown>[\"urlTransform\"]\n skipHtml?: boolean\n className?: string\n copyableCodeBlocks?: boolean\n /** Determines if code blocks should use the collapsible view with \"View Code\" button */\n collapsibleCodeBlocks?: boolean\n}\n\nexport function Markdown({\n children,\n directives,\n includeMath = false,\n breakNewLines = false,\n components: propsComponents,\n remarkPlugins,\n rehypePlugins,\n allowedElements,\n disallowedElements,\n skipHtml,\n urlTransform = defaultUrlTransform,\n className,\n copyableCodeBlocks = true,\n collapsibleCodeBlocks = true,\n}: MarkdownProps) {\n const mathPlugins = useMathPlugins(includeMath)\n const baseComponents = {\n ...COMMON_COMPONENTS,\n ...(collapsibleCodeBlocks ? COLLAPSIBLE_CODE_BLOCK_COMPONENTS : null),\n ...(copyableCodeBlocks ? null : NON_COPYABLE_CODE_BLOCK_COMPONENTS),\n ...propsComponents,\n }\n const components =\n directives?.reduce((acc, directive) => {\n acc[directive.directiveName] = directive.render\n return acc\n }, baseComponents) ?? baseComponents\n\n // The directives this Markdown renders as elements: its own and the components' tags\n const directiveNames = [\n ...(directives?.map((directive) => directive.directiveName) ?? []),\n ...Object.keys(propsComponents ?? {}),\n ].join(\"\\n\")\n\n const mergedRemarkPlugins = useMemo(() => {\n const baseRemarkPlugins: NonNullable<MarkdownProps[\"remarkPlugins\"]> = [\n remarkDirective,\n [reactMarkdownRemarkDirective, { names: directiveNames.split(\"\\n\") }],\n ...mathPlugins.remarkPlugins,\n ]\n\n if (breakNewLines) {\n baseRemarkPlugins.push(remarkBreaks)\n }\n\n // remark-gfm requires lookbehind support, which will throw in <= Safari 16.4\n // with no easily available polyfill.\n if (supportsLookbehind) {\n // Do not treat single tilde as strikethrough to allow for more\n // conversational use cases such as \"~$20-$30\"\n baseRemarkPlugins.push([remarkGfm, { singleTilde: false }])\n }\n\n return [...baseRemarkPlugins, ...(remarkPlugins ?? [])]\n }, [mathPlugins.remarkPlugins, remarkPlugins, breakNewLines, directiveNames])\n\n return (\n <ReactMarkdown\n className={clsx(s.MarkdownContent, className)}\n remarkPlugins={mergedRemarkPlugins}\n rehypePlugins={[...(rehypePlugins ?? []), ...mathPlugins.rehypePlugins]}\n components={components}\n allowedElements={allowedElements}\n disallowedElements={disallowedElements}\n skipHtml={skipHtml}\n urlTransform={urlTransform}\n >\n {children}\n </ReactMarkdown>\n )\n}\n\nconst Pre: MarkdownComponent = ({ children, className }) => {\n const { code, language } = useParseMarkdownPre(children)\n return (\n <CodeBlock language={language} className={className}>\n {code}\n </CodeBlock>\n )\n}\n\nconst InlineCode: MarkdownComponent = ({ children, className }) => (\n <code className={clsx(s.InlineCode, className)}>{children}</code>\n)\n\nconst Anchor: MarkdownComponent = ({ children, node: _node, ...props }) => (\n <TextLink as=\"a\" {...props}>\n {children}\n </TextLink>\n)\n\n// Sourced from common markdown implementations\nconst TableCell: MarkdownComponent = ({ node: _node, children, ...rest }) => {\n return (\n <td {...rest}>\n {Children.map(children, (child, i) =>\n // ReactMarkdown does not support <br> tags in tables without using\n // remark-html (which may not be safe), so we need to manually handle them\n child === \"<br>\" ? <br key={i} /> : child,\n )}\n </td>\n )\n}\n\nconst COMMON_COMPONENTS: Record<string, MarkdownComponent> = {\n code: InlineCode,\n pre: Pre,\n a: Anchor,\n td: TableCell,\n}\n\nconst NonCopyableCodeBlock: MarkdownComponent = ({ children, className }) => {\n const { code, language } = useParseMarkdownPre(children)\n return (\n <CodeBlockBase className={className}>\n <CodeBlockBase.Code language={language}>{code}</CodeBlockBase.Code>\n </CodeBlockBase>\n )\n}\n\nconst NON_COPYABLE_CODE_BLOCK_COMPONENTS: Record<string, MarkdownComponent> = {\n pre: NonCopyableCodeBlock,\n} as const\n\nconst CollapsiblePre: MarkdownComponent = ({ children, className }) => {\n const { code, language } = useParseMarkdownPre(children)\n return (\n <CollapsibleCodeBlock language={language} className={className}>\n {code}\n </CollapsibleCodeBlock>\n )\n}\n\nconst COLLAPSIBLE_CODE_BLOCK_COMPONENTS: Record<string, MarkdownComponent> = {\n pre: CollapsiblePre,\n} as const\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {} from "react";
|
|
2
|
-
import { visit } from "unist-util-visit";
|
|
2
|
+
import { SKIP, visit } from "unist-util-visit";
|
|
3
3
|
import { createId } from "../../lib/ids.js";
|
|
4
4
|
import { decodeBase64, encodeBase64 } from "../../lib/safeBase64.js";
|
|
5
5
|
export function createMarkdownDirective({ render, name, mode, }) {
|
|
@@ -18,16 +18,58 @@ export function createMarkdownDirective({ render, name, mode, }) {
|
|
|
18
18
|
};
|
|
19
19
|
return directive;
|
|
20
20
|
}
|
|
21
|
-
|
|
21
|
+
/**
|
|
22
|
+
* A directive's attribute reaches its element only as a plain HTML attribute: a lowercase name (`title`, `data-*`,
|
|
23
|
+
* `aria-*`), so never a DOM property such as `innerHTML` or React's `dangerouslySetInnerHTML`; never an event handler,
|
|
24
|
+
* an inline style, a frame's document or `is`.
|
|
25
|
+
*/
|
|
26
|
+
const ATTRIBUTE_NAME = /^[a-z][a-z0-9-]*$/;
|
|
27
|
+
const UNSAFE_ATTRIBUTE = /^(?:on|style$|srcdoc$|formaction$|is$)/;
|
|
28
|
+
/** The attributes that load or open a URL: one with a protocol other than Markdown's safe ones is dropped. */
|
|
29
|
+
const URL_ATTRIBUTES = new Set(["href", "src", "action", "cite", "poster", "background", "ping", "data", "codebase"]);
|
|
30
|
+
const SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp|tel|sms)$/i;
|
|
31
|
+
/** react-markdown's `defaultUrlTransform` test, with `tel:` and `sms:` as the Markdown's own transform. */
|
|
32
|
+
const isSafeUrl = (value) => {
|
|
33
|
+
const colon = value.indexOf(":");
|
|
34
|
+
const firstOf = (char) => value.indexOf(char);
|
|
35
|
+
return (colon === -1 ||
|
|
36
|
+
[firstOf("/"), firstOf("?"), firstOf("#")].some((index) => index !== -1 && colon > index) ||
|
|
37
|
+
SAFE_PROTOCOL.test(value.slice(0, colon).trim()));
|
|
38
|
+
};
|
|
39
|
+
const safeAttributes = (attributes) => Object.fromEntries(Object.entries(attributes ?? {}).filter(([key, value]) => ATTRIBUTE_NAME.test(key) &&
|
|
40
|
+
!UNSAFE_ATTRIBUTE.test(key) &&
|
|
41
|
+
!(URL_ATTRIBUTES.has(key) && !isSafeUrl(String(value ?? "")))));
|
|
42
|
+
/**
|
|
43
|
+
* Directives become elements only when the Markdown knows them: a `directives` entry or a `components` key, with
|
|
44
|
+
* their attributes minus event handlers, `style` and `srcdoc`. Any other directive stays what was written: an inline
|
|
45
|
+
* or leaf one its source text, a container one its content in a plain `div`. Text from elsewhere (a server, a user)
|
|
46
|
+
* can't make an element of its choosing with attributes of its choosing.
|
|
47
|
+
*/
|
|
48
|
+
export function reactMarkdownRemarkDirective(options = {}) {
|
|
49
|
+
const names = new Set(options.names ?? []);
|
|
22
50
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
23
|
-
return (tree) => {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
...node.data
|
|
29
|
-
|
|
30
|
-
|
|
51
|
+
return (tree, file) => {
|
|
52
|
+
const source = file?.value == null ? "" : String(file.value);
|
|
53
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
54
|
+
visit(tree, ["textDirective", "leafDirective", "containerDirective"], (node, index, parent) => {
|
|
55
|
+
if (names.has(node.name)) {
|
|
56
|
+
node.data = { hName: node.name, hProperties: safeAttributes(node.attributes), ...node.data };
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (node.type === "containerDirective") {
|
|
60
|
+
node.data = { hName: "div", hProperties: {}, ...node.data };
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
if (!parent || typeof index !== "number")
|
|
64
|
+
return;
|
|
65
|
+
const start = node.position?.start?.offset;
|
|
66
|
+
const end = node.position?.end?.offset;
|
|
67
|
+
const value = typeof start === "number" && typeof end === "number" && end <= source.length
|
|
68
|
+
? source.slice(start, end)
|
|
69
|
+
: `${node.type === "leafDirective" ? "::" : ":"}${node.name}`;
|
|
70
|
+
const text = { type: "text", value };
|
|
71
|
+
parent.children[index] = node.type === "leafDirective" ? { type: "paragraph", children: [text] } : text;
|
|
72
|
+
return SKIP;
|
|
31
73
|
});
|
|
32
74
|
};
|
|
33
75
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"directives.js","sourceRoot":"","sources":["../../../../src/components/Markdown/directives.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,MAAM,OAAO,CAAA;AACtC,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;
|
|
1
|
+
{"version":3,"file":"directives.js","sourceRoot":"","sources":["../../../../src/components/Markdown/directives.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,MAAM,OAAO,CAAA;AACtC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAA;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AACxC,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAA;AAUjE,MAAM,UAAU,uBAAuB,CAAgC,EACrE,MAAM,EACN,IAAI,EACJ,IAAI,GAKL;IACC,MAAM,MAAM,GAAG,kBAAkB,IAAI,EAAE,CAAA;IACvC,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAA;IAEtD,SAAS,SAAS,CAAC,KAAQ;QACzB,MAAM,EAAE,QAAQ,EAAE,GAAG,UAAU,EAAE,GAAG,KAAK,CAAA;QACzC,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAA;QAC9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C,CAAC,IAAI,CAAA;YACvG,OAAO,IAAI,CAAA;QACb,CAAC,CAAC,CAAA;IACJ,CAAC,CAAA;AACH,CAAC","sourcesContent":["import { type ReactNode } from \"react\"\nimport { SKIP, visit } from \"unist-util-visit\"\nimport { createId } from \"../../lib/ids\"\nimport { decodeBase64, encodeBase64 } from \"../../lib/safeBase64\"\n\ntype ValidDirectiveProps = { children?: string } & Partial<Record<string, unknown>>\n\nexport interface MarkdownDirective<T extends ValidDirectiveProps = ValidDirectiveProps> {\n directiveName: string\n render: (props: { attrs?: string; children?: ReactNode }) => ReactNode\n (props: T): string\n}\n\nexport function createMarkdownDirective<T extends ValidDirectiveProps>({\n render,\n name,\n mode,\n}: {\n render: (props: T) => ReactNode\n name: string\n mode: \"inline\" | \"block\"\n}): MarkdownDirective<T> {\n const prefix = `OaiMdDirective_${name}`\n const uniqueName = createId(prefix, prefix.length + 6)\n\n function directive(props: T) {\n const { children, ...attributes } = props\n const attrs = Object.keys(attributes).length >= 0 ? `attrs=\"${encodeBase64(attributes)}\"` : \"\"\n const leader = mode === \"inline\" ? \" :\" : \"\\n\\n:::\"\n\n return `${leader}${uniqueName}${children ? `[${children}]` : \"\"}{${attrs}}`\n }\n\n directive.directiveName = uniqueName\n directive.render = ({ children, attrs }: { children?: ReactNode; attrs?: string }) => {\n const parsedAttrs = attrs ? decodeBase64<T>(attrs) : ({} as T)\n return render({ ...parsedAttrs, children })\n }\n\n return directive\n}\n\n/**\n * A directive's attribute reaches its element only as a plain HTML attribute: a lowercase name (`title`, `data-*`,\n * `aria-*`), so never a DOM property such as `innerHTML` or React's `dangerouslySetInnerHTML`; never an event handler,\n * an inline style, a frame's document or `is`.\n */\nconst ATTRIBUTE_NAME = /^[a-z][a-z0-9-]*$/\nconst UNSAFE_ATTRIBUTE = /^(?:on|style$|srcdoc$|formaction$|is$)/\n\n/** The attributes that load or open a URL: one with a protocol other than Markdown's safe ones is dropped. */\nconst URL_ATTRIBUTES = new Set([\"href\", \"src\", \"action\", \"cite\", \"poster\", \"background\", \"ping\", \"data\", \"codebase\"])\nconst SAFE_PROTOCOL = /^(?:https?|ircs?|mailto|xmpp|tel|sms)$/i\n\n/** react-markdown's `defaultUrlTransform` test, with `tel:` and `sms:` as the Markdown's own transform. */\nconst isSafeUrl = (value: string) => {\n const colon = value.indexOf(\":\")\n const firstOf = (char: string) => value.indexOf(char)\n return (\n colon === -1 ||\n [firstOf(\"/\"), firstOf(\"?\"), firstOf(\"#\")].some((index) => index !== -1 && colon > index) ||\n SAFE_PROTOCOL.test(value.slice(0, colon).trim())\n )\n}\n\nconst safeAttributes = (attributes: Record<string, unknown> | null | undefined) =>\n Object.fromEntries(\n Object.entries(attributes ?? {}).filter(\n ([key, value]) =>\n ATTRIBUTE_NAME.test(key) &&\n !UNSAFE_ATTRIBUTE.test(key) &&\n !(URL_ATTRIBUTES.has(key) && !isSafeUrl(String(value ?? \"\"))),\n ),\n )\n\n/**\n * Directives become elements only when the Markdown knows them: a `directives` entry or a `components` key, with\n * their attributes minus event handlers, `style` and `srcdoc`. Any other directive stays what was written: an inline\n * or leaf one its source text, a container one its content in a plain `div`. Text from elsewhere (a server, a user)\n * can't make an element of its choosing with attributes of its choosing.\n */\nexport function reactMarkdownRemarkDirective(options: { names?: Iterable<string> } = {}) {\n const names = new Set(options.names ?? [])\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return (tree: any, file?: { value?: unknown }) => {\n const source = file?.value == null ? \"\" : String(file.value)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n visit(tree, [\"textDirective\", \"leafDirective\", \"containerDirective\"], (node: any, index, parent: any) => {\n if (names.has(node.name)) {\n node.data = { hName: node.name, hProperties: safeAttributes(node.attributes), ...node.data }\n return\n }\n if (node.type === \"containerDirective\") {\n node.data = { hName: \"div\", hProperties: {}, ...node.data }\n return\n }\n if (!parent || typeof index !== \"number\") return\n const start = node.position?.start?.offset\n const end = node.position?.end?.offset\n const value =\n typeof start === \"number\" && typeof end === \"number\" && end <= source.length\n ? source.slice(start, end)\n : `${node.type === \"leafDirective\" ? \"::\" : \":\"}${node.name}`\n const text = { type: \"text\", value }\n parent.children[index] = node.type === \"leafDirective\" ? { type: \"paragraph\", children: [text] } : text\n return SKIP\n })\n }\n}\n"]}
|
|
@@ -18,6 +18,7 @@ import { PhoneLayoutContext } from "../PhoneLayout/PhoneLayout.js";
|
|
|
18
18
|
import { useLinkComponent } from "../PlexUIProvider/internal.js";
|
|
19
19
|
import { TransitionGroup } from "../Transition/index.js";
|
|
20
20
|
import { createExitGuard, overlayTiming, overlayTimingQuick, reducedMotionEnter } from "../Transition/shared.js";
|
|
21
|
+
import { growsFromButton, MENU_SPRING_MS, sourceScale } from "../../lib/presentMotion.js";
|
|
21
22
|
import { isHoverPointer } from "../../lib/inputMode.js";
|
|
22
23
|
import s from "@plexui/styles/components/Menu/Menu.module.css";
|
|
23
24
|
import { HOLD_PRESSES_CLASS, holdEnteringPresses } from "../../lib/holdEnteringPresses.js";
|
|
@@ -248,6 +249,26 @@ const Content = ({ children, side, sideOffset, align, alignOffset, width, minWid
|
|
|
248
249
|
return;
|
|
249
250
|
return markCoveredMenuTrigger(triggerElement, contentElement);
|
|
250
251
|
}, [cover, triggerElement, contentElement]);
|
|
252
|
+
// A menu that covers its button grows out of it and shrinks back into it, as an iOS 27.2 menu does, on SwiftUI's
|
|
253
|
+
// spring(duration: 0.21, bounce: 0.2), --spring-menu. Its timers wait for the spring.
|
|
254
|
+
// Decided while it is open: a closing menu covers nothing, yet goes back into its button
|
|
255
|
+
const growsRef = useRef(false);
|
|
256
|
+
if (open)
|
|
257
|
+
growsRef.current = cover !== null && growsFromButton(triggerElement);
|
|
258
|
+
const grows = growsRef.current;
|
|
259
|
+
useLayoutEffect(() => {
|
|
260
|
+
if (!open || !contentElement)
|
|
261
|
+
return;
|
|
262
|
+
const scale = grows ? sourceScale(contentElement, triggerElement) : null;
|
|
263
|
+
if (scale) {
|
|
264
|
+
contentElement.style.setProperty("--menu-source-transform", scale);
|
|
265
|
+
contentElement.setAttribute("data-presented-from", "");
|
|
266
|
+
}
|
|
267
|
+
else {
|
|
268
|
+
contentElement.style.removeProperty("--menu-source-transform");
|
|
269
|
+
contentElement.removeAttribute("data-presented-from");
|
|
270
|
+
}
|
|
271
|
+
}, [open, grows, contentElement, triggerElement]);
|
|
251
272
|
const [exitGuard] = useState(createExitGuard);
|
|
252
273
|
const isHorizontal = layout === "horizontal";
|
|
253
274
|
// The content of a closing menu is frozen for its exit, so this reads the owner's latest handler.
|
|
@@ -289,7 +310,7 @@ const Content = ({ children, side, sideOffset, align, alignOffset, width, minWid
|
|
|
289
310
|
if (!modal || isRightClick)
|
|
290
311
|
interactedOutside.current = true;
|
|
291
312
|
};
|
|
292
|
-
return (_jsx(DropdownMenu.Portal, { forceMount: true, container: phoneLayout.container, children: _jsx(PhoneScope, { enabled: phoneLayout.scoped, children: _jsx(TransitionGroup, { className: clsx(s.Menu, HOLD_PRESSES_CLASS), ...overlayTiming, reducedMotionEnterDuration: reducedMotionEnter.menu, ...exitGuard.transition, overlay: true, children: open && (_jsx(RootMenuContent, { ref: setContent, onOpenAutoFocus: (event) => {
|
|
313
|
+
return (_jsx(DropdownMenu.Portal, { forceMount: true, container: phoneLayout.container, children: _jsx(PhoneScope, { enabled: phoneLayout.scoped, children: _jsx(TransitionGroup, { className: clsx(s.Menu, HOLD_PRESSES_CLASS), ...(grows ? { enterDuration: MENU_SPRING_MS, exitDuration: MENU_SPRING_MS } : overlayTiming), reducedMotionEnterDuration: reducedMotionEnter.menu, ...exitGuard.transition, overlay: true, children: open && (_jsx(RootMenuContent, { ref: setContent, onOpenAutoFocus: (event) => {
|
|
293
314
|
onOpenAutoFocus?.(event);
|
|
294
315
|
delegateInitialPhoneSubmenuFocus(event, contentRef.current);
|
|
295
316
|
}, forceMount: true, className: s.MenuList, "data-pill": pill ? "" : undefined, side: side ?? cover?.side, sideOffset: cover ? cover.sideOffset : sideOffset ?? 5, align: align, alignOffset: alignOffset ?? (cover || align === "center" ? 0 : -5), avoidCollisions: true, ...floatingBoundary, onEscapeKeyDown: preventDefaultHandler, onInteractOutside: handleInteractOutside, onCloseAutoFocus: handleCloseAutoFocus, "data-layout": isHorizontal ? "horizontal" : undefined, "data-size": isHorizontal && size ? size : undefined, style: toCssVariables({
|