NewsResource.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. namespace App\Filament\Resources;
  3. use App\Filament\Resources\NewsResource\Pages;
  4. use App\Models\News;
  5. use App\Models\NewsCategory;
  6. use Filament\Forms\Components\Actions\Action;
  7. use Filament\Forms\Components\Group;
  8. use Filament\Forms\Components\Hidden;
  9. use Filament\Forms\Components\Repeater;
  10. use Filament\Forms\Components\RichEditor;
  11. use Filament\Forms\Components\Tabs;
  12. use Filament\Forms\Components\Tabs\Tab;
  13. use Filament\Forms\Components\TextInput;
  14. use Filament\Forms\Components\Textarea;
  15. use Filament\Forms\Components\Select;
  16. use Filament\Forms\Components\Radio;
  17. use Filament\Forms\Components\Section;
  18. use Filament\Forms\Components\Toggle;
  19. use Filament\Forms\Components\DatePicker;
  20. use Filament\Forms\Components\FileUpload;
  21. use Filament\Forms\Get;
  22. use Filament\Forms\Form;
  23. use Filament\Forms\Set;
  24. use Filament\Resources\Resource;
  25. use Filament\Tables;
  26. use Filament\Tables\Columns\IconColumn;
  27. use Filament\Tables\Columns\ImageColumn;
  28. use Filament\Tables\Columns\TextColumn;
  29. use Filament\Tables\Filters\SelectFilter;
  30. use Filament\Tables\Table;
  31. use Illuminate\Database\Eloquent\Builder;
  32. use Illuminate\Support\Facades\DB;
  33. use Illuminate\Support\Str;
  34. use Malzariey\FilamentLexicalEditor\Enums\ToolbarItem;
  35. use Malzariey\FilamentLexicalEditor\FilamentLexicalEditor;
  36. use SolutionForest\FilamentTranslateField\Forms\Component\Translate;
  37. use RalphJSmit\Filament\SEO\SEO;
  38. class NewsResource extends Resource
  39. {
  40. protected static ?string $model = News::class;
  41. protected static ?string $modelLabel = "文章管理";
  42. protected static ?string $navigationIcon = 'heroicon-o-newspaper';
  43. protected static ?string $navigationGroup = '上稿內容管理';
  44. protected static ?string $navigationLabel = "文章管理";
  45. public static function form(Form $form): Form
  46. {
  47. return $form
  48. ->schema([
  49. //
  50. Section::make("新增 文章")->schema([
  51. Group::make()->schema([
  52. Select::make("news_category_id")
  53. ->options(NewsCategory::get()->pluck("name","id"))
  54. ->label("文章分類")
  55. ->columnSpan(1)
  56. ->native(false)
  57. ->afterStateHydrated(function ($component, $state) {
  58. // ✅ 如果沒有值,設定為第一項
  59. if (empty($state)) {
  60. $firstCategoryId = NewsCategory::first()?->id;
  61. if ($firstCategoryId) {
  62. $component->state($firstCategoryId);
  63. }
  64. }
  65. })
  66. ->required(),
  67. ])->columnSpanFull()->columns(2),
  68. Group::make()->schema([
  69. DatePicker::make('post_date')
  70. ->label("發布日期")
  71. ->closeOnDateSelection()->required(),
  72. ])->columnSpanFull()->columns(2),
  73. FileUpload::make('news_img_pc')->label("列表圖(desktop)")
  74. ->disk("public")
  75. // ->helperText('建議寬高限制為:1280*720px,檔案大小限制為1M以下')->maxSize('1024')
  76. ->directory("news"),
  77. FileUpload::make('news_img_mobile')->label("列表圖(mobile)")
  78. ->disk("public")
  79. // ->helperText('建議寬高限制為:600*896px,檔案大小限制為1M以下')->maxSize('1024')
  80. ->directory("news"),
  81. Translate::make()->schema(fn (string $locale) => [
  82. TextInput::make('title')
  83. ->label("標題")
  84. ->columnSpan(1),
  85. TextInput::make('written_by')
  86. ->label("發佈者")->columnSpan(1),
  87. Textarea::make("description")->rows(5)->columnSpanFull()->label("短文"),
  88. ])->locales(["zh_TW", "en"])
  89. ->id("main")
  90. ->columnSpanFull()->columns(3),
  91. TextInput::make('order')->label("排序")->integer()->default(0),
  92. ])->columns(3),
  93. Section::make("SEO")->schema([
  94. // SEO::make(),
  95. Translate::make()->schema(fn (string $locale) => [
  96. TextInput::make('meta_title')->label("SEO 標題")->columnSpan(1),
  97. Textarea::make("meta_keyword")->rows(5)->columnSpanFull()->label("SEO 關鍵字"),
  98. Textarea::make("meta_description")->rows(5)->columnSpanFull()->label("SEO 短文"),
  99. ])
  100. ->locales(["zh_TW", "en"])
  101. ->id("seo"),
  102. FileUpload::make('meta_img')->label("放大預覽圖")->disk("public")
  103. // ->helperText('建議寬高限制為:1200*630px,檔案大小限制為1M以下')->maxSize('1024')
  104. ->directory("seo/news"),
  105. ])->columnSpanFull(),
  106. Section::make("文章內容")->schema([
  107. Repeater::make("paragraphs")->schema([
  108. TextInput::make('item_key')
  109. ->default(fn () => Str::random())
  110. ->hidden()
  111. ->afterStateHydrated(function (TextInput $component, $state) {
  112. if (empty($state)) {
  113. $component->state(Str::random());
  114. }
  115. }),
  116. Radio::make("paragraph_type")->options([
  117. 1 => "圖片",
  118. 2 => "文字",
  119. 3 => "影音",
  120. ])->label("")->default(1)->Live(),
  121. Group::make()->schema([
  122. Section::make('')->schema([
  123. Repeater::make("multiple_images")->schema([
  124. TextInput::make('para_img_item_key')
  125. ->default(fn () => Str::random())
  126. ->hidden()
  127. ->afterStateHydrated(function (TextInput $component, $state) {
  128. if (empty($state)) {
  129. $component->state(Str::random());
  130. }
  131. }),
  132. Translate::make()->schema(fn (string $locale) => [
  133. TextInput::make('image_alt')->label("圖片註文"),
  134. ])->locales(["zh_TW", "en"])
  135. ->id(fn ($get) => "para_img_mul_" . $get('para_img_item_key')),
  136. FileUpload::make('image_url')->label("")->disk("public")
  137. // ->helperText('建議寬高限制為:1080*675px,檔案大小限制為1M以下')->maxSize('1024')
  138. ->directory("news/extraPhoto")
  139. ->maxFiles(10),
  140. ])
  141. ->relationship("photos")
  142. ->label("")
  143. ->orderColumn('order')
  144. ])
  145. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 1),
  146. Group::make()->schema([
  147. FilamentLexicalEditor::make('text_content_tw')
  148. ->label('繁體中文內容')
  149. ->id(fn ($get) => "text_content_tw_" . $get('item_key') . "_" . uniqid())
  150. ->enabledToolbars([
  151. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  152. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  153. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  154. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  155. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  156. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  157. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR
  158. ])
  159. ->live(onBlur: true)
  160. ->columnSpanFull(),
  161. FilamentLexicalEditor::make('text_content_en')
  162. ->label('English Content')
  163. ->id(fn ($get) => "text_content_en_" . $get('item_key') . "_" . uniqid())
  164. ->enabledToolbars([
  165. ToolbarItem::UNDO, ToolbarItem::REDO, ToolbarItem::NORMAL,
  166. ToolbarItem::H2, ToolbarItem::H3, ToolbarItem::H4, ToolbarItem::H5,
  167. ToolbarItem::BULLET, ToolbarItem::NUMBERED, ToolbarItem::FONT_SIZE,
  168. ToolbarItem::BOLD, ToolbarItem::ITALIC, ToolbarItem::UNDERLINE,
  169. ToolbarItem::LINK, ToolbarItem::TEXT_COLOR, ToolbarItem::BACKGROUND_COLOR,
  170. ToolbarItem::SUBSCRIPT, ToolbarItem::LOWERCASE, ToolbarItem::DIVIDER,
  171. ToolbarItem::UPPERCASE, ToolbarItem::CLEAR, ToolbarItem::HR
  172. ])
  173. ->columnSpanFull(),
  174. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 2),
  175. Group::make()->schema([
  176. Section::make("")->schema([
  177. FileUpload::make('video_img')->label("影片底圖")
  178. ->disk("public")
  179. ->directory("news/paragraph/video"),
  180. // ->helperText('建議寬高限制為:2000*720px,出血寬度720px,主要圖像範圍為:1280*720px,檔案大小限制為1M以下')->maxSize('1024'),
  181. Translate::make()->schema(fn (string $locale) => [
  182. TextInput::make('video_img_alt')->label("圖片註文")->columnSpan(1),
  183. ])->locales(["zh_TW", "en"])
  184. ->id(fn ($get) => "para_video_img_alt_" . $get('item_key')),
  185. Radio::make("video_type")->label("")->options([
  186. 1 => "網址",
  187. 2 => "檔案"
  188. ])->columnSpanFull()->default(1)->Live(),
  189. Group::make()->schema([
  190. TextInput::make('link')->label("網址")->nullable(),
  191. ])->visible(fn (Get $get):bool => $get("video_type") == 1)->columnSpanFull(),
  192. Group::make()->schema([
  193. FileUpload::make('video_url')->label("")->disk("public")->directory("news/paragraph/video")
  194. // ->helperText('建議影片寬高限制為:1920*1080px,出血寬度720px,大小限制為:100M以下')
  195. // ->maxSize(102400)
  196. ->nullable(),
  197. ])->visible(fn (Get $get):bool => $get("video_type") == 2)->columnSpanFull(),
  198. ]),
  199. ])->visible(fn (Get $get):bool => $get("paragraph_type") == 3),
  200. ])
  201. ->relationship("paragraphs")
  202. ->label("段落")
  203. ->collapsible()
  204. ->reorderableWithButtons()
  205. ->orderColumn('order')
  206. ->cloneable()
  207. ->mutateRelationshipDataBeforeFillUsing(function (array $data): array {
  208. if ($data['paragraph_type'] == 2 && !empty($data['text_content'])) {
  209. $content = is_string($data['text_content'])
  210. ? json_decode($data['text_content'], true)
  211. : $data['text_content'];
  212. if (is_array($content)) {
  213. $data['text_content_tw'] = $content['zh_TW'] ?? '';
  214. $data['text_content_en'] = $content['en'] ?? '';
  215. }
  216. }
  217. return $data;
  218. })
  219. ->mutateRelationshipDataBeforeSaveUsing(function (array $data): array{
  220. if ($data['paragraph_type'] == 2) {
  221. $data["text_content"] = ["zh_TW" => $data["text_content_tw"], "en" => $data["text_content_en"]];
  222. // 移除臨時的分離欄位,只保留合併的 JSON 欄位
  223. unset($data['text_content_tw']);
  224. unset($data['text_content_en']);
  225. }
  226. return $data;
  227. })
  228. ]),
  229. ]);
  230. }
  231. public static function table(Table $table): Table
  232. {
  233. return $table
  234. ->columns([
  235. //
  236. TextColumn::make("newsCategory.name")->label("分類")->alignCenter(),
  237. TextColumn::make("title")->label("標題")->alignCenter(),
  238. TextColumn::make("written_by")->label("發佈者")->alignCenter(),
  239. TextColumn::make("post_date")->label("發佈時間")->dateTime('Y/m/d')->alignCenter(),
  240. ImageColumn::make("news_img_pc_url")->label("列表圖")->alignCenter(),
  241. TextColumn::make("list_audit_state")->label("狀態")->badge()
  242. ->color(fn (string $state): string => match ($state) {
  243. '暫存' => 'warning',
  244. '已發佈' => 'success',
  245. }),
  246. IconColumn::make("on_top")->label("置頂")
  247. ->color(fn (string $state): string => match ($state) {
  248. 1 => 'success',
  249. default => ''
  250. })
  251. ->icon(fn (string $state): string => match ($state) {
  252. 1 => 'heroicon-o-check-circle',
  253. default => ''
  254. })
  255. ->action(function ($record): void {
  256. $record->on_top = !$record->on_top;
  257. $record->save();
  258. }),
  259. TextColumn::make("created_at")->label("建立時間")->dateTime('Y/m/d H:i:s')->alignCenter(),
  260. TextColumn::make("updated_at")->label("更新時間")->dateTime()->alignCenter(),
  261. ])
  262. ->filters([
  263. SelectFilter::make('news_category_id')->label("分類")
  264. ->options(NewsCategory::orderBy("order")->pluck("name", "id"))
  265. ->attribute('news_category_id'),
  266. SelectFilter::make('post_date')->label("年份")
  267. ->options(News::select(DB::raw("DATE_FORMAT(post_date, '%Y') as year"))->whereNotNull("post_date")->distinct()->pluck("year","year")->toArray())
  268. ->query(
  269. fn (array $data, Builder $query): Builder =>
  270. $query->when(
  271. $data['value'],
  272. fn (Builder $query, $value): Builder => $query->where('post_date', 'like', $data['value']. "%")
  273. )
  274. ),
  275. SelectFilter::make('visible')->label("狀態")
  276. ->options([
  277. 0 => "暫存",
  278. 1 => "已發佈",
  279. ])
  280. ->query(
  281. fn (array $data, Builder $query): Builder =>
  282. $query->when(
  283. $data['value'],
  284. fn (Builder $query, $value): Builder => $query->where('visible', $data['value'])
  285. )
  286. ),
  287. ])
  288. ->actions([
  289. Tables\Actions\EditAction::make(),
  290. Tables\Actions\DeleteAction::make(),
  291. \Filament\Tables\Actions\Action::make("audit")
  292. ->label(fn ($record) => match ($record->visible) {
  293. 0 => '發佈',
  294. 1 => '下架',
  295. })
  296. ->color(fn ($record) => match ($record->visible) {
  297. 0 => 'warning',
  298. 1 => 'gray',
  299. })
  300. ->icon(fn ($record) => match ($record->visible) {
  301. 0 => 'heroicon-m-chevron-double-up',
  302. 1 => 'heroicon-m-chevron-double-down',
  303. })
  304. ->action(function ($record): void {
  305. $record->visible = !$record->visible;
  306. $record->save();
  307. })
  308. ->outlined()
  309. ->requiresConfirmation(),
  310. ])
  311. ->bulkActions([
  312. Tables\Actions\BulkActionGroup::make([
  313. Tables\Actions\DeleteBulkAction::make(),
  314. ]),
  315. ])
  316. ->defaultSort('order', 'desc')
  317. ->defaultSort('created_at', 'desc');
  318. }
  319. public static function getRelations(): array
  320. {
  321. return [
  322. //
  323. ];
  324. }
  325. public static function getPages(): array
  326. {
  327. return [
  328. 'index' => Pages\ListNews::route('/'),
  329. 'create' => Pages\CreateNews::route('/create'),
  330. 'edit' => Pages\EditNews::route('/{record}/edit'),
  331. 'view' => Pages\ViewNews::route('/{record}/view'),
  332. ];
  333. }
  334. }