Gathering detailed insights and metrics for itmar-block-packages
Gathering detailed insights and metrics for itmar-block-packages
Gathering detailed insights and metrics for itmar-block-packages
Gathering detailed insights and metrics for itmar-block-packages
npm install itmar-block-packages
Typescript
Module System
Node Version
NPM Version
JavaScript (99.85%)
PHP (0.15%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
44 Commits
1 Watchers
1 Branches
1 Contributors
Updated on Jul 13, 2025
Latest Version
1.8.0
Package Id
itmar-block-packages@1.8.0
Unpacked Size
767.97 kB
Size
465.39 kB
File Count
36
NPM Version
10.2.4
Node Version
20.11.1
Published on
Jul 13, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
4
1
WordPressのカスタムブロックを作成するためのプラグインで活用するパッケージです。複数のプラグインで共通に使用する機能をパッケージにまとめました。
import {関数名又はコンポーネント名} from "itmar-block-packages"
名前付きインポートでお願いします。
このパッケージは@wordpress/scripts
によるWebPackのトランスパイル環境でトランスパイルされています。そして、このパッケージを使用するには、@wordpress/scripts
のバージョン^27.6.0以上が必要です。以下のコマンドを実行して、@wordpress/scripts
を更新してください:
npm i @wordpress/scripts@^27.6.0 --save-dev
= 1.8.0 =
= 1.7.1 =
= 1.7.0 =
= 1.6.3 =
= 1.6.0 =
= 1.5.0 =
= 1.4.3 =
= 1.4.2 =
= 1.4.1 =
= 1.4.0 =
= 1.3.21 =
= 1.3.20 =
= 1.3.19 =
= 1.3.18 =
= 1.3.17 =
= 1.3.16 =
= 1.3.15 =
= 1.3.14 =
= 1.3.13 =
= 1.3.12 =
= 1.3.11 =
= 1.3.10 =
= 1.3.9 =
= 1.3.8 =
= 1.3.4 =
= 1.3.2 =
= 1.3.1 =
= 1.3.0 =
WordPressのエディタ(ブロックエディタ、サイトエディタ)の大きさを監視し、幅が767ピクセル以下であればtrueを返します。
const is_mobile=useIsIframeMobile();
ブロックの背景色を返します。ユーザー設定で指定されていれば、その色を返し、指定されていないか、カスタムプロパティ(--wpで始まるプロパティ)であれば、getComputedStyleで実際にレンダリングされた色を取得します。
blockRef
style
//ブロックの参照
const blockRef = useRef(null);
//blockPropsの参照
const blockProps = useBlockProps({
ref: blockRef, // ここで参照を blockProps に渡しています
});
//背景色の取得
const baseColor = useElementBackgroundColor(blockRef, blockProps.style);
ViewPortの大きさの大きさを監視し、幅が767ピクセル以下であればtrueを返します。
const is_mobile=useIsMobile();
たくさんの要素をもつオブジェクトや配列の内容の変化で発火するuseEffect
callback
funcdependencies
arrayuseDeepCompareEffect(() => {
・・・
},
[attributes])
iframeにfontawesomeを読み込むカスタムフック
特定のブロックの属性が変更されたとき、その変更内容を返すカスタムフック。引数に指定されたブロック名のブロックで指定されたクラス名をもつブロックの属性の変更内容を返す。第3引数のフラグにtrueを指定すると同じブロック名で同じクラス名をもつブロックの属性を変更されたブロックの属性で自動的に更新する。ただし、変更内容については、指定された属性名の属性を変更及び比較の対象からはずすことができる。
clientId
stringblockName
stringclassName
stringmodFlg
booleanexcludeAttributes
object//clientIdで指定されたブロックの属性変更の内容を返す
const changedAttributes = useBlockAttributeChanges(
clientId,
"itmar/design-checkbox",
"itmar_filter_checkbox",
);
//clientIdで指定されたブロックの属性変更の内容でitmar/design-checkboxという名前のブロックで
//itmar_filter_checkboxというクラス名をもつブロックの属性を自動更新する。
//ただし、labelContentという属性とinputValueという属性については更新対象から除外する
useBlockAttributeChanges(
clientId,
"itmar/design-checkbox",
"itmar_filter_checkbox",
true,
{ labelContent: "", inputValue: false },
);
インナーブロックが挿入されたとき、指定されたブロック名が存在れば、挿入したブロックを削除する。ユーザーに重複したブロックを挿入させたくないときや特定のブロックが存在するとき、ブロックを挿入させないようにするときに活用する。
clientId
stringblockNames
arrayuseDuplicateBlockRemove(clientId, ["itmar/pickup-posts"]);
styled-componetのcssヘルパー関数内で使用するcssのパラメーターやプロパティを返します。
border-radiusに設定するプロパティを文字列で返します。
radius
objectmarginやpaddingに設定するプロパティを文字列で返します。
space
object絶対位置のポジションに関するCSSを返します。
pos
object,boolean"posValue": {
"vertBase": "top",
"horBase": "left",
"vertValue": "3em",
"horValue": "3em",
"isVertCenter": false,
"isHorCenter": false
},
type
string
staic, relative,absolute,fixed,stickyのいづれかtop:50%;left: 50%;transform: translate(-50%, -50%);
を返す。最大幅を設定するためのCSSを返します。
width
stringfree_val
stringwidth: 100%; max-width: var(--wp--style--global--wide-size);
width: 100%; max-width: var(--wp--style--global--content-size);
width: 100%; max-width: ${free_val};
width: 100%; max-width: 100%;
width: fit-content;
widthのCSSを返します。
width
stringfree_val
stringwidth: var(--wp--style--global--wide-size);
width: var(--wp--style--global--content-size);
width: ${free_val};
width: fit-content;
heightのCSSを返します。
height
string
fit, full, freeの文字列free_val
stringheight: fit-content;
height: ${free_val};
height: 100%;
marginによる横方向の配置のためのCSSを返します。 また、camelFlgを設定することで、インナースタイル用のオブジェクトを返します。
align
stringcamelFLg
booleancamelFLgがfalse又は設定されていないとき
margin-left: auto; margin-right: auto;
margin-left: auto; margin-right: 0
margin-right: auto; margin-left: 0
camelFLgがtrueのとき { marginLeft: "auto", marginRight: "auto" }
{ marginLeft: "auto" }
{}
キャメルケースで与えられたstyleオブジェクトをscssの文字列に変換します。
styleObject
objectconst str_scss = convertToScss(styleObject)
WordPressのBorderBoxControlコンポーネントが返すオブジェクトをキャメルケースのCSSに変換して返します。
borderObj
objectconst css_obj = borderProperty(borderObj)
WordPressのBorderRadiusControlコンポーネントが返すオブジェクトをキャメルケースのCSSに変換して返します。
radiusObj
objectconst css_obj = radiusProperty(radiusObj)
marginのcssを返します。
marginObj
objectpaddingのcssを返します。
paddingObj
objectWordPressのブロックエディタのサイドバーにbox-shadowを設定するためのコントロールを表示させるReactコンポーネント。
<ShadowStyle
shadowStyle={{ ...shadow_element }}
onChange={(newStyle, newState) => {
setAttributes({ shadow_result: newStyle.style });
setAttributes({ shadow_element: newState });
}}
/>
設定されたbox-shadowをスタイルオブジェクトとして返します。
shadowState
objectWordPressのブロックエディタのサイドバーに疑似要素を設定するためのコントロールを表示させるReactコンポーネント。現時点のバージョンでは上下左右の矢印表示の設定のみが可能です。
<PseudoElm
element="Arrow"
direction={pseudoInfo.option}
onChange={(direction) => {
setAttributes({
pseudoInfo: { ...pseudoInfo, option: direction },
});
}}
/>
矢印を表示させる疑似要素を生成してscssの文字列で返します。
const arrow = Arrow(direction);
direction
objectメディアライブラリ選択画面を開き、ブロックの属性にmediaとmedia.idをセットします。
<SingleImageSelect
attributes={attributes}
onSelectChange={(media) => {
setAttributes({ media: media, mediaID: media.id });
}}
/>
メディアライブラリ選択画面を開き、複数の画像を選択して、ブロックの属性にmediaとmedia.idをセットします。
<MultiImageSelect
attributes={attributes}
label=__("Selected Images", "text-domain")
onSelectChange={(media) => {
// media から map で id プロパティの配列を生成
const media_ID = media.map((image) => image.id);
setAttributes({
mobile_val: { ...mobile_val, mediaID: media_ID, media: media },
});
}}
onAllDelete={() => {
setAttributes({
mobile_val: { ...mobile_val, mediaID: [], media: [] },
});
}}
/>
ブロックを移動させる移動量を設定するコントロールをサイドバーに表示させます。
<DraggableBox
attributes={position}
onPositionChange={(position) =>
setAttributes({ position: position })
}
/>
参照したブロックを可能とするためのカスタムフックを設定します。
useDraggingMove(
isMovable,
blockRef,
position,
onPositionChange
)
isMovable
boolean
移動を可とするかどうかのフラグblockRef
useRefposition
objectonPositionChange
function
移動量が変化したときに属性値を記録するためのコールバック関数registerBlockTypeの第2引数内にあるeditオブジェクトに、以下の使用例で生成したBlockEditを渡してやることで、ブロックの読み込みをレンダリングの時まで遅らせます。
const LazyEditComponent = React.lazy(() => import("./edit"));
const BlockEdit = (props) => {
return <BlockEditWrapper lazyComponent={LazyEditComponent} {...props} />;
};
WordPressのブロックエディタのサイドバーにアニメーションを設定するためのコントロールを表示させるReactコンポーネント。現時点のバージョンではflipDown,fadeUp,fadeLeft,fadeRightのアニメーション設定が可能です
<AnimationBlock
attributes={attributes}
onChange={(newValue) => setAttributes(newValue)}
/>
設定されたアニメーションのパラメータをオブジェクトとして渡すことで、SCSSの文字列に変換して返します。
anime_prm
objectWordPressのブロックエディタのサイドバーにTypographyを設定するためのコントロールを表示させるReactコンポーネント。
<TypographyControls
title={__("Typography", "text-domain")}
fontStyle=
{
default_fontSize: "16px",
mobile_fontSize: "12px",
fontFamily: "Arial, sans-serif",
fontWeight: "500",
isItalic: false,
}
initialOpen={false}
isMobile={isMobile}
onChange={(newStyle) => {
setAttributes({ font_style_input: newStyle });
}}
/>
固定ページの情報を取得して配列で返します。
homeUrl
string次のようなキーを持つオブジェクトの配列を返します。
value
固定ページのid。ただし、サイトのホームについては-1をかえす。
slug
固定ページのスラッグ
link
固定ページのURL
label
固定ページの名称
カスタム投稿タイプ(ビルトインを含む)の情報を取得して配列で返します。
homeUrl
string次のようなキーを持つオブジェクトの配列を返します。
value
0から始まる通し番号
slug
ポストタイプのスラッグ
link
アーカイブページのURL
label
ポストタイプの名称
RestAPIのエンドポイントを文字列で受けて、その結果を返す
path
stringエンドポイントに対応したレスポンスがPromiseで返る
投稿タイプに登録されているタクソノミー(カテゴリ、タグを含む)の情報およびそのタームの情報をを取得して配列で返します。
post_type
string次のようなキーを持つオブジェクトの配列を返します。
slug
タクソノミーのスラッグ
name
タクソノミーの名称
rest_base
タクソノミーのREST_APIの名称
terms
ターム情報オブジェクトの配列
投稿タイプに登録されているタクソノミー(カテゴリ、タグを含む)の情報およびそのタームの情報をを取得して配列で返します。
rest_base
string"title","date","excerpt","featured_media","meta","acf"の各フィールドの値を投稿タイプの最新データ1件分を返す。この結果で投稿タイプがどのフィールドをサポートしているか、また、どのようなカスタムフィールドが設定されているかの情報を取得することができる。
固定ページを選択できるコンボボックス表示し、固定ページの情報を返します。
selectedSlug
stringlabel
string
コンボボックスのラベルhomeUrl
stringonChange
func
コンボボックスの内容が変化したとき発生するコールバック関数。引数にはfetchPagesOptions
の戻り値が入る。<PageSelectControl
selectedSlug={selectedSlug}
label={__("Select Post Type", "post-blocks")}
homeUrl={post_blocks.home_url}
onChange={(postInfo) => {
setAttributes({ selectedSlug: postInfo.slug });
}}
/>
投稿タイプ名を選択できるコンボボックス表示し、投稿タイプの情報を返します。
selectedSlug
stringlabel
string
コンボボックスのラベルhomeUrl
stringonChange
func
コンボボックスの内容が変化したとき発生するコールバック関数。引数にはfetchArchiveOptions
の戻り値が入る。<ArchiveSelectControl
selectedSlug={selectedSlug}
label={__("Select Post Type", "post-blocks")}
homeUrl={post_blocks.home_url}
onChange={(postInfo) => {
setAttributes({ selectedSlug: postInfo.slug });
}}
/>
投稿タイプに紐づけられている全てのタクソノミー(カテゴリ、タグを含む。)に登録されたタームを選択できるチェックボックス表示し、コールバック関数に選択されたタームの情報を返します。
selectedSlug
string
選択済みの投稿タイプのスラッグ
choiceTerms
array
選択済みのタームの情報。配列の要素は次の形式のオブジェクトであること。
{ taxonomy: タクソノミーのスラッグ, term: タームのスラッグ }
dispTaxonomies
array
選択済みのタクソノミの情報。配列の要素はタクソノミーのスラッグ
type
string
選択するデータのタイプ。将来の拡張のためにセットしている。現時点では"taxonomy"とセットすること。
label
string
onChange
func
チェックボックスの内容が変化したとき発生するコールバック関数。引数には{ taxonomy: タクソノミーのスラッグ, term:{ id: term.id, slug: term.slug, name: term.name } }という形式のオブジェクトを要素とする配列が入る。
onSetDispTax
func
トグルコントロールの内容が変化したとき発生するコールバック関数。引数にはタクソノミーのスラッグを要素とする配列が入る。
<TermChoiceControl
selectedSlug={selectedSlug}
choiceTerms={choiceTerms}
dispTaxonomies={dispTaxonomies}
type="taxonomy"
label={__("Choice Taxsonomy", "post-blocks")}
onChange={(newChoiceTerms) =>
setAttributes({ choiceTerms: newChoiceTerms })
}
onSetDispTax={(newChoiceTerms) => {
setAttributes({ dispTaxonomies: newChoiceTerms });
}}
/>
タイトル、日付、抜粋、アイキャッチ画像、リンクの各フィールドと投稿タイプに紐づけられている全てのカスタムフィールドを選択できるチェックボックス表示し、コールバック関数に選択されたフィールドの情報を返します。 また、各フィールドがどのブロックでレンダリングされるかの設定機能も含みます。
selectedSlug
stringchoiceItems
arraytype
string
選択するデータのタイプ。将来の拡張のためにセットしている。現時点では"field"とセットすること。blockMap
object
フィールド名とブロック名を対にしたオブジェクト{
"title":"itmar/design-title",
"date":"itmar/design-title",
"excerpt":"core/paragraph",
"featured_media":"core/image",
"link":"itmar/design-button"
}
textDomain
string
使用するブロックのテキストドメイン
onChange
func
チェックボックスの内容が変化したとき発生するコールバック関数。引数には選択されたフィールドのフィールド名を要素とする配列が入る。
- `onBlockMapChange` func
コンボボックスの内容が変化したとき発生するコールバック関数。引数には設定されたフィールド名とブロック名を対にしたオブジェクトが入る。
<FieldChoiceControl type="field" selectedSlug={selectedRest} choiceItems={choiceFields} blockMap={blockMap} textDomain="post-blocks" onChange={(newChoiceFields) => { setAttributes({ choiceFields: newChoiceFields }); }} onBlockMapChange={(newBlockMap) => { setAttributes({ blockMap: newBlockMap }); }} />
## Font awesom のアイコンを選択するためのコントロール
### IconSelectControl
WordPressのブロックエディタのサイドバーにFont awesomのアイコンを選択するためのコントロールを表示させるReactコンポーネント。
<IconSelectControl iconStyle={ icon_type: "awesome", icon_url: "", icon_name: "f030", icon_pos: "left", icon_size: "24px", icon_color: "var(--wp--preset--color--content)", icon_space: "5px", icon_family: "Font Awesome 6 Free",
}
setPosition={true}
onChange={(newValue) => {
setAttributes({icon_style: newValue})
}}
/>
iconStyleオブジェクトを再設定します。
setPositionプロプスをtrueにするとicon_posとicon_spaceの各オブジェクトを設定するコントロールが表示されます。
<img src="./img/iconControl.png" alt="IconSelectControlのスクリーンショット" width="100" height="200">
## DOM要素をラップしてレンダリングを変化させるReactコンポーネント
### ToggleElement
DOM要素をdiv要素でラップし、flgの値によって、その要素にopenというクラス名を付加します。呼び出し側でflgの値を変更することで、DOM要素の表示・非表示を操作するときに使用します。
<ToggleElement onToggle={handleHambergerToggle} className="itmar_hamberger_btn" openFlg={flg}
<span></span>
<span></span>
<span></span>
```
CSSでdisplay : grid が設定されたブロックに対し、gridの各種設定を行うため、モーダルウインドウを表示させるReactコンポーネント。
<GridControls
attributes={props.grid_info}
clientId={clientId}
onChange={(newValue) => {
props.onGridChange(newValue)
}}
/>
WordPressのブロックエディタのサイドバーにブロックの配置に関する設定のためのコントロールを表示させるReactコンポーネント。
<BlockPlace
attributes={attributes}
clientId={clientId}
blockRef={blockRef}
isMobile={isMobile}
isSubmenu={is_submenu}
isParallax={true}
onDirectionChange={(position) => {
setAttributes({direction: position });
}}
onReverseChange={(checked) => {
setAttributes({reverse: checked });
}}
onFlexChange={(position,axis) => {
setAttributes({[axis]: position });
}}
onAlignChange={(position) => {
setAttributes({outer_align: position });
}}
onVerticalChange={(position) => {
setAttributes({outer_vertical: position });
}}
onWidthChange={(position) => {
setAttributes({width_val: position });
}}
onHeightChange={(value) => {
setAttributes({ height_val: value });
}}
onFreeWidthChange={(value) => {
setAttributes({free_width: position });
}}
onFreeHeightChange={(value) => {
setAttributes({free_height: position });
}}
onGridChange={(value) => {
setAttributes({grid_info: position });
}}
onPositionChange={(value) => {
setAttributes({ positionType: value });
}}
onPosValueChange={(value) => {
setAttributes({posValue: position });
}}
/>
ブロックコンポーネントの幅を設定する
attributes
objectisMobile
booleanisSubmenu
booleanonWidthChange
function
widthの種別を設定するためのコールバック関数。返ってくる引数はkey,valueの2つでkeyはwidth_valまたはmax_valという文字列でwidthValはfit,full,wideSize,contentSize,freeのいずれかonFreeWidthChange
function
widthの種別がfreeのとき幅を設定するためのコールバック関数。返ってくる引数はkey,valueの2つでkeyはfree_widthまたはmax_free_widthという文字列でvalueは単位付きの文字列<BlockWidth
attributes={attributes}
isMobile={isMobile}
isSubmenu={isFront}
onWidthChange={(key,value) => {
setAttributes(
!isMobile
? { default_val: { ...default_val, [key]: value } }
: { mobile_val: { ...mobile_val, [key]: value } },
);
}}
onFreeWidthChange={(key,value) => {
setAttributes(
!isMobile
? { default_val: { ...default_val, [key]: value } }
: { mobile_val: { ...mobile_val, [key]: value } },
);
}}
/>
ブロックコンポーネントの高さを設定する
attributes
objectisMobile
booleanonHeightChange
function
heightの種別を設定するためのコールバック関数。返ってくる引数はfit,full,freeonFreeHeightChange
function
heightの種別がfreeのとき幅を設定するためのコールバック関数。返ってくる引数は単位付きの文字列<BlockHeight
attributes={attributes}
isMobile={isMobile}
onHeightChange={(value) => {
setAttributes(
!isMobile
? { default_val: { ...default_val, height_val: value } }
: { mobile_val: { ...mobile_val, height_val: value } },
);
}}
onFreeHeightChange={(value) => {
setAttributes(
!isMobile
? { default_val: { ...default_val, free_height: value } }
: { mobile_val: { ...mobile_val, free_height: value } },
);
}}
/>
Hslオブジェクトの値を与えると#000000型のRGB表記に変換するためのユーティリティ関数です。
hue
numbersaturation
numberlightness
number16進数のRGB表記を受け取り、それをHslオブジェクトに変換するためのユーティリティ関数です。
strRgb16
string16進数のRGB表記を受け取り、それを10進数のRGBオブジェクトに変換するためのユーティリティ関数です。
strRgb16
stringpostType
stringblockName
stringnewAttributes
objectonProcessStart
functiononProcessEnd
functiononProcessCancel
function<UpdateAllPostsBlockAttributes
postType={rest_base}
blockName="itmar/markdown-block"
newAttributes={{
element_style_obj: element_style_obj,
backgroundColor: backgroundColor,
backgroundGradient: backgroundGradient,
default_val: default_val,
mobile_val: mobile_val,
radius_value: radius_value,
border_value: border_value,
}}
onProcessStart={startProgress}
onProcessEnd={closeProgress}
onProcessCancel={() => {
dispatch("core/notices").createNotice(
"error",
__("Processing was interrupted.", "markdown-block"),
{ type: "snackbar" },
);
}}
/>
useTargetBlocks
useTargetBlocks
は、Gutenberg ブロックエディタ上で同じ親ブロック内にある特定の名前・属性を持つブロックを取得する React フックです。
ネストされたブロックの検索にも対応しています。
このカスタムフックは、次のような用途に使えます:
1const result = useTargetBlocks(clientId, blockName, attributeFilter?, includeNested?);
引数 | 型 | 説明 |
---|---|---|
clientId | string | 呼び出し元(自分自身)の clientId 。useBlockEditContext() などで取得 |
blockName | string | 対象ブロック名(例: 'itmar/design-text-ctrl' ) |
attributeFilter | `object | null` |
includeNested | boolean | オプション:true でネストされたブロックも対象に含める(デフォルト: false ) |
itmar/design-text-ctrl
ブロックを取得(自分を除く)1import { useBlockEditContext } from '@wordpress/block-editor'; 2import { useTargetBlocks } from '@your-scope/use-target-blocks'; 3 4const MyComponent = () => { 5 const { clientId } = useBlockEditContext(); 6 7 const blocks = useTargetBlocks(clientId, 'itmar/design-text-ctrl'); 8 9 return <div>対象ブロック数: {blocks.length}</div>; 10};
inputName: 'address'
を持つブロックを1件だけ取得1const targetBlock = useTargetBlocks(clientId, 'itmar/design-text-ctrl', { 2 inputName: 'address', 3}); 4 5if (targetBlock) { 6 console.log('Address block found:', targetBlock.clientId); 7}
1const nestedBlock = useTargetBlocks(
2 clientId,
3 'itmar/design-text-ctrl',
4 { inputName: 'address' },
5 true // ネスト含める
6);
@wordpress/data
@wordpress/block-editor
useSelect
, getBlockRootClientId
, getBlock
, getBlocks
flattenBlocks
ネストされたブロックを平坦化するためのユーティリティも内蔵:
1const flattenBlocks = (blocks) => { 2 return blocks.reduce((acc, block) => { 3 acc.push(block); 4 if (block.innerBlocks?.length > 0) { 5 acc.push(...flattenBlocks(block.innerBlocks)); 6 } 7 return acc; 8 }, []); 9};
useTargetBlocks()
は React フックです。関数やイベントハンドラ内部では直接呼び出せません。serializeBlockTree
指定された Gutenberg ブロックオブジェクトを、**ネスト構造を保ったままプレーンな JSON 形式に変換(保存用)**します。
1import { serializeBlockTree } from '@your-scope/block-tree-utils'; 2 3const json = serializeBlockTree(block);
block
: Gutenberg ブロックオブジェクト(name
, attributes
, innerBlocks
を含む)1{ 2 "blockName": "core/group", 3 "attributes": { ... }, 4 "innerBlocks": [ 5 { 6 "blockName": "core/paragraph", 7 "attributes": { ... }, 8 "innerBlocks": [] 9 } 10 ] 11}
createBlockTree
serializeBlockTree
によって得られた JSON 構造を、createBlock()
に渡せる Gutenberg ブロックオブジェクトに再構築します。
1import { createBlockTree } from '@your-scope/block-tree-utils'; 2import { createBlock } from '@wordpress/blocks'; 3 4const wpBlock = createBlockTree(savedJson);
savedJson
: serializeBlockTree
で生成されたブロックデータcreateBlock(name, attributes, innerBlocks)
の形で再帰的に構成された WP ブロックオブジェクトflattenBlocks
Gutenberg のネストされたブロック配列を、1階層の配列としてフラットに展開します。
ブロック構成内にあるすべてのブロック(ネスト含む)を一括走査する際に便利です。
1import { flattenBlocks } from '@your-scope/block-tree-utils'; 2 3const flat = flattenBlocks(innerBlocks);
innerBlocks
: Gutenberg のブロック配列(innerBlocks
を含む構造)1import { 2 serializeBlockTree, 3 createBlockTree, 4 flattenBlocks, 5} from '@your-scope/block-tree-utils'; 6 7const savedData = blocks.map(serializeBlockTree); 8const restored = savedData.map(createBlockTree); 9const flatList = flattenBlocks(restored);
fetchZipToAddress
fetchZipToAddress
は、zipcloud API を使用して、日本の郵便番号から都道府県・市区町村・町域の住所を非同期で取得する JavaScript 関数です。
Gutenberg ブロック開発やフロントエンドフォーム処理において、郵便番号による住所補完機能を簡単に実装できます。
1const addressObj = await fetchZipToAddress("1600022"); 2if (addressObj) { 3 const fullAddress = addressObj.address1 + addressObj.address2 + addressObj.address3; 4 console.log(fullAddress); // 例: 東京都新宿区新宿 5}
1234567
)。null
を返します。alert()
によってユーザーに通知されます。1{ 2 "zipcode": "1600022", 3 "prefcode": "13", 4 "address1": "東京都", 5 "address2": "新宿区", 6 "address3": "新宿", 7 ... 8}
本ライブラリは以下の外部APIを使用しています:
1const handleZipSearch = async () => {
2 const result = await fetchZipToAddress(zipValue);
3 if (result) {
4 setAttributes({ inputValue: result.address1 + result.address2 + result.address3 });
5 }
6};
isValidUrlWithUrlApi
isValidUrlWithUrlApi
は、引数で与えた文字列がURLの形式であるかどうかのバリデーションチェックをします。
if (isValidUrlWithUrlApi(headingContent)) {
setAttributes({ selectedPageUrl: headingContent });
}
Gutenberg ブロックにおける数値・日付・自由書式の表示形式を選択・制御するための UI コンポーネントおよびフォーマット関数です。
このライブラリは、以下の2つの機能を提供します:
<FormatSelectControl />
ブロックエディターの「インスペクター設定」内で、表示形式を選択する UI コンポーネント。
displayFormated()
保存された設定に基づき、日付・数値・自由文字列の値を整形する表示用関数。
FormatSelectControl
ブロック編集画面で「日付」「数値」「自由文字列」のいずれかの表示形式を選択・設定可能にする PanelBody
コンポーネントです。
名前 | 型 | 必須 | 説明 |
---|---|---|---|
titleType | "date" | "plaine" | "user" | ✅ | フォーマット対象の種類を指定します。 |
userFormat | string | ✅ | 現在選択中のフォーマットのキー(例: "num_comma" )。 |
freeStrFormat | string | ✅ | 自由書式入力時の書式文字列(例: "¥%s円" )。 |
decimal | number | ✅ | 数値の小数点以下の桁数(0〜5) |
onFormatChange | (info: FormatSettings) => void | ✅ | 各設定項目の更新を通知するコールバック |
Y-m-d H:i:s
、Y年n月j日 (l)
など"%s"
を含む文字列で、実際の値が置換されますdisplayFormated(content, userFormat, freeStrFormat, decimal)
指定されたフォーマットに従って、値を整形して文字列として返します。
名前 | 型 | 説明 |
---|---|---|
content | string | number | 整形対象の生の値 |
userFormat | string | 日付または数値のフォーマットキー(例: "num_comma" 、"Y-m-d" ) |
freeStrFormat | string | "%s" を含む自由書式文字列 |
decimal | number | 小数点以下の桁数指定(0 なら整数扱い) |
整形後の文字列(string
)
1<FormatSelectControl 2 titleType="plaine" 3 userFormat={attributes.userFormat} 4 freeStrFormat={attributes.freeStrFormat} 5 decimal={attributes.decimal} 6 onFormatChange={(newSettings) => setAttributes(newSettings)} 7/>
const display = displayFormated(
1234567.89,
attributes.userFormat,
attributes.freeStrFormat,
attributes.decimal
);
// → "1,234,567.89"(例: num_comma + decimal: 2 の場合)
✅ 自由書式(freeStrFormat)について
✅ 日付フォーマットの安全性
✅ 数値フォーマットの条件
No vulnerabilities found.
No security vulnerabilities found.