@wordpress/block-library
Version:
Block library for the WordPress editor.
670 lines (669 loc) • 22.2 kB
JavaScript
// packages/block-library/src/playlist/edit.js
import clsx from "clsx";
import { useCallback, useEffect, useMemo, useState } from "@wordpress/element";
import {
store as blockEditorStore,
MediaPlaceholder,
MediaReplaceFlow,
BlockIcon,
useBlockProps,
useInnerBlocksProps,
BlockControls,
InspectorControls,
__experimentalColorGradientSettingsDropdown as ColorGradientSettingsDropdown,
__experimentalUseMultipleOriginColorsAndGradients as useMultipleOriginColorsAndGradients
} from "@wordpress/block-editor";
import {
ToggleControl,
Disabled,
SelectControl,
__experimentalToolsPanel as ToolsPanel,
__experimentalToolsPanelItem as ToolsPanelItem
} from "@wordpress/components";
import { useSelect, useDispatch } from "@wordpress/data";
import { store as noticesStore } from "@wordpress/notices";
import { __, _x } from "@wordpress/i18n";
import { playlist as icon } from "@wordpress/icons";
import { createBlock } from "@wordpress/blocks";
import { createBlobURL } from "@wordpress/blob";
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";
var ALLOWED_MEDIA_TYPES = ["audio"];
var AUDIO_FILE_EXTENSION = /\.(aac|aif|aiff|flac|m4a|m4b|mp3|oga|ogg|opus|wav|weba)$/i;
var DEFAULT_WAVEFORM_STYLE = "bars";
var FILE_LIST_OBJECT_NAME = "[object FileList]";
var WAVEFORM_STYLE_OPTIONS = [
{ 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;
}
var PlaylistEdit = ({
attributes,
setAttributes,
isSelected,
insertBlocksAfter,
clientId
}) => {
const {
order,
showTracklist,
showNumbers,
showImages,
showPlayButtonArtwork,
showArtists,
showTrackLength,
waveformStyle = DEFAULT_WAVEFORM_STYLE,
waveformColor,
waveformGradient,
waveformBackgroundColor,
waveformBackgroundGradient
} = attributes;
const blockProps = useBlockProps();
const waveformPanelId = `${clientId}-waveform`;
const { replaceInnerBlocks, selectBlock } = useDispatch(blockEditorStore);
const { createErrorNotice } = useDispatch(noticesStore);
const dropdownMenuProps = useToolsPanelDropdownMenuProps();
const colorGradientSettings = useMultipleOriginColorsAndGradients();
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 [currentTrackClientId, setCurrentTrackClientId] = useState(null);
const { innerBlockTracks } = useSelect(
(select) => {
const { getBlock: _getBlock } = select(blockEditorStore);
return {
innerBlockTracks: _getBlock(clientId)?.innerBlocks ?? []
};
},
[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]
);
useEffect(() => {
if (validTracks.length === 0) {
if (currentTrackClientId !== null) {
setCurrentTrackClientId(null);
}
return;
}
const currentTrackExists = validTracks.some(
(block) => block.clientId === currentTrackClientId
);
if (!currentTrackExists) {
setCurrentTrackClientId(validTracks[0].clientId);
}
}, [currentTrackClientId, setCurrentTrackClientId, validTracks]);
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;
}
const nextBlocks = [...validTracks, ...newBlocks];
setCurrentTrackClientId(newBlocks[0].clientId);
replaceInnerBlocks(clientId, nextBlocks);
selectBlock(newBlocks[0].clientId);
},
[
clientId,
createTrackBlocks,
replaceInnerBlocks,
selectBlock,
setCurrentTrackClientId,
validTracks
]
);
const playlistContext = useMemo(
() => ({
currentTrackClientId,
setCurrentTrackClientId
}),
[currentTrackClientId, setCurrentTrackClientId]
);
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].sort((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) {
const isSettingColor = colorValue !== void 0;
if (!isSettingColor && waveformColorGradientChange === "gradient") {
waveformColorGradientChange = void 0;
return;
}
waveformColorGradientChange = "color";
setAttributes({
waveformColor: colorValue,
waveformGradient: void 0
});
}
function updateWaveformGradient(gradientValue) {
const isSettingGradient = gradientValue !== void 0;
if (!isSettingGradient && waveformColorGradientChange === "color") {
waveformColorGradientChange = void 0;
return;
}
waveformColorGradientChange = "gradient";
setAttributes({
waveformGradient: gradientValue,
waveformColor: void 0
});
}
function updateWaveformBackgroundColor(colorValue) {
const isSettingColor = colorValue !== void 0;
if (!isSettingColor && waveformBackgroundColorGradientChange === "gradient") {
waveformBackgroundColorGradientChange = void 0;
return;
}
waveformBackgroundColorGradientChange = "color";
setAttributes({
waveformBackgroundColor: colorValue,
waveformBackgroundGradient: void 0
});
}
function updateWaveformBackgroundGradient(gradientValue) {
const isSettingGradient = gradientValue !== void 0;
if (!isSettingGradient && 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 innerBlocksProps = useInnerBlocksProps(blockProps, {
__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 }),
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", __experimentalShareWithChildBlocks: true, 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(
ToolsPanel,
{
label: __("Settings"),
resetAll: () => {
setAttributes({
showTracklist: true,
showArtists: true,
showNumbers: true,
showTrackLength: true,
showImages: true,
showPlayButtonArtwork: false,
order: "asc"
});
},
dropdownMenuProps,
children: [
/* @__PURE__ */ jsx(
ToolsPanelItem,
{
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(
ToolsPanelItem,
{
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(
ToolsPanelItem,
{
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(
ToolsPanelItem,
{
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(
ToolsPanelItem,
{
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(
ToolsPanelItem,
{
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(
ToolsPanelItem,
{
label: __("Order"),
isShownByDefault: true,
hasValue: () => order !== "asc",
onDeselect: () => setAttributes({ order: "asc" }),
children: /* @__PURE__ */ jsx(
SelectControl,
{
label: __("Order"),
value: order,
options: [
{ label: __("Descending"), value: "desc" },
{ label: __("Ascending"), value: "asc" }
],
onChange: (value) => onChangeOrder(value)
}
)
}
)
]
}
) }),
/* @__PURE__ */ jsx(InspectorControls, { group: "styles", children: /* @__PURE__ */ jsxs(
ToolsPanel,
{
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(
ColorGradientSettingsDropdown,
{
__experimentalIsRenderedInSidebar: true,
settings: colorSettings,
panelId: waveformPanelId,
...colorGradientSettings
}
) }),
/* @__PURE__ */ jsx(
ToolsPanelItem,
{
label: __("Shape"),
isShownByDefault: true,
hasValue: () => waveformStyle !== DEFAULT_WAVEFORM_STYLE,
onDeselect: () => onChangeWaveformStyle(DEFAULT_WAVEFORM_STYLE),
panelId: waveformPanelId,
children: /* @__PURE__ */ jsx(
SelectControl,
{
label: __("Shape"),
value: waveformStyle,
options: WAVEFORM_STYLE_OPTIONS,
onChange: onChangeWaveformStyle
}
)
}
)
]
}
) }),
/* @__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",
{
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
}),
children: /* @__PURE__ */ jsx(PlaylistContext.Provider, { value: playlistContext, children: innerBlocksProps.children })
}
),
/* @__PURE__ */ jsx(
Caption,
{
attributes,
setAttributes,
isSelected,
insertBlocksAfter,
label: __("Playlist caption text"),
showToolbarButton: isSelected,
style: { marginTop: 16 }
}
)
] })
] });
};
var edit_default = PlaylistEdit;
export {
edit_default as default
};
//# sourceMappingURL=edit.mjs.map