UNPKG

@wordpress/block-library

Version:
504 lines (503 loc) • 18.6 kB
import clsx from "clsx"; import { useCallback, useEffect, useMemo, useState } from "@wordpress/element"; import { BlockControls, BlockIcon, InspectorControls, MediaPlaceholder, MediaReplaceFlow, __experimentalColorGradientSettingsDropdown, __experimentalUseMultipleOriginColorsAndGradients, store, useBlockProps, useInnerBlocksProps } from "@wordpress/block-editor"; import { Disabled, ToggleControl, __experimentalToolsPanel, __experimentalToolsPanelItem } from "@wordpress/components"; import { useDispatch, useSelect } from "@wordpress/data"; import { store as store$1 } from "@wordpress/notices"; import { __, _x } from "@wordpress/i18n"; import { playlist } from "@wordpress/icons"; import { createBlock } from "@wordpress/blocks"; import { createBlobURL } from "@wordpress/blob"; import { SelectControl } from "@wordpress/ui"; import { Caption } from "../utils/caption.mjs"; import { useToolsPanelDropdownMenuProps } from "../utils/hooks.mjs"; import { WaveformPlayer } from "../utils/waveform-player.mjs"; import { PlaylistContext } from "./context.mjs"; import { getTrackAttributes } from "./utils.mjs"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; // packages/block-library/src/playlist/edit.jsx const ALLOWED_MEDIA_TYPES = ["audio"]; const EMPTY_ARRAY = []; const AUDIO_FILE_EXTENSION = /\.(aac|aif|aiff|flac|m4a|m4b|mp3|oga|ogg|opus|wav|weba)$/i; const DEFAULT_WAVEFORM_STYLE = "bars"; const FILE_LIST_OBJECT_NAME = "[object FileList]"; const ORDER_ITEMS = [{ label: __("Descending"), value: "desc" }, { label: __("Ascending"), value: "asc" }]; const WAVEFORM_STYLE_ITEMS = [ { label: _x("Bars", "waveform style option"), value: "bars" }, { label: _x("Mirror", "waveform style option"), value: "mirror" }, { label: _x("Line", "waveform style option"), value: "line" }, { label: _x("Blocks", "waveform style option"), value: "blocks" }, { label: _x("Dots", "waveform style option"), value: "dots" }, { label: _x("Seekbar", "waveform style option"), value: "seekbar" } ]; function isFile(value) { return Object.prototype.toString.call(value) === "[object File]" || typeof File !== "undefined" && value instanceof File; } function isAudioFile(file) { return file.type ? file.type.startsWith("audio/") : AUDIO_FILE_EXTENSION.test(file.name); } function getTrackIdentifier(track) { return track.id ?? track.src ?? track.blob; } const PlaylistEdit = ({ attributes, setAttributes, isSelected, insertBlocksAfter, clientId }) => { const { order, showTracklist, showNumbers, showImages, showPlayButtonArtwork, showArtists, showTrackLength, waveformStyle = DEFAULT_WAVEFORM_STYLE, waveformColor, waveformGradient, waveformBackgroundColor, waveformBackgroundGradient } = attributes; const selectedOrderItem = ORDER_ITEMS.find((item) => item.value === order) ?? ORDER_ITEMS[0]; const blockProps = useBlockProps(); const waveformPanelId = `${clientId}-waveform`; const { replaceInnerBlocks, replaceBlocks, insertBlocks, selectBlock, __unstableMarkNextChangeAsNotPersistent } = useDispatch(store); const { createErrorNotice } = useDispatch(store$1); const dropdownMenuProps = useToolsPanelDropdownMenuProps(); const colorGradientSettings = __experimentalUseMultipleOriginColorsAndGradients(); const colors = useMemo(() => colorGradientSettings.colors.flatMap((origin) => origin?.colors ?? []), [colorGradientSettings.colors]); const gradients = useMemo(() => colorGradientSettings.gradients.flatMap((origin) => origin?.gradients ?? []), [colorGradientSettings.gradients]); const hasColors = colors.length > 0 || !colorGradientSettings.disableCustomColors; const hasGradients = gradients.length > 0 || !colorGradientSettings.disableCustomGradients; const waveformGradientValue = waveformGradient; const waveformBackgroundGradientValue = waveformBackgroundGradient; let waveformColorGradientChange; let waveformBackgroundColorGradientChange; const onUploadError = useCallback((message) => { createErrorNotice(message, { type: "snackbar" }); }, [createErrorNotice]); const [selectedTrackClientId, setCurrentTrackClientId] = useState(null); const { innerBlockTracks } = useSelect((select) => { const { getBlock: _getBlock } = select(store); return { innerBlockTracks: _getBlock(clientId)?.innerBlocks ?? EMPTY_ARRAY }; }, [clientId]); const validTracks = useMemo(() => innerBlockTracks.filter((block) => !!block.attributes.src || !!block.attributes.blob), [innerBlockTracks]); const tracks = useMemo(() => validTracks.map((block) => ({ ...block.attributes, clientId: block.clientId })), [validTracks]); const currentTrackClientId = validTracks.some((block) => block.clientId === selectedTrackClientId) ? selectedTrackClientId : validTracks[0]?.clientId ?? null; useEffect(() => { if (validTracks.length > 0 || innerBlockTracks.length === 0) return; __unstableMarkNextChangeAsNotPersistent(); replaceInnerBlocks(clientId, []); }, [ clientId, innerBlockTracks, replaceInnerBlocks, validTracks, __unstableMarkNextChangeAsNotPersistent ]); const createTrackBlocks = useCallback((media) => { if (!media) return []; let mediaItems = [media]; if (Object.prototype.toString.call(media) === FILE_LIST_OBJECT_NAME) mediaItems = Array.from(media); else if (Array.isArray(media)) mediaItems = media; let hasInvalidFile = false; const blocks = mediaItems.map((mediaItem) => { if (isFile(mediaItem)) { if (!isAudioFile(mediaItem)) { hasInvalidFile = true; return null; } return createBlock("core/playlist-track", { blob: createBlobURL(mediaItem), title: mediaItem.name }); } const track = getTrackAttributes(mediaItem); return track.src ? createBlock("core/playlist-track", track) : null; }).filter(Boolean); if (hasInvalidFile) onUploadError(__("Only audio files can be added to a playlist.")); return blocks; }, [onUploadError]); const onSelectTracks = useCallback((media) => { const newBlocks = createTrackBlocks(media); if (newBlocks.length === 0) return; setCurrentTrackClientId(newBlocks[0]?.clientId ?? null); replaceInnerBlocks(clientId, newBlocks); }, [ clientId, createTrackBlocks, replaceInnerBlocks, setCurrentTrackClientId ]); const onAddTracks = useCallback((media) => { const existingIds = new Set(validTracks.map((block) => getTrackIdentifier(block.attributes)).filter(Boolean)); const newBlocks = createTrackBlocks(media).filter((block) => !existingIds.has(getTrackIdentifier(block.attributes))); if (newBlocks.length === 0) return; setCurrentTrackClientId(newBlocks[0].clientId); insertBlocks(newBlocks, void 0, clientId, false); selectBlock(newBlocks[0].clientId); }, [ clientId, createTrackBlocks, insertBlocks, selectBlock, setCurrentTrackClientId, validTracks ]); const removeTrack = useCallback((trackClientId) => { replaceBlocks(trackClientId, []); }, [replaceBlocks]); const playlistContext = useMemo(() => ({ currentTrackClientId, setCurrentTrackClientId, removeTrack }), [ currentTrackClientId, setCurrentTrackClientId, removeTrack ]); const currentTrackData = tracks.find((track) => track.clientId === currentTrackClientId) ?? tracks[0]; const onTrackEnded = useCallback(() => { const currentIndex = tracks.findIndex((track) => track.clientId === currentTrackClientId); const nextTrack = tracks[currentIndex + 1] || tracks[0]; if (nextTrack?.clientId) setCurrentTrackClientId(nextTrack.clientId); }, [ currentTrackClientId, setCurrentTrackClientId, tracks ]); const onChangeOrder = useCallback((trackOrder) => { const sortedBlocks = innerBlockTracks.toSorted((a, b) => { const titleA = a.attributes.title || ""; const titleB = b.attributes.title || ""; if (trackOrder === "asc") return titleA.localeCompare(titleB); return titleB.localeCompare(titleA); }); replaceInnerBlocks(clientId, sortedBlocks); setCurrentTrackClientId(sortedBlocks[0]?.clientId ?? null); setAttributes({ order: trackOrder }); }, [ clientId, innerBlockTracks, replaceInnerBlocks, setAttributes, setCurrentTrackClientId ]); function toggleAttribute(attribute) { return (newValue) => { setAttributes({ [attribute]: newValue }); }; } const onChangeWaveformStyle = useCallback((newWaveformStyle) => { setAttributes({ waveformStyle: newWaveformStyle === DEFAULT_WAVEFORM_STYLE ? void 0 : newWaveformStyle }); }, [setAttributes]); function updateWaveformColor(colorValue) { if (!(colorValue !== void 0) && waveformColorGradientChange === "gradient") { waveformColorGradientChange = void 0; return; } waveformColorGradientChange = "color"; setAttributes({ waveformColor: colorValue, waveformGradient: void 0 }); } function updateWaveformGradient(gradientValue) { if (!(gradientValue !== void 0) && waveformColorGradientChange === "color") { waveformColorGradientChange = void 0; return; } waveformColorGradientChange = "gradient"; setAttributes({ waveformGradient: gradientValue, waveformColor: void 0 }); } function updateWaveformBackgroundColor(colorValue) { if (!(colorValue !== void 0) && waveformBackgroundColorGradientChange === "gradient") { waveformBackgroundColorGradientChange = void 0; return; } waveformBackgroundColorGradientChange = "color"; setAttributes({ waveformBackgroundColor: colorValue, waveformBackgroundGradient: void 0 }); } function updateWaveformBackgroundGradient(gradientValue) { if (!(gradientValue !== void 0) && waveformBackgroundColorGradientChange === "color") { waveformBackgroundColorGradientChange = void 0; return; } waveformBackgroundColorGradientChange = "gradient"; setAttributes({ waveformBackgroundGradient: gradientValue, waveformBackgroundColor: void 0 }); } const colorSettings = []; if (hasColors || hasGradients) colorSettings.push({ colorValue: hasColors ? waveformColor : void 0, gradientValue: hasGradients ? waveformGradientValue : void 0, label: __("Waveform & Play button"), onColorChange: hasColors ? updateWaveformColor : void 0, onGradientChange: hasGradients ? updateWaveformGradient : void 0, isShownByDefault: true, clearable: true, enableAlpha: true, resetAllFilter: () => ({ waveformColor: void 0, waveformGradient: void 0 }) }, { colorValue: hasColors ? waveformBackgroundColor : void 0, gradientValue: hasGradients ? waveformBackgroundGradientValue : void 0, label: __("Waveform background"), onColorChange: hasColors ? updateWaveformBackgroundColor : void 0, onGradientChange: hasGradients ? updateWaveformBackgroundGradient : void 0, isShownByDefault: true, clearable: true, enableAlpha: true, resetAllFilter: () => ({ waveformBackgroundColor: void 0, waveformBackgroundGradient: void 0 }) }); const { children: innerBlocks, ...trackListProps } = useInnerBlocksProps({ className: clsx("wp-block-playlist__tracklist", { "wp-block-playlist__tracklist-is-hidden": !showTracklist, "wp-block-playlist__tracklist-show-numbers": showNumbers, "wp-block-playlist__tracklist-length-is-hidden": !showTrackLength }) }, { __experimentalAppenderTagName: "li", renderAppender: false }); if (tracks.length === 0) return /* @__PURE__ */ jsx("div", { ...blockProps, className: clsx("is-placeholder", blockProps.className), children: /* @__PURE__ */ jsx(MediaPlaceholder, { icon: /* @__PURE__ */ jsx(BlockIcon, { icon: playlist }), labels: { title: __("Playlist"), instructions: __("Upload an audio file or pick one from your media library.") }, onSelect: onSelectTracks, accept: "audio/*", multiple: "add", handleUpload: false, allowedTypes: ALLOWED_MEDIA_TYPES, onError: onUploadError }) }); return /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx(BlockControls, { group: "other", children: /* @__PURE__ */ jsx(MediaReplaceFlow, { name: __("Add track"), onSelect: onAddTracks, accept: "audio/*", multiple: "add", handleUpload: false, allowedTypes: ALLOWED_MEDIA_TYPES, onError: onUploadError }) }), /* @__PURE__ */ jsx(InspectorControls, { children: /* @__PURE__ */ jsxs(__experimentalToolsPanel, { label: __("Settings"), resetAll: () => { setAttributes({ showTracklist: true, showArtists: true, showNumbers: true, showTrackLength: true, showImages: true, showPlayButtonArtwork: false, order: "asc" }); }, dropdownMenuProps, children: [ /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Show tracklist"), isShownByDefault: true, hasValue: () => showTracklist !== true, onDeselect: () => setAttributes({ showTracklist: true }), children: /* @__PURE__ */ jsx(ToggleControl, { label: __("Show tracklist"), onChange: toggleAttribute("showTracklist"), checked: showTracklist }) }), showTracklist && /* @__PURE__ */ jsxs(Fragment, { children: [ /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Show artist name in tracklist"), isShownByDefault: true, hasValue: () => showArtists !== true, onDeselect: () => setAttributes({ showArtists: true }), children: /* @__PURE__ */ jsx(ToggleControl, { label: __("Show artist name in tracklist"), onChange: toggleAttribute("showArtists"), checked: showArtists }) }), /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Show track numbers in tracklist"), isShownByDefault: true, hasValue: () => showNumbers !== true, onDeselect: () => setAttributes({ showNumbers: true }), children: /* @__PURE__ */ jsx(ToggleControl, { label: __("Show track numbers in tracklist"), onChange: toggleAttribute("showNumbers"), checked: showNumbers }) }), /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Show track duration in tracklist"), isShownByDefault: true, hasValue: () => showTrackLength !== true, onDeselect: () => setAttributes({ showTrackLength: true }), children: /* @__PURE__ */ jsx(ToggleControl, { label: __("Show track duration in tracklist"), onChange: toggleAttribute("showTrackLength"), checked: showTrackLength }) }) ] }), /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Show tracklist images"), isShownByDefault: true, hasValue: () => showImages !== true, onDeselect: () => setAttributes({ showImages: true }), children: /* @__PURE__ */ jsx(ToggleControl, { label: __("Show tracklist images"), onChange: toggleAttribute("showImages"), checked: showImages }) }), /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Show track image on play button"), isShownByDefault: true, hasValue: () => showPlayButtonArtwork === true, onDeselect: () => setAttributes({ showPlayButtonArtwork: false }), children: /* @__PURE__ */ jsx(ToggleControl, { label: __("Show track image on play button"), onChange: toggleAttribute("showPlayButtonArtwork"), checked: showPlayButtonArtwork === true }) }), /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Order"), isShownByDefault: true, hasValue: () => order !== "asc", onDeselect: () => setAttributes({ order: "asc" }), children: /* @__PURE__ */ jsx(SelectControl, { label: __("Order"), value: selectedOrderItem, items: ORDER_ITEMS, onValueChange: (item) => { if (item && item !== selectedOrderItem) onChangeOrder(item.value); } }) }) ] }) }), /* @__PURE__ */ jsx(InspectorControls, { group: "styles", children: /* @__PURE__ */ jsxs(__experimentalToolsPanel, { label: __("Waveform"), resetAll: () => { setAttributes({ waveformStyle: void 0, waveformColor: void 0, waveformGradient: void 0, waveformBackgroundColor: void 0, waveformBackgroundGradient: void 0 }); }, panelId: waveformPanelId, dropdownMenuProps, children: [colorSettings.length > 0 && /* @__PURE__ */ jsx("div", { className: "wp-block-playlist__waveform-color-controls", children: /* @__PURE__ */ jsx(__experimentalColorGradientSettingsDropdown, { __experimentalIsRenderedInSidebar: true, settings: colorSettings, panelId: waveformPanelId, ...colorGradientSettings }) }), /* @__PURE__ */ jsx(__experimentalToolsPanelItem, { label: __("Shape"), isShownByDefault: true, hasValue: () => waveformStyle !== DEFAULT_WAVEFORM_STYLE, onDeselect: () => onChangeWaveformStyle(DEFAULT_WAVEFORM_STYLE), panelId: waveformPanelId, children: /* @__PURE__ */ jsx(SelectControl, { label: __("Shape"), value: WAVEFORM_STYLE_ITEMS.find((item) => item.value === waveformStyle) ?? WAVEFORM_STYLE_ITEMS[0], items: WAVEFORM_STYLE_ITEMS, onValueChange: (item) => { if (item) onChangeWaveformStyle(item.value); } }) })] }) }), /* @__PURE__ */ jsxs("figure", { ...blockProps, children: [ /* @__PURE__ */ jsx(MediaPlaceholder, { onSelect: onAddTracks, accept: "audio/*", multiple: "add", handleUpload: false, disableMediaButtons: true, allowedTypes: ALLOWED_MEDIA_TYPES, onError: onUploadError }), /* @__PURE__ */ jsx(Disabled, { isDisabled: !isSelected, children: /* @__PURE__ */ jsx(WaveformPlayer, { src: currentTrackData?.src, title: currentTrackData?.title, artist: currentTrackData?.artist, image: currentTrackData?.image, imageAlt: currentTrackData?.imageAlt, waveformStyle, color: waveformColor, gradient: waveformGradientValue, backgroundColor: waveformBackgroundColor, backgroundGradient: waveformBackgroundGradientValue, onEnded: onTrackEnded, showPlayButtonArtwork: showPlayButtonArtwork === true }) }), /* @__PURE__ */ jsx("ol", { ...trackListProps, children: /* @__PURE__ */ jsx(PlaylistContext.Provider, { value: playlistContext, children: innerBlocks }) }), /* @__PURE__ */ jsx(Caption, { attributes, setAttributes, isSelected, insertBlocksAfter, label: __("Playlist caption text"), showToolbarButton: isSelected, style: { marginTop: 16 } }) ] }) ] }); }; export { PlaylistEdit as default }; //# sourceMappingURL=edit.mjs.map