NewsResource.php 22KB

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